ConsoleOptionParser.php 20 KB

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