ConsoleOptionParser.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Console;
  16. use Cake\Utility\Inflector;
  17. /**
  18. * Handles parsing the ARGV in the command line and provides support
  19. * for GetOpt compatible option definition. Provides a builder pattern implementation
  20. * for creating shell option parsers.
  21. *
  22. * ### Options
  23. *
  24. * Named arguments come in two forms, long and short. Long arguments are preceded
  25. * by two - and give a more verbose option name. i.e. `--version`. Short arguments are
  26. * preceded by one - and are only one character long. They usually match with a long option,
  27. * and provide a more terse alternative.
  28. *
  29. * ### Using Options
  30. *
  31. * Options can be defined with both long and short forms. By using `$parser->addOption()`
  32. * you can define new options. The name of the option is used as its long form, and you
  33. * can supply an additional short form, with the `short` option. Short options should
  34. * only be one letter long. Using more than one letter for a short option will raise an exception.
  35. *
  36. * Calling options can be done using syntax similar to most *nix command line tools. Long options
  37. * cane either include an `=` or leave it out.
  38. *
  39. * `cake myshell command --connection default --name=something`
  40. *
  41. * Short options can be defined signally or in groups.
  42. *
  43. * `cake myshell command -cn`
  44. *
  45. * Short options can be combined into groups as seen above. Each letter in a group
  46. * will be treated as a separate option. The previous example is equivalent to:
  47. *
  48. * `cake myshell command -c -n`
  49. *
  50. * Short options can also accept values:
  51. *
  52. * `cake myshell command -c default`
  53. *
  54. * ### Positional arguments
  55. *
  56. * If no positional arguments are defined, all of them will be parsed. If you define positional
  57. * arguments any arguments greater than those defined will cause exceptions. Additionally you can
  58. * declare arguments as optional, by setting the required param to false.
  59. *
  60. * `$parser->addArgument('model', ['required' => false]);`
  61. *
  62. * ### Providing Help text
  63. *
  64. * By providing help text for your positional arguments and named arguments, the ConsoleOptionParser
  65. * can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch.
  66. *
  67. */
  68. class ConsoleOptionParser {
  69. /**
  70. * Description text - displays before options when help is generated
  71. *
  72. * @see ConsoleOptionParser::description()
  73. * @var string
  74. */
  75. protected $_description = null;
  76. /**
  77. * Epilog text - displays after options when help is generated
  78. *
  79. * @see ConsoleOptionParser::epilog()
  80. * @var string
  81. */
  82. protected $_epilog = null;
  83. /**
  84. * Option definitions.
  85. *
  86. * @see ConsoleOptionParser::addOption()
  87. * @var array
  88. */
  89. protected $_options = [];
  90. /**
  91. * Map of short -> long options, generated when using addOption()
  92. *
  93. * @var string
  94. */
  95. protected $_shortOptions = [];
  96. /**
  97. * Positional argument definitions.
  98. *
  99. * @see ConsoleOptionParser::addArgument()
  100. * @var array
  101. */
  102. protected $_args = [];
  103. /**
  104. * Subcommands for this Shell.
  105. *
  106. * @see ConsoleOptionParser::addSubcommand()
  107. * @var array
  108. */
  109. protected $_subcommands = [];
  110. /**
  111. * Command name.
  112. *
  113. * @var string
  114. */
  115. protected $_command = '';
  116. /**
  117. * Construct an OptionParser so you can define its behavior
  118. *
  119. * @param string $command The command name this parser is for. The command name is used for generating help.
  120. * @param bool $defaultOptions Whether you want the verbose and quiet options set. Setting
  121. * this to false will prevent the addition of `--verbose` & `--quiet` options.
  122. */
  123. public function __construct($command = null, $defaultOptions = true) {
  124. $this->command($command);
  125. $this->addOption('help', [
  126. 'short' => 'h',
  127. 'help' => __d('cake_console', 'Display this help.'),
  128. 'boolean' => true
  129. ]);
  130. if ($defaultOptions) {
  131. $this->addOption('verbose', [
  132. 'short' => 'v',
  133. 'help' => __d('cake_console', 'Enable verbose output.'),
  134. 'boolean' => true
  135. ])->addOption('quiet', [
  136. 'short' => 'q',
  137. 'help' => __d('cake_console', 'Enable quiet output.'),
  138. 'boolean' => true
  139. ]);
  140. }
  141. }
  142. /**
  143. * Static factory method for creating new OptionParsers so you can chain methods off of them.
  144. *
  145. * @param string $command The command name this parser is for. The command name is used for generating help.
  146. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  147. * @return ConsoleOptionParser
  148. */
  149. public static function create($command, $defaultOptions = true) {
  150. return new ConsoleOptionParser($command, $defaultOptions);
  151. }
  152. /**
  153. * Build a parser from an array. Uses an array like
  154. *
  155. * {{{
  156. * $spec = [
  157. * 'description' => 'text',
  158. * 'epilog' => 'text',
  159. * 'arguments' => [
  160. * // list of arguments compatible with addArguments.
  161. * ],
  162. * 'options' => [
  163. * // list of options compatible with addOptions
  164. * ],
  165. * 'subcommands' => [
  166. * // list of subcommands to add.
  167. * ]
  168. * ];
  169. * }}}
  170. *
  171. * @param array $spec The spec to build the OptionParser with.
  172. * @return ConsoleOptionParser
  173. */
  174. public static function buildFromArray($spec) {
  175. $parser = new ConsoleOptionParser($spec['command']);
  176. if (!empty($spec['arguments'])) {
  177. $parser->addArguments($spec['arguments']);
  178. }
  179. if (!empty($spec['options'])) {
  180. $parser->addOptions($spec['options']);
  181. }
  182. if (!empty($spec['subcommands'])) {
  183. $parser->addSubcommands($spec['subcommands']);
  184. }
  185. if (!empty($spec['description'])) {
  186. $parser->description($spec['description']);
  187. }
  188. if (!empty($spec['epilog'])) {
  189. $parser->epilog($spec['epilog']);
  190. }
  191. return $parser;
  192. }
  193. /**
  194. * Get or set the command name for shell/task.
  195. *
  196. * @param string $text The text to set, or null if you want to read
  197. * @return mixed If reading, the value of the command. If setting $this will be returned
  198. */
  199. public function command($text = null) {
  200. if ($text !== null) {
  201. $this->_command = Inflector::underscore($text);
  202. return $this;
  203. }
  204. return $this->_command;
  205. }
  206. /**
  207. * Get or set the description text for shell/task.
  208. *
  209. * @param string|array $text The text to set, or null if you want to read. If an array the
  210. * text will be imploded with "\n"
  211. * @return mixed If reading, the value of the description. If setting $this will be returned
  212. */
  213. public function description($text = null) {
  214. if ($text !== null) {
  215. if (is_array($text)) {
  216. $text = implode("\n", $text);
  217. }
  218. $this->_description = $text;
  219. return $this;
  220. }
  221. return $this->_description;
  222. }
  223. /**
  224. * Get or set an epilog to the parser. The epilog is added to the end of
  225. * the options and arguments listing when help is generated.
  226. *
  227. * @param string|array $text Text when setting or null when reading. If an array the text will be imploded with "\n"
  228. * @return mixed If reading, the value of the epilog. If setting $this will be returned.
  229. */
  230. public function epilog($text = null) {
  231. if ($text !== null) {
  232. if (is_array($text)) {
  233. $text = implode("\n", $text);
  234. }
  235. $this->_epilog = $text;
  236. return $this;
  237. }
  238. return $this->_epilog;
  239. }
  240. /**
  241. * Add an option to the option parser. Options allow you to define optional or required
  242. * parameters for your console application. Options are defined by the parameters they use.
  243. *
  244. * ### Options
  245. *
  246. * - `short` - The single letter variant for this option, leave undefined for none.
  247. * - `help` - Help text for this option. Used when generating help for the option.
  248. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  249. * attached option is not provided or has no value. Using default and boolean together will not work.
  250. * are added into the parsed parameters when the option is undefined. Defaults to null.
  251. * - `boolean` - The option uses no value, its just a boolean switch. Defaults to false.
  252. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  253. * it will be false, if present it will be true.
  254. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  255. * An exception will be raised when parse() encounters an invalid value.
  256. *
  257. * @param ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  258. * Will also accept an instance of ConsoleInputOption
  259. * @param array $options An array of parameters that define the behavior of the option
  260. * @return ConsoleOptionParser this.
  261. */
  262. public function addOption($name, $options = []) {
  263. if (is_object($name) && $name instanceof ConsoleInputOption) {
  264. $option = $name;
  265. $name = $option->name();
  266. } else {
  267. $defaults = [
  268. 'name' => $name,
  269. 'short' => null,
  270. 'help' => '',
  271. 'default' => null,
  272. 'boolean' => false,
  273. 'choices' => []
  274. ];
  275. $options += $defaults;
  276. $option = new ConsoleInputOption($options);
  277. }
  278. $this->_options[$name] = $option;
  279. if ($option->short() !== null) {
  280. $this->_shortOptions[$option->short()] = $name;
  281. }
  282. return $this;
  283. }
  284. /**
  285. * Remove an option from the option parser.
  286. *
  287. * @param string $name The option name to remove.
  288. * @return ConsoleOptionParser this
  289. */
  290. public function removeOption($name) {
  291. unset($this->_options[$name]);
  292. return $this;
  293. }
  294. /**
  295. * Add a positional argument to the option parser.
  296. *
  297. * ### Params
  298. *
  299. * - `help` The help text to display for this argument.
  300. * - `required` Whether this parameter is required.
  301. * - `index` The index for the arg, if left undefined the argument will be put
  302. * onto the end of the arguments. If you define the same index twice the first
  303. * option will be overwritten.
  304. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  305. * An exception will be raised when parse() encounters an invalid value.
  306. *
  307. * @param ConsoleInputArgument|string $name The name of the argument. Will also accept an instance of ConsoleInputArgument
  308. * @param array $params Parameters for the argument, see above.
  309. * @return ConsoleOptionParser this.
  310. */
  311. public function addArgument($name, $params = []) {
  312. if (is_object($name) && $name instanceof ConsoleInputArgument) {
  313. $arg = $name;
  314. $index = count($this->_args);
  315. } else {
  316. $defaults = [
  317. 'name' => $name,
  318. 'help' => '',
  319. 'index' => count($this->_args),
  320. 'required' => false,
  321. 'choices' => []
  322. ];
  323. $options = $params + $defaults;
  324. $index = $options['index'];
  325. unset($options['index']);
  326. $arg = new ConsoleInputArgument($options);
  327. }
  328. $this->_args[$index] = $arg;
  329. ksort($this->_args);
  330. return $this;
  331. }
  332. /**
  333. * Add multiple arguments at once. Take an array of argument definitions.
  334. * The keys are used as the argument names, and the values as params for the argument.
  335. *
  336. * @param array $args Array of arguments to add.
  337. * @see ConsoleOptionParser::addArgument()
  338. * @return ConsoleOptionParser this
  339. */
  340. public function addArguments(array $args) {
  341. foreach ($args as $name => $params) {
  342. $this->addArgument($name, $params);
  343. }
  344. return $this;
  345. }
  346. /**
  347. * Add multiple options at once. Takes an array of option definitions.
  348. * The keys are used as option names, and the values as params for the option.
  349. *
  350. * @param array $options Array of options to add.
  351. * @see ConsoleOptionParser::addOption()
  352. * @return ConsoleOptionParser this
  353. */
  354. public function addOptions(array $options) {
  355. foreach ($options as $name => $params) {
  356. $this->addOption($name, $params);
  357. }
  358. return $this;
  359. }
  360. /**
  361. * Append a subcommand to the subcommand list.
  362. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  363. *
  364. * ### Options
  365. *
  366. * - `help` - Help text for the subcommand.
  367. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  368. * specific option parsers. When help is generated for a subcommand, if a parser is present
  369. * it will be used.
  370. *
  371. * @param ConsoleInputSubcommand|string $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  372. * @param array $options Array of params, see above.
  373. * @return ConsoleOptionParser this.
  374. */
  375. public function addSubcommand($name, $options = []) {
  376. if (is_object($name) && $name instanceof ConsoleInputSubcommand) {
  377. $command = $name;
  378. $name = $command->name();
  379. } else {
  380. $defaults = [
  381. 'name' => $name,
  382. 'help' => '',
  383. 'parser' => null
  384. ];
  385. $options += $defaults;
  386. $command = new ConsoleInputSubcommand($options);
  387. }
  388. $this->_subcommands[$name] = $command;
  389. return $this;
  390. }
  391. /**
  392. * Add multiple subcommands at once.
  393. *
  394. * @param array $commands Array of subcommands.
  395. * @return ConsoleOptionParser this
  396. */
  397. public function addSubcommands(array $commands) {
  398. foreach ($commands as $name => $params) {
  399. $this->addSubcommand($name, $params);
  400. }
  401. return $this;
  402. }
  403. /**
  404. * Gets the arguments defined in the parser.
  405. *
  406. * @return array Array of argument descriptions
  407. */
  408. public function arguments() {
  409. return $this->_args;
  410. }
  411. /**
  412. * Get the defined options in the parser.
  413. *
  414. * @return array
  415. */
  416. public function options() {
  417. return $this->_options;
  418. }
  419. /**
  420. * Get the array of defined subcommands
  421. *
  422. * @return array
  423. */
  424. public function subcommands() {
  425. return $this->_subcommands;
  426. }
  427. /**
  428. * Parse the argv array into a set of params and args. If $command is not null
  429. * and $command is equal to a subcommand that has a parser, that parser will be used
  430. * to parse the $argv
  431. *
  432. * @param array $argv Array of args (argv) to parse.
  433. * @param string $command The subcommand to use. If this parameter is a subcommand, that has a parser,
  434. * That parser will be used to parse $argv instead.
  435. * @return Array [$params, $args]
  436. * @throws \Cake\Console\Error\ConsoleException When an invalid parameter is encountered.
  437. */
  438. public function parse($argv) {
  439. $command = isset($argv[0]) ? $argv[0] : null;
  440. if (isset($this->_subcommands[$command])) {
  441. array_shift($argv);
  442. }
  443. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  444. return $this->_subcommands[$command]->parser()->parse($argv);
  445. }
  446. $params = $args = [];
  447. $this->_tokens = $argv;
  448. while (($token = array_shift($this->_tokens)) !== null) {
  449. if (substr($token, 0, 2) === '--') {
  450. $params = $this->_parseLongOption($token, $params);
  451. } elseif (substr($token, 0, 1) === '-') {
  452. $params = $this->_parseShortOption($token, $params);
  453. } else {
  454. $args = $this->_parseArg($token, $args);
  455. }
  456. }
  457. foreach ($this->_args as $i => $arg) {
  458. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  459. throw new Error\ConsoleException(
  460. __d('cake_console', 'Missing required arguments. %s is required.', $arg->name())
  461. );
  462. }
  463. }
  464. foreach ($this->_options as $option) {
  465. $name = $option->name();
  466. $isBoolean = $option->isBoolean();
  467. $default = $option->defaultValue();
  468. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  469. $params[$name] = $default;
  470. }
  471. if ($isBoolean && !isset($params[$name])) {
  472. $params[$name] = false;
  473. }
  474. }
  475. return [$params, $args];
  476. }
  477. /**
  478. * Gets formatted help for this parser object.
  479. * Generates help text based on the description, options, arguments, subcommands and epilog
  480. * in the parser.
  481. *
  482. * @param string $subcommand If present and a valid subcommand that has a linked parser.
  483. * That subcommands help will be shown instead.
  484. * @param string $format Define the output format, can be text or xml
  485. * @param int $width The width to format user content to. Defaults to 72
  486. * @return string Generated help.
  487. */
  488. public function help($subcommand = null, $format = 'text', $width = 72) {
  489. if (
  490. isset($this->_subcommands[$subcommand]) &&
  491. $this->_subcommands[$subcommand]->parser() instanceof self
  492. ) {
  493. $subparser = $this->_subcommands[$subcommand]->parser();
  494. $subparser->command($this->command() . ' ' . $subparser->command());
  495. return $subparser->help(null, $format, $width);
  496. }
  497. $formatter = new HelpFormatter($this);
  498. if ($format === 'text' || $format === true) {
  499. return $formatter->text($width);
  500. } elseif ($format === 'xml') {
  501. return $formatter->xml();
  502. }
  503. }
  504. /**
  505. * Parse the value for a long option out of $this->_tokens. Will handle
  506. * options with an `=` in them.
  507. *
  508. * @param string $option The option to parse.
  509. * @param array $params The params to append the parsed value into
  510. * @return array Params with $option added in.
  511. */
  512. protected function _parseLongOption($option, $params) {
  513. $name = substr($option, 2);
  514. if (strpos($name, '=') !== false) {
  515. list($name, $value) = explode('=', $name, 2);
  516. array_unshift($this->_tokens, $value);
  517. }
  518. return $this->_parseOption($name, $params);
  519. }
  520. /**
  521. * Parse the value for a short option out of $this->_tokens
  522. * If the $option is a combination of multiple shortcuts like -otf
  523. * they will be shifted onto the token stack and parsed individually.
  524. *
  525. * @param string $option The option to parse.
  526. * @param array $params The params to append the parsed value into
  527. * @return array Params with $option added in.
  528. * @throws \Cake\Console\Error\ConsoleException When unknown short options are encountered.
  529. */
  530. protected function _parseShortOption($option, $params) {
  531. $key = substr($option, 1);
  532. if (strlen($key) > 1) {
  533. $flags = str_split($key);
  534. $key = $flags[0];
  535. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  536. array_unshift($this->_tokens, '-' . $flags[$i]);
  537. }
  538. }
  539. if (!isset($this->_shortOptions[$key])) {
  540. throw new Error\ConsoleException(__d('cake_console', 'Unknown short option `%s`', $key));
  541. }
  542. $name = $this->_shortOptions[$key];
  543. return $this->_parseOption($name, $params);
  544. }
  545. /**
  546. * Parse an option by its name index.
  547. *
  548. * @param string $name The name to parse.
  549. * @param array $params The params to append the parsed value into
  550. * @return array Params with $option added in.
  551. * @throws \Cake\Console\Error\ConsoleException
  552. */
  553. protected function _parseOption($name, $params) {
  554. if (!isset($this->_options[$name])) {
  555. throw new Error\ConsoleException(__d('cake_console', 'Unknown option `%s`', $name));
  556. }
  557. $option = $this->_options[$name];
  558. $isBoolean = $option->isBoolean();
  559. $nextValue = $this->_nextToken();
  560. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  561. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  562. array_shift($this->_tokens);
  563. $value = $nextValue;
  564. } elseif ($isBoolean) {
  565. $value = true;
  566. } else {
  567. $value = $option->defaultValue();
  568. }
  569. if ($option->validChoice($value)) {
  570. $params[$name] = $value;
  571. return $params;
  572. }
  573. }
  574. /**
  575. * Check to see if $name has an option (short/long) defined for it.
  576. *
  577. * @param string $name The name of the option.
  578. * @return bool
  579. */
  580. protected function _optionExists($name) {
  581. if (substr($name, 0, 2) === '--') {
  582. return isset($this->_options[substr($name, 2)]);
  583. }
  584. if ($name{0} === '-' && $name{1} !== '-') {
  585. return isset($this->_shortOptions[$name{1}]);
  586. }
  587. return false;
  588. }
  589. /**
  590. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  591. * and that the argument is a valid choice.
  592. *
  593. * @param string $argument The argument to append
  594. * @param array $args The array of parsed args to append to.
  595. * @return array Args
  596. * @throws \Cake\Console\Error\ConsoleException
  597. */
  598. protected function _parseArg($argument, $args) {
  599. if (empty($this->_args)) {
  600. $args[] = $argument;
  601. return $args;
  602. }
  603. $next = count($args);
  604. if (!isset($this->_args[$next])) {
  605. throw new Error\ConsoleException(__d('cake_console', 'Too many arguments.'));
  606. }
  607. if ($this->_args[$next]->validChoice($argument)) {
  608. $args[] = $argument;
  609. return $args;
  610. }
  611. }
  612. /**
  613. * Find the next token in the argv set.
  614. *
  615. * @return string next token or ''
  616. */
  617. protected function _nextToken() {
  618. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  619. }
  620. }