ConsoleOptionParser.php 20 KB

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