Skip to content
Myr

command.js

This file

Path

lib/command.js

2,160 lines · 67.9 KiB · JavaScript

Last changed by

Add implied to option value sources (#1794)John Geebefore adoption72be61c

History of this file

Take 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, DualOptions } = 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, env, cli etc41    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._summary = '';52    this._argsDescription = undefined; // legacy53    this._enablePositionalOptions = false;54    this._passThroughOptions = false;55    this._lifeCycleHooks = {}; // a hash of arrays56    /** @type {boolean | string} */57    this._showHelpAfterError = false;58    this._showSuggestionAfterError = true;5960    // see .configureOutput() for docs61    this._outputConfiguration = {62      writeOut: (str) => process.stdout.write(str),63      writeErr: (str) => process.stderr.write(str),64      getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,65      getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,66      outputError: (str, write) => write(str)67    };6869    this._hidden = false;70    this._hasHelpOption = true;71    this._helpFlags = '-h, --help';72    this._helpDescription = 'display help for command';73    this._helpShortFlag = '-h';74    this._helpLongFlag = '--help';75    this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false76    this._helpCommandName = 'help';77    this._helpCommandnameAndArgs = 'help [command]';78    this._helpCommandDescription = 'display help for command';79    this._helpConfiguration = {};80  }8182  /**83   * Copy settings that are useful to have in common across root command and subcommands.84   *85   * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)86   *87   * @param {Command} sourceCommand88   * @return {Command} `this` command for chaining89   */90  copyInheritedSettings(sourceCommand) {91    this._outputConfiguration = sourceCommand._outputConfiguration;92    this._hasHelpOption = sourceCommand._hasHelpOption;93    this._helpFlags = sourceCommand._helpFlags;94    this._helpDescription = sourceCommand._helpDescription;95    this._helpShortFlag = sourceCommand._helpShortFlag;96    this._helpLongFlag = sourceCommand._helpLongFlag;97    this._helpCommandName = sourceCommand._helpCommandName;98    this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;99    this._helpCommandDescription = sourceCommand._helpCommandDescription;100    this._helpConfiguration = sourceCommand._helpConfiguration;101    this._exitCallback = sourceCommand._exitCallback;102    this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;103    this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;104    this._allowExcessArguments = sourceCommand._allowExcessArguments;105    this._enablePositionalOptions = sourceCommand._enablePositionalOptions;106    this._showHelpAfterError = sourceCommand._showHelpAfterError;107    this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;108109    return this;110  }111112  /**113   * Define a command.114   *115   * There are two styles of command: pay attention to where to put the description.116   *117   * @example118   * // Command implemented using action handler (description is supplied separately to `.command`)119   * program120   *   .command('clone <source> [destination]')121   *   .description('clone a repository into a newly created directory')122   *   .action((source, destination) => {123   *     console.log('clone command called');124   *   });125   *126   * // Command implemented using separate executable file (description is second parameter to `.command`)127   * program128   *   .command('start <service>', 'start named service')129   *   .command('stop [service]', 'stop named service, or all if no name supplied');130   *131   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`132   * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)133   * @param {Object} [execOpts] - configuration options (for executable)134   * @return {Command} returns new command for action handler, or `this` for executable command135   */136137  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {138    let desc = actionOptsOrExecDesc;139    let opts = execOpts;140    if (typeof desc === 'object' && desc !== null) {141      opts = desc;142      desc = null;143    }144    opts = opts || {};145    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);146147    const cmd = this.createCommand(name);148    if (desc) {149      cmd.description(desc);150      cmd._executableHandler = true;151    }152    if (opts.isDefault) this._defaultCommandName = cmd._name;153    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden154    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor155    if (args) cmd.arguments(args);156    this.commands.push(cmd);157    cmd.parent = this;158    cmd.copyInheritedSettings(this);159160    if (desc) return this;161    return cmd;162  }163164  /**165   * Factory routine to create a new unattached command.166   *167   * See .command() for creating an attached subcommand, which uses this routine to168   * create the command. You can override createCommand to customise subcommands.169   *170   * @param {string} [name]171   * @return {Command} new command172   */173174  createCommand(name) {175    return new Command(name);176  }177178  /**179   * You can customise the help with a subclass of Help by overriding createHelp,180   * or by overriding Help properties using configureHelp().181   *182   * @return {Help}183   */184185  createHelp() {186    return Object.assign(new Help(), this.configureHelp());187  }188189  /**190   * You can customise the help by overriding Help properties using configureHelp(),191   * or with a subclass of Help by overriding createHelp().192   *193   * @param {Object} [configuration] - configuration options194   * @return {Command|Object} `this` command for chaining, or stored configuration195   */196197  configureHelp(configuration) {198    if (configuration === undefined) return this._helpConfiguration;199200    this._helpConfiguration = configuration;201    return this;202  }203204  /**205   * The default output goes to stdout and stderr. You can customise this for special206   * applications. You can also customise the display of errors by overriding outputError.207   *208   * The configuration properties are all functions:209   *210   *     // functions to change where being written, stdout and stderr211   *     writeOut(str)212   *     writeErr(str)213   *     // matching functions to specify width for wrapping help214   *     getOutHelpWidth()215   *     getErrHelpWidth()216   *     // functions based on what is being written out217   *     outputError(str, write) // used for displaying errors, and not used for displaying help218   *219   * @param {Object} [configuration] - configuration options220   * @return {Command|Object} `this` command for chaining, or stored configuration221   */222223  configureOutput(configuration) {224    if (configuration === undefined) return this._outputConfiguration;225226    Object.assign(this._outputConfiguration, configuration);227    return this;228  }229230  /**231   * Display the help or a custom message after an error occurs.232   *233   * @param {boolean|string} [displayHelp]234   * @return {Command} `this` command for chaining235   */236  showHelpAfterError(displayHelp = true) {237    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;238    this._showHelpAfterError = displayHelp;239    return this;240  }241242  /**243   * Display suggestion of similar commands for unknown commands, or options for unknown options.244   *245   * @param {boolean} [displaySuggestion]246   * @return {Command} `this` command for chaining247   */248  showSuggestionAfterError(displaySuggestion = true) {249    this._showSuggestionAfterError = !!displaySuggestion;250    return this;251  }252253  /**254   * Add a prepared subcommand.255   *256   * See .command() for creating an attached subcommand which inherits settings from its parent.257   *258   * @param {Command} cmd - new subcommand259   * @param {Object} [opts] - configuration options260   * @return {Command} `this` command for chaining261   */262263  addCommand(cmd, opts) {264    if (!cmd._name) {265      throw new Error(`Command passed to .addCommand() must have a name266- specify the name in Command constructor or using .name()`);267    }268269    opts = opts || {};270    if (opts.isDefault) this._defaultCommandName = cmd._name;271    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation272273    this.commands.push(cmd);274    cmd.parent = this;275    return this;276  }277278  /**279   * Factory routine to create a new unattached argument.280   *281   * See .argument() for creating an attached argument, which uses this routine to282   * create the argument. You can override createArgument to return a custom argument.283   *284   * @param {string} name285   * @param {string} [description]286   * @return {Argument} new argument287   */288289  createArgument(name, description) {290    return new Argument(name, description);291  }292293  /**294   * Define argument syntax for command.295   *296   * The default is that the argument is required, and you can explicitly297   * indicate this with <> around the name. Put [] around the name for an optional argument.298   *299   * @example300   * program.argument('<input-file>');301   * program.argument('[output-file]');302   *303   * @param {string} name304   * @param {string} [description]305   * @param {Function|*} [fn] - custom argument processing function306   * @param {*} [defaultValue]307   * @return {Command} `this` command for chaining308   */309  argument(name, description, fn, defaultValue) {310    const argument = this.createArgument(name, description);311    if (typeof fn === 'function') {312      argument.default(defaultValue).argParser(fn);313    } else {314      argument.default(fn);315    }316    this.addArgument(argument);317    return this;318  }319320  /**321   * Define argument syntax for command, adding multiple at once (without descriptions).322   *323   * See also .argument().324   *325   * @example326   * program.arguments('<cmd> [env]');327   *328   * @param {string} names329   * @return {Command} `this` command for chaining330   */331332  arguments(names) {333    names.split(/ +/).forEach((detail) => {334      this.argument(detail);335    });336    return this;337  }338339  /**340   * Define argument syntax for command, adding a prepared argument.341   *342   * @param {Argument} argument343   * @return {Command} `this` command for chaining344   */345  addArgument(argument) {346    const previousArgument = this._args.slice(-1)[0];347    if (previousArgument && previousArgument.variadic) {348      throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);349    }350    if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {351      throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);352    }353    this._args.push(argument);354    return this;355  }356357  /**358   * Override default decision whether to add implicit help command.359   *360   *    addHelpCommand() // force on361   *    addHelpCommand(false); // force off362   *    addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details363   *364   * @return {Command} `this` command for chaining365   */366367  addHelpCommand(enableOrNameAndArgs, description) {368    if (enableOrNameAndArgs === false) {369      this._addImplicitHelpCommand = false;370    } else {371      this._addImplicitHelpCommand = true;372      if (typeof enableOrNameAndArgs === 'string') {373        this._helpCommandName = enableOrNameAndArgs.split(' ')[0];374        this._helpCommandnameAndArgs = enableOrNameAndArgs;375      }376      this._helpCommandDescription = description || this._helpCommandDescription;377    }378    return this;379  }380381  /**382   * @return {boolean}383   * @api private384   */385386  _hasImplicitHelpCommand() {387    if (this._addImplicitHelpCommand === undefined) {388      return this.commands.length && !this._actionHandler && !this._findCommand('help');389    }390    return this._addImplicitHelpCommand;391  }392393  /**394   * Add hook for life cycle event.395   *396   * @param {string} event397   * @param {Function} listener398   * @return {Command} `this` command for chaining399   */400401  hook(event, listener) {402    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];403    if (!allowedValues.includes(event)) {404      throw new Error(`Unexpected value for event passed to hook : '${event}'.405Expecting one of '${allowedValues.join("', '")}'`);406    }407    if (this._lifeCycleHooks[event]) {408      this._lifeCycleHooks[event].push(listener);409    } else {410      this._lifeCycleHooks[event] = [listener];411    }412    return this;413  }414415  /**416   * Register callback to use as replacement for calling process.exit.417   *418   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing419   * @return {Command} `this` command for chaining420   */421422  exitOverride(fn) {423    if (fn) {424      this._exitCallback = fn;425    } else {426      this._exitCallback = (err) => {427        if (err.code !== 'commander.executeSubCommandAsync') {428          throw err;429        } else {430          // Async callback from spawn events, not useful to throw.431        }432      };433    }434    return this;435  }436437  /**438   * Call process.exit, and _exitCallback if defined.439   *440   * @param {number} exitCode exit code for using with process.exit441   * @param {string} code an id string representing the error442   * @param {string} message human-readable description of the error443   * @return never444   * @api private445   */446447  _exit(exitCode, code, message) {448    if (this._exitCallback) {449      this._exitCallback(new CommanderError(exitCode, code, message));450      // Expecting this line is not reached.451    }452    process.exit(exitCode);453  }454455  /**456   * Register callback `fn` for the command.457   *458   * @example459   * program460   *   .command('serve')461   *   .description('start service')462   *   .action(function() {463   *      // do work here464   *   });465   *466   * @param {Function} fn467   * @return {Command} `this` command for chaining468   */469470  action(fn) {471    const listener = (args) => {472      // The .action callback takes an extra parameter which is the command or options.473      const expectedArgsCount = this._args.length;474      const actionArgs = args.slice(0, expectedArgsCount);475      if (this._storeOptionsAsProperties) {476        actionArgs[expectedArgsCount] = this; // backwards compatible "options"477      } else {478        actionArgs[expectedArgsCount] = this.opts();479      }480      actionArgs.push(this);481482      return fn.apply(this, actionArgs);483    };484    this._actionHandler = listener;485    return this;486  }487488  /**489   * Factory routine to create a new unattached option.490   *491   * See .option() for creating an attached option, which uses this routine to492   * create the option. You can override createOption to return a custom option.493   *494   * @param {string} flags495   * @param {string} [description]496   * @return {Option} new option497   */498499  createOption(flags, description) {500    return new Option(flags, description);501  }502503  /**504   * Add an option.505   *506   * @param {Option} option507   * @return {Command} `this` command for chaining508   */509  addOption(option) {510    const oname = option.name();511    const name = option.attributeName();512513    // store default value514    if (option.negate) {515      // --no-foo is special and defaults foo to true, unless a --foo option is already defined516      const positiveLongFlag = option.long.replace(/^--no-/, '--');517      if (!this._findOption(positiveLongFlag)) {518        this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');519      }520    } else if (option.defaultValue !== undefined) {521      this.setOptionValueWithSource(name, option.defaultValue, 'default');522    }523524    // register the option525    this.options.push(option);526527    // handler for cli and env supplied values528    const handleOptionValue = (val, invalidValueMessage, valueSource) => {529      // val is null for optional option used without an optional-argument.530      // val is undefined for boolean and negated option.531      if (val == null && option.presetArg !== undefined) {532        val = option.presetArg;533      }534535      // custom processing536      const oldValue = this.getOptionValue(name);537      if (val !== null && option.parseArg) {538        try {539          val = option.parseArg(val, oldValue);540        } catch (err) {541          if (err.code === 'commander.invalidArgument') {542            const message = `${invalidValueMessage} ${err.message}`;543            this.error(message, { exitCode: err.exitCode, code: err.code });544          }545          throw err;546        }547      } else if (val !== null && option.variadic) {548        val = option._concatValue(val, oldValue);549      }550551      // Fill-in appropriate missing values. Long winded but easy to follow.552      if (val == null) {553        if (option.negate) {554          val = false;555        } else if (option.isBoolean() || option.optional) {556          val = true;557        } else {558          val = ''; // not normal, parseArg might have failed or be a mock function for testing559        }560      }561      this.setOptionValueWithSource(name, val, valueSource);562    };563564    this.on('option:' + oname, (val) => {565      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;566      handleOptionValue(val, invalidValueMessage, 'cli');567    });568569    if (option.envVar) {570      this.on('optionEnv:' + oname, (val) => {571        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;572        handleOptionValue(val, invalidValueMessage, 'env');573      });574    }575576    return this;577  }578579  /**580   * Internal implementation shared by .option() and .requiredOption()581   *582   * @api private583   */584  _optionEx(config, flags, description, fn, defaultValue) {585    if (typeof flags === 'object' && flags instanceof Option) {586      throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');587    }588    const option = this.createOption(flags, description);589    option.makeOptionMandatory(!!config.mandatory);590    if (typeof fn === 'function') {591      option.default(defaultValue).argParser(fn);592    } else if (fn instanceof RegExp) {593      // deprecated594      const regex = fn;595      fn = (val, def) => {596        const m = regex.exec(val);597        return m ? m[0] : def;598      };599      option.default(defaultValue).argParser(fn);600    } else {601      option.default(fn);602    }603604    return this.addOption(option);605  }606607  /**608   * Define option with `flags`, `description` and optional609   * coercion `fn`.610   *611   * The `flags` string contains the short and/or long flags,612   * separated by comma, a pipe or space. The following are all valid613   * all will output this way when `--help` is used.614   *615   *     "-p, --pepper"616   *     "-p|--pepper"617   *     "-p --pepper"618   *619   * @example620   * // simple boolean defaulting to undefined621   * program.option('-p, --pepper', 'add pepper');622   *623   * program.pepper624   * // => undefined625   *626   * --pepper627   * program.pepper628   * // => true629   *630   * // simple boolean defaulting to true (unless non-negated option is also defined)631   * program.option('-C, --no-cheese', 'remove cheese');632   *633   * program.cheese634   * // => true635   *636   * --no-cheese637   * program.cheese638   * // => false639   *640   * // required argument641   * program.option('-C, --chdir <path>', 'change the working directory');642   *643   * --chdir /tmp644   * program.chdir645   * // => "/tmp"646   *647   * // optional argument648   * program.option('-c, --cheese [type]', 'add cheese [marble]');649   *650   * @param {string} flags651   * @param {string} [description]652   * @param {Function|*} [fn] - custom option processing function or default value653   * @param {*} [defaultValue]654   * @return {Command} `this` command for chaining655   */656657  option(flags, description, fn, defaultValue) {658    return this._optionEx({}, flags, description, fn, defaultValue);659  }660661  /**662  * Add a required option which must have a value after parsing. This usually means663  * the option must be specified on the command line. (Otherwise the same as .option().)664  *665  * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.666  *667  * @param {string} flags668  * @param {string} [description]669  * @param {Function|*} [fn] - custom option processing function or default value670  * @param {*} [defaultValue]671  * @return {Command} `this` command for chaining672  */673674  requiredOption(flags, description, fn, defaultValue) {675    return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);676  }677678  /**679   * Alter parsing of short flags with optional values.680   *681   * @example682   * // for `.option('-f,--flag [value]'):683   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour684   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`685   *686   * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.687   */688  combineFlagAndOptionalValue(combine = true) {689    this._combineFlagAndOptionalValue = !!combine;690    return this;691  }692693  /**694   * Allow unknown options on the command line.695   *696   * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown697   * for unknown options.698   */699  allowUnknownOption(allowUnknown = true) {700    this._allowUnknownOption = !!allowUnknown;701    return this;702  }703704  /**705   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.706   *707   * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown708   * for excess arguments.709   */710  allowExcessArguments(allowExcess = true) {711    this._allowExcessArguments = !!allowExcess;712    return this;713  }714715  /**716   * Enable positional options. Positional means global options are specified before subcommands which lets717   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.718   * The default behaviour is non-positional and global options may appear anywhere on the command line.719   *720   * @param {Boolean} [positional=true]721   */722  enablePositionalOptions(positional = true) {723    this._enablePositionalOptions = !!positional;724    return this;725  }726727  /**728   * Pass through options that come after command-arguments rather than treat them as command-options,729   * so actual command-options come before command-arguments. Turning this on for a subcommand requires730   * positional options to have been enabled on the program (parent commands).731   * The default behaviour is non-positional and options may appear before or after command-arguments.732   *733   * @param {Boolean} [passThrough=true]734   * for unknown options.735   */736  passThroughOptions(passThrough = true) {737    this._passThroughOptions = !!passThrough;738    if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {739      throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');740    }741    return this;742  }743744  /**745    * Whether to store option values as properties on command object,746    * or store separately (specify false). In both cases the option values can be accessed using .opts().747    *748    * @param {boolean} [storeAsProperties=true]749    * @return {Command} `this` command for chaining750    */751752  storeOptionsAsProperties(storeAsProperties = true) {753    this._storeOptionsAsProperties = !!storeAsProperties;754    if (this.options.length) {755      throw new Error('call .storeOptionsAsProperties() before adding options');756    }757    return this;758  }759760  /**761   * Retrieve option value.762   *763   * @param {string} key764   * @return {Object} value765   */766767  getOptionValue(key) {768    if (this._storeOptionsAsProperties) {769      return this[key];770    }771    return this._optionValues[key];772  }773774  /**775   * Store option value.776   *777   * @param {string} key778   * @param {Object} value779   * @return {Command} `this` command for chaining780   */781782  setOptionValue(key, value) {783    return this.setOptionValueWithSource(key, value, undefined);784  }785786  /**787    * Store option value and where the value came from.788    *789    * @param {string} key790    * @param {Object} value791    * @param {string} source - expected values are default/config/env/cli/implied792    * @return {Command} `this` command for chaining793    */794795  setOptionValueWithSource(key, value, source) {796    if (this._storeOptionsAsProperties) {797      this[key] = value;798    } else {799      this._optionValues[key] = value;800    }801    this._optionValueSources[key] = source;802    return this;803  }804805  /**806    * Get source of option value.807    * Expected values are default | config | env | cli | implied808    *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();949    this._checkForConflictingOptions();950951    // executableFile and executableDir might be full path, or just a name952    let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;953    let executableDir = this._executableDir || '';954    if (this._scriptPath) {955      let resolvedScriptPath; // resolve possible symlink for installed npm binary956      try {957        resolvedScriptPath = fs.realpathSync(this._scriptPath);958      } catch (err) {959        resolvedScriptPath = this._scriptPath;960      }961      executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);962    }963964    // Look for a local file in preference to a command in PATH.965    if (executableDir) {966      let localFile = findFile(executableDir, executableFile);967968      // Legacy search using prefix of script name instead of command name969      if (!localFile && !subcommand._executableFile && this._scriptPath) {970        const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));971        if (legacyName !== this._name) {972          localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);973        }974      }975      executableFile = localFile || executableFile;976    }977978    launchWithNode = sourceExt.includes(path.extname(executableFile));979980    let proc;981    if (process.platform !== 'win32') {982      if (launchWithNode) {983        args.unshift(executableFile);984        // add executable arguments to spawn985        args = incrementNodeInspectorPort(process.execArgv).concat(args);986987        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });988      } else {989        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });990      }991    } else {992      args.unshift(executableFile);993      // add executable arguments to spawn994      args = incrementNodeInspectorPort(process.execArgv).concat(args);995      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });996    }997998    if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn999      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1000      signals.forEach((signal) => {1001        // @ts-ignore1002        process.on(signal, () => {1003          if (proc.killed === false && proc.exitCode === null) {1004            proc.kill(signal);1005          }1006        });1007      });1008    }10091010    // By default terminate process when spawned process terminates.1011    // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1012    const exitCallback = this._exitCallback;1013    if (!exitCallback) {1014      proc.on('close', process.exit.bind(process));1015    } else {1016      proc.on('close', () => {1017        exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1018      });1019    }1020    proc.on('error', (err) => {1021      // @ts-ignore1022      if (err.code === 'ENOENT') {1023        const executableDirMessage = executableDir1024          ? `searched for local subcommand relative to directory '${executableDir}'`1025          : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1026        const executableMissing = `'${executableFile}' does not exist1027 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1028 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1029 - ${executableDirMessage}`;1030        throw new Error(executableMissing);1031      // @ts-ignore1032      } else if (err.code === 'EACCES') {1033        throw new Error(`'${executableFile}' not executable`);1034      }1035      if (!exitCallback) {1036        process.exit(1);1037      } else {1038        const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1039        wrappedError.nestedError = err;1040        exitCallback(wrappedError);1041      }1042    });10431044    // Store the reference to the child process1045    this.runningCommand = proc;1046  }10471048  /**1049   * @api private1050   */10511052  _dispatchSubcommand(commandName, operands, unknown) {1053    const subCommand = this._findCommand(commandName);1054    if (!subCommand) this.help({ error: true });10551056    let hookResult;1057    hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, 'preSubcommand');1058    hookResult = this._chainOrCall(hookResult, () => {1059      if (subCommand._executableHandler) {1060        this._executeSubCommand(subCommand, operands.concat(unknown));1061      } else {1062        return subCommand._parseCommand(operands, unknown);1063      }1064    });1065    return hookResult;1066  }10671068  /**1069   * Check this.args against expected this._args.1070   *1071   * @api private1072   */10731074  _checkNumberOfArguments() {1075    // too few1076    this._args.forEach((arg, i) => {1077      if (arg.required && this.args[i] == null) {1078        this.missingArgument(arg.name());1079      }1080    });1081    // too many1082    if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {1083      return;1084    }1085    if (this.args.length > this._args.length) {1086      this._excessArguments(this.args);1087    }1088  }10891090  /**1091   * Process this.args using this._args and save as this.processedArgs!1092   *1093   * @api private1094   */10951096  _processArguments() {1097    const myParseArg = (argument, value, previous) => {1098      // Extra processing for nice error message on parsing failure.1099      let parsedValue = value;1100      if (value !== null && argument.parseArg) {1101        try {1102          parsedValue = argument.parseArg(value, previous);1103        } catch (err) {1104          if (err.code === 'commander.invalidArgument') {1105            const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;1106            this.error(message, { exitCode: err.exitCode, code: err.code });1107          }1108          throw err;1109        }1110      }1111      return parsedValue;1112    };11131114    this._checkNumberOfArguments();11151116    const processedArgs = [];1117    this._args.forEach((declaredArg, index) => {1118      let value = declaredArg.defaultValue;1119      if (declaredArg.variadic) {1120        // Collect together remaining arguments for passing together as an array.1121        if (index < this.args.length) {1122          value = this.args.slice(index);1123          if (declaredArg.parseArg) {1124            value = value.reduce((processed, v) => {1125              return myParseArg(declaredArg, v, processed);1126            }, declaredArg.defaultValue);1127          }1128        } else if (value === undefined) {1129          value = [];1130        }1131      } else if (index < this.args.length) {1132        value = this.args[index];1133        if (declaredArg.parseArg) {1134          value = myParseArg(declaredArg, value, declaredArg.defaultValue);1135        }1136      }1137      processedArgs[index] = value;1138    });1139    this.processedArgs = processedArgs;1140  }11411142  /**1143   * Once we have a promise we chain, but call synchronously until then.1144   *1145   * @param {Promise|undefined} promise1146   * @param {Function} fn1147   * @return {Promise|undefined}1148   * @api private1149   */11501151  _chainOrCall(promise, fn) {1152    // thenable1153    if (promise && promise.then && typeof promise.then === 'function') {1154      // already have a promise, chain callback1155      return promise.then(() => fn());1156    }1157    // callback might return a promise1158    return fn();1159  }11601161  /**1162   *1163   * @param {Promise|undefined} promise1164   * @param {string} event1165   * @return {Promise|undefined}1166   * @api private1167   */11681169  _chainOrCallHooks(promise, event) {1170    let result = promise;1171    const hooks = [];1172    getCommandAndParents(this)1173      .reverse()1174      .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1175      .forEach(hookedCommand => {1176        hookedCommand._lifeCycleHooks[event].forEach((callback) => {1177          hooks.push({ hookedCommand, callback });1178        });1179      });1180    if (event === 'postAction') {1181      hooks.reverse();1182    }11831184    hooks.forEach((hookDetail) => {1185      result = this._chainOrCall(result, () => {1186        return hookDetail.callback(hookDetail.hookedCommand, this);1187      });1188    });1189    return result;1190  }11911192  /**1193   *1194   * @param {Promise|undefined} promise1195   * @param {Command} subCommand1196   * @param {string} event1197   * @return {Promise|undefined}1198   * @api private1199   */12001201  _chainOrCallSubCommandHook(promise, subCommand, event) {1202    let result = promise;1203    if (this._lifeCycleHooks[event] !== undefined) {1204      this._lifeCycleHooks[event].forEach((hook) => {1205        result = this._chainOrCall(result, () => {1206          return hook(this, subCommand);1207        });1208      });1209    }1210    return result;1211  }12121213  /**1214   * Process arguments in context of this command.1215   * Returns action result, in case it is a promise.1216   *1217   * @api private1218   */12191220  _parseCommand(operands, unknown) {1221    const parsed = this.parseOptions(unknown);1222    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1223    this._parseOptionsImplied();1224    operands = operands.concat(parsed.operands);1225    unknown = parsed.unknown;1226    this.args = operands.concat(unknown);12271228    if (operands && this._findCommand(operands[0])) {1229      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1230    }1231    if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1232      if (operands.length === 1) {1233        this.help();1234      }1235      return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);1236    }1237    if (this._defaultCommandName) {1238      outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1239      return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1240    }1241    if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1242      // probably missing subcommand and no handler, user needs help (and exit)1243      this.help({ error: true });1244    }12451246    outputHelpIfRequested(this, parsed.unknown);1247    this._checkForMissingMandatoryOptions();1248    this._checkForConflictingOptions();12491250    // We do not always call this check to avoid masking a "better" error, like unknown command.1251    const checkForUnknownOptions = () => {1252      if (parsed.unknown.length > 0) {1253        this.unknownOption(parsed.unknown[0]);1254      }1255    };12561257    const commandEvent = `command:${this.name()}`;1258    if (this._actionHandler) {1259      checkForUnknownOptions();1260      this._processArguments();12611262      let actionResult;1263      actionResult = this._chainOrCallHooks(actionResult, 'preAction');1264      actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));1265      if (this.parent) {1266        actionResult = this._chainOrCall(actionResult, () => {1267          this.parent.emit(commandEvent, operands, unknown); // legacy1268        });1269      }1270      actionResult = this._chainOrCallHooks(actionResult, 'postAction');1271      return actionResult;1272    }1273    if (this.parent && this.parent.listenerCount(commandEvent)) {1274      checkForUnknownOptions();1275      this._processArguments();1276      this.parent.emit(commandEvent, operands, unknown); // legacy1277    } else if (operands.length) {1278      if (this._findCommand('*')) { // legacy default command1279        return this._dispatchSubcommand('*', operands, unknown);1280      }1281      if (this.listenerCount('command:*')) {1282        // skip option check, emit event for possible misspelling suggestion1283        this.emit('command:*', operands, unknown);1284      } else if (this.commands.length) {1285        this.unknownCommand();1286      } else {1287        checkForUnknownOptions();1288        this._processArguments();1289      }1290    } else if (this.commands.length) {1291      checkForUnknownOptions();1292      // This command has subcommands and nothing hooked up at this level, so display help (and exit).1293      this.help({ error: true });1294    } else {1295      checkForUnknownOptions();1296      this._processArguments();1297      // fall through for caller to handle after calling .parse()1298    }1299  }13001301  /**1302   * Find matching command.1303   *1304   * @api private1305   */1306  _findCommand(name) {1307    if (!name) return undefined;1308    return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1309  }13101311  /**1312   * Return an option matching `arg` if any.1313   *1314   * @param {string} arg1315   * @return {Option}1316   * @api private1317   */13181319  _findOption(arg) {1320    return this.options.find(option => option.is(arg));1321  }13221323  /**1324   * Display an error message if a mandatory option does not have a value.1325   * Called after checking for help flags in leaf subcommand.1326   *1327   * @api private1328   */13291330  _checkForMissingMandatoryOptions() {1331    // Walk up hierarchy so can call in subcommand after checking for displaying help.1332    for (let cmd = this; cmd; cmd = cmd.parent) {1333      cmd.options.forEach((anOption) => {1334        if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1335          cmd.missingMandatoryOptionValue(anOption);1336        }1337      });1338    }1339  }13401341  /**1342   * Display an error message if conflicting options are used together in this.1343   *1344   * @api private1345   */1346  _checkForConflictingLocalOptions() {1347    const definedNonDefaultOptions = this.options.filter(1348      (option) => {1349        const optionKey = option.attributeName();1350        if (this.getOptionValue(optionKey) === undefined) {1351          return false;1352        }1353        return this.getOptionValueSource(optionKey) !== 'default';1354      }1355    );13561357    const optionsWithConflicting = definedNonDefaultOptions.filter(1358      (option) => option.conflictsWith.length > 01359    );13601361    optionsWithConflicting.forEach((option) => {1362      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1363        option.conflictsWith.includes(defined.attributeName())1364      );1365      if (conflictingAndDefined) {1366        this._conflictingOption(option, conflictingAndDefined);1367      }1368    });1369  }13701371  /**1372   * Display an error message if conflicting options are used together.1373   * Called after checking for help flags in leaf subcommand.1374   *1375   * @api private1376   */1377  _checkForConflictingOptions() {1378    // Walk up hierarchy so can call in subcommand after checking for displaying help.1379    for (let cmd = this; cmd; cmd = cmd.parent) {1380      cmd._checkForConflictingLocalOptions();1381    }1382  }13831384  /**1385   * Parse options from `argv` removing known options,1386   * and return argv split into operands and unknown arguments.1387   *1388   * Examples:1389   *1390   *     argv => operands, unknown1391   *     --known kkk op => [op], []1392   *     op --known kkk => [op], []1393   *     sub --unknown uuu op => [sub], [--unknown uuu op]1394   *     sub -- --unknown uuu op => [sub --unknown uuu op], []1395   *1396   * @param {String[]} argv1397   * @return {{operands: String[], unknown: String[]}}1398   */13991400  parseOptions(argv) {1401    const operands = []; // operands, not options or values1402    const unknown = []; // first unknown option and remaining unknown args1403    let dest = operands;1404    const args = argv.slice();14051406    function maybeOption(arg) {1407      return arg.length > 1 && arg[0] === '-';1408    }14091410    // parse options1411    let activeVariadicOption = null;1412    while (args.length) {1413      const arg = args.shift();14141415      // literal1416      if (arg === '--') {1417        if (dest === unknown) dest.push(arg);1418        dest.push(...args);1419        break;1420      }14211422      if (activeVariadicOption && !maybeOption(arg)) {1423        this.emit(`option:${activeVariadicOption.name()}`, arg);1424        continue;1425      }1426      activeVariadicOption = null;14271428      if (maybeOption(arg)) {1429        const option = this._findOption(arg);1430        // recognised option, call listener to assign value with possible custom processing1431        if (option) {1432          if (option.required) {1433            const value = args.shift();1434            if (value === undefined) this.optionMissingArgument(option);1435            this.emit(`option:${option.name()}`, value);1436          } else if (option.optional) {1437            let value = null;1438            // historical behaviour is optional value is following arg unless an option1439            if (args.length > 0 && !maybeOption(args[0])) {1440              value = args.shift();1441            }1442            this.emit(`option:${option.name()}`, value);1443          } else { // boolean flag1444            this.emit(`option:${option.name()}`);1445          }1446          activeVariadicOption = option.variadic ? option : null;1447          continue;1448        }1449      }14501451      // Look for combo options following single dash, eat first one if known.1452      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1453        const option = this._findOption(`-${arg[1]}`);1454        if (option) {1455          if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1456            // option with value following in same argument1457            this.emit(`option:${option.name()}`, arg.slice(2));1458          } else {1459            // boolean option, emit and put back remainder of arg for further processing1460            this.emit(`option:${option.name()}`);1461            args.unshift(`-${arg.slice(2)}`);1462          }1463          continue;1464        }1465      }14661467      // Look for known long flag with value, like --foo=bar1468      if (/^--[^=]+=/.test(arg)) {1469        const index = arg.indexOf('=');1470        const option = this._findOption(arg.slice(0, index));1471        if (option && (option.required || option.optional)) {1472          this.emit(`option:${option.name()}`, arg.slice(index + 1));1473          continue;1474        }1475      }14761477      // Not a recognised option by this command.1478      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.14791480      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1481      if (maybeOption(arg)) {1482        dest = unknown;1483      }14841485      // If using positionalOptions, stop processing our options at subcommand.1486      if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1487        if (this._findCommand(arg)) {1488          operands.push(arg);1489          if (args.length > 0) unknown.push(...args);1490          break;1491        } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1492          operands.push(arg);1493          if (args.length > 0) operands.push(...args);1494          break;1495        } else if (this._defaultCommandName) {1496          unknown.push(arg);1497          if (args.length > 0) unknown.push(...args);1498          break;1499        }1500      }15011502      // If using passThroughOptions, stop processing options at first command-argument.1503      if (this._passThroughOptions) {1504        dest.push(arg);1505        if (args.length > 0) dest.push(...args);1506        break;1507      }15081509      // add arg1510      dest.push(arg);1511    }15121513    return { operands, unknown };1514  }15151516  /**1517   * Return an object containing local option values as key-value pairs.1518   *1519   * @return {Object}1520   */1521  opts() {1522    if (this._storeOptionsAsProperties) {1523      // Preserve original behaviour so backwards compatible when still using properties1524      const result = {};1525      const len = this.options.length;15261527      for (let i = 0; i < len; i++) {1528        const key = this.options[i].attributeName();1529        result[key] = key === this._versionOptionName ? this._version : this[key];1530      }1531      return result;1532    }15331534    return this._optionValues;1535  }15361537  /**1538   * Return an object containing merged local and global option values as key-value pairs.1539   *1540   * @return {Object}1541   */1542  optsWithGlobals() {1543    // globals overwrite locals1544    return getCommandAndParents(this).reduce(1545      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1546      {}1547    );1548  }15491550  /**1551   * Display error message and exit (or call exitOverride).1552   *1553   * @param {string} message1554   * @param {Object} [errorOptions]1555   * @param {string} [errorOptions.code] - an id string representing the error1556   * @param {number} [errorOptions.exitCode] - used with process.exit1557   */1558  error(message, errorOptions) {1559    // output handling1560    this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1561    if (typeof this._showHelpAfterError === 'string') {1562      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1563    } else if (this._showHelpAfterError) {1564      this._outputConfiguration.writeErr('\n');1565      this.outputHelp({ error: true });1566    }15671568    // exit handling1569    const config = errorOptions || {};1570    const exitCode = config.exitCode || 1;1571    const code = config.code || 'commander.error';1572    this._exit(exitCode, code, message);1573  }15741575  /**1576   * Apply any option related environment variables, if option does1577   * not have a value from cli or client code.1578   *1579   * @api private1580   */1581  _parseOptionsEnv() {1582    this.options.forEach((option) => {1583      if (option.envVar && option.envVar in process.env) {1584        const optionKey = option.attributeName();1585        // Priority check. Do not overwrite cli or options from unknown source (client-code).1586        if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {1587          if (option.required || option.optional) { // option can take a value1588            // keep very simple, optional always takes value1589            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1590          } else { // boolean1591            // keep very simple, only care that envVar defined and not the value1592            this.emit(`optionEnv:${option.name()}`);1593          }1594        }1595      }1596    });1597  }15981599  /**1600   * Apply any implied option values, if option is undefined or default value.1601   *1602   * @api private1603   */1604  _parseOptionsImplied() {1605    const dualHelper = new DualOptions(this.options);1606    const hasCustomOptionValue = (optionKey) => {1607      return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1608    };1609    this.options1610      .filter(option => (option.implied !== undefined) &&1611        hasCustomOptionValue(option.attributeName()) &&1612        dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1613      .forEach((option) => {1614        Object.keys(option.implied)1615          .filter(impliedKey => !hasCustomOptionValue(impliedKey))1616          .forEach(impliedKey => {1617            this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1618          });1619      });1620  }16211622  /**1623   * Argument `name` is missing.1624   *1625   * @param {string} name1626   * @api private1627   */16281629  missingArgument(name) {1630    const message = `error: missing required argument '${name}'`;1631    this.error(message, { code: 'commander.missingArgument' });1632  }16331634  /**1635   * `Option` is missing an argument.1636   *1637   * @param {Option} option1638   * @api private1639   */16401641  optionMissingArgument(option) {1642    const message = `error: option '${option.flags}' argument missing`;1643    this.error(message, { code: 'commander.optionMissingArgument' });1644  }16451646  /**1647   * `Option` does not have a value, and is a mandatory option.1648   *1649   * @param {Option} option1650   * @api private1651   */16521653  missingMandatoryOptionValue(option) {1654    const message = `error: required option '${option.flags}' not specified`;1655    this.error(message, { code: 'commander.missingMandatoryOptionValue' });1656  }16571658  /**1659   * `Option` conflicts with another option.1660   *1661   * @param {Option} option1662   * @param {Option} conflictingOption1663   * @api private1664   */1665  _conflictingOption(option, conflictingOption) {1666    // The calling code does not know whether a negated option is the source of the1667    // value, so do some work to take an educated guess.1668    const findBestOptionFromValue = (option) => {1669      const optionKey = option.attributeName();1670      const optionValue = this.getOptionValue(optionKey);1671      const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1672      const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1673      if (negativeOption && (1674        (negativeOption.presetArg === undefined && optionValue === false) ||1675        (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1676      )) {1677        return negativeOption;1678      }1679      return positiveOption || option;1680    };16811682    const getErrorMessage = (option) => {1683      const bestOption = findBestOptionFromValue(option);1684      const optionKey = bestOption.attributeName();1685      const source = this.getOptionValueSource(optionKey);1686      if (source === 'env') {1687        return `environment variable '${bestOption.envVar}'`;1688      }1689      return `option '${bestOption.flags}'`;1690    };16911692    const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1693    this.error(message, { code: 'commander.conflictingOption' });1694  }16951696  /**1697   * Unknown option `flag`.1698   *1699   * @param {string} flag1700   * @api private1701   */17021703  unknownOption(flag) {1704    if (this._allowUnknownOption) return;1705    let suggestion = '';17061707    if (flag.startsWith('--') && this._showSuggestionAfterError) {1708      // Looping to pick up the global options too1709      let candidateFlags = [];1710      let command = this;1711      do {1712        const moreFlags = command.createHelp().visibleOptions(command)1713          .filter(option => option.long)1714          .map(option => option.long);1715        candidateFlags = candidateFlags.concat(moreFlags);1716        command = command.parent;1717      } while (command && !command._enablePositionalOptions);1718      suggestion = suggestSimilar(flag, candidateFlags);1719    }17201721    const message = `error: unknown option '${flag}'${suggestion}`;1722    this.error(message, { code: 'commander.unknownOption' });1723  }17241725  /**1726   * Excess arguments, more than expected.1727   *1728   * @param {string[]} receivedArgs1729   * @api private1730   */17311732  _excessArguments(receivedArgs) {1733    if (this._allowExcessArguments) return;17341735    const expected = this._args.length;1736    const s = (expected === 1) ? '' : 's';1737    const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1738    const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1739    this.error(message, { code: 'commander.excessArguments' });1740  }17411742  /**1743   * Unknown command.1744   *1745   * @api private1746   */17471748  unknownCommand() {1749    const unknownName = this.args[0];1750    let suggestion = '';17511752    if (this._showSuggestionAfterError) {1753      const candidateNames = [];1754      this.createHelp().visibleCommands(this).forEach((command) => {1755        candidateNames.push(command.name());1756        // just visible alias1757        if (command.alias()) candidateNames.push(command.alias());1758      });1759      suggestion = suggestSimilar(unknownName, candidateNames);1760    }17611762    const message = `error: unknown command '${unknownName}'${suggestion}`;1763    this.error(message, { code: 'commander.unknownCommand' });1764  }17651766  /**1767   * Set the program version to `str`.1768   *1769   * This method auto-registers the "-V, --version" flag1770   * which will print the version number when passed.1771   *1772   * You can optionally supply the  flags and description to override the defaults.1773   *1774   * @param {string} str1775   * @param {string} [flags]1776   * @param {string} [description]1777   * @return {this | string} `this` command for chaining, or version string if no arguments1778   */17791780  version(str, flags, description) {1781    if (str === undefined) return this._version;1782    this._version = str;1783    flags = flags || '-V, --version';1784    description = description || 'output the version number';1785    const versionOption = this.createOption(flags, description);1786    this._versionOptionName = versionOption.attributeName();1787    this.options.push(versionOption);1788    this.on('option:' + versionOption.name(), () => {1789      this._outputConfiguration.writeOut(`${str}\n`);1790      this._exit(0, 'commander.version', str);1791    });1792    return this;1793  }17941795  /**1796   * Set the description.1797   *1798   * @param {string} [str]1799   * @param {Object} [argsDescription]1800   * @return {string|Command}1801   */1802  description(str, argsDescription) {1803    if (str === undefined && argsDescription === undefined) return this._description;1804    this._description = str;1805    if (argsDescription) {1806      this._argsDescription = argsDescription;1807    }1808    return this;1809  }18101811  /**1812   * Set the summary. Used when listed as subcommand of parent.1813   *1814   * @param {string} [str]1815   * @return {string|Command}1816   */1817  summary(str) {1818    if (str === undefined) return this._summary;1819    this._summary = str;1820    return this;1821  }18221823  /**1824   * Set an alias for the command.1825   *1826   * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1827   *1828   * @param {string} [alias]1829   * @return {string|Command}1830   */18311832  alias(alias) {1833    if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility18341835    /** @type {Command} */1836    let command = this;1837    if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1838      // assume adding alias for last added executable subcommand, rather than this1839      command = this.commands[this.commands.length - 1];1840    }18411842    if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');18431844    command._aliases.push(alias);1845    return this;1846  }18471848  /**1849   * Set aliases for the command.1850   *1851   * Only the first alias is shown in the auto-generated help.1852   *1853   * @param {string[]} [aliases]1854   * @return {string[]|Command}1855   */18561857  aliases(aliases) {1858    // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1859    if (aliases === undefined) return this._aliases;18601861    aliases.forEach((alias) => this.alias(alias));1862    return this;1863  }18641865  /**1866   * Set / get the command usage `str`.1867   *1868   * @param {string} [str]1869   * @return {String|Command}1870   */18711872  usage(str) {1873    if (str === undefined) {1874      if (this._usage) return this._usage;18751876      const args = this._args.map((arg) => {1877        return humanReadableArgName(arg);1878      });1879      return [].concat(1880        (this.options.length || this._hasHelpOption ? '[options]' : []),1881        (this.commands.length ? '[command]' : []),1882        (this._args.length ? args : [])1883      ).join(' ');1884    }18851886    this._usage = str;1887    return this;1888  }18891890  /**1891   * Get or set the name of the command.1892   *1893   * @param {string} [str]1894   * @return {string|Command}1895   */18961897  name(str) {1898    if (str === undefined) return this._name;1899    this._name = str;1900    return this;1901  }19021903  /**1904   * Set the name of the command from script filename, such as process.argv[1],1905   * or require.main.filename, or __filename.1906   *1907   * (Used internally and public although not documented in README.)1908   *1909   * @example1910   * program.nameFromFilename(require.main.filename);1911   *1912   * @param {string} filename1913   * @return {Command}1914   */19151916  nameFromFilename(filename) {1917    this._name = path.basename(filename, path.extname(filename));19181919    return this;1920  }19211922  /**1923   * Get or set the directory for searching for executable subcommands of this command.1924   *1925   * @example1926   * program.executableDir(__dirname);1927   * // or1928   * program.executableDir('subcommands');1929   *1930   * @param {string} [path]1931   * @return {string|Command}1932   */19331934  executableDir(path) {1935    if (path === undefined) return this._executableDir;1936    this._executableDir = path;1937    return this;1938  }19391940  /**1941   * Return program help documentation.1942   *1943   * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1944   * @return {string}1945   */19461947  helpInformation(contextOptions) {1948    const helper = this.createHelp();1949    if (helper.helpWidth === undefined) {1950      helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1951    }1952    return helper.formatHelp(this, helper);1953  }19541955  /**1956   * @api private1957   */19581959  _getHelpContext(contextOptions) {1960    contextOptions = contextOptions || {};1961    const context = { error: !!contextOptions.error };1962    let write;1963    if (context.error) {1964      write = (arg) => this._outputConfiguration.writeErr(arg);1965    } else {1966      write = (arg) => this._outputConfiguration.writeOut(arg);1967    }1968    context.write = contextOptions.write || write;1969    context.command = this;1970    return context;1971  }19721973  /**1974   * Output help information for this command.1975   *1976   * Outputs built-in help, and custom text added using `.addHelpText()`.1977   *1978   * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1979   */19801981  outputHelp(contextOptions) {1982    let deprecatedCallback;1983    if (typeof contextOptions === 'function') {1984      deprecatedCallback = contextOptions;1985      contextOptions = undefined;1986    }1987    const context = this._getHelpContext(contextOptions);19881989    getCommandAndParents(this).reverse().forEach(command => command.emit('beforeAllHelp', context));1990    this.emit('beforeHelp', context);19911992    let helpInformation = this.helpInformation(context);1993    if (deprecatedCallback) {1994      helpInformation = deprecatedCallback(helpInformation);1995      if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1996        throw new Error('outputHelp callback must return a string or a Buffer');1997      }1998    }1999    context.write(helpInformation);2000

The first 2,000 of 2,160 lines.