PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Console/ConsoleOptionParser.php

https://bitbucket.org/daveschwan/ronin-group
PHP | 652 lines | 293 code | 37 blank | 322 comment | 54 complexity | a035abc5a91281b9bdce1f2f5ed0589a MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, MIT, BSD-3-Clause, Apache-2.0
  1. <?php
  2. /**
  3. * ConsoleOptionParser file
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 2.0
  15. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  16. */
  17. App::uses('TaskCollection', 'Console');
  18. App::uses('ConsoleOutput', 'Console');
  19. App::uses('ConsoleInput', 'Console');
  20. App::uses('ConsoleInputSubcommand', 'Console');
  21. App::uses('ConsoleInputOption', 'Console');
  22. App::uses('ConsoleInputArgument', 'Console');
  23. App::uses('ConsoleOptionParser', 'Console');
  24. App::uses('HelpFormatter', 'Console');
  25. /**
  26. * Handles parsing the ARGV in the command line and provides support
  27. * for GetOpt compatible option definition. Provides a builder pattern implementation
  28. * for creating shell option parsers.
  29. *
  30. * ### Options
  31. *
  32. * Named arguments come in two forms, long and short. Long arguments are preceded
  33. * by two - and give a more verbose option name. i.e. `--version`. Short arguments are
  34. * preceded by one - and are only one character long. They usually match with a long option,
  35. * and provide a more terse alternative.
  36. *
  37. * ### Using Options
  38. *
  39. * Options can be defined with both long and short forms. By using `$parser->addOption()`
  40. * you can define new options. The name of the option is used as its long form, and you
  41. * can supply an additional short form, with the `short` option. Short options should
  42. * only be one letter long. Using more than one letter for a short option will raise an exception.
  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. * Short options can be combined into groups as seen above. Each letter in a group
  54. * will be treated as a separate option. The previous example is equivalent to:
  55. *
  56. * `cake myshell command -c -n`
  57. *
  58. * Short options can also accept values:
  59. *
  60. * `cake myshell command -c default`
  61. *
  62. * ### Positional arguments
  63. *
  64. * If no positional arguments are defined, all of them will be parsed. If you define positional
  65. * arguments any arguments greater than those defined will cause exceptions. Additionally you can
  66. * declare arguments as optional, by setting the required param to false.
  67. *
  68. * `$parser->addArgument('model', array('required' => false));`
  69. *
  70. * ### Providing Help text
  71. *
  72. * By providing help text for your positional arguments and named arguments, the ConsoleOptionParser
  73. * can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch.
  74. *
  75. * @package Cake.Console
  76. */
  77. class ConsoleOptionParser {
  78. /**
  79. * Description text - displays before options when help is generated
  80. *
  81. * @see ConsoleOptionParser::description()
  82. * @var string
  83. */
  84. protected $_description = null;
  85. /**
  86. * Epilog text - displays after options when help is generated
  87. *
  88. * @see ConsoleOptionParser::epilog()
  89. * @var string
  90. */
  91. protected $_epilog = null;
  92. /**
  93. * Option definitions.
  94. *
  95. * @see ConsoleOptionParser::addOption()
  96. * @var array
  97. */
  98. protected $_options = array();
  99. /**
  100. * Map of short -> long options, generated when using addOption()
  101. *
  102. * @var string
  103. */
  104. protected $_shortOptions = array();
  105. /**
  106. * Positional argument definitions.
  107. *
  108. * @see ConsoleOptionParser::addArgument()
  109. * @var array
  110. */
  111. protected $_args = array();
  112. /**
  113. * Subcommands for this Shell.
  114. *
  115. * @see ConsoleOptionParser::addSubcommand()
  116. * @var array
  117. */
  118. protected $_subcommands = array();
  119. /**
  120. * Command name.
  121. *
  122. * @var string
  123. */
  124. protected $_command = '';
  125. /**
  126. * Construct an OptionParser so you can define its behavior
  127. *
  128. * @param string $command The command name this parser is for. The command name is used for generating help.
  129. * @param boolean $defaultOptions Whether you want the verbose and quiet options set. Setting
  130. * this to false will prevent the addition of `--verbose` & `--quiet` options.
  131. */
  132. public function __construct($command = null, $defaultOptions = true) {
  133. $this->command($command);
  134. $this->addOption('help', array(
  135. 'short' => 'h',
  136. 'help' => __d('cake_console', 'Display this help.'),
  137. 'boolean' => true
  138. ));
  139. if ($defaultOptions) {
  140. $this->addOption('verbose', array(
  141. 'short' => 'v',
  142. 'help' => __d('cake_console', 'Enable verbose output.'),
  143. 'boolean' => true
  144. ))->addOption('quiet', array(
  145. 'short' => 'q',
  146. 'help' => __d('cake_console', 'Enable quiet output.'),
  147. 'boolean' => true
  148. ));
  149. }
  150. }
  151. /**
  152. * Static factory method for creating new OptionParsers so you can chain methods off of them.
  153. *
  154. * @param string $command The command name this parser is for. The command name is used for generating help.
  155. * @param boolean $defaultOptions Whether you want the verbose and quiet options set.
  156. * @return ConsoleOptionParser
  157. */
  158. public static function create($command, $defaultOptions = true) {
  159. return new ConsoleOptionParser($command, $defaultOptions);
  160. }
  161. /**
  162. * Build a parser from an array. Uses an array like
  163. *
  164. * {{{
  165. * $spec = array(
  166. * 'description' => 'text',
  167. * 'epilog' => 'text',
  168. * 'arguments' => array(
  169. * // list of arguments compatible with addArguments.
  170. * ),
  171. * 'options' => array(
  172. * // list of options compatible with addOptions
  173. * ),
  174. * 'subcommands' => array(
  175. * // list of subcommands to add.
  176. * )
  177. * );
  178. * }}}
  179. *
  180. * @param array $spec The spec to build the OptionParser with.
  181. * @return ConsoleOptionParser
  182. */
  183. public static function buildFromArray($spec) {
  184. $parser = new ConsoleOptionParser($spec['command']);
  185. if (!empty($spec['arguments'])) {
  186. $parser->addArguments($spec['arguments']);
  187. }
  188. if (!empty($spec['options'])) {
  189. $parser->addOptions($spec['options']);
  190. }
  191. if (!empty($spec['subcommands'])) {
  192. $parser->addSubcommands($spec['subcommands']);
  193. }
  194. if (!empty($spec['description'])) {
  195. $parser->description($spec['description']);
  196. }
  197. if (!empty($spec['epilog'])) {
  198. $parser->epilog($spec['epilog']);
  199. }
  200. return $parser;
  201. }
  202. /**
  203. * Get or set the command name for shell/task.
  204. *
  205. * @param string $text The text to set, or null if you want to read
  206. * @return mixed If reading, the value of the command. If setting $this will be returned
  207. */
  208. public function command($text = null) {
  209. if ($text !== null) {
  210. $this->_command = Inflector::underscore($text);
  211. return $this;
  212. }
  213. return $this->_command;
  214. }
  215. /**
  216. * Get or set the description text for shell/task.
  217. *
  218. * @param string|array $text The text to set, or null if you want to read. If an array the
  219. * text will be imploded with "\n"
  220. * @return mixed If reading, the value of the description. If setting $this will be returned
  221. */
  222. public function description($text = null) {
  223. if ($text !== null) {
  224. if (is_array($text)) {
  225. $text = implode("\n", $text);
  226. }
  227. $this->_description = $text;
  228. return $this;
  229. }
  230. return $this->_description;
  231. }
  232. /**
  233. * Get or set an epilog to the parser. The epilog is added to the end of
  234. * the options and arguments listing when help is generated.
  235. *
  236. * @param string|array $text Text when setting or null when reading. If an array the text will be imploded with "\n"
  237. * @return mixed If reading, the value of the epilog. If setting $this will be returned.
  238. */
  239. public function epilog($text = null) {
  240. if ($text !== null) {
  241. if (is_array($text)) {
  242. $text = implode("\n", $text);
  243. }
  244. $this->_epilog = $text;
  245. return $this;
  246. }
  247. return $this->_epilog;
  248. }
  249. /**
  250. * Add an option to the option parser. Options allow you to define optional or required
  251. * parameters for your console application. Options are defined by the parameters they use.
  252. *
  253. * ### Options
  254. *
  255. * - `short` - The single letter variant for this option, leave undefined for none.
  256. * - `help` - Help text for this option. Used when generating help for the option.
  257. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  258. * attached option is not provided or has no value. Using default and boolean together will not work.
  259. * are added into the parsed parameters when the option is undefined. Defaults to null.
  260. * - `boolean` - The option uses no value, its just a boolean switch. Defaults to false.
  261. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  262. * it will be false, if present it will be true.
  263. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  264. * An exception will be raised when parse() encounters an invalid value.
  265. *
  266. * @param ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  267. * Will also accept an instance of ConsoleInputOption
  268. * @param array $options An array of parameters that define the behavior of the option
  269. * @return ConsoleOptionParser $this.
  270. */
  271. public function addOption($name, $options = array()) {
  272. if (is_object($name) && $name instanceof ConsoleInputOption) {
  273. $option = $name;
  274. $name = $option->name();
  275. } else {
  276. $defaults = array(
  277. 'name' => $name,
  278. 'short' => null,
  279. 'help' => '',
  280. 'default' => null,
  281. 'boolean' => false,
  282. 'choices' => array()
  283. );
  284. $options = array_merge($defaults, $options);
  285. $option = new ConsoleInputOption($options);
  286. }
  287. $this->_options[$name] = $option;
  288. if ($option->short() !== null) {
  289. $this->_shortOptions[$option->short()] = $name;
  290. }
  291. return $this;
  292. }
  293. /**
  294. * Add a positional argument to the option parser.
  295. *
  296. * ### Params
  297. *
  298. * - `help` The help text to display for this argument.
  299. * - `required` Whether this parameter is required.
  300. * - `index` The index for the arg, if left undefined the argument will be put
  301. * onto the end of the arguments. If you define the same index twice the first
  302. * option will be overwritten.
  303. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  304. * An exception will be raised when parse() encounters an invalid value.
  305. *
  306. * @param ConsoleInputArgument|string $name The name of the argument. Will also accept an instance of ConsoleInputArgument
  307. * @param array $params Parameters for the argument, see above.
  308. * @return ConsoleOptionParser $this.
  309. */
  310. public function addArgument($name, $params = array()) {
  311. if (is_object($name) && $name instanceof ConsoleInputArgument) {
  312. $arg = $name;
  313. $index = count($this->_args);
  314. } else {
  315. $defaults = array(
  316. 'name' => $name,
  317. 'help' => '',
  318. 'index' => count($this->_args),
  319. 'required' => false,
  320. 'choices' => array()
  321. );
  322. $options = array_merge($defaults, $params);
  323. $index = $options['index'];
  324. unset($options['index']);
  325. $arg = new ConsoleInputArgument($options);
  326. }
  327. $this->_args[$index] = $arg;
  328. ksort($this->_args);
  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 ConsoleInputSubcommand|string $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)) !== null) {
  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. * @throws ConsoleException When unknown short options are encountered.
  524. */
  525. protected function _parseShortOption($option, $params) {
  526. $key = substr($option, 1);
  527. if (strlen($key) > 1) {
  528. $flags = str_split($key);
  529. $key = $flags[0];
  530. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  531. array_unshift($this->_tokens, '-' . $flags[$i]);
  532. }
  533. }
  534. if (!isset($this->_shortOptions[$key])) {
  535. throw new ConsoleException(__d('cake_console', 'Unknown short option `%s`', $key));
  536. }
  537. $name = $this->_shortOptions[$key];
  538. return $this->_parseOption($name, $params);
  539. }
  540. /**
  541. * Parse an option by its name index.
  542. *
  543. * @param string $name The name to parse.
  544. * @param array $params The params to append the parsed value into
  545. * @return array Params with $option added in.
  546. * @throws ConsoleException
  547. */
  548. protected function _parseOption($name, $params) {
  549. if (!isset($this->_options[$name])) {
  550. throw new ConsoleException(__d('cake_console', 'Unknown option `%s`', $name));
  551. }
  552. $option = $this->_options[$name];
  553. $isBoolean = $option->isBoolean();
  554. $nextValue = $this->_nextToken();
  555. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  556. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  557. array_shift($this->_tokens);
  558. $value = $nextValue;
  559. } elseif ($isBoolean) {
  560. $value = true;
  561. } else {
  562. $value = $option->defaultValue();
  563. }
  564. if ($option->validChoice($value)) {
  565. $params[$name] = $value;
  566. return $params;
  567. }
  568. }
  569. /**
  570. * Check to see if $name has an option (short/long) defined for it.
  571. *
  572. * @param string $name The name of the option.
  573. * @return boolean
  574. */
  575. protected function _optionExists($name) {
  576. if (substr($name, 0, 2) === '--') {
  577. return isset($this->_options[substr($name, 2)]);
  578. }
  579. if ($name{0} === '-' && $name{1} !== '-') {
  580. return isset($this->_shortOptions[$name{1}]);
  581. }
  582. return false;
  583. }
  584. /**
  585. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  586. * and that the argument is a valid choice.
  587. *
  588. * @param string $argument The argument to append
  589. * @param array $args The array of parsed args to append to.
  590. * @return array Args
  591. * @throws ConsoleException
  592. */
  593. protected function _parseArg($argument, $args) {
  594. if (empty($this->_args)) {
  595. $args[] = $argument;
  596. return $args;
  597. }
  598. $next = count($args);
  599. if (!isset($this->_args[$next])) {
  600. throw new ConsoleException(__d('cake_console', 'Too many arguments.'));
  601. }
  602. if ($this->_args[$next]->validChoice($argument)) {
  603. $args[] = $argument;
  604. return $args;
  605. }
  606. }
  607. /**
  608. * Find the next token in the argv set.
  609. *
  610. * @return string next token or ''
  611. */
  612. protected function _nextToken() {
  613. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  614. }
  615. }