ConsoleOptionParser.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Console;
  16. use Cake\Console\Exception\ConsoleException;
  17. use Cake\Utility\Inflector;
  18. use LogicException;
  19. /**
  20. * Handles parsing the ARGV in the command line and provides support
  21. * for GetOpt compatible option definition. Provides a builder pattern implementation
  22. * for creating shell option parsers.
  23. *
  24. * ### Options
  25. *
  26. * Named arguments come in two forms, long and short. Long arguments are preceded
  27. * by two - and give a more verbose option name. i.e. `--version`. Short arguments are
  28. * preceded by one - and are only one character long. They usually match with a long option,
  29. * and provide a more terse alternative.
  30. *
  31. * ### Using Options
  32. *
  33. * Options can be defined with both long and short forms. By using `$parser->addOption()`
  34. * you can define new options. The name of the option is used as its long form, and you
  35. * can supply an additional short form, with the `short` option. Short options should
  36. * only be one letter long. Using more than one letter for a short option will raise an exception.
  37. *
  38. * Calling options can be done using syntax similar to most *nix command line tools. Long options
  39. * cane either include an `=` or leave it out.
  40. *
  41. * `cake myshell command --connection default --name=something`
  42. *
  43. * Short options can be defined singly or in groups.
  44. *
  45. * `cake myshell command -cn`
  46. *
  47. * Short options can be combined into groups as seen above. Each letter in a group
  48. * will be treated as a separate option. The previous example is equivalent to:
  49. *
  50. * `cake myshell command -c -n`
  51. *
  52. * Short options can also accept values:
  53. *
  54. * `cake myshell command -c default`
  55. *
  56. * ### Positional arguments
  57. *
  58. * If no positional arguments are defined, all of them will be parsed. If you define positional
  59. * arguments any arguments greater than those defined will cause exceptions. Additionally you can
  60. * declare arguments as optional, by setting the required param to false.
  61. *
  62. * ```
  63. * $parser->addArgument('model', ['required' => false]);
  64. * ```
  65. *
  66. * ### Providing Help text
  67. *
  68. * By providing help text for your positional arguments and named arguments, the ConsoleOptionParser
  69. * can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch.
  70. */
  71. class ConsoleOptionParser
  72. {
  73. /**
  74. * Description text - displays before options when help is generated
  75. *
  76. * @see \Cake\Console\ConsoleOptionParser::description()
  77. * @var string
  78. */
  79. protected $_description;
  80. /**
  81. * Epilog text - displays after options when help is generated
  82. *
  83. * @see \Cake\Console\ConsoleOptionParser::epilog()
  84. * @var string
  85. */
  86. protected $_epilog;
  87. /**
  88. * Option definitions.
  89. *
  90. * @see \Cake\Console\ConsoleOptionParser::addOption()
  91. * @var \Cake\Console\ConsoleInputOption[]
  92. */
  93. protected $_options = [];
  94. /**
  95. * Map of short -> long options, generated when using addOption()
  96. *
  97. * @var array
  98. */
  99. protected $_shortOptions = [];
  100. /**
  101. * Positional argument definitions.
  102. *
  103. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  104. * @var \Cake\Console\ConsoleInputArgument[]
  105. */
  106. protected $_args = [];
  107. /**
  108. * Subcommands for this Shell.
  109. *
  110. * @see \Cake\Console\ConsoleOptionParser::addSubcommand()
  111. * @var \Cake\Console\ConsoleInputSubcommand[]
  112. */
  113. protected $_subcommands = [];
  114. /**
  115. * Command name.
  116. *
  117. * @var string
  118. */
  119. protected $_command = '';
  120. /**
  121. * Array of args (argv).
  122. *
  123. * @var array
  124. */
  125. protected $_tokens = [];
  126. /**
  127. * Root alias used in help output
  128. *
  129. * @see \Cake\Console\HelpFormatter::setAlias()
  130. * @var string
  131. */
  132. protected $rootName = 'cake';
  133. /**
  134. * Construct an OptionParser so you can define its behavior
  135. *
  136. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  137. * @param bool $defaultOptions Whether you want the verbose and quiet options set. Setting
  138. * this to false will prevent the addition of `--verbose` & `--quiet` options.
  139. */
  140. public function __construct($command = null, $defaultOptions = true)
  141. {
  142. $this->setCommand($command);
  143. $this->addOption('help', [
  144. 'short' => 'h',
  145. 'help' => 'Display this help.',
  146. 'boolean' => true
  147. ]);
  148. if ($defaultOptions) {
  149. $this->addOption('verbose', [
  150. 'short' => 'v',
  151. 'help' => 'Enable verbose output.',
  152. 'boolean' => true
  153. ])->addOption('quiet', [
  154. 'short' => 'q',
  155. 'help' => 'Enable quiet output.',
  156. 'boolean' => true
  157. ]);
  158. }
  159. }
  160. /**
  161. * Static factory method for creating new OptionParsers so you can chain methods off of them.
  162. *
  163. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  164. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  165. * @return static
  166. */
  167. public static function create($command, $defaultOptions = true)
  168. {
  169. return new static($command, $defaultOptions);
  170. }
  171. /**
  172. * Build a parser from an array. Uses an array like
  173. *
  174. * ```
  175. * $spec = [
  176. * 'description' => 'text',
  177. * 'epilog' => 'text',
  178. * 'arguments' => [
  179. * // list of arguments compatible with addArguments.
  180. * ],
  181. * 'options' => [
  182. * // list of options compatible with addOptions
  183. * ],
  184. * 'subcommands' => [
  185. * // list of subcommands to add.
  186. * ]
  187. * ];
  188. * ```
  189. *
  190. * @param array $spec The spec to build the OptionParser with.
  191. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  192. * @return static
  193. */
  194. public static function buildFromArray($spec, $defaultOptions = true)
  195. {
  196. $parser = new static($spec['command'], $defaultOptions);
  197. if (!empty($spec['arguments'])) {
  198. $parser->addArguments($spec['arguments']);
  199. }
  200. if (!empty($spec['options'])) {
  201. $parser->addOptions($spec['options']);
  202. }
  203. if (!empty($spec['subcommands'])) {
  204. $parser->addSubcommands($spec['subcommands']);
  205. }
  206. if (!empty($spec['description'])) {
  207. $parser->setDescription($spec['description']);
  208. }
  209. if (!empty($spec['epilog'])) {
  210. $parser->setEpilog($spec['epilog']);
  211. }
  212. return $parser;
  213. }
  214. /**
  215. * Returns an array representation of this parser.
  216. *
  217. * @return array
  218. */
  219. public function toArray()
  220. {
  221. $result = [
  222. 'command' => $this->_command,
  223. 'arguments' => $this->_args,
  224. 'options' => $this->_options,
  225. 'subcommands' => $this->_subcommands,
  226. 'description' => $this->_description,
  227. 'epilog' => $this->_epilog
  228. ];
  229. return $result;
  230. }
  231. /**
  232. * Get or set the command name for shell/task.
  233. *
  234. * @param array|\Cake\Console\ConsoleOptionParser $spec ConsoleOptionParser or spec to merge with.
  235. * @return $this
  236. */
  237. public function merge($spec)
  238. {
  239. if ($spec instanceof ConsoleOptionParser) {
  240. $spec = $spec->toArray();
  241. }
  242. if (!empty($spec['arguments'])) {
  243. $this->addArguments($spec['arguments']);
  244. }
  245. if (!empty($spec['options'])) {
  246. $this->addOptions($spec['options']);
  247. }
  248. if (!empty($spec['subcommands'])) {
  249. $this->addSubcommands($spec['subcommands']);
  250. }
  251. if (!empty($spec['description'])) {
  252. $this->setDescription($spec['description']);
  253. }
  254. if (!empty($spec['epilog'])) {
  255. $this->setEpilog($spec['epilog']);
  256. }
  257. return $this;
  258. }
  259. /**
  260. * Sets the command name for shell/task.
  261. *
  262. * @param string $text The text to set.
  263. * @return $this
  264. */
  265. public function setCommand($text)
  266. {
  267. $this->_command = Inflector::underscore($text);
  268. return $this;
  269. }
  270. /**
  271. * Gets the command name for shell/task.
  272. *
  273. * @return string The value of the command.
  274. */
  275. public function getCommand()
  276. {
  277. return $this->_command;
  278. }
  279. /**
  280. * Gets or sets the command name for shell/task.
  281. *
  282. * @deprecated 3.4.0 Use setCommand()/getCommand() instead.
  283. * @param string|null $text The text to set, or null if you want to read
  284. * @return string|$this If reading, the value of the command. If setting $this will be returned.
  285. */
  286. public function command($text = null)
  287. {
  288. if ($text !== null) {
  289. return $this->setCommand($text);
  290. }
  291. return $this->getCommand();
  292. }
  293. /**
  294. * Sets the description text for shell/task.
  295. *
  296. * @param string|array $text The text to set. If an array the
  297. * text will be imploded with "\n".
  298. * @return $this
  299. */
  300. public function setDescription($text)
  301. {
  302. if (is_array($text)) {
  303. $text = implode("\n", $text);
  304. }
  305. $this->_description = $text;
  306. return $this;
  307. }
  308. /**
  309. * Gets the description text for shell/task.
  310. *
  311. * @return string The value of the description
  312. */
  313. public function getDescription()
  314. {
  315. return $this->_description;
  316. }
  317. /**
  318. * Get or set the description text for shell/task.
  319. *
  320. * @deprecated 3.4.0 Use setDescription()/getDescription() instead.
  321. * @param string|array|null $text The text to set, or null if you want to read. If an array the
  322. * text will be imploded with "\n".
  323. * @return string|$this If reading, the value of the description. If setting $this will be returned.
  324. */
  325. public function description($text = null)
  326. {
  327. if ($text !== null) {
  328. return $this->setDescription($text);
  329. }
  330. return $this->getDescription();
  331. }
  332. /**
  333. * Sets an epilog to the parser. The epilog is added to the end of
  334. * the options and arguments listing when help is generated.
  335. *
  336. * @param string|array $text The text to set. If an array the text will
  337. * be imploded with "\n".
  338. * @return $this
  339. */
  340. public function setEpilog($text)
  341. {
  342. if (is_array($text)) {
  343. $text = implode("\n", $text);
  344. }
  345. $this->_epilog = $text;
  346. return $this;
  347. }
  348. /**
  349. * Gets the epilog.
  350. *
  351. * @return string The value of the epilog.
  352. */
  353. public function getEpilog()
  354. {
  355. return $this->_epilog;
  356. }
  357. /**
  358. * Gets or sets an epilog to the parser. The epilog is added to the end of
  359. * the options and arguments listing when help is generated.
  360. *
  361. * @deprecated 3.4.0 Use setEpilog()/getEpilog() instead.
  362. * @param string|array|null $text Text when setting or null when reading. If an array the text will
  363. * be imploded with "\n".
  364. * @return string|$this If reading, the value of the epilog. If setting $this will be returned.
  365. */
  366. public function epilog($text = null)
  367. {
  368. if ($text !== null) {
  369. return $this->setEpilog($text);
  370. }
  371. return $this->getEpilog();
  372. }
  373. /**
  374. * Add an option to the option parser. Options allow you to define optional or required
  375. * parameters for your console application. Options are defined by the parameters they use.
  376. *
  377. * ### Options
  378. *
  379. * - `short` - The single letter variant for this option, leave undefined for none.
  380. * - `help` - Help text for this option. Used when generating help for the option.
  381. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  382. * attached option is not provided or has no value. Using default and boolean together will not work.
  383. * are added into the parsed parameters when the option is undefined. Defaults to null.
  384. * - `boolean` - The option uses no value, it's just a boolean switch. Defaults to false.
  385. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  386. * it will be false, if present it will be true.
  387. * - `multiple` - The option can be provided multiple times. The parsed option
  388. * will be an array of values when this option is enabled.
  389. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  390. * An exception will be raised when parse() encounters an invalid value.
  391. *
  392. * @param \Cake\Console\ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  393. * Will also accept an instance of ConsoleInputOption
  394. * @param array $options An array of parameters that define the behavior of the option
  395. * @return $this
  396. */
  397. public function addOption($name, array $options = [])
  398. {
  399. if ($name instanceof ConsoleInputOption) {
  400. $option = $name;
  401. $name = $option->name();
  402. } else {
  403. $defaults = [
  404. 'name' => $name,
  405. 'short' => null,
  406. 'help' => '',
  407. 'default' => null,
  408. 'boolean' => false,
  409. 'choices' => []
  410. ];
  411. $options += $defaults;
  412. $option = new ConsoleInputOption($options);
  413. }
  414. $this->_options[$name] = $option;
  415. asort($this->_options);
  416. if ($option->short() !== null) {
  417. $this->_shortOptions[$option->short()] = $name;
  418. asort($this->_shortOptions);
  419. }
  420. return $this;
  421. }
  422. /**
  423. * Remove an option from the option parser.
  424. *
  425. * @param string $name The option name to remove.
  426. * @return $this
  427. */
  428. public function removeOption($name)
  429. {
  430. unset($this->_options[$name]);
  431. return $this;
  432. }
  433. /**
  434. * Add a positional argument to the option parser.
  435. *
  436. * ### Params
  437. *
  438. * - `help` The help text to display for this argument.
  439. * - `required` Whether this parameter is required.
  440. * - `index` The index for the arg, if left undefined the argument will be put
  441. * onto the end of the arguments. If you define the same index twice the first
  442. * option will be overwritten.
  443. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  444. * An exception will be raised when parse() encounters an invalid value.
  445. *
  446. * @param \Cake\Console\ConsoleInputArgument|string $name The name of the argument.
  447. * Will also accept an instance of ConsoleInputArgument.
  448. * @param array $params Parameters for the argument, see above.
  449. * @return $this
  450. */
  451. public function addArgument($name, array $params = [])
  452. {
  453. if ($name instanceof ConsoleInputArgument) {
  454. $arg = $name;
  455. $index = count($this->_args);
  456. } else {
  457. $defaults = [
  458. 'name' => $name,
  459. 'help' => '',
  460. 'index' => count($this->_args),
  461. 'required' => false,
  462. 'choices' => []
  463. ];
  464. $options = $params + $defaults;
  465. $index = $options['index'];
  466. unset($options['index']);
  467. $arg = new ConsoleInputArgument($options);
  468. }
  469. foreach ($this->_args as $k => $a) {
  470. if ($a->isEqualTo($arg)) {
  471. return $this;
  472. }
  473. if (!empty($options['required']) && !$a->isRequired()) {
  474. throw new LogicException('A required argument cannot follow an optional one');
  475. }
  476. }
  477. $this->_args[$index] = $arg;
  478. ksort($this->_args);
  479. return $this;
  480. }
  481. /**
  482. * Add multiple arguments at once. Take an array of argument definitions.
  483. * The keys are used as the argument names, and the values as params for the argument.
  484. *
  485. * @param array $args Array of arguments to add.
  486. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  487. * @return $this
  488. */
  489. public function addArguments(array $args)
  490. {
  491. foreach ($args as $name => $params) {
  492. if ($params instanceof ConsoleInputArgument) {
  493. $name = $params;
  494. $params = [];
  495. }
  496. $this->addArgument($name, $params);
  497. }
  498. return $this;
  499. }
  500. /**
  501. * Add multiple options at once. Takes an array of option definitions.
  502. * The keys are used as option names, and the values as params for the option.
  503. *
  504. * @param array $options Array of options to add.
  505. * @see \Cake\Console\ConsoleOptionParser::addOption()
  506. * @return $this
  507. */
  508. public function addOptions(array $options)
  509. {
  510. foreach ($options as $name => $params) {
  511. if ($params instanceof ConsoleInputOption) {
  512. $name = $params;
  513. $params = [];
  514. }
  515. $this->addOption($name, $params);
  516. }
  517. return $this;
  518. }
  519. /**
  520. * Append a subcommand to the subcommand list.
  521. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  522. *
  523. * ### Options
  524. *
  525. * - `help` - Help text for the subcommand.
  526. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  527. * specific option parsers. When help is generated for a subcommand, if a parser is present
  528. * it will be used.
  529. *
  530. * @param \Cake\Console\ConsoleInputSubcommand|string $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  531. * @param array $options Array of params, see above.
  532. * @return $this
  533. */
  534. public function addSubcommand($name, array $options = [])
  535. {
  536. if ($name instanceof ConsoleInputSubcommand) {
  537. $command = $name;
  538. $name = $command->name();
  539. } else {
  540. $name = Inflector::underscore($name);
  541. $defaults = [
  542. 'name' => $name,
  543. 'help' => '',
  544. 'parser' => null
  545. ];
  546. $options += $defaults;
  547. $command = new ConsoleInputSubcommand($options);
  548. }
  549. $this->_subcommands[$name] = $command;
  550. asort($this->_subcommands);
  551. return $this;
  552. }
  553. /**
  554. * Remove a subcommand from the option parser.
  555. *
  556. * @param string $name The subcommand name to remove.
  557. * @return $this
  558. */
  559. public function removeSubcommand($name)
  560. {
  561. unset($this->_subcommands[$name]);
  562. return $this;
  563. }
  564. /**
  565. * Add multiple subcommands at once.
  566. *
  567. * @param array $commands Array of subcommands.
  568. * @return $this
  569. */
  570. public function addSubcommands(array $commands)
  571. {
  572. foreach ($commands as $name => $params) {
  573. if ($params instanceof ConsoleInputSubcommand) {
  574. $name = $params;
  575. $params = [];
  576. }
  577. $this->addSubcommand($name, $params);
  578. }
  579. return $this;
  580. }
  581. /**
  582. * Gets the arguments defined in the parser.
  583. *
  584. * @return array Array of argument descriptions
  585. */
  586. public function arguments()
  587. {
  588. return $this->_args;
  589. }
  590. /**
  591. * Get the defined options in the parser.
  592. *
  593. * @return array
  594. */
  595. public function options()
  596. {
  597. return $this->_options;
  598. }
  599. /**
  600. * Get the array of defined subcommands
  601. *
  602. * @return array
  603. */
  604. public function subcommands()
  605. {
  606. return $this->_subcommands;
  607. }
  608. /**
  609. * Parse the argv array into a set of params and args. If $command is not null
  610. * and $command is equal to a subcommand that has a parser, that parser will be used
  611. * to parse the $argv
  612. *
  613. * @param array $argv Array of args (argv) to parse.
  614. * @return array [$params, $args]
  615. * @throws \Cake\Console\Exception\ConsoleException When an invalid parameter is encountered.
  616. */
  617. public function parse($argv)
  618. {
  619. $command = isset($argv[0]) ? Inflector::underscore($argv[0]) : null;
  620. if (isset($this->_subcommands[$command])) {
  621. array_shift($argv);
  622. }
  623. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  624. return $this->_subcommands[$command]->parser()->parse($argv);
  625. }
  626. $params = $args = [];
  627. $this->_tokens = $argv;
  628. while (($token = array_shift($this->_tokens)) !== null) {
  629. if (isset($this->_subcommands[$token])) {
  630. continue;
  631. }
  632. if (substr($token, 0, 2) === '--') {
  633. $params = $this->_parseLongOption($token, $params);
  634. } elseif (substr($token, 0, 1) === '-') {
  635. $params = $this->_parseShortOption($token, $params);
  636. } else {
  637. $args = $this->_parseArg($token, $args);
  638. }
  639. }
  640. foreach ($this->_args as $i => $arg) {
  641. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  642. throw new ConsoleException(
  643. sprintf('Missing required arguments. %s is required.', $arg->name())
  644. );
  645. }
  646. }
  647. foreach ($this->_options as $option) {
  648. $name = $option->name();
  649. $isBoolean = $option->isBoolean();
  650. $default = $option->defaultValue();
  651. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  652. $params[$name] = $default;
  653. }
  654. if ($isBoolean && !isset($params[$name])) {
  655. $params[$name] = false;
  656. }
  657. }
  658. return [$params, $args];
  659. }
  660. /**
  661. * Gets formatted help for this parser object.
  662. *
  663. * Generates help text based on the description, options, arguments, subcommands and epilog
  664. * in the parser.
  665. *
  666. * @param string|null $subcommand If present and a valid subcommand that has a linked parser.
  667. * That subcommands help will be shown instead.
  668. * @param string $format Define the output format, can be text or xml
  669. * @param int $width The width to format user content to. Defaults to 72
  670. * @return string Generated help.
  671. */
  672. public function help($subcommand = null, $format = 'text', $width = 72)
  673. {
  674. if ($subcommand === null) {
  675. $formatter = new HelpFormatter($this);
  676. $formatter->setAlias($this->rootName);
  677. if ($format === 'text') {
  678. return $formatter->text($width);
  679. }
  680. if ($format === 'xml') {
  681. return $formatter->xml();
  682. }
  683. }
  684. if (isset($this->_subcommands[$subcommand])) {
  685. $command = $this->_subcommands[$subcommand];
  686. $subparser = $command->parser();
  687. if (!($subparser instanceof self)) {
  688. $subparser = clone $this;
  689. }
  690. if (strlen($subparser->getDescription()) === 0) {
  691. $subparser->setDescription($command->getRawHelp());
  692. }
  693. $subparser->setCommand($this->getCommand() . ' ' . $subcommand);
  694. $subparser->setRootName($this->rootName);
  695. return $subparser->help(null, $format, $width);
  696. }
  697. return $this->getCommandError($subcommand);
  698. }
  699. /**
  700. * Set the alias used in the HelpFormatter
  701. *
  702. * @param string $alias The alias
  703. * @return void
  704. * @deprecated 3.5.0 Use setRootName() instead.
  705. */
  706. public function setHelpAlias($alias)
  707. {
  708. $this->rootName = $alias;
  709. }
  710. /**
  711. * Set the root name used in the HelpFormatter
  712. *
  713. * @param string $name The root command name
  714. * @return $this
  715. */
  716. public function setRootName($name)
  717. {
  718. $this->rootName = (string)$name;
  719. return $this;
  720. }
  721. /**
  722. * Get the message output in the console stating that the command can not be found and tries to guess what the user
  723. * wanted to say. Output a list of available subcommands as well.
  724. *
  725. * @param string $command Unknown command name trying to be dispatched.
  726. * @return string The message to be displayed in the console.
  727. */
  728. protected function getCommandError($command)
  729. {
  730. $rootCommand = $this->getCommand();
  731. $subcommands = array_keys((array)$this->subcommands());
  732. $bestGuess = $this->findClosestItem($command, $subcommands);
  733. $out = [
  734. sprintf(
  735. 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.',
  736. $rootCommand,
  737. $command,
  738. $this->rootName,
  739. $rootCommand
  740. ),
  741. ''
  742. ];
  743. if ($bestGuess !== null) {
  744. $out[] = sprintf('Did you mean : `%s %s` ?', $rootCommand, $bestGuess);
  745. $out[] = '';
  746. }
  747. $out[] = sprintf('Available subcommands for the `%s` command are : ', $rootCommand);
  748. $out[] = '';
  749. foreach ($subcommands as $subcommand) {
  750. $out[] = ' - ' . $subcommand;
  751. }
  752. return implode("\n", $out);
  753. }
  754. /**
  755. * Get the message output in the console stating that the option can not be found and tries to guess what the user
  756. * wanted to say. Output a list of available options as well.
  757. *
  758. * @param string $option Unknown option name trying to be used.
  759. * @return string The message to be displayed in the console.
  760. */
  761. protected function getOptionError($option)
  762. {
  763. $availableOptions = array_keys($this->_options);
  764. $bestGuess = $this->findClosestItem($option, $availableOptions);
  765. $out = [
  766. sprintf('Unknown option `%s`.', $option),
  767. ''
  768. ];
  769. if ($bestGuess !== null) {
  770. $out[] = sprintf('Did you mean `%s` ?', $bestGuess);
  771. $out[] = '';
  772. }
  773. $out[] = 'Available options are :';
  774. $out[] = '';
  775. foreach ($availableOptions as $availableOption) {
  776. $out[] = ' - ' . $availableOption;
  777. }
  778. return implode("\n", $out);
  779. }
  780. /**
  781. * Get the message output in the console stating that the short option can not be found. Output a list of available
  782. * short options and what option they refer to as well.
  783. *
  784. * @param string $option Unknown short option name trying to be used.
  785. * @return string The message to be displayed in the console.
  786. */
  787. protected function getShortOptionError($option)
  788. {
  789. $out = [sprintf('Unknown short option `%s`', $option)];
  790. $out[] = '';
  791. $out[] = 'Available short options are :';
  792. $out[] = '';
  793. foreach ($this->_shortOptions as $short => $long) {
  794. $out[] = sprintf(' - `%s` (short for `--%s`)', $short, $long);
  795. }
  796. return implode("\n", $out);
  797. }
  798. /**
  799. * Tries to guess the item name the user originally wanted using the some regex pattern and the levenshtein
  800. * algorithm.
  801. *
  802. * @param string $needle Unknown item (either a subcommand name or an option for instance) trying to be used.
  803. * @param array $haystack List of items available for the type $needle belongs to.
  804. * @return string|null The closest name to the item submitted by the user.
  805. */
  806. protected function findClosestItem($needle, $haystack)
  807. {
  808. $bestGuess = null;
  809. foreach ($haystack as $item) {
  810. if (preg_match('/^' . $needle . '/', $item)) {
  811. return $item;
  812. }
  813. }
  814. foreach ($haystack as $item) {
  815. if (preg_match('/' . $needle . '/', $item)) {
  816. return $item;
  817. }
  818. $score = levenshtein($needle, $item);
  819. if (!isset($bestScore) || $score < $bestScore) {
  820. $bestScore = $score;
  821. $bestGuess = $item;
  822. }
  823. }
  824. return $bestGuess;
  825. }
  826. /**
  827. * Parse the value for a long option out of $this->_tokens. Will handle
  828. * options with an `=` in them.
  829. *
  830. * @param string $option The option to parse.
  831. * @param array $params The params to append the parsed value into
  832. * @return array Params with $option added in.
  833. */
  834. protected function _parseLongOption($option, $params)
  835. {
  836. $name = substr($option, 2);
  837. if (strpos($name, '=') !== false) {
  838. list($name, $value) = explode('=', $name, 2);
  839. array_unshift($this->_tokens, $value);
  840. }
  841. return $this->_parseOption($name, $params);
  842. }
  843. /**
  844. * Parse the value for a short option out of $this->_tokens
  845. * If the $option is a combination of multiple shortcuts like -otf
  846. * they will be shifted onto the token stack and parsed individually.
  847. *
  848. * @param string $option The option to parse.
  849. * @param array $params The params to append the parsed value into
  850. * @return array Params with $option added in.
  851. * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered.
  852. */
  853. protected function _parseShortOption($option, $params)
  854. {
  855. $key = substr($option, 1);
  856. if (strlen($key) > 1) {
  857. $flags = str_split($key);
  858. $key = $flags[0];
  859. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  860. array_unshift($this->_tokens, '-' . $flags[$i]);
  861. }
  862. }
  863. if (!isset($this->_shortOptions[$key])) {
  864. throw new ConsoleException($this->getShortOptionError($key));
  865. }
  866. $name = $this->_shortOptions[$key];
  867. return $this->_parseOption($name, $params);
  868. }
  869. /**
  870. * Parse an option by its name index.
  871. *
  872. * @param string $name The name to parse.
  873. * @param array $params The params to append the parsed value into
  874. * @return array Params with $option added in.
  875. * @throws \Cake\Console\Exception\ConsoleException
  876. */
  877. protected function _parseOption($name, $params)
  878. {
  879. if (!isset($this->_options[$name])) {
  880. throw new ConsoleException($this->getOptionError($name));
  881. }
  882. $option = $this->_options[$name];
  883. $isBoolean = $option->isBoolean();
  884. $nextValue = $this->_nextToken();
  885. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  886. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  887. array_shift($this->_tokens);
  888. $value = $nextValue;
  889. } elseif ($isBoolean) {
  890. $value = true;
  891. } else {
  892. $value = $option->defaultValue();
  893. }
  894. if ($option->validChoice($value)) {
  895. if ($option->acceptsMultiple()) {
  896. $params[$name][] = $value;
  897. } else {
  898. $params[$name] = $value;
  899. }
  900. return $params;
  901. }
  902. return [];
  903. }
  904. /**
  905. * Check to see if $name has an option (short/long) defined for it.
  906. *
  907. * @param string $name The name of the option.
  908. * @return bool
  909. */
  910. protected function _optionExists($name)
  911. {
  912. if (substr($name, 0, 2) === '--') {
  913. return isset($this->_options[substr($name, 2)]);
  914. }
  915. if ($name{0} === '-' && $name{1} !== '-') {
  916. return isset($this->_shortOptions[$name{1}]);
  917. }
  918. return false;
  919. }
  920. /**
  921. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  922. * and that the argument is a valid choice.
  923. *
  924. * @param string $argument The argument to append
  925. * @param array $args The array of parsed args to append to.
  926. * @return array Args
  927. * @throws \Cake\Console\Exception\ConsoleException
  928. */
  929. protected function _parseArg($argument, $args)
  930. {
  931. if (empty($this->_args)) {
  932. $args[] = $argument;
  933. return $args;
  934. }
  935. $next = count($args);
  936. if (!isset($this->_args[$next])) {
  937. throw new ConsoleException('Too many arguments.');
  938. }
  939. if ($this->_args[$next]->validChoice($argument)) {
  940. $args[] = $argument;
  941. return $args;
  942. }
  943. }
  944. /**
  945. * Find the next token in the argv set.
  946. *
  947. * @return string next token or ''
  948. */
  949. protected function _nextToken()
  950. {
  951. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  952. }
  953. }