tis-cli前端项目快速搭建命令行工具
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1924 lines
60 KiB

4 years ago
  1. const EventEmitter = require('events').EventEmitter;
  2. const childProcess = require('child_process');
  3. const path = require('path');
  4. const fs = require('fs');
  5. const { Argument, humanReadableArgName } = require('./argument.js');
  6. const { CommanderError } = require('./error.js');
  7. const { Help } = require('./help.js');
  8. const { Option, splitOptionFlags } = require('./option.js');
  9. const { suggestSimilar } = require('./suggestSimilar');
  10. // @ts-check
  11. class Command extends EventEmitter {
  12. /**
  13. * Initialize a new `Command`.
  14. *
  15. * @param {string} [name]
  16. */
  17. constructor(name) {
  18. super();
  19. /** @type {Command[]} */
  20. this.commands = [];
  21. /** @type {Option[]} */
  22. this.options = [];
  23. this.parent = null;
  24. this._allowUnknownOption = false;
  25. this._allowExcessArguments = true;
  26. /** @type {Argument[]} */
  27. this._args = [];
  28. /** @type {string[]} */
  29. this.args = []; // cli args with options removed
  30. this.rawArgs = [];
  31. this.processedArgs = []; // like .args but after custom processing and collecting variadic
  32. this._scriptPath = null;
  33. this._name = name || '';
  34. this._optionValues = {};
  35. this._optionValueSources = {}; // default < env < cli
  36. this._storeOptionsAsProperties = false;
  37. this._actionHandler = null;
  38. this._executableHandler = false;
  39. this._executableFile = null; // custom name for executable
  40. this._defaultCommandName = null;
  41. this._exitCallback = null;
  42. this._aliases = [];
  43. this._combineFlagAndOptionalValue = true;
  44. this._description = '';
  45. this._argsDescription = undefined; // legacy
  46. this._enablePositionalOptions = false;
  47. this._passThroughOptions = false;
  48. this._lifeCycleHooks = {}; // a hash of arrays
  49. /** @type {boolean | string} */
  50. this._showHelpAfterError = false;
  51. this._showSuggestionAfterError = false;
  52. // see .configureOutput() for docs
  53. this._outputConfiguration = {
  54. writeOut: (str) => process.stdout.write(str),
  55. writeErr: (str) => process.stderr.write(str),
  56. getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,
  57. getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,
  58. outputError: (str, write) => write(str)
  59. };
  60. this._hidden = false;
  61. this._hasHelpOption = true;
  62. this._helpFlags = '-h, --help';
  63. this._helpDescription = 'display help for command';
  64. this._helpShortFlag = '-h';
  65. this._helpLongFlag = '--help';
  66. this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false
  67. this._helpCommandName = 'help';
  68. this._helpCommandnameAndArgs = 'help [command]';
  69. this._helpCommandDescription = 'display help for command';
  70. this._helpConfiguration = {};
  71. }
  72. /**
  73. * Copy settings that are useful to have in common across root command and subcommands.
  74. *
  75. * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
  76. *
  77. * @param {Command} sourceCommand
  78. * @return {Command} returns `this` for executable command
  79. */
  80. copyInheritedSettings(sourceCommand) {
  81. this._outputConfiguration = sourceCommand._outputConfiguration;
  82. this._hasHelpOption = sourceCommand._hasHelpOption;
  83. this._helpFlags = sourceCommand._helpFlags;
  84. this._helpDescription = sourceCommand._helpDescription;
  85. this._helpShortFlag = sourceCommand._helpShortFlag;
  86. this._helpLongFlag = sourceCommand._helpLongFlag;
  87. this._helpCommandName = sourceCommand._helpCommandName;
  88. this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
  89. this._helpCommandDescription = sourceCommand._helpCommandDescription;
  90. this._helpConfiguration = sourceCommand._helpConfiguration;
  91. this._exitCallback = sourceCommand._exitCallback;
  92. this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
  93. this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
  94. this._allowExcessArguments = sourceCommand._allowExcessArguments;
  95. this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
  96. this._showHelpAfterError = sourceCommand._showHelpAfterError;
  97. this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
  98. return this;
  99. }
  100. /**
  101. * Define a command.
  102. *
  103. * There are two styles of command: pay attention to where to put the description.
  104. *
  105. * @example
  106. * // Command implemented using action handler (description is supplied separately to `.command`)
  107. * program
  108. * .command('clone <source> [destination]')
  109. * .description('clone a repository into a newly created directory')
  110. * .action((source, destination) => {
  111. * console.log('clone command called');
  112. * });
  113. *
  114. * // Command implemented using separate executable file (description is second parameter to `.command`)
  115. * program
  116. * .command('start <service>', 'start named service')
  117. * .command('stop [service]', 'stop named service, or all if no name supplied');
  118. *
  119. * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
  120. * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
  121. * @param {Object} [execOpts] - configuration options (for executable)
  122. * @return {Command} returns new command for action handler, or `this` for executable command
  123. */
  124. command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
  125. let desc = actionOptsOrExecDesc;
  126. let opts = execOpts;
  127. if (typeof desc === 'object' && desc !== null) {
  128. opts = desc;
  129. desc = null;
  130. }
  131. opts = opts || {};
  132. const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
  133. const cmd = this.createCommand(name);
  134. if (desc) {
  135. cmd.description(desc);
  136. cmd._executableHandler = true;
  137. }
  138. if (opts.isDefault) this._defaultCommandName = cmd._name;
  139. cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
  140. cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
  141. if (args) cmd.arguments(args);
  142. this.commands.push(cmd);
  143. cmd.parent = this;
  144. cmd.copyInheritedSettings(this);
  145. if (desc) return this;
  146. return cmd;
  147. };
  148. /**
  149. * Factory routine to create a new unattached command.
  150. *
  151. * See .command() for creating an attached subcommand, which uses this routine to
  152. * create the command. You can override createCommand to customise subcommands.
  153. *
  154. * @param {string} [name]
  155. * @return {Command} new command
  156. */
  157. createCommand(name) {
  158. return new Command(name);
  159. };
  160. /**
  161. * You can customise the help with a subclass of Help by overriding createHelp,
  162. * or by overriding Help properties using configureHelp().
  163. *
  164. * @return {Help}
  165. */
  166. createHelp() {
  167. return Object.assign(new Help(), this.configureHelp());
  168. };
  169. /**
  170. * You can customise the help by overriding Help properties using configureHelp(),
  171. * or with a subclass of Help by overriding createHelp().
  172. *
  173. * @param {Object} [configuration] - configuration options
  174. * @return {Command|Object} `this` command for chaining, or stored configuration
  175. */
  176. configureHelp(configuration) {
  177. if (configuration === undefined) return this._helpConfiguration;
  178. this._helpConfiguration = configuration;
  179. return this;
  180. }
  181. /**
  182. * The default output goes to stdout and stderr. You can customise this for special
  183. * applications. You can also customise the display of errors by overriding outputError.
  184. *
  185. * The configuration properties are all functions:
  186. *
  187. * // functions to change where being written, stdout and stderr
  188. * writeOut(str)
  189. * writeErr(str)
  190. * // matching functions to specify width for wrapping help
  191. * getOutHelpWidth()
  192. * getErrHelpWidth()
  193. * // functions based on what is being written out
  194. * outputError(str, write) // used for displaying errors, and not used for displaying help
  195. *
  196. * @param {Object} [configuration] - configuration options
  197. * @return {Command|Object} `this` command for chaining, or stored configuration
  198. */
  199. configureOutput(configuration) {
  200. if (configuration === undefined) return this._outputConfiguration;
  201. Object.assign(this._outputConfiguration, configuration);
  202. return this;
  203. }
  204. /**
  205. * Display the help or a custom message after an error occurs.
  206. *
  207. * @param {boolean|string} [displayHelp]
  208. * @return {Command} `this` command for chaining
  209. */
  210. showHelpAfterError(displayHelp = true) {
  211. if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
  212. this._showHelpAfterError = displayHelp;
  213. return this;
  214. }
  215. /**
  216. * Display suggestion of similar commands for unknown commands, or options for unknown options.
  217. *
  218. * @param {boolean} [displaySuggestion]
  219. * @return {Command} `this` command for chaining
  220. */
  221. showSuggestionAfterError(displaySuggestion = true) {
  222. this._showSuggestionAfterError = !!displaySuggestion;
  223. return this;
  224. }
  225. /**
  226. * Add a prepared subcommand.
  227. *
  228. * See .command() for creating an attached subcommand which inherits settings from its parent.
  229. *
  230. * @param {Command} cmd - new subcommand
  231. * @param {Object} [opts] - configuration options
  232. * @return {Command} `this` command for chaining
  233. */
  234. addCommand(cmd, opts) {
  235. if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
  236. // To keep things simple, block automatic name generation for deeply nested executables.
  237. // Fail fast and detect when adding rather than later when parsing.
  238. function checkExplicitNames(commandArray) {
  239. commandArray.forEach((cmd) => {
  240. if (cmd._executableHandler && !cmd._executableFile) {
  241. throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);
  242. }
  243. checkExplicitNames(cmd.commands);
  244. });
  245. }
  246. checkExplicitNames(cmd.commands);
  247. opts = opts || {};
  248. if (opts.isDefault) this._defaultCommandName = cmd._name;
  249. if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
  250. this.commands.push(cmd);
  251. cmd.parent = this;
  252. return this;
  253. };
  254. /**
  255. * Factory routine to create a new unattached argument.
  256. *
  257. * See .argument() for creating an attached argument, which uses this routine to
  258. * create the argument. You can override createArgument to return a custom argument.
  259. *
  260. * @param {string} name
  261. * @param {string} [description]
  262. * @return {Argument} new argument
  263. */
  264. createArgument(name, description) {
  265. return new Argument(name, description);
  266. };
  267. /**
  268. * Define argument syntax for command.
  269. *
  270. * The default is that the argument is required, and you can explicitly
  271. * indicate this with <> around the name. Put [] around the name for an optional argument.
  272. *
  273. * @example
  274. * program.argument('<input-file>');
  275. * program.argument('[output-file]');
  276. *
  277. * @param {string} name
  278. * @param {string} [description]
  279. * @param {Function|*} [fn] - custom argument processing function
  280. * @param {*} [defaultValue]
  281. * @return {Command} `this` command for chaining
  282. */
  283. argument(name, description, fn, defaultValue) {
  284. const argument = this.createArgument(name, description);
  285. if (typeof fn === 'function') {
  286. argument.default(defaultValue).argParser(fn);
  287. } else {
  288. argument.default(fn);
  289. }
  290. this.addArgument(argument);
  291. return this;
  292. }
  293. /**
  294. * Define argument syntax for command, adding multiple at once (without descriptions).
  295. *
  296. * See also .argument().
  297. *
  298. * @example
  299. * program.arguments('<cmd> [env]');
  300. *
  301. * @param {string} names
  302. * @return {Command} `this` command for chaining
  303. */
  304. arguments(names) {
  305. names.split(/ +/).forEach((detail) => {
  306. this.argument(detail);
  307. });
  308. return this;
  309. };
  310. /**
  311. * Define argument syntax for command, adding a prepared argument.
  312. *
  313. * @param {Argument} argument
  314. * @return {Command} `this` command for chaining
  315. */
  316. addArgument(argument) {
  317. const previousArgument = this._args.slice(-1)[0];
  318. if (previousArgument && previousArgument.variadic) {
  319. throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
  320. }
  321. if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
  322. throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
  323. }
  324. this._args.push(argument);
  325. return this;
  326. }
  327. /**
  328. * Override default decision whether to add implicit help command.
  329. *
  330. * addHelpCommand() // force on
  331. * addHelpCommand(false); // force off
  332. * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
  333. *
  334. * @return {Command} `this` command for chaining
  335. */
  336. addHelpCommand(enableOrNameAndArgs, description) {
  337. if (enableOrNameAndArgs === false) {
  338. this._addImplicitHelpCommand = false;
  339. } else {
  340. this._addImplicitHelpCommand = true;
  341. if (typeof enableOrNameAndArgs === 'string') {
  342. this._helpCommandName = enableOrNameAndArgs.split(' ')[0];
  343. this._helpCommandnameAndArgs = enableOrNameAndArgs;
  344. }
  345. this._helpCommandDescription = description || this._helpCommandDescription;
  346. }
  347. return this;
  348. };
  349. /**
  350. * @return {boolean}
  351. * @api private
  352. */
  353. _hasImplicitHelpCommand() {
  354. if (this._addImplicitHelpCommand === undefined) {
  355. return this.commands.length && !this._actionHandler && !this._findCommand('help');
  356. }
  357. return this._addImplicitHelpCommand;
  358. };
  359. /**
  360. * Add hook for life cycle event.
  361. *
  362. * @param {string} event
  363. * @param {Function} listener
  364. * @return {Command} `this` command for chaining
  365. */
  366. hook(event, listener) {
  367. const allowedValues = ['preAction', 'postAction'];
  368. if (!allowedValues.includes(event)) {
  369. throw new Error(`Unexpected value for event passed to hook : '${event}'.
  370. Expecting one of '${allowedValues.join("', '")}'`);
  371. }
  372. if (this._lifeCycleHooks[event]) {
  373. this._lifeCycleHooks[event].push(listener);
  374. } else {
  375. this._lifeCycleHooks[event] = [listener];
  376. }
  377. return this;
  378. }
  379. /**
  380. * Register callback to use as replacement for calling process.exit.
  381. *
  382. * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
  383. * @return {Command} `this` command for chaining
  384. */
  385. exitOverride(fn) {
  386. if (fn) {
  387. this._exitCallback = fn;
  388. } else {
  389. this._exitCallback = (err) => {
  390. if (err.code !== 'commander.executeSubCommandAsync') {
  391. throw err;
  392. } else {
  393. // Async callback from spawn events, not useful to throw.
  394. }
  395. };
  396. }
  397. return this;
  398. };
  399. /**
  400. * Call process.exit, and _exitCallback if defined.
  401. *
  402. * @param {number} exitCode exit code for using with process.exit
  403. * @param {string} code an id string representing the error
  404. * @param {string} message human-readable description of the error
  405. * @return never
  406. * @api private
  407. */
  408. _exit(exitCode, code, message) {
  409. if (this._exitCallback) {
  410. this._exitCallback(new CommanderError(exitCode, code, message));
  411. // Expecting this line is not reached.
  412. }
  413. process.exit(exitCode);
  414. };
  415. /**
  416. * Register callback `fn` for the command.
  417. *
  418. * @example
  419. * program
  420. * .command('help')
  421. * .description('display verbose help')
  422. * .action(function() {
  423. * // output help here
  424. * });
  425. *
  426. * @param {Function} fn
  427. * @return {Command} `this` command for chaining
  428. */
  429. action(fn) {
  430. const listener = (args) => {
  431. // The .action callback takes an extra parameter which is the command or options.
  432. const expectedArgsCount = this._args.length;
  433. const actionArgs = args.slice(0, expectedArgsCount);
  434. if (this._storeOptionsAsProperties) {
  435. actionArgs[expectedArgsCount] = this; // backwards compatible "options"
  436. } else {
  437. actionArgs[expectedArgsCount] = this.opts();
  438. }
  439. actionArgs.push(this);
  440. return fn.apply(this, actionArgs);
  441. };
  442. this._actionHandler = listener;
  443. return this;
  444. };
  445. /**
  446. * Factory routine to create a new unattached option.
  447. *
  448. * See .option() for creating an attached option, which uses this routine to
  449. * create the option. You can override createOption to return a custom option.
  450. *
  451. * @param {string} flags
  452. * @param {string} [description]
  453. * @return {Option} new option
  454. */
  455. createOption(flags, description) {
  456. return new Option(flags, description);
  457. };
  458. /**
  459. * Add an option.
  460. *
  461. * @param {Option} option
  462. * @return {Command} `this` command for chaining
  463. */
  464. addOption(option) {
  465. const oname = option.name();
  466. const name = option.attributeName();
  467. let defaultValue = option.defaultValue;
  468. // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value
  469. if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
  470. // when --no-foo we make sure default is true, unless a --foo option is already defined
  471. if (option.negate) {
  472. const positiveLongFlag = option.long.replace(/^--no-/, '--');
  473. defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;
  474. }
  475. // preassign only if we have a default
  476. if (defaultValue !== undefined) {
  477. this._setOptionValueWithSource(name, defaultValue, 'default');
  478. }
  479. }
  480. // register the option
  481. this.options.push(option);
  482. // handler for cli and env supplied values
  483. const handleOptionValue = (val, invalidValueMessage, valueSource) => {
  484. // Note: using closure to access lots of lexical scoped variables.
  485. const oldValue = this.getOptionValue(name);
  486. // custom processing
  487. if (val !== null && option.parseArg) {
  488. try {
  489. val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);
  490. } catch (err) {
  491. if (err.code === 'commander.invalidArgument') {
  492. const message = `${invalidValueMessage} ${err.message}`;
  493. this._displayError(err.exitCode, err.code, message);
  494. }
  495. throw err;
  496. }
  497. } else if (val !== null && option.variadic) {
  498. val = option._concatValue(val, oldValue);
  499. }
  500. // unassigned or boolean value
  501. if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {
  502. // if no value, negate false, and we have a default, then use it!
  503. if (val == null) {
  504. this._setOptionValueWithSource(name, option.negate ? false : defaultValue || true, valueSource);
  505. } else {
  506. this._setOptionValueWithSource(name, val, valueSource);
  507. }
  508. } else if (val !== null) {
  509. // reassign
  510. this._setOptionValueWithSource(name, option.negate ? false : val, valueSource);
  511. }
  512. };
  513. this.on('option:' + oname, (val) => {
  514. const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
  515. handleOptionValue(val, invalidValueMessage, 'cli');
  516. });
  517. if (option.envVar) {
  518. this.on('optionEnv:' + oname, (val) => {
  519. const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
  520. handleOptionValue(val, invalidValueMessage, 'env');
  521. });
  522. }
  523. return this;
  524. }
  525. /**
  526. * Internal implementation shared by .option() and .requiredOption()
  527. *
  528. * @api private
  529. */
  530. _optionEx(config, flags, description, fn, defaultValue) {
  531. const option = this.createOption(flags, description);
  532. option.makeOptionMandatory(!!config.mandatory);
  533. if (typeof fn === 'function') {
  534. option.default(defaultValue).argParser(fn);
  535. } else if (fn instanceof RegExp) {
  536. // deprecated
  537. const regex = fn;
  538. fn = (val, def) => {
  539. const m = regex.exec(val);
  540. return m ? m[0] : def;
  541. };
  542. option.default(defaultValue).argParser(fn);
  543. } else {
  544. option.default(fn);
  545. }
  546. return this.addOption(option);
  547. }
  548. /**
  549. * Define option with `flags`, `description` and optional
  550. * coercion `fn`.
  551. *
  552. * The `flags` string contains the short and/or long flags,
  553. * separated by comma, a pipe or space. The following are all valid
  554. * all will output this way when `--help` is used.
  555. *
  556. * "-p, --pepper"
  557. * "-p|--pepper"
  558. * "-p --pepper"
  559. *
  560. * @example
  561. * // simple boolean defaulting to undefined
  562. * program.option('-p, --pepper', 'add pepper');
  563. *
  564. * program.pepper
  565. * // => undefined
  566. *
  567. * --pepper
  568. * program.pepper
  569. * // => true
  570. *
  571. * // simple boolean defaulting to true (unless non-negated option is also defined)
  572. * program.option('-C, --no-cheese', 'remove cheese');
  573. *
  574. * program.cheese
  575. * // => true
  576. *
  577. * --no-cheese
  578. * program.cheese
  579. * // => false
  580. *
  581. * // required argument
  582. * program.option('-C, --chdir <path>', 'change the working directory');
  583. *
  584. * --chdir /tmp
  585. * program.chdir
  586. * // => "/tmp"
  587. *
  588. * // optional argument
  589. * program.option('-c, --cheese [type]', 'add cheese [marble]');
  590. *
  591. * @param {string} flags
  592. * @param {string} [description]
  593. * @param {Function|*} [fn] - custom option processing function or default value
  594. * @param {*} [defaultValue]
  595. * @return {Command} `this` command for chaining
  596. */
  597. option(flags, description, fn, defaultValue) {
  598. return this._optionEx({}, flags, description, fn, defaultValue);
  599. };
  600. /**
  601. * Add a required option which must have a value after parsing. This usually means
  602. * the option must be specified on the command line. (Otherwise the same as .option().)
  603. *
  604. * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
  605. *
  606. * @param {string} flags
  607. * @param {string} [description]
  608. * @param {Function|*} [fn] - custom option processing function or default value
  609. * @param {*} [defaultValue]
  610. * @return {Command} `this` command for chaining
  611. */
  612. requiredOption(flags, description, fn, defaultValue) {
  613. return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
  614. };
  615. /**
  616. * Alter parsing of short flags with optional values.
  617. *
  618. * @example
  619. * // for `.option('-f,--flag [value]'):
  620. * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
  621. * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
  622. *
  623. * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
  624. */
  625. combineFlagAndOptionalValue(combine = true) {
  626. this._combineFlagAndOptionalValue = !!combine;
  627. return this;
  628. };
  629. /**
  630. * Allow unknown options on the command line.
  631. *
  632. * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
  633. * for unknown options.
  634. */
  635. allowUnknownOption(allowUnknown = true) {
  636. this._allowUnknownOption = !!allowUnknown;
  637. return this;
  638. };
  639. /**
  640. * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
  641. *
  642. * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
  643. * for excess arguments.
  644. */
  645. allowExcessArguments(allowExcess = true) {
  646. this._allowExcessArguments = !!allowExcess;
  647. return this;
  648. };
  649. /**
  650. * Enable positional options. Positional means global options are specified before subcommands which lets
  651. * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
  652. * The default behaviour is non-positional and global options may appear anywhere on the command line.
  653. *
  654. * @param {Boolean} [positional=true]
  655. */
  656. enablePositionalOptions(positional = true) {
  657. this._enablePositionalOptions = !!positional;
  658. return this;
  659. };
  660. /**
  661. * Pass through options that come after command-arguments rather than treat them as command-options,
  662. * so actual command-options come before command-arguments. Turning this on for a subcommand requires
  663. * positional options to have been enabled on the program (parent commands).
  664. * The default behaviour is non-positional and options may appear before or after command-arguments.
  665. *
  666. * @param {Boolean} [passThrough=true]
  667. * for unknown options.
  668. */
  669. passThroughOptions(passThrough = true) {
  670. this._passThroughOptions = !!passThrough;
  671. if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
  672. throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');
  673. }
  674. return this;
  675. };
  676. /**
  677. * Whether to store option values as properties on command object,
  678. * or store separately (specify false). In both cases the option values can be accessed using .opts().
  679. *
  680. * @param {boolean} [storeAsProperties=true]
  681. * @return {Command} `this` command for chaining
  682. */
  683. storeOptionsAsProperties(storeAsProperties = true) {
  684. this._storeOptionsAsProperties = !!storeAsProperties;
  685. if (this.options.length) {
  686. throw new Error('call .storeOptionsAsProperties() before adding options');
  687. }
  688. return this;
  689. };
  690. /**
  691. * Retrieve option value.
  692. *
  693. * @param {string} key
  694. * @return {Object} value
  695. */
  696. getOptionValue(key) {
  697. if (this._storeOptionsAsProperties) {
  698. return this[key];
  699. }
  700. return this._optionValues[key];
  701. };
  702. /**
  703. * Store option value.
  704. *
  705. * @param {string} key
  706. * @param {Object} value
  707. * @return {Command} `this` command for chaining
  708. */
  709. setOptionValue(key, value) {
  710. if (this._storeOptionsAsProperties) {
  711. this[key] = value;
  712. } else {
  713. this._optionValues[key] = value;
  714. }
  715. return this;
  716. };
  717. /**
  718. * @api private
  719. */
  720. _setOptionValueWithSource(key, value, source) {
  721. this.setOptionValue(key, value);
  722. this._optionValueSources[key] = source;
  723. }
  724. /**
  725. * Get user arguments implied or explicit arguments.
  726. * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.
  727. *
  728. * @api private
  729. */
  730. _prepareUserArgs(argv, parseOptions) {
  731. if (argv !== undefined && !Array.isArray(argv)) {
  732. throw new Error('first parameter to parse must be array or undefined');
  733. }
  734. parseOptions = parseOptions || {};
  735. // Default to using process.argv
  736. if (argv === undefined) {
  737. argv = process.argv;
  738. // @ts-ignore: unknown property
  739. if (process.versions && process.versions.electron) {
  740. parseOptions.from = 'electron';
  741. }
  742. }
  743. this.rawArgs = argv.slice();
  744. // make it a little easier for callers by supporting various argv conventions
  745. let userArgs;
  746. switch (parseOptions.from) {
  747. case undefined:
  748. case 'node':
  749. this._scriptPath = argv[1];
  750. userArgs = argv.slice(2);
  751. break;
  752. case 'electron':
  753. // @ts-ignore: unknown property
  754. if (process.defaultApp) {
  755. this._scriptPath = argv[1];
  756. userArgs = argv.slice(2);
  757. } else {
  758. userArgs = argv.slice(1);
  759. }
  760. break;
  761. case 'user':
  762. userArgs = argv.slice(0);
  763. break;
  764. default:
  765. throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
  766. }
  767. if (!this._scriptPath && require.main) {
  768. this._scriptPath = require.main.filename;
  769. }
  770. // Guess name, used in usage in help.
  771. this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));
  772. return userArgs;
  773. }
  774. /**
  775. * Parse `argv`, setting options and invoking commands when defined.
  776. *
  777. * The default expectation is that the arguments are from node and have the application as argv[0]
  778. * and the script being run in argv[1], with user parameters after that.
  779. *
  780. * @example
  781. * program.parse(process.argv);
  782. * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
  783. * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  784. *
  785. * @param {string[]} [argv] - optional, defaults to process.argv
  786. * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
  787. * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
  788. * @return {Command} `this` command for chaining
  789. */
  790. parse(argv, parseOptions) {
  791. const userArgs = this._prepareUserArgs(argv, parseOptions);
  792. this._parseCommand([], userArgs);
  793. return this;
  794. };
  795. /**
  796. * Parse `argv`, setting options and invoking commands when defined.
  797. *
  798. * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
  799. *
  800. * The default expectation is that the arguments are from node and have the application as argv[0]
  801. * and the script being run in argv[1], with user parameters after that.
  802. *
  803. * @example
  804. * await program.parseAsync(process.argv);
  805. * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
  806. * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
  807. *
  808. * @param {string[]} [argv]
  809. * @param {Object} [parseOptions]
  810. * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
  811. * @return {Promise}
  812. */
  813. async parseAsync(argv, parseOptions) {
  814. const userArgs = this._prepareUserArgs(argv, parseOptions);
  815. await this._parseCommand([], userArgs);
  816. return this;
  817. };
  818. /**
  819. * Execute a sub-command executable.
  820. *
  821. * @api private
  822. */
  823. _executeSubCommand(subcommand, args) {
  824. args = args.slice();
  825. let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
  826. const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
  827. // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
  828. this._checkForMissingMandatoryOptions();
  829. // Want the entry script as the reference for command name and directory for searching for other files.
  830. let scriptPath = this._scriptPath;
  831. // Fallback in case not set, due to how Command created or called.
  832. if (!scriptPath && require.main) {
  833. scriptPath = require.main.filename;
  834. }
  835. let baseDir;
  836. try {
  837. const resolvedLink = fs.realpathSync(scriptPath);
  838. baseDir = path.dirname(resolvedLink);
  839. } catch (e) {
  840. baseDir = '.'; // dummy, probably not going to find executable!
  841. }
  842. // name of the subcommand, like `pm-install`
  843. let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;
  844. if (subcommand._executableFile) {
  845. bin = subcommand._executableFile;
  846. }
  847. const localBin = path.join(baseDir, bin);
  848. if (fs.existsSync(localBin)) {
  849. // prefer local `./<bin>` to bin in the $PATH
  850. bin = localBin;
  851. } else {
  852. // Look for source files.
  853. sourceExt.forEach((ext) => {
  854. if (fs.existsSync(`${localBin}${ext}`)) {
  855. bin = `${localBin}${ext}`;
  856. }
  857. });
  858. }
  859. launchWithNode = sourceExt.includes(path.extname(bin));
  860. let proc;
  861. if (process.platform !== 'win32') {
  862. if (launchWithNode) {
  863. args.unshift(bin);
  864. // add executable arguments to spawn
  865. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  866. proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
  867. } else {
  868. proc = childProcess.spawn(bin, args, { stdio: 'inherit' });
  869. }
  870. } else {
  871. args.unshift(bin);
  872. // add executable arguments to spawn
  873. args = incrementNodeInspectorPort(process.execArgv).concat(args);
  874. proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
  875. }
  876. const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  877. signals.forEach((signal) => {
  878. // @ts-ignore
  879. process.on(signal, () => {
  880. if (proc.killed === false && proc.exitCode === null) {
  881. proc.kill(signal);
  882. }
  883. });
  884. });
  885. // By default terminate process when spawned process terminates.
  886. // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
  887. const exitCallback = this._exitCallback;
  888. if (!exitCallback) {
  889. proc.on('close', process.exit.bind(process));
  890. } else {
  891. proc.on('close', () => {
  892. exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
  893. });
  894. }
  895. proc.on('error', (err) => {
  896. // @ts-ignore
  897. if (err.code === 'ENOENT') {
  898. const executableMissing = `'${bin}' does not exist
  899. - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
  900. - if the default executable name is not suitable, use the executableFile option to supply a custom name`;
  901. throw new Error(executableMissing);
  902. // @ts-ignore
  903. } else if (err.code === 'EACCES') {
  904. throw new Error(`'${bin}' not executable`);
  905. }
  906. if (!exitCallback) {
  907. process.exit(1);
  908. } else {
  909. const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
  910. wrappedError.nestedError = err;
  911. exitCallback(wrappedError);
  912. }
  913. });
  914. // Store the reference to the child process
  915. this.runningCommand = proc;
  916. };
  917. /**
  918. * @api private
  919. */
  920. _dispatchSubcommand(commandName, operands, unknown) {
  921. const subCommand = this._findCommand(commandName);
  922. if (!subCommand) this.help({ error: true });
  923. if (subCommand._executableHandler) {
  924. this._executeSubCommand(subCommand, operands.concat(unknown));
  925. } else {
  926. return subCommand._parseCommand(operands, unknown);
  927. }
  928. };
  929. /**
  930. * Check this.args against expected this._args.
  931. *
  932. * @api private
  933. */
  934. _checkNumberOfArguments() {
  935. // too few
  936. this._args.forEach((arg, i) => {
  937. if (arg.required && this.args[i] == null) {
  938. this.missingArgument(arg.name());
  939. }
  940. });
  941. // too many
  942. if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {
  943. return;
  944. }
  945. if (this.args.length > this._args.length) {
  946. this._excessArguments(this.args);
  947. }
  948. };
  949. /**
  950. * Process this.args using this._args and save as this.processedArgs!
  951. *
  952. * @api private
  953. */
  954. _processArguments() {
  955. const myParseArg = (argument, value, previous) => {
  956. // Extra processing for nice error message on parsing failure.
  957. let parsedValue = value;
  958. if (value !== null && argument.parseArg) {
  959. try {
  960. parsedValue = argument.parseArg(value, previous);
  961. } catch (err) {
  962. if (err.code === 'commander.invalidArgument') {
  963. const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;
  964. this._displayError(err.exitCode, err.code, message);
  965. }
  966. throw err;
  967. }
  968. }
  969. return parsedValue;
  970. };
  971. this._checkNumberOfArguments();
  972. const processedArgs = [];
  973. this._args.forEach((declaredArg, index) => {
  974. let value = declaredArg.defaultValue;
  975. if (declaredArg.variadic) {
  976. // Collect together remaining arguments for passing together as an array.
  977. if (index < this.args.length) {
  978. value = this.args.slice(index);
  979. if (declaredArg.parseArg) {
  980. value = value.reduce((processed, v) => {
  981. return myParseArg(declaredArg, v, processed);
  982. }, declaredArg.defaultValue);
  983. }
  984. } else if (value === undefined) {
  985. value = [];
  986. }
  987. } else if (index < this.args.length) {
  988. value = this.args[index];
  989. if (declaredArg.parseArg) {
  990. value = myParseArg(declaredArg, value, declaredArg.defaultValue);
  991. }
  992. }
  993. processedArgs[index] = value;
  994. });
  995. this.processedArgs = processedArgs;
  996. }
  997. /**
  998. * Once we have a promise we chain, but call synchronously until then.
  999. *
  1000. * @param {Promise|undefined} promise
  1001. * @param {Function} fn
  1002. * @return {Promise|undefined}
  1003. */
  1004. _chainOrCall(promise, fn) {
  1005. // thenable
  1006. if (promise && promise.then && typeof promise.then === 'function') {
  1007. // already have a promise, chain callback
  1008. return promise.then(() => fn());
  1009. }
  1010. // callback might return a promise
  1011. return fn();
  1012. }
  1013. /**
  1014. *
  1015. * @param {Promise|undefined} promise
  1016. * @param {string} event
  1017. * @return {Promise|undefined}
  1018. * @api private
  1019. */
  1020. _chainOrCallHooks(promise, event) {
  1021. let result = promise;
  1022. const hooks = [];
  1023. getCommandAndParents(this)
  1024. .reverse()
  1025. .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)
  1026. .forEach(hookedCommand => {
  1027. hookedCommand._lifeCycleHooks[event].forEach((callback) => {
  1028. hooks.push({ hookedCommand, callback });
  1029. });
  1030. });
  1031. if (event === 'postAction') {
  1032. hooks.reverse();
  1033. }
  1034. hooks.forEach((hookDetail) => {
  1035. result = this._chainOrCall(result, () => {
  1036. return hookDetail.callback(hookDetail.hookedCommand, this);
  1037. });
  1038. });
  1039. return result;
  1040. }
  1041. /**
  1042. * Process arguments in context of this command.
  1043. * Returns action result, in case it is a promise.
  1044. *
  1045. * @api private
  1046. */
  1047. _parseCommand(operands, unknown) {
  1048. const parsed = this.parseOptions(unknown);
  1049. this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
  1050. operands = operands.concat(parsed.operands);
  1051. unknown = parsed.unknown;
  1052. this.args = operands.concat(unknown);
  1053. if (operands && this._findCommand(operands[0])) {
  1054. return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
  1055. }
  1056. if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
  1057. if (operands.length === 1) {
  1058. this.help();
  1059. }
  1060. return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
  1061. }
  1062. if (this._defaultCommandName) {
  1063. outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
  1064. return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
  1065. }
  1066. if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
  1067. // probably missing subcommand and no handler, user needs help (and exit)
  1068. this.help({ error: true });
  1069. }
  1070. outputHelpIfRequested(this, parsed.unknown);
  1071. this._checkForMissingMandatoryOptions();
  1072. // We do not always call this check to avoid masking a "better" error, like unknown command.
  1073. const checkForUnknownOptions = () => {
  1074. if (parsed.unknown.length > 0) {
  1075. this.unknownOption(parsed.unknown[0]);
  1076. }
  1077. };
  1078. const commandEvent = `command:${this.name()}`;
  1079. if (this._actionHandler) {
  1080. checkForUnknownOptions();
  1081. this._processArguments();
  1082. let actionResult;
  1083. actionResult = this._chainOrCallHooks(actionResult, 'preAction');
  1084. actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));
  1085. if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy
  1086. actionResult = this._chainOrCallHooks(actionResult, 'postAction');
  1087. return actionResult;
  1088. }
  1089. if (this.parent && this.parent.listenerCount(commandEvent)) {
  1090. checkForUnknownOptions();
  1091. this._processArguments();
  1092. this.parent.emit(commandEvent, operands, unknown); // legacy
  1093. } else if (operands.length) {
  1094. if (this._findCommand('*')) { // legacy default command
  1095. return this._dispatchSubcommand('*', operands, unknown);
  1096. }
  1097. if (this.listenerCount('command:*')) {
  1098. // skip option check, emit event for possible misspelling suggestion
  1099. this.emit('command:*', operands, unknown);
  1100. } else if (this.commands.length) {
  1101. this.unknownCommand();
  1102. } else {
  1103. checkForUnknownOptions();
  1104. this._processArguments();
  1105. }
  1106. } else if (this.commands.length) {
  1107. checkForUnknownOptions();
  1108. // This command has subcommands and nothing hooked up at this level, so display help (and exit).
  1109. this.help({ error: true });
  1110. } else {
  1111. checkForUnknownOptions();
  1112. this._processArguments();
  1113. // fall through for caller to handle after calling .parse()
  1114. }
  1115. };
  1116. /**
  1117. * Find matching command.
  1118. *
  1119. * @api private
  1120. */
  1121. _findCommand(name) {
  1122. if (!name) return undefined;
  1123. return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
  1124. };
  1125. /**
  1126. * Return an option matching `arg` if any.
  1127. *
  1128. * @param {string} arg
  1129. * @return {Option}
  1130. * @api private
  1131. */
  1132. _findOption(arg) {
  1133. return this.options.find(option => option.is(arg));
  1134. };
  1135. /**
  1136. * Display an error message if a mandatory option does not have a value.
  1137. * Lazy calling after checking for help flags from leaf subcommand.
  1138. *
  1139. * @api private
  1140. */
  1141. _checkForMissingMandatoryOptions() {
  1142. // Walk up hierarchy so can call in subcommand after checking for displaying help.
  1143. for (let cmd = this; cmd; cmd = cmd.parent) {
  1144. cmd.options.forEach((anOption) => {
  1145. if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {
  1146. cmd.missingMandatoryOptionValue(anOption);
  1147. }
  1148. });
  1149. }
  1150. };
  1151. /**
  1152. * Parse options from `argv` removing known options,
  1153. * and return argv split into operands and unknown arguments.
  1154. *
  1155. * Examples:
  1156. *
  1157. * argv => operands, unknown
  1158. * --known kkk op => [op], []
  1159. * op --known kkk => [op], []
  1160. * sub --unknown uuu op => [sub], [--unknown uuu op]
  1161. * sub -- --unknown uuu op => [sub --unknown uuu op], []
  1162. *
  1163. * @param {String[]} argv
  1164. * @return {{operands: String[], unknown: String[]}}
  1165. */
  1166. parseOptions(argv) {
  1167. const operands = []; // operands, not options or values
  1168. const unknown = []; // first unknown option and remaining unknown args
  1169. let dest = operands;
  1170. const args = argv.slice();
  1171. function maybeOption(arg) {
  1172. return arg.length > 1 && arg[0] === '-';
  1173. }
  1174. // parse options
  1175. let activeVariadicOption = null;
  1176. while (args.length) {
  1177. const arg = args.shift();
  1178. // literal
  1179. if (arg === '--') {
  1180. if (dest === unknown) dest.push(arg);
  1181. dest.push(...args);
  1182. break;
  1183. }
  1184. if (activeVariadicOption && !maybeOption(arg)) {
  1185. this.emit(`option:${activeVariadicOption.name()}`, arg);
  1186. continue;
  1187. }
  1188. activeVariadicOption = null;
  1189. if (maybeOption(arg)) {
  1190. const option = this._findOption(arg);
  1191. // recognised option, call listener to assign value with possible custom processing
  1192. if (option) {
  1193. if (option.required) {
  1194. const value = args.shift();
  1195. if (value === undefined) this.optionMissingArgument(option);
  1196. this.emit(`option:${option.name()}`, value);
  1197. } else if (option.optional) {
  1198. let value = null;
  1199. // historical behaviour is optional value is following arg unless an option
  1200. if (args.length > 0 && !maybeOption(args[0])) {
  1201. value = args.shift();
  1202. }
  1203. this.emit(`option:${option.name()}`, value);
  1204. } else { // boolean flag
  1205. this.emit(`option:${option.name()}`);
  1206. }
  1207. activeVariadicOption = option.variadic ? option : null;
  1208. continue;
  1209. }
  1210. }
  1211. // Look for combo options following single dash, eat first one if known.
  1212. if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
  1213. const option = this._findOption(`-${arg[1]}`);
  1214. if (option) {
  1215. if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
  1216. // option with value following in same argument
  1217. this.emit(`option:${option.name()}`, arg.slice(2));
  1218. } else {
  1219. // boolean option, emit and put back remainder of arg for further processing
  1220. this.emit(`option:${option.name()}`);
  1221. args.unshift(`-${arg.slice(2)}`);
  1222. }
  1223. continue;
  1224. }
  1225. }
  1226. // Look for known long flag with value, like --foo=bar
  1227. if (/^--[^=]+=/.test(arg)) {
  1228. const index = arg.indexOf('=');
  1229. const option = this._findOption(arg.slice(0, index));
  1230. if (option && (option.required || option.optional)) {
  1231. this.emit(`option:${option.name()}`, arg.slice(index + 1));
  1232. continue;
  1233. }
  1234. }
  1235. // Not a recognised option by this command.
  1236. // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
  1237. // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
  1238. if (maybeOption(arg)) {
  1239. dest = unknown;
  1240. }
  1241. // If using positionalOptions, stop processing our options at subcommand.
  1242. if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
  1243. if (this._findCommand(arg)) {
  1244. operands.push(arg);
  1245. if (args.length > 0) unknown.push(...args);
  1246. break;
  1247. } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
  1248. operands.push(arg);
  1249. if (args.length > 0) operands.push(...args);
  1250. break;
  1251. } else if (this._defaultCommandName) {
  1252. unknown.push(arg);
  1253. if (args.length > 0) unknown.push(...args);
  1254. break;
  1255. }
  1256. }
  1257. // If using passThroughOptions, stop processing options at first command-argument.
  1258. if (this._passThroughOptions) {
  1259. dest.push(arg);
  1260. if (args.length > 0) dest.push(...args);
  1261. break;
  1262. }
  1263. // add arg
  1264. dest.push(arg);
  1265. }
  1266. return { operands, unknown };
  1267. };
  1268. /**
  1269. * Return an object containing options as key-value pairs
  1270. *
  1271. * @return {Object}
  1272. */
  1273. opts() {
  1274. if (this._storeOptionsAsProperties) {
  1275. // Preserve original behaviour so backwards compatible when still using properties
  1276. const result = {};
  1277. const len = this.options.length;
  1278. for (let i = 0; i < len; i++) {
  1279. const key = this.options[i].attributeName();
  1280. result[key] = key === this._versionOptionName ? this._version : this[key];
  1281. }
  1282. return result;
  1283. }
  1284. return this._optionValues;
  1285. };
  1286. /**
  1287. * Internal bottleneck for handling of parsing errors.
  1288. *
  1289. * @api private
  1290. */
  1291. _displayError(exitCode, code, message) {
  1292. this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
  1293. if (typeof this._showHelpAfterError === 'string') {
  1294. this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
  1295. } else if (this._showHelpAfterError) {
  1296. this._outputConfiguration.writeErr('\n');
  1297. this.outputHelp({ error: true });
  1298. }
  1299. this._exit(exitCode, code, message);
  1300. }
  1301. /**
  1302. * Apply any option related environment variables, if option does
  1303. * not have a value from cli or client code.
  1304. *
  1305. * @api private
  1306. */
  1307. _parseOptionsEnv() {
  1308. this.options.forEach((option) => {
  1309. if (option.envVar && option.envVar in process.env) {
  1310. const optionKey = option.attributeName();
  1311. // env is second lowest priority source, above default
  1312. if (this.getOptionValue(optionKey) === undefined || this._optionValueSources[optionKey] === 'default') {
  1313. if (option.required || option.optional) { // option can take a value
  1314. // keep very simple, optional always takes value
  1315. this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
  1316. } else { // boolean
  1317. // keep very simple, only care that envVar defined and not the value
  1318. this.emit(`optionEnv:${option.name()}`);
  1319. }
  1320. }
  1321. }
  1322. });
  1323. }
  1324. /**
  1325. * Argument `name` is missing.
  1326. *
  1327. * @param {string} name
  1328. * @api private
  1329. */
  1330. missingArgument(name) {
  1331. const message = `error: missing required argument '${name}'`;
  1332. this._displayError(1, 'commander.missingArgument', message);
  1333. };
  1334. /**
  1335. * `Option` is missing an argument.
  1336. *
  1337. * @param {Option} option
  1338. * @api private
  1339. */
  1340. optionMissingArgument(option) {
  1341. const message = `error: option '${option.flags}' argument missing`;
  1342. this._displayError(1, 'commander.optionMissingArgument', message);
  1343. };
  1344. /**
  1345. * `Option` does not have a value, and is a mandatory option.
  1346. *
  1347. * @param {Option} option
  1348. * @api private
  1349. */
  1350. missingMandatoryOptionValue(option) {
  1351. const message = `error: required option '${option.flags}' not specified`;
  1352. this._displayError(1, 'commander.missingMandatoryOptionValue', message);
  1353. };
  1354. /**
  1355. * Unknown option `flag`.
  1356. *
  1357. * @param {string} flag
  1358. * @api private
  1359. */
  1360. unknownOption(flag) {
  1361. if (this._allowUnknownOption) return;
  1362. let suggestion = '';
  1363. if (flag.startsWith('--') && this._showSuggestionAfterError) {
  1364. // Looping to pick up the global options too
  1365. let candidateFlags = [];
  1366. let command = this;
  1367. do {
  1368. const moreFlags = command.createHelp().visibleOptions(command)
  1369. .filter(option => option.long)
  1370. .map(option => option.long);
  1371. candidateFlags = candidateFlags.concat(moreFlags);
  1372. command = command.parent;
  1373. } while (command && !command._enablePositionalOptions);
  1374. suggestion = suggestSimilar(flag, candidateFlags);
  1375. }
  1376. const message = `error: unknown option '${flag}'${suggestion}`;
  1377. this._displayError(1, 'commander.unknownOption', message);
  1378. };
  1379. /**
  1380. * Excess arguments, more than expected.
  1381. *
  1382. * @param {string[]} receivedArgs
  1383. * @api private
  1384. */
  1385. _excessArguments(receivedArgs) {
  1386. if (this._allowExcessArguments) return;
  1387. const expected = this._args.length;
  1388. const s = (expected === 1) ? '' : 's';
  1389. const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
  1390. const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
  1391. this._displayError(1, 'commander.excessArguments', message);
  1392. };
  1393. /**
  1394. * Unknown command.
  1395. *
  1396. * @api private
  1397. */
  1398. unknownCommand() {
  1399. const unknownName = this.args[0];
  1400. let suggestion = '';
  1401. if (this._showSuggestionAfterError) {
  1402. const candidateNames = [];
  1403. this.createHelp().visibleCommands(this).forEach((command) => {
  1404. candidateNames.push(command.name());
  1405. // just visible alias
  1406. if (command.alias()) candidateNames.push(command.alias());
  1407. });
  1408. suggestion = suggestSimilar(unknownName, candidateNames);
  1409. }
  1410. const message = `error: unknown command '${unknownName}'${suggestion}`;
  1411. this._displayError(1, 'commander.unknownCommand', message);
  1412. };
  1413. /**
  1414. * Set the program version to `str`.
  1415. *
  1416. * This method auto-registers the "-V, --version" flag
  1417. * which will print the version number when passed.
  1418. *
  1419. * You can optionally supply the flags and description to override the defaults.
  1420. *
  1421. * @param {string} str
  1422. * @param {string} [flags]
  1423. * @param {string} [description]
  1424. * @return {this | string} `this` command for chaining, or version string if no arguments
  1425. */
  1426. version(str, flags, description) {
  1427. if (str === undefined) return this._version;
  1428. this._version = str;
  1429. flags = flags || '-V, --version';
  1430. description = description || 'output the version number';
  1431. const versionOption = this.createOption(flags, description);
  1432. this._versionOptionName = versionOption.attributeName();
  1433. this.options.push(versionOption);
  1434. this.on('option:' + versionOption.name(), () => {
  1435. this._outputConfiguration.writeOut(`${str}\n`);
  1436. this._exit(0, 'commander.version', str);
  1437. });
  1438. return this;
  1439. };
  1440. /**
  1441. * Set the description to `str`.
  1442. *
  1443. * @param {string} [str]
  1444. * @param {Object} [argsDescription]
  1445. * @return {string|Command}
  1446. */
  1447. description(str, argsDescription) {
  1448. if (str === undefined && argsDescription === undefined) return this._description;
  1449. this._description = str;
  1450. if (argsDescription) {
  1451. this._argsDescription = argsDescription;
  1452. }
  1453. return this;
  1454. };
  1455. /**
  1456. * Set an alias for the command.
  1457. *
  1458. * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
  1459. *
  1460. * @param {string} [alias]
  1461. * @return {string|Command}
  1462. */
  1463. alias(alias) {
  1464. if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
  1465. /** @type {Command} */
  1466. let command = this;
  1467. if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
  1468. // assume adding alias for last added executable subcommand, rather than this
  1469. command = this.commands[this.commands.length - 1];
  1470. }
  1471. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  1472. command._aliases.push(alias);
  1473. return this;
  1474. };
  1475. /**
  1476. * Set aliases for the command.
  1477. *
  1478. * Only the first alias is shown in the auto-generated help.
  1479. *
  1480. * @param {string[]} [aliases]
  1481. * @return {string[]|Command}
  1482. */
  1483. aliases(aliases) {
  1484. // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
  1485. if (aliases === undefined) return this._aliases;
  1486. aliases.forEach((alias) => this.alias(alias));
  1487. return this;
  1488. };
  1489. /**
  1490. * Set / get the command usage `str`.
  1491. *
  1492. * @param {string} [str]
  1493. * @return {String|Command}
  1494. */
  1495. usage(str) {
  1496. if (str === undefined) {
  1497. if (this._usage) return this._usage;
  1498. const args = this._args.map((arg) => {
  1499. return humanReadableArgName(arg);
  1500. });
  1501. return [].concat(
  1502. (this.options.length || this._hasHelpOption ? '[options]' : []),
  1503. (this.commands.length ? '[command]' : []),
  1504. (this._args.length ? args : [])
  1505. ).join(' ');
  1506. }
  1507. this._usage = str;
  1508. return this;
  1509. };
  1510. /**
  1511. * Get or set the name of the command
  1512. *
  1513. * @param {string} [str]
  1514. * @return {string|Command}
  1515. */
  1516. name(str) {
  1517. if (str === undefined) return this._name;
  1518. this._name = str;
  1519. return this;
  1520. };
  1521. /**
  1522. * Return program help documentation.
  1523. *
  1524. * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
  1525. * @return {string}
  1526. */
  1527. helpInformation(contextOptions) {
  1528. const helper = this.createHelp();
  1529. if (helper.helpWidth === undefined) {
  1530. helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
  1531. }
  1532. return helper.formatHelp(this, helper);
  1533. };
  1534. /**
  1535. * @api private
  1536. */
  1537. _getHelpContext(contextOptions) {
  1538. contextOptions = contextOptions || {};
  1539. const context = { error: !!contextOptions.error };
  1540. let write;
  1541. if (context.error) {
  1542. write = (arg) => this._outputConfiguration.writeErr(arg);
  1543. } else {
  1544. write = (arg) => this._outputConfiguration.writeOut(arg);
  1545. }
  1546. context.write = contextOptions.write || write;
  1547. context.command = this;
  1548. return context;
  1549. }
  1550. /**
  1551. * Output help information for this command.
  1552. *
  1553. * Outputs built-in help, and custom text added using `.addHelpText()`.
  1554. *
  1555. * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
  1556. */
  1557. outputHelp(contextOptions) {
  1558. let deprecatedCallback;
  1559. if (typeof contextOptions === 'function') {
  1560. deprecatedCallback = contextOptions;
  1561. contextOptions = undefined;
  1562. }
  1563. const context = this._getHelpContext(contextOptions);
  1564. getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));
  1565. this.emit('beforeHelp', context);
  1566. let helpInformation = this.helpInformation(context);
  1567. if (deprecatedCallback) {
  1568. helpInformation = deprecatedCallback(helpInformation);
  1569. if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
  1570. throw new Error('outputHelp callback must return a string or a Buffer');
  1571. }
  1572. }
  1573. context.write(helpInformation);
  1574. this.emit(this._helpLongFlag); // deprecated
  1575. this.emit('afterHelp', context);
  1576. getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context));
  1577. };
  1578. /**
  1579. * You can pass in flags and a description to override the help
  1580. * flags and help description for your command. Pass in false to
  1581. * disable the built-in help option.
  1582. *
  1583. * @param {string | boolean} [flags]
  1584. * @param {string} [description]
  1585. * @return {Command} `this` command for chaining
  1586. */
  1587. helpOption(flags, description) {
  1588. if (typeof flags === 'boolean') {
  1589. this._hasHelpOption = flags;
  1590. return this;
  1591. }
  1592. this._helpFlags = flags || this._helpFlags;
  1593. this._helpDescription = description || this._helpDescription;
  1594. const helpFlags = splitOptionFlags(this._helpFlags);
  1595. this._helpShortFlag = helpFlags.shortFlag;
  1596. this._helpLongFlag = helpFlags.longFlag;
  1597. return this;
  1598. };
  1599. /**
  1600. * Output help information and exit.
  1601. *
  1602. * Outputs built-in help, and custom text added using `.addHelpText()`.
  1603. *
  1604. * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
  1605. */
  1606. help(contextOptions) {
  1607. this.outputHelp(contextOptions);
  1608. let exitCode = process.exitCode || 0;
  1609. if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
  1610. exitCode = 1;
  1611. }
  1612. // message: do not have all displayed text available so only passing placeholder.
  1613. this._exit(exitCode, 'commander.help', '(outputHelp)');
  1614. };
  1615. /**
  1616. * Add additional text to be displayed with the built-in help.
  1617. *
  1618. * Position is 'before' or 'after' to affect just this command,
  1619. * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
  1620. *
  1621. * @param {string} position - before or after built-in help
  1622. * @param {string | Function} text - string to add, or a function returning a string
  1623. * @return {Command} `this` command for chaining
  1624. */
  1625. addHelpText(position, text) {
  1626. const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
  1627. if (!allowedValues.includes(position)) {
  1628. throw new Error(`Unexpected value for position to addHelpText.
  1629. Expecting one of '${allowedValues.join("', '")}'`);
  1630. }
  1631. const helpEvent = `${position}Help`;
  1632. this.on(helpEvent, (context) => {
  1633. let helpStr;
  1634. if (typeof text === 'function') {
  1635. helpStr = text({ error: context.error, command: context.command });
  1636. } else {
  1637. helpStr = text;
  1638. }
  1639. // Ignore falsy value when nothing to output.
  1640. if (helpStr) {
  1641. context.write(`${helpStr}\n`);
  1642. }
  1643. });
  1644. return this;
  1645. }
  1646. };
  1647. /**
  1648. * Output help information if help flags specified
  1649. *
  1650. * @param {Command} cmd - command to output help for
  1651. * @param {Array} args - array of options to search for help flags
  1652. * @api private
  1653. */
  1654. function outputHelpIfRequested(cmd, args) {
  1655. const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
  1656. if (helpOption) {
  1657. cmd.outputHelp();
  1658. // (Do not have all displayed text available so only passing placeholder.)
  1659. cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
  1660. }
  1661. }
  1662. /**
  1663. * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
  1664. *
  1665. * @param {string[]} args - array of arguments from node.execArgv
  1666. * @returns {string[]}
  1667. * @api private
  1668. */
  1669. function incrementNodeInspectorPort(args) {
  1670. // Testing for these options:
  1671. // --inspect[=[host:]port]
  1672. // --inspect-brk[=[host:]port]
  1673. // --inspect-port=[host:]port
  1674. return args.map((arg) => {
  1675. if (!arg.startsWith('--inspect')) {
  1676. return arg;
  1677. }
  1678. let debugOption;
  1679. let debugHost = '127.0.0.1';
  1680. let debugPort = '9229';
  1681. let match;
  1682. if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
  1683. // e.g. --inspect
  1684. debugOption = match[1];
  1685. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
  1686. debugOption = match[1];
  1687. if (/^\d+$/.test(match[3])) {
  1688. // e.g. --inspect=1234
  1689. debugPort = match[3];
  1690. } else {
  1691. // e.g. --inspect=localhost
  1692. debugHost = match[3];
  1693. }
  1694. } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
  1695. // e.g. --inspect=localhost:1234
  1696. debugOption = match[1];
  1697. debugHost = match[3];
  1698. debugPort = match[4];
  1699. }
  1700. if (debugOption && debugPort !== '0') {
  1701. return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
  1702. }
  1703. return arg;
  1704. });
  1705. }
  1706. /**
  1707. * @param {Command} startCommand
  1708. * @returns {Command[]}
  1709. * @api private
  1710. */
  1711. function getCommandAndParents(startCommand) {
  1712. const result = [];
  1713. for (let command = startCommand; command; command = command.parent) {
  1714. result.push(command);
  1715. }
  1716. return result;
  1717. }
  1718. exports.Command = Command;