ConsoleOptionParser.php 20 KB

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