ConsoleOptionParser.php 19 KB

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