ConsoleOptionParser.php 18 KB

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