ConsoleOptionParser.php 30 KB

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