PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Console/ConsoleOptionParser.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 651 lines | 291 code | 38 blank | 322 comment | 57 complexity | 7ddb97b7a963d0e0010d0ae724eda685 MD5 | raw file
  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. 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 mixed $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 mixed $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 mixed $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 mixed $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. return $this;
  330. }
  331. /**
  332. * Add multiple arguments at once. Take an array of argument definitions.
  333. * The keys are used as the argument names, and the values as params for the argument.
  334. *
  335. * @param array $args Array of arguments to add.
  336. * @see ConsoleOptionParser::addArgument()
  337. * @return ConsoleOptionParser $this
  338. */
  339. public function addArguments(array $args) {
  340. foreach ($args as $name => $params) {
  341. $this->addArgument($name, $params);
  342. }
  343. return $this;
  344. }
  345. /**
  346. * Add multiple options at once. Takes an array of option definitions.
  347. * The keys are used as option names, and the values as params for the option.
  348. *
  349. * @param array $options Array of options to add.
  350. * @see ConsoleOptionParser::addOption()
  351. * @return ConsoleOptionParser $this
  352. */
  353. public function addOptions(array $options) {
  354. foreach ($options as $name => $params) {
  355. $this->addOption($name, $params);
  356. }
  357. return $this;
  358. }
  359. /**
  360. * Append a subcommand to the subcommand list.
  361. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  362. *
  363. * ### Options
  364. *
  365. * - `help` - Help text for the subcommand.
  366. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  367. * specific option parsers. When help is generated for a subcommand, if a parser is present
  368. * it will be used.
  369. *
  370. * @param mixed $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  371. * @param array $options Array of params, see above.
  372. * @return ConsoleOptionParser $this.
  373. */
  374. public function addSubcommand($name, $options = array()) {
  375. if (is_object($name) && $name instanceof ConsoleInputSubcommand) {
  376. $command = $name;
  377. $name = $command->name();
  378. } else {
  379. $defaults = array(
  380. 'name' => $name,
  381. 'help' => '',
  382. 'parser' => null
  383. );
  384. $options = array_merge($defaults, $options);
  385. $command = new ConsoleInputSubcommand($options);
  386. }
  387. $this->_subcommands[$name] = $command;
  388. return $this;
  389. }
  390. /**
  391. * Add multiple subcommands at once.
  392. *
  393. * @param array $commands Array of subcommands.
  394. * @return ConsoleOptionParser $this
  395. */
  396. public function addSubcommands(array $commands) {
  397. foreach ($commands as $name => $params) {
  398. $this->addSubcommand($name, $params);
  399. }
  400. return $this;
  401. }
  402. /**
  403. * Gets the arguments defined in the parser.
  404. *
  405. * @return array Array of argument descriptions
  406. */
  407. public function arguments() {
  408. return $this->_args;
  409. }
  410. /**
  411. * Get the defined options in the parser.
  412. *
  413. * @return array
  414. */
  415. public function options() {
  416. return $this->_options;
  417. }
  418. /**
  419. * Get the array of defined subcommands
  420. *
  421. * @return array
  422. */
  423. public function subcommands() {
  424. return $this->_subcommands;
  425. }
  426. /**
  427. * Parse the argv array into a set of params and args. If $command is not null
  428. * and $command is equal to a subcommand that has a parser, that parser will be used
  429. * to parse the $argv
  430. *
  431. * @param array $argv Array of args (argv) to parse.
  432. * @param string $command The subcommand to use. If this parameter is a subcommand, that has a parser,
  433. * That parser will be used to parse $argv instead.
  434. * @return Array array($params, $args)
  435. * @throws ConsoleException When an invalid parameter is encountered.
  436. */
  437. public function parse($argv, $command = null) {
  438. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  439. return $this->_subcommands[$command]->parser()->parse($argv);
  440. }
  441. $params = $args = array();
  442. $this->_tokens = $argv;
  443. while ($token = array_shift($this->_tokens)) {
  444. if (substr($token, 0, 2) == '--') {
  445. $params = $this->_parseLongOption($token, $params);
  446. } elseif (substr($token, 0, 1) == '-') {
  447. $params = $this->_parseShortOption($token, $params);
  448. } else {
  449. $args = $this->_parseArg($token, $args);
  450. }
  451. }
  452. foreach ($this->_args as $i => $arg) {
  453. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  454. throw new ConsoleException(
  455. __d('cake_console', 'Missing required arguments. %s is required.', $arg->name())
  456. );
  457. }
  458. }
  459. foreach ($this->_options as $option) {
  460. $name = $option->name();
  461. $isBoolean = $option->isBoolean();
  462. $default = $option->defaultValue();
  463. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  464. $params[$name] = $default;
  465. }
  466. if ($isBoolean && !isset($params[$name])) {
  467. $params[$name] = false;
  468. }
  469. }
  470. return array($params, $args);
  471. }
  472. /**
  473. * Gets formatted help for this parser object.
  474. * Generates help text based on the description, options, arguments, subcommands and epilog
  475. * in the parser.
  476. *
  477. * @param string $subcommand If present and a valid subcommand that has a linked parser.
  478. * That subcommands help will be shown instead.
  479. * @param string $format Define the output format, can be text or xml
  480. * @param integer $width The width to format user content to. Defaults to 72
  481. * @return string Generated help.
  482. */
  483. public function help($subcommand = null, $format = 'text', $width = 72) {
  484. if (
  485. isset($this->_subcommands[$subcommand]) &&
  486. $this->_subcommands[$subcommand]->parser() instanceof self
  487. ) {
  488. $subparser = $this->_subcommands[$subcommand]->parser();
  489. $subparser->command($this->command() . ' ' . $subparser->command());
  490. return $subparser->help(null, $format, $width);
  491. }
  492. $formatter = new HelpFormatter($this);
  493. if ($format == 'text' || $format === true) {
  494. return $formatter->text($width);
  495. } elseif ($format == 'xml') {
  496. return $formatter->xml();
  497. }
  498. }
  499. /**
  500. * Parse the value for a long option out of $this->_tokens. Will handle
  501. * options with an `=` in them.
  502. *
  503. * @param string $option The option to parse.
  504. * @param array $params The params to append the parsed value into
  505. * @return array Params with $option added in.
  506. */
  507. protected function _parseLongOption($option, $params) {
  508. $name = substr($option, 2);
  509. if (strpos($name, '=') !== false) {
  510. list($name, $value) = explode('=', $name, 2);
  511. array_unshift($this->_tokens, $value);
  512. }
  513. return $this->_parseOption($name, $params);
  514. }
  515. /**
  516. * Parse the value for a short option out of $this->_tokens
  517. * If the $option is a combination of multiple shortcuts like -otf
  518. * they will be shifted onto the token stack and parsed individually.
  519. *
  520. * @param string $option The option to parse.
  521. * @param array $params The params to append the parsed value into
  522. * @return array Params with $option added in.
  523. */
  524. protected function _parseShortOption($option, $params) {
  525. $key = substr($option, 1);
  526. if (strlen($key) > 1) {
  527. $flags = str_split($key);
  528. $key = $flags[0];
  529. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  530. array_unshift($this->_tokens, '-' . $flags[$i]);
  531. }
  532. }
  533. if (!isset($this->_shortOptions[$key])) {
  534. throw new ConsoleException(__d('cake_console', 'Unknown short option `%s`', $key));
  535. }
  536. $name = $this->_shortOptions[$key];
  537. return $this->_parseOption($name, $params);
  538. }
  539. /**
  540. * Parse an option by its name index.
  541. *
  542. * @param string $name The name to parse.
  543. * @param array $params The params to append the parsed value into
  544. * @return array Params with $option added in.
  545. * @throws ConsoleException
  546. */
  547. protected function _parseOption($name, $params) {
  548. if (!isset($this->_options[$name])) {
  549. throw new ConsoleException(__d('cake_console', 'Unknown option `%s`', $name));
  550. }
  551. $option = $this->_options[$name];
  552. $isBoolean = $option->isBoolean();
  553. $nextValue = $this->_nextToken();
  554. if (!$isBoolean && !empty($nextValue) && !$this->_optionExists($nextValue)) {
  555. array_shift($this->_tokens);
  556. $value = $nextValue;
  557. } elseif ($isBoolean) {
  558. $value = true;
  559. } else {
  560. $value = $option->defaultValue();
  561. }
  562. if ($option->validChoice($value)) {
  563. $params[$name] = $value;
  564. return $params;
  565. }
  566. }
  567. /**
  568. * Check to see if $name has an option (short/long) defined for it.
  569. *
  570. * @param string $name The name of the option.
  571. * @return boolean
  572. */
  573. protected function _optionExists($name) {
  574. if (substr($name, 0, 2) === '--') {
  575. return isset($this->_options[substr($name, 2)]);
  576. }
  577. if ($name{0} === '-' && $name{1} !== '-') {
  578. return isset($this->_shortOptions[$name{1}]);
  579. }
  580. return false;
  581. }
  582. /**
  583. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  584. * and that the argument is a valid choice.
  585. *
  586. * @param string $argument The argument to append
  587. * @param array $args The array of parsed args to append to.
  588. * @return array Args
  589. * @throws ConsoleException
  590. */
  591. protected function _parseArg($argument, $args) {
  592. if (empty($this->_args)) {
  593. array_push($args, $argument);
  594. return $args;
  595. }
  596. $next = count($args);
  597. if (!isset($this->_args[$next])) {
  598. throw new ConsoleException(__d('cake_console', 'Too many arguments.'));
  599. }
  600. if ($this->_args[$next]->validChoice($argument)) {
  601. array_push($args, $argument);
  602. return $args;
  603. }
  604. }
  605. /**
  606. * Find the next token in the argv set.
  607. *
  608. * @return string next token or ''
  609. */
  610. protected function _nextToken() {
  611. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  612. }
  613. }