command.js
This file
Path
lib/command.js
2,084 lines · 65.6 KiB · JavaScript
Last changed by
feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
History of this fileTake it
1const EventEmitter = require('events').EventEmitter;2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');5const process = require('process');67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');10const { Option, splitOptionFlags } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');1213// @ts-check1415class Command extends EventEmitter {16 /**17 * Initialize a new `Command`.18 *19 * @param {string} [name]20 */2122 constructor(name) {23 super();24 /** @type {Command[]} */25 this.commands = [];26 /** @type {Option[]} */27 this.options = [];28 this.parent = null;29 this._allowUnknownOption = false;30 this._allowExcessArguments = true;31 /** @type {Argument[]} */32 this._args = [];33 /** @type {string[]} */34 this.args = []; // cli args with options removed35 this.rawArgs = [];36 this.processedArgs = []; // like .args but after custom processing and collecting variadic37 this._scriptPath = null;38 this._name = name || '';39 this._optionValues = {};40 this._optionValueSources = {}; // default < config < env < cli41 this._storeOptionsAsProperties = false;42 this._actionHandler = null;43 this._executableHandler = false;44 this._executableFile = null; // custom name for executable45 this._executableDir = null; // custom search directory for subcommands46 this._defaultCommandName = null;47 this._exitCallback = null;48 this._aliases = [];49 this._combineFlagAndOptionalValue = true;50 this._description = '';51 this._argsDescription = undefined; // legacy52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arrays55 /** @type {boolean | string} */56 this._showHelpAfterError = false;57 this._showSuggestionAfterError = true;5859 // see .configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),63 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,64 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,65 outputError: (str, write) => write(str)66 };6768 this._hidden = false;69 this._hasHelpOption = true;70 this._helpFlags = '-h, --help';71 this._helpDescription = 'display help for command';72 this._helpShortFlag = '-h';73 this._helpLongFlag = '--help';74 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false75 this._helpCommandName = 'help';76 this._helpCommandnameAndArgs = 'help [command]';77 this._helpCommandDescription = 'display help for command';78 this._helpConfiguration = {};79 }8081 /**82 * Copy settings that are useful to have in common across root command and subcommands.83 *84 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)85 *86 * @param {Command} sourceCommand87 * @return {Command} `this` command for chaining88 */89 copyInheritedSettings(sourceCommand) {90 this._outputConfiguration = sourceCommand._outputConfiguration;91 this._hasHelpOption = sourceCommand._hasHelpOption;92 this._helpFlags = sourceCommand._helpFlags;93 this._helpDescription = sourceCommand._helpDescription;94 this._helpShortFlag = sourceCommand._helpShortFlag;95 this._helpLongFlag = sourceCommand._helpLongFlag;96 this._helpCommandName = sourceCommand._helpCommandName;97 this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;98 this._helpCommandDescription = sourceCommand._helpCommandDescription;99 this._helpConfiguration = sourceCommand._helpConfiguration;100 this._exitCallback = sourceCommand._exitCallback;101 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;102 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;103 this._allowExcessArguments = sourceCommand._allowExcessArguments;104 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;105 this._showHelpAfterError = sourceCommand._showHelpAfterError;106 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;107108 return this;109 }110111 /**112 * Define a command.113 *114 * There are two styles of command: pay attention to where to put the description.115 *116 * @example117 * // Command implemented using action handler (description is supplied separately to `.command`)118 * program119 * .command('clone <source> [destination]')120 * .description('clone a repository into a newly created directory')121 * .action((source, destination) => {122 * console.log('clone command called');123 * });124 *125 * // Command implemented using separate executable file (description is second parameter to `.command`)126 * program127 * .command('start <service>', 'start named service')128 * .command('stop [service]', 'stop named service, or all if no name supplied');129 *130 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`131 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)132 * @param {Object} [execOpts] - configuration options (for executable)133 * @return {Command} returns new command for action handler, or `this` for executable command134 */135136 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {137 let desc = actionOptsOrExecDesc;138 let opts = execOpts;139 if (typeof desc === 'object' && desc !== null) {140 opts = desc;141 desc = null;142 }143 opts = opts || {};144 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);145146 const cmd = this.createCommand(name);147 if (desc) {148 cmd.description(desc);149 cmd._executableHandler = true;150 }151 if (opts.isDefault) this._defaultCommandName = cmd._name;152 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden153 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor154 if (args) cmd.arguments(args);155 this.commands.push(cmd);156 cmd.parent = this;157 cmd.copyInheritedSettings(this);158159 if (desc) return this;160 return cmd;161 }162163 /**164 * Factory routine to create a new unattached command.165 *166 * See .command() for creating an attached subcommand, which uses this routine to167 * create the command. You can override createCommand to customise subcommands.168 *169 * @param {string} [name]170 * @return {Command} new command171 */172173 createCommand(name) {174 return new Command(name);175 }176177 /**178 * You can customise the help with a subclass of Help by overriding createHelp,179 * or by overriding Help properties using configureHelp().180 *181 * @return {Help}182 */183184 createHelp() {185 return Object.assign(new Help(), this.configureHelp());186 }187188 /**189 * You can customise the help by overriding Help properties using configureHelp(),190 * or with a subclass of Help by overriding createHelp().191 *192 * @param {Object} [configuration] - configuration options193 * @return {Command|Object} `this` command for chaining, or stored configuration194 */195196 configureHelp(configuration) {197 if (configuration === undefined) return this._helpConfiguration;198199 this._helpConfiguration = configuration;200 return this;201 }202203 /**204 * The default output goes to stdout and stderr. You can customise this for special205 * applications. You can also customise the display of errors by overriding outputError.206 *207 * The configuration properties are all functions:208 *209 * // functions to change where being written, stdout and stderr210 * writeOut(str)211 * writeErr(str)212 * // matching functions to specify width for wrapping help213 * getOutHelpWidth()214 * getErrHelpWidth()215 * // functions based on what is being written out216 * outputError(str, write) // used for displaying errors, and not used for displaying help217 *218 * @param {Object} [configuration] - configuration options219 * @return {Command|Object} `this` command for chaining, or stored configuration220 */221222 configureOutput(configuration) {223 if (configuration === undefined) return this._outputConfiguration;224225 Object.assign(this._outputConfiguration, configuration);226 return this;227 }228229 /**230 * Display the help or a custom message after an error occurs.231 *232 * @param {boolean|string} [displayHelp]233 * @return {Command} `this` command for chaining234 */235 showHelpAfterError(displayHelp = true) {236 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;237 this._showHelpAfterError = displayHelp;238 return this;239 }240241 /**242 * Display suggestion of similar commands for unknown commands, or options for unknown options.243 *244 * @param {boolean} [displaySuggestion]245 * @return {Command} `this` command for chaining246 */247 showSuggestionAfterError(displaySuggestion = true) {248 this._showSuggestionAfterError = !!displaySuggestion;249 return this;250 }251252 /**253 * Add a prepared subcommand.254 *255 * See .command() for creating an attached subcommand which inherits settings from its parent.256 *257 * @param {Command} cmd - new subcommand258 * @param {Object} [opts] - configuration options259 * @return {Command} `this` command for chaining260 */261262 addCommand(cmd, opts) {263 if (!cmd._name) {264 throw new Error(`Command passed to .addCommand() must have a name265- specify the name in Command constructor or using .name()`);266 }267268 opts = opts || {};269 if (opts.isDefault) this._defaultCommandName = cmd._name;270 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation271272 this.commands.push(cmd);273 cmd.parent = this;274 return this;275 }276277 /**278 * Factory routine to create a new unattached argument.279 *280 * See .argument() for creating an attached argument, which uses this routine to281 * create the argument. You can override createArgument to return a custom argument.282 *283 * @param {string} name284 * @param {string} [description]285 * @return {Argument} new argument286 */287288 createArgument(name, description) {289 return new Argument(name, description);290 }291292 /**293 * Define argument syntax for command.294 *295 * The default is that the argument is required, and you can explicitly296 * indicate this with <> around the name. Put [] around the name for an optional argument.297 *298 * @example299 * program.argument('<input-file>');300 * program.argument('[output-file]');301 *302 * @param {string} name303 * @param {string} [description]304 * @param {Function|*} [fn] - custom argument processing function305 * @param {*} [defaultValue]306 * @return {Command} `this` command for chaining307 */308 argument(name, description, fn, defaultValue) {309 const argument = this.createArgument(name, description);310 if (typeof fn === 'function') {311 argument.default(defaultValue).argParser(fn);312 } else {313 argument.default(fn);314 }315 this.addArgument(argument);316 return this;317 }318319 /**320 * Define argument syntax for command, adding multiple at once (without descriptions).321 *322 * See also .argument().323 *324 * @example325 * program.arguments('<cmd> [env]');326 *327 * @param {string} names328 * @return {Command} `this` command for chaining329 */330331 arguments(names) {332 names.split(/ +/).forEach((detail) => {333 this.argument(detail);334 });335 return this;336 }337338 /**339 * Define argument syntax for command, adding a prepared argument.340 *341 * @param {Argument} argument342 * @return {Command} `this` command for chaining343 */344 addArgument(argument) {345 const previousArgument = this._args.slice(-1)[0];346 if (previousArgument && previousArgument.variadic) {347 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);348 }349 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {350 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);351 }352 this._args.push(argument);353 return this;354 }355356 /**357 * Override default decision whether to add implicit help command.358 *359 * addHelpCommand() // force on360 * addHelpCommand(false); // force off361 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details362 *363 * @return {Command} `this` command for chaining364 */365366 addHelpCommand(enableOrNameAndArgs, description) {367 if (enableOrNameAndArgs === false) {368 this._addImplicitHelpCommand = false;369 } else {370 this._addImplicitHelpCommand = true;371 if (typeof enableOrNameAndArgs === 'string') {372 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];373 this._helpCommandnameAndArgs = enableOrNameAndArgs;374 }375 this._helpCommandDescription = description || this._helpCommandDescription;376 }377 return this;378 }379380 /**381 * @return {boolean}382 * @api private383 */384385 _hasImplicitHelpCommand() {386 if (this._addImplicitHelpCommand === undefined) {387 return this.commands.length && !this._actionHandler && !this._findCommand('help');388 }389 return this._addImplicitHelpCommand;390 }391392 /**393 * Add hook for life cycle event.394 *395 * @param {string} event396 * @param {Function} listener397 * @return {Command} `this` command for chaining398 */399400 hook(event, listener) {401 const allowedValues = ['preAction', 'postAction'];402 if (!allowedValues.includes(event)) {403 throw new Error(`Unexpected value for event passed to hook : '${event}'.404Expecting one of '${allowedValues.join("', '")}'`);405 }406 if (this._lifeCycleHooks[event]) {407 this._lifeCycleHooks[event].push(listener);408 } else {409 this._lifeCycleHooks[event] = [listener];410 }411 return this;412 }413414 /**415 * Register callback to use as replacement for calling process.exit.416 *417 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing418 * @return {Command} `this` command for chaining419 */420421 exitOverride(fn) {422 if (fn) {423 this._exitCallback = fn;424 } else {425 this._exitCallback = (err) => {426 if (err.code !== 'commander.executeSubCommandAsync') {427 throw err;428 } else {429 // Async callback from spawn events, not useful to throw.430 }431 };432 }433 return this;434 }435436 /**437 * Call process.exit, and _exitCallback if defined.438 *439 * @param {number} exitCode exit code for using with process.exit440 * @param {string} code an id string representing the error441 * @param {string} message human-readable description of the error442 * @return never443 * @api private444 */445446 _exit(exitCode, code, message) {447 if (this._exitCallback) {448 this._exitCallback(new CommanderError(exitCode, code, message));449 // Expecting this line is not reached.450 }451 process.exit(exitCode);452 }453454 /**455 * Register callback `fn` for the command.456 *457 * @example458 * program459 * .command('serve')460 * .description('start service')461 * .action(function() {462 * // do work here463 * });464 *465 * @param {Function} fn466 * @return {Command} `this` command for chaining467 */468469 action(fn) {470 const listener = (args) => {471 // The .action callback takes an extra parameter which is the command or options.472 const expectedArgsCount = this._args.length;473 const actionArgs = args.slice(0, expectedArgsCount);474 if (this._storeOptionsAsProperties) {475 actionArgs[expectedArgsCount] = this; // backwards compatible "options"476 } else {477 actionArgs[expectedArgsCount] = this.opts();478 }479 actionArgs.push(this);480481 return fn.apply(this, actionArgs);482 };483 this._actionHandler = listener;484 return this;485 }486487 /**488 * Factory routine to create a new unattached option.489 *490 * See .option() for creating an attached option, which uses this routine to491 * create the option. You can override createOption to return a custom option.492 *493 * @param {string} flags494 * @param {string} [description]495 * @return {Option} new option496 */497498 createOption(flags, description) {499 return new Option(flags, description);500 }501502 /**503 * Add an option.504 *505 * @param {Option} option506 * @return {Command} `this` command for chaining507 */508 addOption(option) {509 const oname = option.name();510 const name = option.attributeName();511512 // store default value513 if (option.negate) {514 // --no-foo is special and defaults foo to true, unless a --foo option is already defined515 const positiveLongFlag = option.long.replace(/^--no-/, '--');516 if (!this._findOption(positiveLongFlag)) {517 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');518 }519 } else if (option.defaultValue !== undefined) {520 this.setOptionValueWithSource(name, option.defaultValue, 'default');521 }522523 // register the option524 this.options.push(option);525526 // handler for cli and env supplied values527 const handleOptionValue = (val, invalidValueMessage, valueSource) => {528 // val is null for optional option used without an optional-argument.529 // val is undefined for boolean and negated option.530 if (val == null && option.presetArg !== undefined) {531 val = option.presetArg;532 }533534 // custom processing535 const oldValue = this.getOptionValue(name);536 if (val !== null && option.parseArg) {537 try {538 val = option.parseArg(val, oldValue);539 } catch (err) {540 if (err.code === 'commander.invalidArgument') {541 const message = `${invalidValueMessage} ${err.message}`;542 this.error(message, { exitCode: err.exitCode, code: err.code });543 }544 throw err;545 }546 } else if (val !== null && option.variadic) {547 val = option._concatValue(val, oldValue);548 }549550 // Fill-in appropriate missing values. Long winded but easy to follow.551 if (val == null) {552 if (option.negate) {553 val = false;554 } else if (option.isBoolean() || option.optional) {555 val = true;556 } else {557 val = ''; // not normal, parseArg might have failed or be a mock function for testing558 }559 }560 this.setOptionValueWithSource(name, val, valueSource);561 };562563 this.on('option:' + oname, (val) => {564 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;565 handleOptionValue(val, invalidValueMessage, 'cli');566 });567568 if (option.envVar) {569 this.on('optionEnv:' + oname, (val) => {570 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;571 handleOptionValue(val, invalidValueMessage, 'env');572 });573 }574575 return this;576 }577578 /**579 * Internal implementation shared by .option() and .requiredOption()580 *581 * @api private582 */583 _optionEx(config, flags, description, fn, defaultValue) {584 if (typeof flags === 'object' && flags instanceof Option) {585 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');586 }587 const option = this.createOption(flags, description);588 option.makeOptionMandatory(!!config.mandatory);589 if (typeof fn === 'function') {590 option.default(defaultValue).argParser(fn);591 } else if (fn instanceof RegExp) {592 // deprecated593 const regex = fn;594 fn = (val, def) => {595 const m = regex.exec(val);596 return m ? m[0] : def;597 };598 option.default(defaultValue).argParser(fn);599 } else {600 option.default(fn);601 }602603 return this.addOption(option);604 }605606 /**607 * Define option with `flags`, `description` and optional608 * coercion `fn`.609 *610 * The `flags` string contains the short and/or long flags,611 * separated by comma, a pipe or space. The following are all valid612 * all will output this way when `--help` is used.613 *614 * "-p, --pepper"615 * "-p|--pepper"616 * "-p --pepper"617 *618 * @example619 * // simple boolean defaulting to undefined620 * program.option('-p, --pepper', 'add pepper');621 *622 * program.pepper623 * // => undefined624 *625 * --pepper626 * program.pepper627 * // => true628 *629 * // simple boolean defaulting to true (unless non-negated option is also defined)630 * program.option('-C, --no-cheese', 'remove cheese');631 *632 * program.cheese633 * // => true634 *635 * --no-cheese636 * program.cheese637 * // => false638 *639 * // required argument640 * program.option('-C, --chdir <path>', 'change the working directory');641 *642 * --chdir /tmp643 * program.chdir644 * // => "/tmp"645 *646 * // optional argument647 * program.option('-c, --cheese [type]', 'add cheese [marble]');648 *649 * @param {string} flags650 * @param {string} [description]651 * @param {Function|*} [fn] - custom option processing function or default value652 * @param {*} [defaultValue]653 * @return {Command} `this` command for chaining654 */655656 option(flags, description, fn, defaultValue) {657 return this._optionEx({}, flags, description, fn, defaultValue);658 }659660 /**661 * Add a required option which must have a value after parsing. This usually means662 * the option must be specified on the command line. (Otherwise the same as .option().)663 *664 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.665 *666 * @param {string} flags667 * @param {string} [description]668 * @param {Function|*} [fn] - custom option processing function or default value669 * @param {*} [defaultValue]670 * @return {Command} `this` command for chaining671 */672673 requiredOption(flags, description, fn, defaultValue) {674 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);675 }676677 /**678 * Alter parsing of short flags with optional values.679 *680 * @example681 * // for `.option('-f,--flag [value]'):682 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour683 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`684 *685 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.686 */687 combineFlagAndOptionalValue(combine = true) {688 this._combineFlagAndOptionalValue = !!combine;689 return this;690 }691692 /**693 * Allow unknown options on the command line.694 *695 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown696 * for unknown options.697 */698 allowUnknownOption(allowUnknown = true) {699 this._allowUnknownOption = !!allowUnknown;700 return this;701 }702703 /**704 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.705 *706 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown707 * for excess arguments.708 */709 allowExcessArguments(allowExcess = true) {710 this._allowExcessArguments = !!allowExcess;711 return this;712 }713714 /**715 * Enable positional options. Positional means global options are specified before subcommands which lets716 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.717 * The default behaviour is non-positional and global options may appear anywhere on the command line.718 *719 * @param {Boolean} [positional=true]720 */721 enablePositionalOptions(positional = true) {722 this._enablePositionalOptions = !!positional;723 return this;724 }725726 /**727 * Pass through options that come after command-arguments rather than treat them as command-options,728 * so actual command-options come before command-arguments. Turning this on for a subcommand requires729 * positional options to have been enabled on the program (parent commands).730 * The default behaviour is non-positional and options may appear before or after command-arguments.731 *732 * @param {Boolean} [passThrough=true]733 * for unknown options.734 */735 passThroughOptions(passThrough = true) {736 this._passThroughOptions = !!passThrough;737 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {738 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');739 }740 return this;741 }742743 /**744 * Whether to store option values as properties on command object,745 * or store separately (specify false). In both cases the option values can be accessed using .opts().746 *747 * @param {boolean} [storeAsProperties=true]748 * @return {Command} `this` command for chaining749 */750751 storeOptionsAsProperties(storeAsProperties = true) {752 this._storeOptionsAsProperties = !!storeAsProperties;753 if (this.options.length) {754 throw new Error('call .storeOptionsAsProperties() before adding options');755 }756 return this;757 }758759 /**760 * Retrieve option value.761 *762 * @param {string} key763 * @return {Object} value764 */765766 getOptionValue(key) {767 if (this._storeOptionsAsProperties) {768 return this[key];769 }770 return this._optionValues[key];771 }772773 /**774 * Store option value.775 *776 * @param {string} key777 * @param {Object} value778 * @return {Command} `this` command for chaining779 */780781 setOptionValue(key, value) {782 if (this._storeOptionsAsProperties) {783 this[key] = value;784 } else {785 this._optionValues[key] = value;786 }787 return this;788 }789790 /**791 * Store option value and where the value came from.792 *793 * @param {string} key794 * @param {Object} value795 * @param {string} source - expected values are default/config/env/cli796 * @return {Command} `this` command for chaining797 */798799 setOptionValueWithSource(key, value, source) {800 this.setOptionValue(key, value);801 this._optionValueSources[key] = source;802 return this;803 }804805 /**806 * Get source of option value.807 * Expected values are default | config | env | cli808 *809 * @param {string} key810 * @return {string}811 */812813 getOptionValueSource(key) {814 return this._optionValueSources[key];815 }816817 /**818 * Get user arguments from implied or explicit arguments.819 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.820 *821 * @api private822 */823824 _prepareUserArgs(argv, parseOptions) {825 if (argv !== undefined && !Array.isArray(argv)) {826 throw new Error('first parameter to parse must be array or undefined');827 }828 parseOptions = parseOptions || {};829830 // Default to using process.argv831 if (argv === undefined) {832 argv = process.argv;833 // @ts-ignore: unknown property834 if (process.versions && process.versions.electron) {835 parseOptions.from = 'electron';836 }837 }838 this.rawArgs = argv.slice();839840 // make it a little easier for callers by supporting various argv conventions841 let userArgs;842 switch (parseOptions.from) {843 case undefined:844 case 'node':845 this._scriptPath = argv[1];846 userArgs = argv.slice(2);847 break;848 case 'electron':849 // @ts-ignore: unknown property850 if (process.defaultApp) {851 this._scriptPath = argv[1];852 userArgs = argv.slice(2);853 } else {854 userArgs = argv.slice(1);855 }856 break;857 case 'user':858 userArgs = argv.slice(0);859 break;860 default:861 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);862 }863864 // Find default name for program from arguments.865 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);866 this._name = this._name || 'program';867868 return userArgs;869 }870871 /**872 * Parse `argv`, setting options and invoking commands when defined.873 *874 * The default expectation is that the arguments are from node and have the application as argv[0]875 * and the script being run in argv[1], with user parameters after that.876 *877 * @example878 * program.parse(process.argv);879 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions880 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]881 *882 * @param {string[]} [argv] - optional, defaults to process.argv883 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron884 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'885 * @return {Command} `this` command for chaining886 */887888 parse(argv, parseOptions) {889 const userArgs = this._prepareUserArgs(argv, parseOptions);890 this._parseCommand([], userArgs);891892 return this;893 }894895 /**896 * Parse `argv`, setting options and invoking commands when defined.897 *898 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.899 *900 * The default expectation is that the arguments are from node and have the application as argv[0]901 * and the script being run in argv[1], with user parameters after that.902 *903 * @example904 * await program.parseAsync(process.argv);905 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions906 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]907 *908 * @param {string[]} [argv]909 * @param {Object} [parseOptions]910 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'911 * @return {Promise}912 */913914 async parseAsync(argv, parseOptions) {915 const userArgs = this._prepareUserArgs(argv, parseOptions);916 await this._parseCommand([], userArgs);917918 return this;919 }920921 /**922 * Execute a sub-command executable.923 *924 * @api private925 */926927 _executeSubCommand(subcommand, args) {928 args = args.slice();929 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.930 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];931932 function findFile(baseDir, baseName) {933 // Look for specified file934 const localBin = path.resolve(baseDir, baseName);935 if (fs.existsSync(localBin)) return localBin;936937 // Stop looking if candidate already has an expected extension.938 if (sourceExt.includes(path.extname(baseName))) return undefined;939940 // Try all the extensions.941 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));942 if (foundExt) return `${localBin}${foundExt}`;943944 return undefined;945 }946947 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.948 this._checkForMissingMandatoryOptions();949950 // executableFile and executableDir might be full path, or just a name951 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;952 let executableDir = this._executableDir || '';953 if (this._scriptPath) {954 let resolvedScriptPath; // resolve possible symlink for installed npm binary955 try {956 resolvedScriptPath = fs.realpathSync(this._scriptPath);957 } catch (err) {958 resolvedScriptPath = this._scriptPath;959 }960 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);961 }962963 // Look for a local file in preference to a command in PATH.964 if (executableDir) {965 let localFile = findFile(executableDir, executableFile);966967 // Legacy search using prefix of script name instead of command name968 if (!localFile && !subcommand._executableFile && this._scriptPath) {969 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));970 if (legacyName !== this._name) {971 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);972 }973 }974 executableFile = localFile || executableFile;975 }976977 launchWithNode = sourceExt.includes(path.extname(executableFile));978979 let proc;980 if (process.platform !== 'win32') {981 if (launchWithNode) {982 args.unshift(executableFile);983 // add executable arguments to spawn984 args = incrementNodeInspectorPort(process.execArgv).concat(args);985986 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });987 } else {988 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });989 }990 } else {991 args.unshift(executableFile);992 // add executable arguments to spawn993 args = incrementNodeInspectorPort(process.execArgv).concat(args);994 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });995 }996997 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn998 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];999 signals.forEach((signal) => {1000 // @ts-ignore1001 process.on(signal, () => {1002 if (proc.killed === false && proc.exitCode === null) {1003 proc.kill(signal);1004 }1005 });1006 });1007 }10081009 // By default terminate process when spawned process terminates.1010 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1011 const exitCallback = this._exitCallback;1012 if (!exitCallback) {1013 proc.on('close', process.exit.bind(process));1014 } else {1015 proc.on('close', () => {1016 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1017 });1018 }1019 proc.on('error', (err) => {1020 // @ts-ignore1021 if (err.code === 'ENOENT') {1022 const executableDirMessage = executableDir1023 ? `searched for local subcommand relative to directory '${executableDir}'`1024 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1025 const executableMissing = `'${executableFile}' does not exist1026 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1027 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1028 - ${executableDirMessage}`;1029 throw new Error(executableMissing);1030 // @ts-ignore1031 } else if (err.code === 'EACCES') {1032 throw new Error(`'${executableFile}' not executable`);1033 }1034 if (!exitCallback) {1035 process.exit(1);1036 } else {1037 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1038 wrappedError.nestedError = err;1039 exitCallback(wrappedError);1040 }1041 });10421043 // Store the reference to the child process1044 this.runningCommand = proc;1045 }10461047 /**1048 * @api private1049 */10501051 _dispatchSubcommand(commandName, operands, unknown) {1052 const subCommand = this._findCommand(commandName);1053 if (!subCommand) this.help({ error: true });10541055 if (subCommand._executableHandler) {1056 this._executeSubCommand(subCommand, operands.concat(unknown));1057 } else {1058 return subCommand._parseCommand(operands, unknown);1059 }1060 }10611062 /**1063 * Check this.args against expected this._args.1064 *1065 * @api private1066 */10671068 _checkNumberOfArguments() {1069 // too few1070 this._args.forEach((arg, i) => {1071 if (arg.required && this.args[i] == null) {1072 this.missingArgument(arg.name());1073 }1074 });1075 // too many1076 if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1077 return;1078 }1079 if (this.args.length > this._args.length) {1080 this._excessArguments(this.args);1081 }1082 }10831084 /**1085 * Process this.args using this._args and save as this.processedArgs!1086 *1087 * @api private1088 */10891090 _processArguments() {1091 const myParseArg = (argument, value, previous) => {1092 // Extra processing for nice error message on parsing failure.1093 let parsedValue = value;1094 if (value !== null && argument.parseArg) {1095 try {1096 parsedValue = argument.parseArg(value, previous);1097 } catch (err) {1098 if (err.code === 'commander.invalidArgument') {1099 const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;1100 this.error(message, { exitCode: err.exitCode, code: err.code });1101 }1102 throw err;1103 }1104 }1105 return parsedValue;1106 };11071108 this._checkNumberOfArguments();11091110 const processedArgs = [];1111 this._args.forEach((declaredArg, index) => {1112 let value = declaredArg.defaultValue;1113 if (declaredArg.variadic) {1114 // Collect together remaining arguments for passing together as an array.1115 if (index < this.args.length) {1116 value = this.args.slice(index);1117 if (declaredArg.parseArg) {1118 value = value.reduce((processed, v) => {1119 return myParseArg(declaredArg, v, processed);1120 }, declaredArg.defaultValue);1121 }1122 } else if (value === undefined) {1123 value = [];1124 }1125 } else if (index < this.args.length) {1126 value = this.args[index];1127 if (declaredArg.parseArg) {1128 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1129 }1130 }1131 processedArgs[index] = value;1132 });1133 this.processedArgs = processedArgs;1134 }11351136 /**1137 * Once we have a promise we chain, but call synchronously until then.1138 *1139 * @param {Promise|undefined} promise1140 * @param {Function} fn1141 * @return {Promise|undefined}1142 * @api private1143 */11441145 _chainOrCall(promise, fn) {1146 // thenable1147 if (promise && promise.then && typeof promise.then === 'function') {1148 // already have a promise, chain callback1149 return promise.then(() => fn());1150 }1151 // callback might return a promise1152 return fn();1153 }11541155 /**1156 *1157 * @param {Promise|undefined} promise1158 * @param {string} event1159 * @return {Promise|undefined}1160 * @api private1161 */11621163 _chainOrCallHooks(promise, event) {1164 let result = promise;1165 const hooks = [];1166 getCommandAndParents(this)1167 .reverse()1168 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1169 .forEach(hookedCommand => {1170 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1171 hooks.push({ hookedCommand, callback });1172 });1173 });1174 if (event === 'postAction') {1175 hooks.reverse();1176 }11771178 hooks.forEach((hookDetail) => {1179 result = this._chainOrCall(result, () => {1180 return hookDetail.callback(hookDetail.hookedCommand, this);1181 });1182 });1183 return result;1184 }11851186 /**1187 * Process arguments in context of this command.1188 * Returns action result, in case it is a promise.1189 *1190 * @api private1191 */11921193 _parseCommand(operands, unknown) {1194 const parsed = this.parseOptions(unknown);1195 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1196 operands = operands.concat(parsed.operands);1197 unknown = parsed.unknown;1198 this.args = operands.concat(unknown);11991200 if (operands && this._findCommand(operands[0])) {1201 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1202 }1203 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1204 if (operands.length === 1) {1205 this.help();1206 }1207 return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1208 }1209 if (this._defaultCommandName) {1210 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1211 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1212 }1213 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1214 // probably missing subcommand and no handler, user needs help (and exit)1215 this.help({ error: true });1216 }12171218 outputHelpIfRequested(this, parsed.unknown);1219 this._checkForMissingMandatoryOptions();1220 this._checkForConflictingOptions();12211222 // We do not always call this check to avoid masking a "better" error, like unknown command.1223 const checkForUnknownOptions = () => {1224 if (parsed.unknown.length > 0) {1225 this.unknownOption(parsed.unknown[0]);1226 }1227 };12281229 const commandEvent = `command:${this.name()}`;1230 if (this._actionHandler) {1231 checkForUnknownOptions();1232 this._processArguments();12331234 let actionResult;1235 actionResult = this._chainOrCallHooks(actionResult, 'preAction');1236 actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));1237 if (this.parent) {1238 actionResult = this._chainOrCall(actionResult, () => {1239 this.parent.emit(commandEvent, operands, unknown); // legacy1240 });1241 }1242 actionResult = this._chainOrCallHooks(actionResult, 'postAction');1243 return actionResult;1244 }1245 if (this.parent && this.parent.listenerCount(commandEvent)) {1246 checkForUnknownOptions();1247 this._processArguments();1248 this.parent.emit(commandEvent, operands, unknown); // legacy1249 } else if (operands.length) {1250 if (this._findCommand('*')) { // legacy default command1251 return this._dispatchSubcommand('*', operands, unknown);1252 }1253 if (this.listenerCount('command:*')) {1254 // skip option check, emit event for possible misspelling suggestion1255 this.emit('command:*', operands, unknown);1256 } else if (this.commands.length) {1257 this.unknownCommand();1258 } else {1259 checkForUnknownOptions();1260 this._processArguments();1261 }1262 } else if (this.commands.length) {1263 checkForUnknownOptions();1264 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1265 this.help({ error: true });1266 } else {1267 checkForUnknownOptions();1268 this._processArguments();1269 // fall through for caller to handle after calling .parse()1270 }1271 }12721273 /**1274 * Find matching command.1275 *1276 * @api private1277 */1278 _findCommand(name) {1279 if (!name) return undefined;1280 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1281 }12821283 /**1284 * Return an option matching `arg` if any.1285 *1286 * @param {string} arg1287 * @return {Option}1288 * @api private1289 */12901291 _findOption(arg) {1292 return this.options.find(option => option.is(arg));1293 }12941295 /**1296 * Display an error message if a mandatory option does not have a value.1297 * Lazy calling after checking for help flags from leaf subcommand.1298 *1299 * @api private1300 */13011302 _checkForMissingMandatoryOptions() {1303 // Walk up hierarchy so can call in subcommand after checking for displaying help.1304 for (let cmd = this; cmd; cmd = cmd.parent) {1305 cmd.options.forEach((anOption) => {1306 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1307 cmd.missingMandatoryOptionValue(anOption);1308 }1309 });1310 }1311 }13121313 /**1314 * Display an error message if conflicting options are used together.1315 *1316 * @api private1317 */1318 _checkForConflictingOptions() {1319 const definedNonDefaultOptions = this.options.filter(1320 (option) => {1321 const optionKey = option.attributeName();1322 if (this.getOptionValue(optionKey) === undefined) {1323 return false;1324 }1325 return this.getOptionValueSource(optionKey) !== 'default';1326 }1327 );13281329 const optionsWithConflicting = definedNonDefaultOptions.filter(1330 (option) => option.conflictsWith.length > 01331 );13321333 optionsWithConflicting.forEach((option) => {1334 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1335 option.conflictsWith.includes(defined.attributeName())1336 );1337 if (conflictingAndDefined) {1338 this._conflictingOption(option, conflictingAndDefined);1339 }1340 });1341 }13421343 /**1344 * Parse options from `argv` removing known options,1345 * and return argv split into operands and unknown arguments.1346 *1347 * Examples:1348 *1349 * argv => operands, unknown1350 * --known kkk op => [op], []1351 * op --known kkk => [op], []1352 * sub --unknown uuu op => [sub], [--unknown uuu op]1353 * sub -- --unknown uuu op => [sub --unknown uuu op], []1354 *1355 * @param {String[]} argv1356 * @return {{operands: String[], unknown: String[]}}1357 */13581359 parseOptions(argv) {1360 const operands = []; // operands, not options or values1361 const unknown = []; // first unknown option and remaining unknown args1362 let dest = operands;1363 const args = argv.slice();13641365 function maybeOption(arg) {1366 return arg.length > 1 && arg[0] === '-';1367 }13681369 // parse options1370 let activeVariadicOption = null;1371 while (args.length) {1372 const arg = args.shift();13731374 // literal1375 if (arg === '--') {1376 if (dest === unknown) dest.push(arg);1377 dest.push(...args);1378 break;1379 }13801381 if (activeVariadicOption && !maybeOption(arg)) {1382 this.emit(`option:${activeVariadicOption.name()}`, arg);1383 continue;1384 }1385 activeVariadicOption = null;13861387 if (maybeOption(arg)) {1388 const option = this._findOption(arg);1389 // recognised option, call listener to assign value with possible custom processing1390 if (option) {1391 if (option.required) {1392 const value = args.shift();1393 if (value === undefined) this.optionMissingArgument(option);1394 this.emit(`option:${option.name()}`, value);1395 } else if (option.optional) {1396 let value = null;1397 // historical behaviour is optional value is following arg unless an option1398 if (args.length > 0 && !maybeOption(args[0])) {1399 value = args.shift();1400 }1401 this.emit(`option:${option.name()}`, value);1402 } else { // boolean flag1403 this.emit(`option:${option.name()}`);1404 }1405 activeVariadicOption = option.variadic ? option : null;1406 continue;1407 }1408 }14091410 // Look for combo options following single dash, eat first one if known.1411 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1412 const option = this._findOption(`-${arg[1]}`);1413 if (option) {1414 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1415 // option with value following in same argument1416 this.emit(`option:${option.name()}`, arg.slice(2));1417 } else {1418 // boolean option, emit and put back remainder of arg for further processing1419 this.emit(`option:${option.name()}`);1420 args.unshift(`-${arg.slice(2)}`);1421 }1422 continue;1423 }1424 }14251426 // Look for known long flag with value, like --foo=bar1427 if (/^--[^=]+=/.test(arg)) {1428 const index = arg.indexOf('=');1429 const option = this._findOption(arg.slice(0, index));1430 if (option && (option.required || option.optional)) {1431 this.emit(`option:${option.name()}`, arg.slice(index + 1));1432 continue;1433 }1434 }14351436 // Not a recognised option by this command.1437 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.14381439 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1440 if (maybeOption(arg)) {1441 dest = unknown;1442 }14431444 // If using positionalOptions, stop processing our options at subcommand.1445 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1446 if (this._findCommand(arg)) {1447 operands.push(arg);1448 if (args.length > 0) unknown.push(...args);1449 break;1450 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1451 operands.push(arg);1452 if (args.length > 0) operands.push(...args);1453 break;1454 } else if (this._defaultCommandName) {1455 unknown.push(arg);1456 if (args.length > 0) unknown.push(...args);1457 break;1458 }1459 }14601461 // If using passThroughOptions, stop processing options at first command-argument.1462 if (this._passThroughOptions) {1463 dest.push(arg);1464 if (args.length > 0) dest.push(...args);1465 break;1466 }14671468 // add arg1469 dest.push(arg);1470 }14711472 return { operands, unknown };1473 }14741475 /**1476 * Return an object containing local option values as key-value pairs.1477 *1478 * @return {Object}1479 */1480 opts() {1481 if (this._storeOptionsAsProperties) {1482 // Preserve original behaviour so backwards compatible when still using properties1483 const result = {};1484 const len = this.options.length;14851486 for (let i = 0; i < len; i++) {1487 const key = this.options[i].attributeName();1488 result[key] = key === this._versionOptionName ? this._version : this[key];1489 }1490 return result;1491 }14921493 return this._optionValues;1494 }14951496 /**1497 * Return an object containing merged local and global option values as key-value pairs.1498 *1499 * @return {Object}1500 */1501 optsWithGlobals() {1502 // globals overwrite locals1503 return getCommandAndParents(this).reduce(1504 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1505 {}1506 );1507 }15081509 /**1510 * Display error message and exit (or call exitOverride).1511 *1512 * @param {string} message1513 * @param {Object} [errorOptions]1514 * @param {string} [errorOptions.code] - an id string representing the error1515 * @param {number} [errorOptions.exitCode] - used with process.exit1516 */1517 error(message, errorOptions) {1518 // output handling1519 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1520 if (typeof this._showHelpAfterError === 'string') {1521 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1522 } else if (this._showHelpAfterError) {1523 this._outputConfiguration.writeErr('\n');1524 this.outputHelp({ error: true });1525 }15261527 // exit handling1528 const config = errorOptions || {};1529 const exitCode = config.exitCode || 1;1530 const code = config.code || 'commander.error';1531 this._exit(exitCode, code, message);1532 }15331534 /**1535 * Apply any option related environment variables, if option does1536 * not have a value from cli or client code.1537 *1538 * @api private1539 */1540 _parseOptionsEnv() {1541 this.options.forEach((option) => {1542 if (option.envVar && option.envVar in process.env) {1543 const optionKey = option.attributeName();1544 // Priority check. Do not overwrite cli or options from unknown source (client-code).1545 if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {1546 if (option.required || option.optional) { // option can take a value1547 // keep very simple, optional always takes value1548 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1549 } else { // boolean1550 // keep very simple, only care that envVar defined and not the value1551 this.emit(`optionEnv:${option.name()}`);1552 }1553 }1554 }1555 });1556 }15571558 /**1559 * Argument `name` is missing.1560 *1561 * @param {string} name1562 * @api private1563 */15641565 missingArgument(name) {1566 const message = `error: missing required argument '${name}'`;1567 this.error(message, { code: 'commander.missingArgument' });1568 }15691570 /**1571 * `Option` is missing an argument.1572 *1573 * @param {Option} option1574 * @api private1575 */15761577 optionMissingArgument(option) {1578 const message = `error: option '${option.flags}' argument missing`;1579 this.error(message, { code: 'commander.optionMissingArgument' });1580 }15811582 /**1583 * `Option` does not have a value, and is a mandatory option.1584 *1585 * @param {Option} option1586 * @api private1587 */15881589 missingMandatoryOptionValue(option) {1590 const message = `error: required option '${option.flags}' not specified`;1591 this.error(message, { code: 'commander.missingMandatoryOptionValue' });1592 }15931594 /**1595 * `Option` conflicts with another option.1596 *1597 * @param {Option} option1598 * @param {Option} conflictingOption1599 * @api private1600 */1601 _conflictingOption(option, conflictingOption) {1602 // The calling code does not know whether a negated option is the source of the1603 // value, so do some work to take an educated guess.1604 const findBestOptionFromValue = (option) => {1605 const optionKey = option.attributeName();1606 const optionValue = this.getOptionValue(optionKey);1607 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1608 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1609 if (negativeOption && (1610 (negativeOption.presetArg === undefined && optionValue === false) ||1611 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1612 )) {1613 return negativeOption;1614 }1615 return positiveOption || option;1616 };16171618 const getErrorMessage = (option) => {1619 const bestOption = findBestOptionFromValue(option);1620 const optionKey = bestOption.attributeName();1621 const source = this.getOptionValueSource(optionKey);1622 if (source === 'env') {1623 return `environment variable '${bestOption.envVar}'`;1624 }1625 return `option '${bestOption.flags}'`;1626 };16271628 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1629 this.error(message, { code: 'commander.conflictingOption' });1630 }16311632 /**1633 * Unknown option `flag`.1634 *1635 * @param {string} flag1636 * @api private1637 */16381639 unknownOption(flag) {1640 if (this._allowUnknownOption) return;1641 let suggestion = '';16421643 if (flag.startsWith('--') && this._showSuggestionAfterError) {1644 // Looping to pick up the global options too1645 let candidateFlags = [];1646 let command = this;1647 do {1648 const moreFlags = command.createHelp().visibleOptions(command)1649 .filter(option => option.long)1650 .map(option => option.long);1651 candidateFlags = candidateFlags.concat(moreFlags);1652 command = command.parent;1653 } while (command && !command._enablePositionalOptions);1654 suggestion = suggestSimilar(flag, candidateFlags);1655 }16561657 const message = `error: unknown option '${flag}'${suggestion}`;1658 this.error(message, { code: 'commander.unknownOption' });1659 }16601661 /**1662 * Excess arguments, more than expected.1663 *1664 * @param {string[]} receivedArgs1665 * @api private1666 */16671668 _excessArguments(receivedArgs) {1669 if (this._allowExcessArguments) return;16701671 const expected = this._args.length;1672 const s = (expected === 1) ? '' : 's';1673 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1674 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1675 this.error(message, { code: 'commander.excessArguments' });1676 }16771678 /**1679 * Unknown command.1680 *1681 * @api private1682 */16831684 unknownCommand() {1685 const unknownName = this.args[0];1686 let suggestion = '';16871688 if (this._showSuggestionAfterError) {1689 const candidateNames = [];1690 this.createHelp().visibleCommands(this).forEach((command) => {1691 candidateNames.push(command.name());1692 // just visible alias1693 if (command.alias()) candidateNames.push(command.alias());1694 });1695 suggestion = suggestSimilar(unknownName, candidateNames);1696 }16971698 const message = `error: unknown command '${unknownName}'${suggestion}`;1699 this.error(message, { code: 'commander.unknownCommand' });1700 }17011702 /**1703 * Set the program version to `str`.1704 *1705 * This method auto-registers the "-V, --version" flag1706 * which will print the version number when passed.1707 *1708 * You can optionally supply the flags and description to override the defaults.1709 *1710 * @param {string} str1711 * @param {string} [flags]1712 * @param {string} [description]1713 * @return {this | string} `this` command for chaining, or version string if no arguments1714 */17151716 version(str, flags, description) {1717 if (str === undefined) return this._version;1718 this._version = str;1719 flags = flags || '-V, --version';1720 description = description || 'output the version number';1721 const versionOption = this.createOption(flags, description);1722 this._versionOptionName = versionOption.attributeName();1723 this.options.push(versionOption);1724 this.on('option:' + versionOption.name(), () => {1725 this._outputConfiguration.writeOut(`${str}\n`);1726 this._exit(0, 'commander.version', str);1727 });1728 return this;1729 }17301731 /**1732 * Set the description to `str`.1733 *1734 * @param {string} [str]1735 * @param {Object} [argsDescription]1736 * @return {string|Command}1737 */1738 description(str, argsDescription) {1739 if (str === undefined && argsDescription === undefined) return this._description;1740 this._description = str;1741 if (argsDescription) {1742 this._argsDescription = argsDescription;1743 }1744 return this;1745 }17461747 /**1748 * Set an alias for the command.1749 *1750 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1751 *1752 * @param {string} [alias]1753 * @return {string|Command}1754 */17551756 alias(alias) {1757 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility17581759 /** @type {Command} */1760 let command = this;1761 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1762 // assume adding alias for last added executable subcommand, rather than this1763 command = this.commands[this.commands.length - 1];1764 }17651766 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');17671768 command._aliases.push(alias);1769 return this;1770 }17711772 /**1773 * Set aliases for the command.1774 *1775 * Only the first alias is shown in the auto-generated help.1776 *1777 * @param {string[]} [aliases]1778 * @return {string[]|Command}1779 */17801781 aliases(aliases) {1782 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1783 if (aliases === undefined) return this._aliases;17841785 aliases.forEach((alias) => this.alias(alias));1786 return this;1787 }17881789 /**1790 * Set / get the command usage `str`.1791 *1792 * @param {string} [str]1793 * @return {String|Command}1794 */17951796 usage(str) {1797 if (str === undefined) {1798 if (this._usage) return this._usage;17991800 const args = this._args.map((arg) => {1801 return humanReadableArgName(arg);1802 });1803 return [].concat(1804 (this.options.length || this._hasHelpOption ? '[options]' : []),1805 (this.commands.length ? '[command]' : []),1806 (this._args.length ? args : [])1807 ).join(' ');1808 }18091810 this._usage = str;1811 return this;1812 }18131814 /**1815 * Get or set the name of the command.1816 *1817 * @param {string} [str]1818 * @return {string|Command}1819 */18201821 name(str) {1822 if (str === undefined) return this._name;1823 this._name = str;1824 return this;1825 }18261827 /**1828 * Set the name of the command from script filename, such as process.argv[1],1829 * or require.main.filename, or __filename.1830 *1831 * (Used internally and public although not documented in README.)1832 *1833 * @example1834 * program.nameFromFilename(require.main.filename);1835 *1836 * @param {string} filename1837 * @return {Command}1838 */18391840 nameFromFilename(filename) {1841 this._name = path.basename(filename, path.extname(filename));18421843 return this;1844 }18451846 /**1847 * Get or set the directory for searching for executable subcommands of this command.1848 *1849 * @example1850 * program.executableDir(__dirname);1851 * // or1852 * program.executableDir('subcommands');1853 *1854 * @param {string} [path]1855 * @return {string|Command}1856 */18571858 executableDir(path) {1859 if (path === undefined) return this._executableDir;1860 this._executableDir = path;1861 return this;1862 }18631864 /**1865 * Return program help documentation.1866 *1867 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1868 * @return {string}1869 */18701871 helpInformation(contextOptions) {1872 const helper = this.createHelp();1873 if (helper.helpWidth === undefined) {1874 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1875 }1876 return helper.formatHelp(this, helper);1877 }18781879 /**1880 * @api private1881 */18821883 _getHelpContext(contextOptions) {1884 contextOptions = contextOptions || {};1885 const context = { error: !!contextOptions.error };1886 let write;1887 if (context.error) {1888 write = (arg) => this._outputConfiguration.writeErr(arg);1889 } else {1890 write = (arg) => this._outputConfiguration.writeOut(arg);1891 }1892 context.write = contextOptions.write || write;1893 context.command = this;1894 return context;1895 }18961897 /**1898 * Output help information for this command.1899 *1900 * Outputs built-in help, and custom text added using `.addHelpText()`.1901 *1902 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1903 */19041905 outputHelp(contextOptions) {1906 let deprecatedCallback;1907 if (typeof contextOptions === 'function') {1908 deprecatedCallback = contextOptions;1909 contextOptions = undefined;1910 }1911 const context = this._getHelpContext(contextOptions);19121913 getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));1914 this.emit('beforeHelp', context);19151916 let helpInformation = this.helpInformation(context);1917 if (deprecatedCallback) {1918 helpInformation = deprecatedCallback(helpInformation);1919 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1920 throw new Error('outputHelp callback must return a string or a Buffer');1921 }1922 }1923 context.write(helpInformation);19241925 this.emit(this._helpLongFlag); // deprecated1926 this.emit('afterHelp', context);1927 getCommandAndParents(this).forEach(command => command.emit('afterAllHelp', context));1928 }19291930 /**1931 * You can pass in flags and a description to override the help1932 * flags and help description for your command. Pass in false to1933 * disable the built-in help option.1934 *1935 * @param {string | boolean} [flags]1936 * @param {string} [description]1937 * @return {Command} `this` command for chaining1938 */19391940 helpOption(flags, description) {1941 if (typeof flags === 'boolean') {1942 this._hasHelpOption = flags;1943 return this;1944 }1945 this._helpFlags = flags || this._helpFlags;1946 this._helpDescription = description || this._helpDescription;19471948 const helpFlags = splitOptionFlags(this._helpFlags);1949 this._helpShortFlag = helpFlags.shortFlag;1950 this._helpLongFlag = helpFlags.longFlag;19511952 return this;1953 }19541955 /**1956 * Output help information and exit.1957 *1958 * Outputs built-in help, and custom text added using `.addHelpText()`.1959 *1960 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1961 */19621963 help(contextOptions) {1964 this.outputHelp(contextOptions);1965 let exitCode = process.exitCode || 0;1966 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1967 exitCode = 1;1968 }1969 // message: do not have all displayed text available so only passing placeholder.1970 this._exit(exitCode, 'commander.help', '(outputHelp)');1971 }19721973 /**1974 * Add additional text to be displayed with the built-in help.1975 *1976 * Position is 'before' or 'after' to affect just this command,1977 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1978 *1979 * @param {string} position - before or after built-in help1980 * @param {string | Function} text - string to add, or a function returning a string1981 * @return {Command} `this` command for chaining1982 */1983 addHelpText(position, text) {1984 const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1985 if (!allowedValues.includes(position)) {1986 throw new Error(`Unexpected value for position to addHelpText.1987Expecting one of '${allowedValues.join("', '")}'`);1988 }1989 const helpEvent = `${position}Help`;1990 this.on(helpEvent, (context) => {1991 let helpStr;1992 if (typeof text === 'function') {1993 helpStr = text({ error: context.error, command: context.command });1994 } else {1995 helpStr = text;1996 }1997 // Ignore falsy value when nothing to output.1998 if (helpStr) {1999 context.write(`${helpStr}\n`);2000 }The first 2,000 of 2,084 lines.