Base for a static organization website

ConsoleOptionParser.php 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 bool $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 bool $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 string|$this 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 string|$this 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 string|$this 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 $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 += $defaults;
  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 $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 = $params + $defaults;
  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 $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 $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 $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 += $defaults;
  385. $command = new ConsoleInputSubcommand($options);
  386. }
  387. $this->_subcommands[$name] = $command;
  388. return $this;
  389. }
  390. /**
  391. * Remove a subcommand from the option parser.
  392. *
  393. * @param string $name The subcommand name to remove.
  394. * @return $this
  395. */
  396. public function removeSubcommand($name) {
  397. unset($this->_subcommands[$name]);
  398. return $this;
  399. }
  400. /**
  401. * Add multiple subcommands at once.
  402. *
  403. * @param array $commands Array of subcommands.
  404. * @return $this
  405. */
  406. public function addSubcommands(array $commands) {
  407. foreach ($commands as $name => $params) {
  408. $this->addSubcommand($name, $params);
  409. }
  410. return $this;
  411. }
  412. /**
  413. * Gets the arguments defined in the parser.
  414. *
  415. * @return array Array of argument descriptions
  416. */
  417. public function arguments() {
  418. return $this->_args;
  419. }
  420. /**
  421. * Get the defined options in the parser.
  422. *
  423. * @return array
  424. */
  425. public function options() {
  426. return $this->_options;
  427. }
  428. /**
  429. * Get the array of defined subcommands
  430. *
  431. * @return array
  432. */
  433. public function subcommands() {
  434. return $this->_subcommands;
  435. }
  436. /**
  437. * Parse the argv array into a set of params and args. If $command is not null
  438. * and $command is equal to a subcommand that has a parser, that parser will be used
  439. * to parse the $argv
  440. *
  441. * @param array $argv Array of args (argv) to parse.
  442. * @param string $command The subcommand to use. If this parameter is a subcommand, that has a parser,
  443. * That parser will be used to parse $argv instead.
  444. * @return Array array($params, $args)
  445. * @throws ConsoleException When an invalid parameter is encountered.
  446. */
  447. public function parse($argv, $command = null) {
  448. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  449. return $this->_subcommands[$command]->parser()->parse($argv);
  450. }
  451. $params = $args = array();
  452. $this->_tokens = $argv;
  453. while (($token = array_shift($this->_tokens)) !== null) {
  454. if (substr($token, 0, 2) === '--') {
  455. $params = $this->_parseLongOption($token, $params);
  456. } elseif (substr($token, 0, 1) === '-') {
  457. $params = $this->_parseShortOption($token, $params);
  458. } else {
  459. $args = $this->_parseArg($token, $args);
  460. }
  461. }
  462. foreach ($this->_args as $i => $arg) {
  463. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  464. throw new ConsoleException(
  465. __d('cake_console', 'Missing required arguments. %s is required.', $arg->name())
  466. );
  467. }
  468. }
  469. foreach ($this->_options as $option) {
  470. $name = $option->name();
  471. $isBoolean = $option->isBoolean();
  472. $default = $option->defaultValue();
  473. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  474. $params[$name] = $default;
  475. }
  476. if ($isBoolean && !isset($params[$name])) {
  477. $params[$name] = false;
  478. }
  479. }
  480. return array($params, $args);
  481. }
  482. /**
  483. * Gets formatted help for this parser object.
  484. * Generates help text based on the description, options, arguments, subcommands and epilog
  485. * in the parser.
  486. *
  487. * @param string $subcommand If present and a valid subcommand that has a linked parser.
  488. * That subcommands help will be shown instead.
  489. * @param string $format Define the output format, can be text or xml
  490. * @param int $width The width to format user content to. Defaults to 72
  491. * @return string Generated help.
  492. */
  493. public function help($subcommand = null, $format = 'text', $width = 72) {
  494. if (isset($this->_subcommands[$subcommand]) &&
  495. $this->_subcommands[$subcommand]->parser() instanceof self
  496. ) {
  497. $subparser = $this->_subcommands[$subcommand]->parser();
  498. $subparser->command($this->command() . ' ' . $subparser->command());
  499. return $subparser->help(null, $format, $width);
  500. }
  501. $formatter = new HelpFormatter($this);
  502. if ($format === 'text' || $format === true) {
  503. return $formatter->text($width);
  504. } elseif ($format === 'xml') {
  505. return $formatter->xml();
  506. }
  507. }
  508. /**
  509. * Parse the value for a long option out of $this->_tokens. Will handle
  510. * options with an `=` in them.
  511. *
  512. * @param string $option The option to parse.
  513. * @param array $params The params to append the parsed value into
  514. * @return array Params with $option added in.
  515. */
  516. protected function _parseLongOption($option, $params) {
  517. $name = substr($option, 2);
  518. if (strpos($name, '=') !== false) {
  519. list($name, $value) = explode('=', $name, 2);
  520. array_unshift($this->_tokens, $value);
  521. }
  522. return $this->_parseOption($name, $params);
  523. }
  524. /**
  525. * Parse the value for a short option out of $this->_tokens
  526. * If the $option is a combination of multiple shortcuts like -otf
  527. * they will be shifted onto the token stack and parsed individually.
  528. *
  529. * @param string $option The option to parse.
  530. * @param array $params The params to append the parsed value into
  531. * @return array Params with $option added in.
  532. * @throws ConsoleException When unknown short options are encountered.
  533. */
  534. protected function _parseShortOption($option, $params) {
  535. $key = substr($option, 1);
  536. if (strlen($key) > 1) {
  537. $flags = str_split($key);
  538. $key = $flags[0];
  539. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  540. array_unshift($this->_tokens, '-' . $flags[$i]);
  541. }
  542. }
  543. if (!isset($this->_shortOptions[$key])) {
  544. throw new ConsoleException(__d('cake_console', 'Unknown short option `%s`', $key));
  545. }
  546. $name = $this->_shortOptions[$key];
  547. return $this->_parseOption($name, $params);
  548. }
  549. /**
  550. * Parse an option by its name index.
  551. *
  552. * @param string $name The name to parse.
  553. * @param array $params The params to append the parsed value into
  554. * @return array Params with $option added in.
  555. * @throws ConsoleException
  556. */
  557. protected function _parseOption($name, $params) {
  558. if (!isset($this->_options[$name])) {
  559. throw new ConsoleException(__d('cake_console', 'Unknown option `%s`', $name));
  560. }
  561. $option = $this->_options[$name];
  562. $isBoolean = $option->isBoolean();
  563. $nextValue = $this->_nextToken();
  564. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  565. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  566. array_shift($this->_tokens);
  567. $value = $nextValue;
  568. } elseif ($isBoolean) {
  569. $value = true;
  570. } else {
  571. $value = $option->defaultValue();
  572. }
  573. if ($option->validChoice($value)) {
  574. $params[$name] = $value;
  575. return $params;
  576. }
  577. return array();
  578. }
  579. /**
  580. * Check to see if $name has an option (short/long) defined for it.
  581. *
  582. * @param string $name The name of the option.
  583. * @return bool
  584. */
  585. protected function _optionExists($name) {
  586. if (substr($name, 0, 2) === '--') {
  587. return isset($this->_options[substr($name, 2)]);
  588. }
  589. if ($name{0} === '-' && $name{1} !== '-') {
  590. return isset($this->_shortOptions[$name{1}]);
  591. }
  592. return false;
  593. }
  594. /**
  595. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  596. * and that the argument is a valid choice.
  597. *
  598. * @param string $argument The argument to append
  599. * @param array $args The array of parsed args to append to.
  600. * @return array Args
  601. * @throws ConsoleException
  602. */
  603. protected function _parseArg($argument, $args) {
  604. if (empty($this->_args)) {
  605. $args[] = $argument;
  606. return $args;
  607. }
  608. $next = count($args);
  609. if (!isset($this->_args[$next])) {
  610. throw new ConsoleException(__d('cake_console', 'Too many arguments.'));
  611. }
  612. if ($this->_args[$next]->validChoice($argument)) {
  613. $args[] = $argument;
  614. return $args;
  615. }
  616. }
  617. /**
  618. * Find the next token in the argv set.
  619. *
  620. * @return string next token or ''
  621. */
  622. protected function _nextToken() {
  623. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  624. }
  625. }