command.js
This file
Path
lib/command.js
2,662 lines · 81.8 KiB · JavaScript
Last changed by
Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
History of this fileTake it
The walk stopped after 200 commits: lines older than 43f4743 point at it.
Fix: Use `node`-prefixed requires for builtins (#2170)Sam Gammonbefore adoptionf7b8475
lines 1–5why, one step back1const EventEmitter = require('node:events').EventEmitter;2const childProcess = require('node:child_process');3const path = require('node:path');4const fs = require('node:fs');5const process = require('node:process');Fix dateJohn Geebefore adoption43f4743
lines 6–8why, one step back67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 9why, one step back9const { Help, stripColor } = require('./help.js');Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 10why, one step back10const { Option, DualOptions } = require('./option.js');Fix dateJohn Geebefore adoption43f4743
lines 11–27why, one step back11const { suggestSimilar } = require('./suggestSimilar');1213class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();22 /** @type {Command[]} */23 this.commands = [];24 /** @type {Option[]} */25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;Disallow excess arguments (#2223)John Geebefore adoption58c28eb
line 28why, one step back28 this._allowExcessArguments = false;Fix dateJohn Geebefore adoption43f4743
line 29why, one step back29 /** @type {Argument[]} */Add public Arguments property (#2010)John Geebefore adoption7d23437
lines 30–31why, one step back30 this.registeredArguments = [];31 this._args = this.registeredArguments; // deprecated old nameFix dateJohn Geebefore adoption43f4743
lines 32–38why, one step back32 /** @type {string[]} */33 this.args = []; // cli args with options removed34 this.rawArgs = [];35 this.processedArgs = []; // like .args but after custom processing and collecting variadic36 this._scriptPath = null;37 this._name = name || '';38 this._optionValues = {};Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 39why, one step back39 this._optionValueSources = {}; // default, env, cli etcFix dateJohn Geebefore adoption43f4743
lines 40–43why, one step back40 this._storeOptionsAsProperties = false;41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executableMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 44why, one step back44 this._executableDir = null; // custom search directory for subcommandsFix dateJohn Geebefore adoption43f4743
lines 45–49why, one step back45 this._defaultCommandName = null;46 this._exitCallback = null;47 this._aliases = [];48 this._combineFlagAndOptionalValue = true;49 this._description = '';Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 50why, one step back50 this._summary = '';Fix dateJohn Geebefore adoption43f4743
lines 51–54why, one step back51 this._argsDescription = undefined; // legacy52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arraysMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 55why, one step back55 /** @type {(boolean | string)} */Fix dateJohn Geebefore adoption43f4743
line 56why, one step back56 this._showHelpAfterError = false;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 57why, one step back57 this._showSuggestionAfterError = true;Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 58why, one step back58 this._savedState = null; // used in save/restoreStateBeforeParseFix dateJohn Geebefore adoption43f4743
line 59why, one step back59Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 60why, one step back60 // see configureOutput() for docsFix dateJohn Geebefore adoption43f4743
lines 61–63why, one step back61 this._outputConfiguration = {62 writeOut: (str) => process.stdout.write(str),63 writeErr: (str) => process.stderr.write(str),Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 64why, one step back64 outputError: (str, write) => write(str),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 65–68why, one step back65 getOutHelpWidth: () =>66 process.stdout.isTTY ? process.stdout.columns : undefined,67 getErrHelpWidth: () =>68 process.stderr.isTTY ? process.stderr.columns : undefined,Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 69–73why, one step back69 getOutHasColors: () =>70 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),71 getErrHasColors: () =>72 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),73 stripColor: (str) => stripColor(str),Fix dateJohn Geebefore adoption43f4743
lines 74–76why, one step back74 };7576 this._hidden = false;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 77–81why, one step back77 /** @type {(Option | null | undefined)} */78 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.79 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited80 /** @type {Command} */81 this._helpCommand = undefined; // lazy initialised, inheritedFix dateJohn Geebefore adoption43f4743
lines 82–90why, one step back82 this._helpConfiguration = {};83 }8485 /**86 * Copy settings that are useful to have in common across root command and subcommands.87 *88 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)89 *90 * @param {Command} sourceCommandMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 91why, one step back91 * @return {Command} `this` command for chainingFix dateJohn Geebefore adoption43f4743
lines 92–94why, one step back92 */93 copyInheritedSettings(sourceCommand) {94 this._outputConfiguration = sourceCommand._outputConfiguration;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 95–96why, one step back95 this._helpOption = sourceCommand._helpOption;96 this._helpCommand = sourceCommand._helpCommand;Fix dateJohn Geebefore adoption43f4743
lines 97–99why, one step back97 this._helpConfiguration = sourceCommand._helpConfiguration;98 this._exitCallback = sourceCommand._exitCallback;99 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 100–101why, one step back100 this._combineFlagAndOptionalValue =101 sourceCommand._combineFlagAndOptionalValue;Fix dateJohn Geebefore adoption43f4743
lines 102–110why, one step back102 this._allowExcessArguments = sourceCommand._allowExcessArguments;103 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;104 this._showHelpAfterError = sourceCommand._showHelpAfterError;105 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;106107 return this;108 }109110 /**Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 111why, one step back111 * @returns {Command[]}Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 112why, one step back112 * @privateIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 113–116why, one step back113 */114115 _getCommandAndAncestors() {116 const result = [];ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 117why, one step back117 // eslint-disable-next-line @typescript-eslint/no-this-aliasIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 118–124why, one step back118 for (let command = this; command; command = command.parent) {119 result.push(command);120 }121 return result;122 }123124 /**Fix dateJohn Geebefore adoption43f4743
lines 125–143why, one step back125 * Define a command.126 *127 * There are two styles of command: pay attention to where to put the description.128 *129 * @example130 * // Command implemented using action handler (description is supplied separately to `.command`)131 * program132 * .command('clone <source> [destination]')133 * .description('clone a repository into a newly created directory')134 * .action((source, destination) => {135 * console.log('clone command called');136 * });137 *138 * // Command implemented using separate executable file (description is second parameter to `.command`)139 * program140 * .command('start <service>', 'start named service')141 * .command('stop [service]', 'stop named service, or all if no name supplied');142 *143 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 144–145why, one step back144 * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)145 * @param {object} [execOpts] - configuration options (for executable)Fix dateJohn Geebefore adoption43f4743
lines 146–167why, one step back146 * @return {Command} returns new command for action handler, or `this` for executable command147 */148149 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {150 let desc = actionOptsOrExecDesc;151 let opts = execOpts;152 if (typeof desc === 'object' && desc !== null) {153 opts = desc;154 desc = null;155 }156 opts = opts || {};157 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);158159 const cmd = this.createCommand(name);160 if (desc) {161 cmd.description(desc);162 cmd._executableHandler = true;163 }164 if (opts.isDefault) this._defaultCommandName = cmd._name;165 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden166 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor167 if (args) cmd.arguments(args);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 168why, one step back168 this._registerCommand(cmd);Fix dateJohn Geebefore adoption43f4743
lines 169–173why, one step back169 cmd.parent = this;170 cmd.copyInheritedSettings(this);171172 if (desc) return this;173 return cmd;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 174why, one step back174 }Fix dateJohn Geebefore adoption43f4743
lines 175–187why, one step back175176 /**177 * Factory routine to create a new unattached command.178 *179 * See .command() for creating an attached subcommand, which uses this routine to180 * create the command. You can override createCommand to customise subcommands.181 *182 * @param {string} [name]183 * @return {Command} new command184 */185186 createCommand(name) {187 return new Command(name);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 188why, one step back188 }Fix dateJohn Geebefore adoption43f4743
lines 189–198why, one step back189190 /**191 * You can customise the help with a subclass of Help by overriding createHelp,192 * or by overriding Help properties using configureHelp().193 *194 * @return {Help}195 */196197 createHelp() {198 return Object.assign(new Help(), this.configureHelp());Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 199why, one step back199 }Fix dateJohn Geebefore adoption43f4743
lines 200–204why, one step back200201 /**202 * You can customise the help by overriding Help properties using configureHelp(),203 * or with a subclass of Help by overriding createHelp().204 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 205–206why, one step back205 * @param {object} [configuration] - configuration options206 * @return {(Command | object)} `this` command for chaining, or stored configurationFix dateJohn Geebefore adoption43f4743
lines 207–221why, one step back207 */208209 configureHelp(configuration) {210 if (configuration === undefined) return this._helpConfiguration;211212 this._helpConfiguration = configuration;213 return this;214 }215216 /**217 * The default output goes to stdout and stderr. You can customise this for special218 * applications. You can also customise the display of errors by overriding outputError.219 *220 * The configuration properties are all functions:221 *Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 222why, one step back222 * // change how output being written, defaults to stdout and stderrFix dateJohn Geebefore adoption43f4743
lines 223–224why, one step back223 * writeOut(str)224 * writeErr(str)Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 225–227why, one step back225 * // change how output being written for errors, defaults to writeErr226 * outputError(str, write) // used for displaying errors and not used for displaying help227 * // specify width for wrapping helpFix dateJohn Geebefore adoption43f4743
lines 228–229why, one step back228 * getOutHelpWidth()229 * getErrHelpWidth()Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 230–232why, one step back230 * // color support, currently only used with Help231 * getOutHasColors()232 * getErrHasColors()Prepare for 13.0.0-0 (#2292)John Geebefore adoption53fc8a4
line 233why, one step back233 * stripColor() // used to remove ANSI escape codes if output does not have colorsFix dateJohn Geebefore adoption43f4743
line 234why, one step back234 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 235–236why, one step back235 * @param {object} [configuration] - configuration options236 * @return {(Command | object)} `this` command for chaining, or stored configurationFix dateJohn Geebefore adoption43f4743
lines 237–248why, one step back237 */238239 configureOutput(configuration) {240 if (configuration === undefined) return this._outputConfiguration;241242 Object.assign(this._outputConfiguration, configuration);243 return this;244 }245246 /**247 * Display the help or a custom message after an error occurs.248 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 249why, one step back249 * @param {(boolean|string)} [displayHelp]Fix dateJohn Geebefore adoption43f4743
lines 250–274why, one step back250 * @return {Command} `this` command for chaining251 */252 showHelpAfterError(displayHelp = true) {253 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;254 this._showHelpAfterError = displayHelp;255 return this;256 }257258 /**259 * Display suggestion of similar commands for unknown commands, or options for unknown options.260 *261 * @param {boolean} [displaySuggestion]262 * @return {Command} `this` command for chaining263 */264 showSuggestionAfterError(displaySuggestion = true) {265 this._showSuggestionAfterError = !!displaySuggestion;266 return this;267 }268269 /**270 * Add a prepared subcommand.271 *272 * See .command() for creating an attached subcommand which inherits settings from its parent.273 *274 * @param {Command} cmd - new subcommandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 275why, one step back275 * @param {object} [opts] - configuration optionsFix dateJohn Geebefore adoption43f4743
lines 276–279why, one step back276 * @return {Command} `this` command for chaining277 */278279 addCommand(cmd, opts) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 280–282why, one step back280 if (!cmd._name) {281 throw new Error(`Command passed to .addCommand() must have a name282- specify the name in Command constructor or using .name()`);Fix dateJohn Geebefore adoption43f4743
lines 283–288why, one step back283 }284285 opts = opts || {};286 if (opts.isDefault) this._defaultCommandName = cmd._name;287 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation288Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 289why, one step back289 this._registerCommand(cmd);Fix dateJohn Geebefore adoption43f4743
line 290why, one step back290 cmd.parent = this;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 291–292why, one step back291 cmd._checkForBrokenPassThrough();292Fix dateJohn Geebefore adoption43f4743
line 293why, one step back293 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 294why, one step back294 }Fix dateJohn Geebefore adoption43f4743
lines 295–308why, one step back295296 /**297 * Factory routine to create a new unattached argument.298 *299 * See .argument() for creating an attached argument, which uses this routine to300 * create the argument. You can override createArgument to return a custom argument.301 *302 * @param {string} name303 * @param {string} [description]304 * @return {Argument} new argument305 */306307 createArgument(name, description) {308 return new Argument(name, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 309why, one step back309 }Fix dateJohn Geebefore adoption43f4743
lines 310–322why, one step back310311 /**312 * Define argument syntax for command.313 *314 * The default is that the argument is required, and you can explicitly315 * indicate this with <> around the name. Put [] around the name for an optional argument.316 *317 * @example318 * program.argument('<input-file>');319 * program.argument('[output-file]');320 *321 * @param {string} name322 * @param {string} [description]Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 323why, one step back323 * @param {(Function|*)} [fn] - custom argument processing functionFix dateJohn Geebefore adoption43f4743
lines 324–350why, one step back324 * @param {*} [defaultValue]325 * @return {Command} `this` command for chaining326 */327 argument(name, description, fn, defaultValue) {328 const argument = this.createArgument(name, description);329 if (typeof fn === 'function') {330 argument.default(defaultValue).argParser(fn);331 } else {332 argument.default(fn);333 }334 this.addArgument(argument);335 return this;336 }337338 /**339 * Define argument syntax for command, adding multiple at once (without descriptions).340 *341 * See also .argument().342 *343 * @example344 * program.arguments('<cmd> [env]');345 *346 * @param {string} names347 * @return {Command} `this` command for chaining348 */349350 arguments(names) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 351–356why, one step back351 names352 .trim()353 .split(/ +/)354 .forEach((detail) => {355 this.argument(detail);356 });Fix dateJohn Geebefore adoption43f4743
line 357why, one step back357 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 358why, one step back358 }Fix dateJohn Geebefore adoption43f4743
lines 359–366why, one step back359360 /**361 * Define argument syntax for command, adding a prepared argument.362 *363 * @param {Argument} argument364 * @return {Command} `this` command for chaining365 */366 addArgument(argument) {Add public Arguments property (#2010)John Geebefore adoption7d23437
line 367why, one step back367 const previousArgument = this.registeredArguments.slice(-1)[0];Fix dateJohn Geebefore adoption43f4743
line 368why, one step back368 if (previousArgument && previousArgument.variadic) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 369–371why, one step back369 throw new Error(370 `only the last argument can be variadic '${previousArgument.name()}'`,371 );Fix dateJohn Geebefore adoption43f4743
line 372why, one step back372 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 373–380why, one step back373 if (374 argument.required &&375 argument.defaultValue !== undefined &&376 argument.parseArg === undefined377 ) {378 throw new Error(379 `a default value for a required argument is never used: '${argument.name()}'`,380 );Fix dateJohn Geebefore adoption43f4743
line 381why, one step back381 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 382why, one step back382 this.registeredArguments.push(argument);Fix dateJohn Geebefore adoption43f4743
lines 383–386why, one step back383 return this;384 }385386 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 387why, one step back387 * Customise or override default help command. By default a help command is automatically added if your command has subcommands.Fix dateJohn Geebefore adoption43f4743
line 388why, one step back388 *ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 389why, one step back389 * @exampleMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 390–393why, one step back390 * program.helpCommand('help [cmd]');391 * program.helpCommand('help [cmd]', 'show help');392 * program.helpCommand(false); // suppress default help command393 * program.helpCommand(true); // add help command even if no subcommandsFix dateJohn Geebefore adoption43f4743
line 394why, one step back394 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 395–396why, one step back395 * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added396 * @param {string} [description] - custom descriptionFix dateJohn Geebefore adoption43f4743
lines 397–399why, one step back397 * @return {Command} `this` command for chaining398 */399Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 400–403why, one step back400 helpCommand(enableOrNameAndArgs, description) {401 if (typeof enableOrNameAndArgs === 'boolean') {402 this._addImplicitHelpCommand = enableOrNameAndArgs;403 return this;Fix dateJohn Geebefore adoption43f4743
line 404why, one step back404 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 405–417why, one step back405406 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';407 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);408 const helpDescription = description ?? 'display help for command';409410 const helpCommand = this.createCommand(helpName);411 helpCommand.helpOption(false);412 if (helpArgs) helpCommand.arguments(helpArgs);413 if (helpDescription) helpCommand.description(helpDescription);414415 this._addImplicitHelpCommand = true;416 this._helpCommand = helpCommand;417Fix dateJohn Geebefore adoption43f4743
line 418why, one step back418 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 419why, one step back419 }Fix dateJohn Geebefore adoption43f4743
lines 420–421why, one step back420421 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 422–426why, one step back422 * Add prepared custom help command.423 *424 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`425 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only426 * @return {Command} `this` command for chainingFix dateJohn Geebefore adoption43f4743
line 427why, one step back427 */Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 428–434why, one step back428 addHelpCommand(helpCommand, deprecatedDescription) {429 // If not passed an object, call through to helpCommand for backwards compatibility,430 // as addHelpCommand was originally used like helpCommand is now.431 if (typeof helpCommand !== 'object') {432 this.helpCommand(helpCommand, deprecatedDescription);433 return this;434 }Fix dateJohn Geebefore adoption43f4743
line 435why, one step back435Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 436–447why, one step back436 this._addImplicitHelpCommand = true;437 this._helpCommand = helpCommand;438 return this;439 }440441 /**442 * Lazy create help command.443 *444 * @return {(Command|null)}445 * @package446 */447 _getHelpCommand() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 448–452why, one step back448 const hasImplicitHelpCommand =449 this._addImplicitHelpCommand ??450 (this.commands.length &&451 !this._actionHandler &&452 !this._findCommand('help'));Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 453–458why, one step back453454 if (hasImplicitHelpCommand) {455 if (this._helpCommand === undefined) {456 this.helpCommand(undefined, undefined); // use default name and description457 }458 return this._helpCommand;Fix dateJohn Geebefore adoption43f4743
line 459why, one step back459 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 460why, one step back460 return null;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 461why, one step back461 }Fix dateJohn Geebefore adoption43f4743
lines 462–471why, one step back462463 /**464 * Add hook for life cycle event.465 *466 * @param {string} event467 * @param {Function} listener468 * @return {Command} `this` command for chaining469 */470471 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 472why, one step back472 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Fix dateJohn Geebefore adoption43f4743
lines 473–504why, one step back473 if (!allowedValues.includes(event)) {474 throw new Error(`Unexpected value for event passed to hook : '${event}'.475Expecting one of '${allowedValues.join("', '")}'`);476 }477 if (this._lifeCycleHooks[event]) {478 this._lifeCycleHooks[event].push(listener);479 } else {480 this._lifeCycleHooks[event] = [listener];481 }482 return this;483 }484485 /**486 * Register callback to use as replacement for calling process.exit.487 *488 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing489 * @return {Command} `this` command for chaining490 */491492 exitOverride(fn) {493 if (fn) {494 this._exitCallback = fn;495 } else {496 this._exitCallback = (err) => {497 if (err.code !== 'commander.executeSubCommandAsync') {498 throw err;499 } else {500 // Async callback from spawn events, not useful to throw.501 }502 };503 }504 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 505why, one step back505 }Fix dateJohn Geebefore adoption43f4743
lines 506–513why, one step back506507 /**508 * Call process.exit, and _exitCallback if defined.509 *510 * @param {number} exitCode exit code for using with process.exit511 * @param {string} code an id string representing the error512 * @param {string} message human-readable description of the error513 * @return neverMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 514why, one step back514 * @privateFix dateJohn Geebefore adoption43f4743
lines 515–522why, one step back515 */516517 _exit(exitCode, code, message) {518 if (this._exitCallback) {519 this._exitCallback(new CommanderError(exitCode, code, message));520 // Expecting this line is not reached.521 }522 process.exit(exitCode);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 523why, one step back523 }Fix dateJohn Geebefore adoption43f4743
lines 524–542why, one step back524525 /**526 * Register callback `fn` for the command.527 *528 * @example529 * program530 * .command('serve')531 * .description('start service')532 * .action(function() {533 * // do work here534 * });535 *536 * @param {Function} fn537 * @return {Command} `this` command for chaining538 */539540 action(fn) {541 const listener = (args) => {542 // The .action callback takes an extra parameter which is the command or options.Add public Arguments property (#2010)John Geebefore adoption7d23437
line 543why, one step back543 const expectedArgsCount = this.registeredArguments.length;Fix dateJohn Geebefore adoption43f4743
lines 544–555why, one step back544 const actionArgs = args.slice(0, expectedArgsCount);545 if (this._storeOptionsAsProperties) {546 actionArgs[expectedArgsCount] = this; // backwards compatible "options"547 } else {548 actionArgs[expectedArgsCount] = this.opts();549 }550 actionArgs.push(this);551552 return fn.apply(this, actionArgs);553 };554 this._actionHandler = listener;555 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 556why, one step back556 }Fix dateJohn Geebefore adoption43f4743
lines 557–570why, one step back557558 /**559 * Factory routine to create a new unattached option.560 *561 * See .option() for creating an attached option, which uses this routine to562 * create the option. You can override createOption to return a custom option.563 *564 * @param {string} flags565 * @param {string} [description]566 * @return {Option} new option567 */568569 createOption(flags, description) {570 return new Option(flags, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 571why, one step back571 }Fix dateJohn Geebefore adoption43f4743
lines 572–573why, one step back572573 /**Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 574–575why, one step back574 * Wrap parseArgs to catch 'commander.invalidArgument'.575 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 576why, one step back576 * @param {(Option | Argument)} targetRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 577why, one step back577 * @param {string} valueReplace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6
line 578why, one step back578 * @param {*} previousRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 579why, one step back579 * @param {string} invalidArgumentMessageMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 580why, one step back580 * @privateRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 581–595why, one step back581 */582583 _callParseArg(target, value, previous, invalidArgumentMessage) {584 try {585 return target.parseArg(value, previous);586 } catch (err) {587 if (err.code === 'commander.invalidArgument') {588 const message = `${invalidArgumentMessage} ${err.message}`;589 this.error(message, { exitCode: err.exitCode, code: err.code });590 }591 throw err;592 }593 }594595 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 596–599why, one step back596 * Check for option flag conflicts.597 * Register option if no conflicts found, or throw on conflict.598 *599 * @param {Option} optionFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 600why, one step back600 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 601–603why, one step back601 */602603 _registerOption(option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 604–605why, one step back604 const matchingOption =605 (option.short && this._findOption(option.short)) ||Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 606–607why, one step back606 (option.long && this._findOption(option.long));607 if (matchingOption) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 608–611why, one step back608 const matchingFlag =609 option.long && this._findOption(option.long)610 ? option.long611 : option.short;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 612–623why, one step back612 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'613- already used by option '${matchingOption.flags}'`);614 }615616 this.options.push(option);617 }618619 /**620 * Check for command name and alias conflicts with existing commands.621 * Register command if no conflicts found, or throw on conflict.622 *623 * @param {Command} commandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 624why, one step back624 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 625–631why, one step back625 */626627 _registerCommand(command) {628 const knownBy = (cmd) => {629 return [cmd.name()].concat(cmd.aliases());630 };631Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 632–634why, one step back632 const alreadyUsed = knownBy(command).find((name) =>633 this._findCommand(name),634 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 635–637why, one step back635 if (alreadyUsed) {636 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');637 const newCmd = knownBy(command).join('|');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 638–640why, one step back638 throw new Error(639 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,640 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 641–646why, one step back641 }642643 this.commands.push(command);644 }645646 /**Fix dateJohn Geebefore adoption43f4743
lines 647–652why, one step back647 * Add an option.648 *649 * @param {Option} option650 * @return {Command} `this` command for chaining651 */652 addOption(option) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 653–654why, one step back653 this._registerOption(option);654Fix dateJohn Geebefore adoption43f4743
lines 655–657why, one step back655 const oname = option.name();656 const name = option.attributeName();657Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 658–662why, one step back658 // store default value659 if (option.negate) {660 // --no-foo is special and defaults foo to true, unless a --foo option is already defined661 const positiveLongFlag = option.long.replace(/^--no-/, '--');662 if (!this._findOption(positiveLongFlag)) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 663–667why, one step back663 this.setOptionValueWithSource(664 name,665 option.defaultValue === undefined ? true : option.defaultValue,666 'default',667 );Fix dateJohn Geebefore adoption43f4743
line 668why, one step back668 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 669–670why, one step back669 } else if (option.defaultValue !== undefined) {670 this.setOptionValueWithSource(name, option.defaultValue, 'default');Fix dateJohn Geebefore adoption43f4743
lines 671–674why, one step back671 }672673 // handler for cli and env supplied values674 const handleOptionValue = (val, invalidValueMessage, valueSource) => {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 675–679why, one step back675 // val is null for optional option used without an optional-argument.676 // val is undefined for boolean and negated option.677 if (val == null && option.presetArg !== undefined) {678 val = option.presetArg;679 }Fix dateJohn Geebefore adoption43f4743
lines 680–681why, one step back680681 // custom processingMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 682why, one step back682 const oldValue = this.getOptionValue(name);Fix dateJohn Geebefore adoption43f4743
line 683why, one step back683 if (val !== null && option.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 684why, one step back684 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Fix dateJohn Geebefore adoption43f4743
lines 685–688why, one step back685 } else if (val !== null && option.variadic) {686 val = option._concatValue(val, oldValue);687 }688Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 689–694why, one step back689 // Fill-in appropriate missing values. Long winded but easy to follow.690 if (val == null) {691 if (option.negate) {692 val = false;693 } else if (option.isBoolean() || option.optional) {694 val = true;Fix dateJohn Geebefore adoption43f4743
line 695why, one step back695 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 696why, one step back696 val = ''; // not normal, parseArg might have failed or be a mock function for testingFix dateJohn Geebefore adoption43f4743
lines 697–698why, one step back697 }698 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 699why, one step back699 this.setOptionValueWithSource(name, val, valueSource);Fix dateJohn Geebefore adoption43f4743
lines 700–719why, one step back700 };701702 this.on('option:' + oname, (val) => {703 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;704 handleOptionValue(val, invalidValueMessage, 'cli');705 });706707 if (option.envVar) {708 this.on('optionEnv:' + oname, (val) => {709 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;710 handleOptionValue(val, invalidValueMessage, 'env');711 });712 }713714 return this;715 }716717 /**718 * Internal implementation shared by .option() and .requiredOption()719 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 720why, one step back720 * @return {Command} `this` command for chainingMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 721why, one step back721 * @privateFix dateJohn Geebefore adoption43f4743
lines 722–723why, one step back722 */723 _optionEx(config, flags, description, fn, defaultValue) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 724why, one step back724 if (typeof flags === 'object' && flags instanceof Option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 725–727why, one step back725 throw new Error(726 'To add an Option object use addOption() instead of option() or requiredOption()',727 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 728why, one step back728 }Fix dateJohn Geebefore adoption43f4743
lines 729–748why, one step back729 const option = this.createOption(flags, description);730 option.makeOptionMandatory(!!config.mandatory);731 if (typeof fn === 'function') {732 option.default(defaultValue).argParser(fn);733 } else if (fn instanceof RegExp) {734 // deprecated735 const regex = fn;736 fn = (val, def) => {737 const m = regex.exec(val);738 return m ? m[0] : def;739 };740 option.default(defaultValue).argParser(fn);741 } else {742 option.default(fn);743 }744745 return this.addOption(option);746 }747748 /**Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 749why, one step back749 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.Fix dateJohn Geebefore adoption43f4743
line 750why, one step back750 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 751–752why, one step back751 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required752 * option-argument is indicated by `<>` and an optional option-argument by `[]`.Fix dateJohn Geebefore adoption43f4743
line 753why, one step back753 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 754why, one step back754 * See the README for more details, and see also addOption() and requiredOption().Fix dateJohn Geebefore adoption43f4743
lines 755–756why, one step back755 *756 * @exampleRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 757–761why, one step back757 * program758 * .option('-p, --pepper', 'add pepper')759 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument760 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default761 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse functionFix dateJohn Geebefore adoption43f4743
lines 762–764why, one step back762 *763 * @param {string} flags764 * @param {string} [description]Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 765why, one step back765 * @param {(Function|*)} [parseArg] - custom option processing function or default valueFix dateJohn Geebefore adoption43f4743
lines 766–769why, one step back766 * @param {*} [defaultValue]767 * @return {Command} `this` command for chaining768 */769Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 770–771why, one step back770 option(flags, description, parseArg, defaultValue) {771 return this._optionEx({}, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 772why, one step back772 }Fix dateJohn Geebefore adoption43f4743
lines 773–774why, one step back773774 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 775–785why, one step back775 * Add a required option which must have a value after parsing. This usually means776 * the option must be specified on the command line. (Otherwise the same as .option().)777 *778 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.779 *780 * @param {string} flags781 * @param {string} [description]782 * @param {(Function|*)} [parseArg] - custom option processing function or default value783 * @param {*} [defaultValue]784 * @return {Command} `this` command for chaining785 */Fix dateJohn Geebefore adoption43f4743
line 786why, one step back786Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 787why, one step back787 requiredOption(flags, description, parseArg, defaultValue) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 788–794why, one step back788 return this._optionEx(789 { mandatory: true },790 flags,791 description,792 parseArg,793 defaultValue,794 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 795why, one step back795 }Fix dateJohn Geebefore adoption43f4743
lines 796–804why, one step back796797 /**798 * Alter parsing of short flags with optional values.799 *800 * @example801 * // for `.option('-f,--flag [value]'):802 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour803 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`804 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 805–806why, one step back805 * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.806 * @return {Command} `this` command for chainingFix dateJohn Geebefore adoption43f4743
lines 807–810why, one step back807 */808 combineFlagAndOptionalValue(combine = true) {809 this._combineFlagAndOptionalValue = !!combine;810 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 811why, one step back811 }Fix dateJohn Geebefore adoption43f4743
lines 812–815why, one step back812813 /**814 * Allow unknown options on the command line.815 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 816–817why, one step back816 * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.817 * @return {Command} `this` command for chainingFix dateJohn Geebefore adoption43f4743
lines 818–821why, one step back818 */819 allowUnknownOption(allowUnknown = true) {820 this._allowUnknownOption = !!allowUnknown;821 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 822why, one step back822 }Fix dateJohn Geebefore adoption43f4743
lines 823–826why, one step back823824 /**825 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.826 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 827–828why, one step back827 * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.828 * @return {Command} `this` command for chainingFix dateJohn Geebefore adoption43f4743
lines 829–832why, one step back829 */830 allowExcessArguments(allowExcess = true) {831 this._allowExcessArguments = !!allowExcess;832 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 833why, one step back833 }Fix dateJohn Geebefore adoption43f4743
lines 834–839why, one step back834835 /**836 * Enable positional options. Positional means global options are specified before subcommands which lets837 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.838 * The default behaviour is non-positional and global options may appear anywhere on the command line.839 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 840–841why, one step back840 * @param {boolean} [positional]841 * @return {Command} `this` command for chainingFix dateJohn Geebefore adoption43f4743
lines 842–845why, one step back842 */843 enablePositionalOptions(positional = true) {844 this._enablePositionalOptions = !!positional;845 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 846why, one step back846 }Fix dateJohn Geebefore adoption43f4743
lines 847–853why, one step back847848 /**849 * Pass through options that come after command-arguments rather than treat them as command-options,850 * so actual command-options come before command-arguments. Turning this on for a subcommand requires851 * positional options to have been enabled on the program (parent commands).852 * The default behaviour is non-positional and options may appear before or after command-arguments.853 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 854–855why, one step back854 * @param {boolean} [passThrough] for unknown options.855 * @return {Command} `this` command for chainingFix dateJohn Geebefore adoption43f4743
lines 856–858why, one step back856 */857 passThroughOptions(passThrough = true) {858 this._passThroughOptions = !!passThrough;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 859why, one step back859 this._checkForBrokenPassThrough();Fix dateJohn Geebefore adoption43f4743
line 860why, one step back860 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 861why, one step back861 }Fix dateJohn Geebefore adoption43f4743
lines 862–863why, one step back862863 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 864–867why, one step back864 * @private865 */866867 _checkForBrokenPassThrough() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 868–875why, one step back868 if (869 this.parent &&870 this._passThroughOptions &&871 !this.parent._enablePositionalOptions872 ) {873 throw new Error(874 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,875 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 876–879why, one step back876 }877 }878879 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 880–885why, one step back880 * Whether to store option values as properties on command object,881 * or store separately (specify false). In both cases the option values can be accessed using .opts().882 *883 * @param {boolean} [storeAsProperties=true]884 * @return {Command} `this` command for chaining885 */Fix dateJohn Geebefore adoption43f4743
lines 886–890why, one step back886887 storeOptionsAsProperties(storeAsProperties = true) {888 if (this.options.length) {889 throw new Error('call .storeOptionsAsProperties() before adding options');890 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 891why, one step back891 if (Object.keys(this._optionValues).length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 892–894why, one step back892 throw new Error(893 'call .storeOptionsAsProperties() before setting option values',894 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 895why, one step back895 }Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
line 896why, one step back896 this._storeOptionsAsProperties = !!storeAsProperties;Fix dateJohn Geebefore adoption43f4743
line 897why, one step back897 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 898why, one step back898 }Fix dateJohn Geebefore adoption43f4743
lines 899–903why, one step back899900 /**901 * Retrieve option value.902 *903 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 904why, one step back904 * @return {object} valueFix dateJohn Geebefore adoption43f4743
lines 905–911why, one step back905 */906907 getOptionValue(key) {908 if (this._storeOptionsAsProperties) {909 return this[key];910 }911 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 912why, one step back912 }Fix dateJohn Geebefore adoption43f4743
lines 913–917why, one step back913914 /**915 * Store option value.916 *917 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 918why, one step back918 * @param {object} valueFix dateJohn Geebefore adoption43f4743
lines 919–922why, one step back919 * @return {Command} `this` command for chaining920 */921922 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 923why, one step back923 return this.setOptionValueWithSource(key, value, undefined);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 924why, one step back924 }Fix dateJohn Geebefore adoption43f4743
lines 925–926why, one step back925926 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 927–929why, one step back927 * Store option value and where the value came from.928 *929 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 930why, one step back930 * @param {object} valueReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 931–933why, one step back931 * @param {string} source - expected values are default/config/env/cli/implied932 * @return {Command} `this` command for chaining933 */Fix dateJohn Geebefore adoption43f4743
lines 934–935why, one step back934935 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 936–940why, one step back936 if (this._storeOptionsAsProperties) {937 this[key] = value;938 } else {939 this._optionValues[key] = value;940 }Fix dateJohn Geebefore adoption43f4743
lines 941–945why, one step back941 this._optionValueSources[key] = source;942 return this;943 }944945 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 946–951why, one step back946 * Get source of option value.947 * Expected values are default | config | env | cli | implied948 *949 * @param {string} key950 * @return {string}951 */Fix dateJohn Geebefore adoption43f4743
lines 952–954why, one step back952953 getOptionValueSource(key) {954 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 955why, one step back955 }Fix dateJohn Geebefore adoption43f4743
lines 956–957why, one step back956957 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 958–963why, one step back958 * Get source of option value. See also .optsWithGlobals().959 * Expected values are default | config | env | cli | implied960 *961 * @param {string} key962 * @return {string}963 */Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 964–967why, one step back964965 getOptionValueSourceWithGlobals(key) {966 // global overwrites local, like optsWithGlobals967 let source;Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 968why, one step back968 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 969–976why, one step back969 if (cmd.getOptionValueSource(key) !== undefined) {970 source = cmd.getOptionValueSource(key);971 }972 });973 return source;974 }975976 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 977–978why, one step back977 * Get user arguments from implied or explicit arguments.978 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.Fix dateJohn Geebefore adoption43f4743
line 979why, one step back979 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 980why, one step back980 * @privateFix dateJohn Geebefore adoption43f4743
lines 981–988why, one step back981 */982983 _prepareUserArgs(argv, parseOptions) {984 if (argv !== undefined && !Array.isArray(argv)) {985 throw new Error('first parameter to parse must be array or undefined');986 }987 parseOptions = parseOptions || {};988Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 989–991why, one step back989 // auto-detect argument conventions if nothing supplied990 if (argv === undefined && parseOptions.from === undefined) {991 if (process.versions?.electron) {Fix dateJohn Geebefore adoption43f4743
lines 992–993why, one step back992 parseOptions.from = 'electron';993 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 994–1003why, one step back994 // check node specific options for scenarios where user CLI args follow executable without scriptname995 const execArgv = process.execArgv ?? [];996 if (997 execArgv.includes('-e') ||998 execArgv.includes('--eval') ||999 execArgv.includes('-p') ||1000 execArgv.includes('--print')1001 ) {1002 parseOptions.from = 'eval'; // internal usage, not documented1003 }Fix dateJohn Geebefore adoption43f4743
line 1004why, one step back1004 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1005–1009why, one step back10051006 // default to using process.argv1007 if (argv === undefined) {1008 argv = process.argv;1009 }Fix dateJohn Geebefore adoption43f4743
lines 1010–1011why, one step back1010 this.rawArgs = argv.slice();1011Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1012why, one step back1012 // extract the user args and scriptPathFix dateJohn Geebefore adoption43f4743
lines 1013–1020why, one step back1013 let userArgs;1014 switch (parseOptions.from) {1015 case undefined:1016 case 'node':1017 this._scriptPath = argv[1];1018 userArgs = argv.slice(2);1019 break;1020 case 'electron':ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1021why, one step back1021 // @ts-ignore: because defaultApp is an unknown propertyFix dateJohn Geebefore adoption43f4743
lines 1022–1031why, one step back1022 if (process.defaultApp) {1023 this._scriptPath = argv[1];1024 userArgs = argv.slice(2);1025 } else {1026 userArgs = argv.slice(1);1027 }1028 break;1029 case 'user':1030 userArgs = argv.slice(0);1031 break;Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1032–1034why, one step back1032 case 'eval':1033 userArgs = argv.slice(1);1034 break;Fix dateJohn Geebefore adoption43f4743
line 1035why, one step back1035 default:Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1036–1038why, one step back1036 throw new Error(1037 `unexpected parse option { from: '${parseOptions.from}' }`,1038 );Fix dateJohn Geebefore adoption43f4743
lines 1039–1040why, one step back1039 }1040Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1041why, one step back1041 // Find default name for program from arguments.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1042–1043why, one step back1042 if (!this._name && this._scriptPath)1043 this.nameFromFilename(this._scriptPath);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1044why, one step back1044 this._name = this._name || 'program';Fix dateJohn Geebefore adoption43f4743
lines 1045–1051why, one step back10451046 return userArgs;1047 }10481049 /**1050 * Parse `argv`, setting options and invoking commands when defined.1051 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1052why, one step back1052 * Use parseAsync instead of parse if any of your action handlers are async.Fix dateJohn Geebefore adoption43f4743
line 1053why, one step back1053 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1054–1060why, one step back1054 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1055 *1056 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1057 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1058 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1059 * - `'user'`: just user arguments1060 *Fix dateJohn Geebefore adoption43f4743
line 1061why, one step back1061 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1062–1063why, one step back1062 * program.parse(); // parse process.argv and auto-detect electron and special node flags1063 * program.parse(process.argv); // assume argv[0] is app and argv[1] is scriptFix dateJohn Geebefore adoption43f4743
lines 1064–1065why, one step back1064 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1065 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 1066–1068why, one step back1066 * @param {string[]} [argv] - optional, defaults to process.argv1067 * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1068 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'Fix dateJohn Geebefore adoption43f4743
lines 1069–1072why, one step back1069 * @return {Command} `this` command for chaining1070 */10711072 parse(argv, parseOptions) {Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1073why, one step back1073 this._prepareForParse();Fix dateJohn Geebefore adoption43f4743
lines 1074–1077why, one step back1074 const userArgs = this._prepareUserArgs(argv, parseOptions);1075 this._parseCommand([], userArgs);10761077 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1078why, one step back1078 }Fix dateJohn Geebefore adoption43f4743
lines 1079–1082why, one step back10791080 /**1081 * Parse `argv`, setting options and invoking commands when defined.1082 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1083why, one step back1083 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!Fix dateJohn Geebefore adoption43f4743
line 1084why, one step back1084 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1085–1088why, one step back1085 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1086 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1087 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1088 * - `'user'`: just user argumentsFix dateJohn Geebefore adoption43f4743
lines 1089–1090why, one step back1089 *1090 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1091–1092why, one step back1091 * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1092 * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is scriptFix dateJohn Geebefore adoption43f4743
lines 1093–1095why, one step back1093 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1094 *1095 * @param {string[]} [argv]Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1096why, one step back1096 * @param {object} [parseOptions]Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1097why, one step back1097 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'Fix dateJohn Geebefore adoption43f4743
lines 1098–1101why, one step back1098 * @return {Promise}1099 */11001101 async parseAsync(argv, parseOptions) {Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1102why, one step back1102 this._prepareForParse();Fix dateJohn Geebefore adoption43f4743
lines 1103–1106why, one step back1103 const userArgs = this._prepareUserArgs(argv, parseOptions);1104 await this._parseCommand([], userArgs);11051106 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1107why, one step back1107 }Fix dateJohn Geebefore adoption43f4743
line 1108why, one step back1108Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1109–1116why, one step back1109 _prepareForParse() {1110 if (this._savedState === null) {1111 this.saveStateBeforeParse();1112 } else {1113 this.restoreStateBeforeParse();1114 }1115 }1116Fix dateJohn Geebefore adoption43f4743
line 1117why, one step back1117 /**Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1118–1158why, one step back1118 * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.1119 * Not usually called directly, but available for subclasses to save their custom state.1120 *1121 * This is called in a lazy way. Only commands used in parsing chain will have state saved.1122 */1123 saveStateBeforeParse() {1124 this._savedState = {1125 // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing1126 _name: this._name,1127 // option values before parse have default values (including false for negated options)1128 // shallow clones1129 _optionValues: { ...this._optionValues },1130 _optionValueSources: { ...this._optionValueSources },1131 };1132 }11331134 /**1135 * Restore state before parse for calls after the first.1136 * Not usually called directly, but available for subclasses to save their custom state.1137 *1138 * This is called in a lazy way. Only commands used in parsing chain will have state restored.1139 */1140 restoreStateBeforeParse() {1141 if (this._storeOptionsAsProperties)1142 throw new Error(`Can not call parse again when storeOptionsAsProperties is true.1143- either make a new Command for each call to parse, or stop storing options as properties`);11441145 // clear state from _prepareUserArgs1146 this._name = this._savedState._name;1147 this._scriptPath = null;1148 this.rawArgs = [];1149 // clear state from setOptionValueWithSource1150 this._optionValues = { ...this._savedState._optionValues };1151 this._optionValueSources = { ...this._savedState._optionValueSources };1152 // clear state from _parseCommand1153 this.args = [];1154 // clear state from _processArguments1155 this.processedArgs = [];1156 }11571158 /**Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1159–1178why, one step back1159 * Throw if expected executable is missing. Add lots of help for author.1160 *1161 * @param {string} executableFile1162 * @param {string} executableDir1163 * @param {string} subcommandName1164 */1165 _checkForMissingExecutable(executableFile, executableDir, subcommandName) {1166 if (fs.existsSync(executableFile)) return;11671168 const executableDirMessage = executableDir1169 ? `searched for local subcommand relative to directory '${executableDir}'`1170 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1171 const executableMissing = `'${executableFile}' does not exist1172 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1173 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1174 - ${executableDirMessage}`;1175 throw new Error(executableMissing);1176 }11771178 /**Fix dateJohn Geebefore adoption43f4743
lines 1179–1180why, one step back1179 * Execute a sub-command executable.1180 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1181why, one step back1181 * @privateFix dateJohn Geebefore adoption43f4743
lines 1182–1188why, one step back1182 */11831184 _executeSubCommand(subcommand, args) {1185 args = args.slice();1186 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1187 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];1188Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1189–1192why, one step back1189 function findFile(baseDir, baseName) {1190 // Look for specified file1191 const localBin = path.resolve(baseDir, baseName);1192 if (fs.existsSync(localBin)) return localBin;Fix dateJohn Geebefore adoption43f4743
line 1193why, one step back1193Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1194–1195why, one step back1194 // Stop looking if candidate already has an expected extension.1195 if (sourceExt.includes(path.extname(baseName))) return undefined;Fix dateJohn Geebefore adoption43f4743
line 1196why, one step back1196Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1197why, one step back1197 // Try all the extensions.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1198–1200why, one step back1198 const foundExt = sourceExt.find((ext) =>1199 fs.existsSync(`${localBin}${ext}`),1200 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1201–1203why, one step back1201 if (foundExt) return `${localBin}${foundExt}`;12021203 return undefined;Fix dateJohn Geebefore adoption43f4743
lines 1204–1205why, one step back1204 }1205Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1206–1207why, one step back1206 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1207 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1208why, one step back1208 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1209–1210why, one step back12091210 // executableFile and executableDir might be full path, or just a nameReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1211–1212why, one step back1211 let executableFile =1212 subcommand._executableFile || `${this._name}-${subcommand._name}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1213–1217why, one step back1213 let executableDir = this._executableDir || '';1214 if (this._scriptPath) {1215 let resolvedScriptPath; // resolve possible symlink for installed npm binary1216 try {1217 resolvedScriptPath = fs.realpathSync(this._scriptPath);Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585
line 1218why, one step back1218 } catch {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1219–1220why, one step back1219 resolvedScriptPath = this._scriptPath;1220 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1221–1224why, one step back1221 executableDir = path.resolve(1222 path.dirname(resolvedScriptPath),1223 executableDir,1224 );Fix dateJohn Geebefore adoption43f4743
lines 1225–1226why, one step back1225 }1226Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1227–1232why, one step back1227 // Look for a local file in preference to a command in PATH.1228 if (executableDir) {1229 let localFile = findFile(executableDir, executableFile);12301231 // Legacy search using prefix of script name instead of command name1232 if (!localFile && !subcommand._executableFile && this._scriptPath) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1233–1236why, one step back1233 const legacyName = path.basename(1234 this._scriptPath,1235 path.extname(this._scriptPath),1236 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1237why, one step back1237 if (legacyName !== this._name) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1238–1241why, one step back1238 localFile = findFile(1239 executableDir,1240 `${legacyName}-${subcommand._name}`,1241 );Fix dateJohn Geebefore adoption43f4743
line 1242why, one step back1242 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1243–1244why, one step back1243 }1244 executableFile = localFile || executableFile;Fix dateJohn Geebefore adoption43f4743
lines 1245–1246why, one step back1245 }1246Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1247–1248why, one step back1247 launchWithNode = sourceExt.includes(path.extname(executableFile));1248Fix dateJohn Geebefore adoption43f4743
lines 1249–1251why, one step back1249 let proc;1250 if (process.platform !== 'win32') {1251 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1252why, one step back1252 args.unshift(executableFile);Fix dateJohn Geebefore adoption43f4743
lines 1253–1257why, one step back1253 // add executable arguments to spawn1254 args = incrementNodeInspectorPort(process.execArgv).concat(args);12551256 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1257 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1258why, one step back1258 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Fix dateJohn Geebefore adoption43f4743
lines 1259–1260why, one step back1259 }1260 } else {Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1261–1265why, one step back1261 this._checkForMissingExecutable(1262 executableFile,1263 executableDir,1264 subcommand._name,1265 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1266why, one step back1266 args.unshift(executableFile);Fix dateJohn Geebefore adoption43f4743
lines 1267–1271why, one step back1267 // add executable arguments to spawn1268 args = incrementNodeInspectorPort(process.execArgv).concat(args);1269 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1270 }1271Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1272–1273why, one step back1272 if (!proc.killed) {1273 // testing mainly to avoid leak warnings during unit tests with mocked spawnMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1274–1277why, one step back1274 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1275 signals.forEach((signal) => {1276 process.on(signal, () => {1277 if (proc.killed === false && proc.exitCode === null) {Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1278why, one step back1278 // @ts-ignore because signals not typed to known stringsMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1279–1281why, one step back1279 proc.kill(signal);1280 }1281 });Fix dateJohn Geebefore adoption43f4743
line 1282why, one step back1282 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1283why, one step back1283 }Fix dateJohn Geebefore adoption43f4743
lines 1284–1286why, one step back12841285 // By default terminate process when spawned process terminates.1286 const exitCallback = this._exitCallback;ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1287why, one step back1287 proc.on('close', (code) => {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1288–1291why, one step back1288 code = code ?? 1; // code is null if spawned process terminated due to a signal1289 if (!exitCallback) {1290 process.exit(code);1291 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1292–1298why, one step back1292 exitCallback(1293 new CommanderError(1294 code,1295 'commander.executeSubCommandAsync',1296 '(close)',1297 ),1298 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1299–1300why, one step back1299 }1300 });Fix dateJohn Geebefore adoption43f4743
line 1301why, one step back1301 proc.on('error', (err) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1302why, one step back1302 // @ts-ignore: because err.code is an unknown propertyFix dateJohn Geebefore adoption43f4743
line 1303why, one step back1303 if (err.code === 'ENOENT') {Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1304–1308why, one step back1304 this._checkForMissingExecutable(1305 executableFile,1306 executableDir,1307 subcommand._name,1308 );Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1309why, one step back1309 // @ts-ignore: because err.code is an unknown propertyFix dateJohn Geebefore adoption43f4743
line 1310why, one step back1310 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1311why, one step back1311 throw new Error(`'${executableFile}' not executable`);Fix dateJohn Geebefore adoption43f4743
lines 1312–1315why, one step back1312 }1313 if (!exitCallback) {1314 process.exit(1);1315 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1316–1320why, one step back1316 const wrappedError = new CommanderError(1317 1,1318 'commander.executeSubCommandAsync',1319 '(error)',1320 );Fix dateJohn Geebefore adoption43f4743
lines 1321–1327why, one step back1321 wrappedError.nestedError = err;1322 exitCallback(wrappedError);1323 }1324 });13251326 // Store the reference to the child process1327 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1328why, one step back1328 }Fix dateJohn Geebefore adoption43f4743
lines 1329–1330why, one step back13291330 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1331why, one step back1331 * @privateFix dateJohn Geebefore adoption43f4743
lines 1332–1337why, one step back1332 */13331334 _dispatchSubcommand(commandName, operands, unknown) {1335 const subCommand = this._findCommand(commandName);1336 if (!subCommand) this.help({ error: true });1337Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1338why, one step back1338 subCommand._prepareForParse();Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1339why, one step back1339 let promiseChain;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1340–1344why, one step back1340 promiseChain = this._chainOrCallSubCommandHook(1341 promiseChain,1342 subCommand,1343 'preSubcommand',1344 );Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1345why, one step back1345 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1346–1351why, one step back1346 if (subCommand._executableHandler) {1347 this._executeSubCommand(subCommand, operands.concat(unknown));1348 } else {1349 return subCommand._parseCommand(operands, unknown);1350 }1351 });Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1352why, one step back1352 return promiseChain;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1353why, one step back1353 }Fix dateJohn Geebefore adoption43f4743
lines 1354–1355why, one step back13541355 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1356–1358why, one step back1356 * Invoke help directly if possible, or dispatch if necessary.1357 * e.g. help foo1358 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1359why, one step back1359 * @privateHave help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1360–1371why, one step back1360 */13611362 _dispatchHelpCommand(subcommandName) {1363 if (!subcommandName) {1364 this.help();1365 }1366 const subCommand = this._findCommand(subcommandName);1367 if (subCommand && !subCommand._executableHandler) {1368 subCommand.help();1369 }13701371 // Fallback to parsing the help flag to invoke the help.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1372–1376why, one step back1372 return this._dispatchSubcommand(1373 subcommandName,1374 [],1375 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1376 );Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1377–1379why, one step back1377 }13781379 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1380why, one step back1380 * Check this.args against expected this.registeredArguments.Fix dateJohn Geebefore adoption43f4743
line 1381why, one step back1381 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1382why, one step back1382 * @privateFix dateJohn Geebefore adoption43f4743
lines 1383–1386why, one step back1383 */13841385 _checkNumberOfArguments() {1386 // too fewAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1387why, one step back1387 this.registeredArguments.forEach((arg, i) => {Fix dateJohn Geebefore adoption43f4743
lines 1388–1392why, one step back1388 if (arg.required && this.args[i] == null) {1389 this.missingArgument(arg.name());1390 }1391 });1392 // too manyReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1393–1396why, one step back1393 if (1394 this.registeredArguments.length > 0 &&1395 this.registeredArguments[this.registeredArguments.length - 1].variadic1396 ) {Fix dateJohn Geebefore adoption43f4743
lines 1397–1398why, one step back1397 return;1398 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1399why, one step back1399 if (this.args.length > this.registeredArguments.length) {Fix dateJohn Geebefore adoption43f4743
lines 1400–1401why, one step back1400 this._excessArguments(this.args);1401 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1402why, one step back1402 }Fix dateJohn Geebefore adoption43f4743
lines 1403–1404why, one step back14031404 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1405why, one step back1405 * Process this.args using this.registeredArguments and save as this.processedArgs!Fix dateJohn Geebefore adoption43f4743
line 1406why, one step back1406 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1407why, one step back1407 * @privateFix dateJohn Geebefore adoption43f4743
lines 1408–1414why, one step back1408 */14091410 _processArguments() {1411 const myParseArg = (argument, value, previous) => {1412 // Extra processing for nice error message on parsing failure.1413 let parsedValue = value;1414 if (value !== null && argument.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 1415why, one step back1415 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1416–1421why, one step back1416 parsedValue = this._callParseArg(1417 argument,1418 value,1419 previous,1420 invalidValueMessage,1421 );Fix dateJohn Geebefore adoption43f4743
lines 1422–1428why, one step back1422 }1423 return parsedValue;1424 };14251426 this._checkNumberOfArguments();14271428 const processedArgs = [];Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1429why, one step back1429 this.registeredArguments.forEach((declaredArg, index) => {Fix dateJohn Geebefore adoption43f4743
lines 1430–1456why, one step back1430 let value = declaredArg.defaultValue;1431 if (declaredArg.variadic) {1432 // Collect together remaining arguments for passing together as an array.1433 if (index < this.args.length) {1434 value = this.args.slice(index);1435 if (declaredArg.parseArg) {1436 value = value.reduce((processed, v) => {1437 return myParseArg(declaredArg, v, processed);1438 }, declaredArg.defaultValue);1439 }1440 } else if (value === undefined) {1441 value = [];1442 }1443 } else if (index < this.args.length) {1444 value = this.args[index];1445 if (declaredArg.parseArg) {1446 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1447 }1448 }1449 processedArgs[index] = value;1450 });1451 this.processedArgs = processedArgs;1452 }14531454 /**1455 * Once we have a promise we chain, but call synchronously until then.1456 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1457why, one step back1457 * @param {(Promise|undefined)} promiseFix dateJohn Geebefore adoption43f4743
line 1458why, one step back1458 * @param {Function} fnMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1459–1460why, one step back1459 * @return {(Promise|undefined)}1460 * @privateFix dateJohn Geebefore adoption43f4743
lines 1461–1474why, one step back1461 */14621463 _chainOrCall(promise, fn) {1464 // thenable1465 if (promise && promise.then && typeof promise.then === 'function') {1466 // already have a promise, chain callback1467 return promise.then(() => fn());1468 }1469 // callback might return a promise1470 return fn();1471 }14721473 /**1474 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1475why, one step back1475 * @param {(Promise|undefined)} promiseFix dateJohn Geebefore adoption43f4743
line 1476why, one step back1476 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1477–1478why, one step back1477 * @return {(Promise|undefined)}1478 * @privateFix dateJohn Geebefore adoption43f4743
lines 1479–1483why, one step back1479 */14801481 _chainOrCallHooks(promise, event) {1482 let result = promise;1483 const hooks = [];Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1484why, one step back1484 this._getCommandAndAncestors()Fix dateJohn Geebefore adoption43f4743
line 1485why, one step back1485 .reverse()Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1486–1487why, one step back1486 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1487 .forEach((hookedCommand) => {Fix dateJohn Geebefore adoption43f4743
lines 1488–1500why, one step back1488 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1489 hooks.push({ hookedCommand, callback });1490 });1491 });1492 if (event === 'postAction') {1493 hooks.reverse();1494 }14951496 hooks.forEach((hookDetail) => {1497 result = this._chainOrCall(result, () => {1498 return hookDetail.callback(hookDetail.hookedCommand, this);1499 });1500 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1501–1505why, one step back1501 return result;1502 }15031504 /**1505 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1506why, one step back1506 * @param {(Promise|undefined)} promisefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1507–1508why, one step back1507 * @param {Command} subCommand1508 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1509–1510why, one step back1509 * @return {(Promise|undefined)}1510 * @privatefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1511–1521why, one step back1511 */15121513 _chainOrCallSubCommandHook(promise, subCommand, event) {1514 let result = promise;1515 if (this._lifeCycleHooks[event] !== undefined) {1516 this._lifeCycleHooks[event].forEach((hook) => {1517 result = this._chainOrCall(result, () => {1518 return hook(this, subCommand);1519 });1520 });1521 }Fix dateJohn Geebefore adoption43f4743
lines 1522–1528why, one step back1522 return result;1523 }15241525 /**1526 * Process arguments in context of this command.1527 * Returns action result, in case it is a promise.1528 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1529why, one step back1529 * @privateFix dateJohn Geebefore adoption43f4743
lines 1530–1534why, one step back1530 */15311532 _parseCommand(operands, unknown) {1533 const parsed = this.parseOptions(unknown);1534 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1535why, one step back1535 this._parseOptionsImplied();Fix dateJohn Geebefore adoption43f4743
lines 1536–1542why, one step back1536 operands = operands.concat(parsed.operands);1537 unknown = parsed.unknown;1538 this.args = operands.concat(unknown);15391540 if (operands && this._findCommand(operands[0])) {1541 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1542 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1543–1546why, one step back1543 if (1544 this._getHelpCommand() &&1545 operands[0] === this._getHelpCommand().name()1546 ) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1547why, one step back1547 return this._dispatchHelpCommand(operands[1]);Fix dateJohn Geebefore adoption43f4743
lines 1548–1549why, one step back1548 }1549 if (this._defaultCommandName) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1550why, one step back1550 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default commandReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1551–1555why, one step back1551 return this._dispatchSubcommand(1552 this._defaultCommandName,1553 operands,1554 unknown,1555 );Fix dateJohn Geebefore adoption43f4743
line 1556why, one step back1556 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1557–1562why, one step back1557 if (1558 this.commands.length &&1559 this.args.length === 0 &&1560 !this._actionHandler &&1561 !this._defaultCommandName1562 ) {Fix dateJohn Geebefore adoption43f4743
lines 1563–1566why, one step back1563 // probably missing subcommand and no handler, user needs help (and exit)1564 this.help({ error: true });1565 }1566Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1567why, one step back1567 this._outputHelpIfRequested(parsed.unknown);Fix dateJohn Geebefore adoption43f4743
line 1568why, one step back1568 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1569why, one step back1569 this._checkForConflictingOptions();Fix dateJohn Geebefore adoption43f4743
lines 1570–1582why, one step back15701571 // We do not always call this check to avoid masking a "better" error, like unknown command.1572 const checkForUnknownOptions = () => {1573 if (parsed.unknown.length > 0) {1574 this.unknownOption(parsed.unknown[0]);1575 }1576 };15771578 const commandEvent = `command:${this.name()}`;1579 if (this._actionHandler) {1580 checkForUnknownOptions();1581 this._processArguments();1582Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1583–1584why, one step back1583 let promiseChain;1584 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1585–1587why, one step back1585 promiseChain = this._chainOrCall(promiseChain, () =>1586 this._actionHandler(this.processedArgs),1587 );Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
line 1588why, one step back1588 if (this.parent) {Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1589why, one step back1589 promiseChain = this._chainOrCall(promiseChain, () => {Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1590–1592why, one step back1590 this.parent.emit(commandEvent, operands, unknown); // legacy1591 });1592 }Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1593–1594why, one step back1593 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1594 return promiseChain;Fix dateJohn Geebefore adoption43f4743
lines 1595–1600why, one step back1595 }1596 if (this.parent && this.parent.listenerCount(commandEvent)) {1597 checkForUnknownOptions();1598 this._processArguments();1599 this.parent.emit(commandEvent, operands, unknown); // legacy1600 } else if (operands.length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1601–1602why, one step back1601 if (this._findCommand('*')) {1602 // legacy default commandFix dateJohn Geebefore adoption43f4743
lines 1603–1622why, one step back1603 return this._dispatchSubcommand('*', operands, unknown);1604 }1605 if (this.listenerCount('command:*')) {1606 // skip option check, emit event for possible misspelling suggestion1607 this.emit('command:*', operands, unknown);1608 } else if (this.commands.length) {1609 this.unknownCommand();1610 } else {1611 checkForUnknownOptions();1612 this._processArguments();1613 }1614 } else if (this.commands.length) {1615 checkForUnknownOptions();1616 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1617 this.help({ error: true });1618 } else {1619 checkForUnknownOptions();1620 this._processArguments();1621 // fall through for caller to handle after calling .parse()1622 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1623why, one step back1623 }Fix dateJohn Geebefore adoption43f4743
lines 1624–1627why, one step back16241625 /**1626 * Find matching command.1627 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1628why, one step back1628 * @privateFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1629why, one step back1629 * @return {Command | undefined}Fix dateJohn Geebefore adoption43f4743
lines 1630–1632why, one step back1630 */1631 _findCommand(name) {1632 if (!name) return undefined;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1633–1635why, one step back1633 return this.commands.find(1634 (cmd) => cmd._name === name || cmd._aliases.includes(name),1635 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1636why, one step back1636 }Fix dateJohn Geebefore adoption43f4743
lines 1637–1642why, one step back16371638 /**1639 * Return an option matching `arg` if any.1640 *1641 * @param {string} arg1642 * @return {Option}Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1643why, one step back1643 * @packageFix dateJohn Geebefore adoption43f4743
lines 1644–1646why, one step back1644 */16451646 _findOption(arg) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1647why, one step back1647 return this.options.find((option) => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1648why, one step back1648 }Fix dateJohn Geebefore adoption43f4743
lines 1649–1651why, one step back16491650 /**1651 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1652why, one step back1652 * Called after checking for help flags in leaf subcommand.Fix dateJohn Geebefore adoption43f4743
line 1653why, one step back1653 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1654why, one step back1654 * @privateFix dateJohn Geebefore adoption43f4743
lines 1655–1658why, one step back1655 */16561657 _checkForMissingMandatoryOptions() {1658 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1659why, one step back1659 this._getCommandAndAncestors().forEach((cmd) => {Fix dateJohn Geebefore adoption43f4743
line 1660why, one step back1660 cmd.options.forEach((anOption) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1661–1664why, one step back1661 if (1662 anOption.mandatory &&1663 cmd.getOptionValue(anOption.attributeName()) === undefined1664 ) {Fix dateJohn Geebefore adoption43f4743
lines 1665–1667why, one step back1665 cmd.missingMandatoryOptionValue(anOption);1666 }1667 });Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1668why, one step back1668 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1669why, one step back1669 }Fix dateJohn Geebefore adoption43f4743
lines 1670–1671why, one step back16701671 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1672why, one step back1672 * Display an error message if conflicting options are used together in this.feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1673why, one step back1673 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1674why, one step back1674 * @privatefeat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1675why, one step back1675 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1676why, one step back1676 _checkForConflictingLocalOptions() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1677–1680why, one step back1677 const definedNonDefaultOptions = this.options.filter((option) => {1678 const optionKey = option.attributeName();1679 if (this.getOptionValue(optionKey) === undefined) {1680 return false;feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1681why, one step back1681 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1682–1683why, one step back1682 return this.getOptionValueSource(optionKey) !== 'default';1683 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1684–1685why, one step back16841685 const optionsWithConflicting = definedNonDefaultOptions.filter(Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1686why, one step back1686 (option) => option.conflictsWith.length > 0,feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1687–1690why, one step back1687 );16881689 optionsWithConflicting.forEach((option) => {1690 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1691why, one step back1691 option.conflictsWith.includes(defined.attributeName()),feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1692–1696why, one step back1692 );1693 if (conflictingAndDefined) {1694 this._conflictingOption(option, conflictingAndDefined);1695 }1696 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1697–1702why, one step back1697 }16981699 /**1700 * Display an error message if conflicting options are used together.1701 * Called after checking for help flags in leaf subcommand.1702 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1703why, one step back1703 * @privateCheck for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1704–1706why, one step back1704 */1705 _checkForConflictingOptions() {1706 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1707why, one step back1707 this._getCommandAndAncestors().forEach((cmd) => {Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1708why, one step back1708 cmd._checkForConflictingLocalOptions();Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1709why, one step back1709 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1710–1712why, one step back1710 }17111712 /**Fix dateJohn Geebefore adoption43f4743
lines 1713–1714why, one step back1713 * Parse options from `argv` removing known options,1714 * and return argv split into operands and unknown arguments.Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1715–1716why, one step back1715 *1716 * Side effects: modifies command by storing options. Does not reset state if called again.Fix dateJohn Geebefore adoption43f4743
lines 1717–1725why, one step back1717 *1718 * Examples:1719 *1720 * argv => operands, unknown1721 * --known kkk op => [op], []1722 * op --known kkk => [op], []1723 * sub --unknown uuu op => [sub], [--unknown uuu op]1724 * sub -- --unknown uuu op => [sub --unknown uuu op], []1725 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1726–1727why, one step back1726 * @param {string[]} argv1727 * @return {{operands: string[], unknown: string[]}}Fix dateJohn Geebefore adoption43f4743
lines 1728–1772why, one step back1728 */17291730 parseOptions(argv) {1731 const operands = []; // operands, not options or values1732 const unknown = []; // first unknown option and remaining unknown args1733 let dest = operands;1734 const args = argv.slice();17351736 function maybeOption(arg) {1737 return arg.length > 1 && arg[0] === '-';1738 }17391740 // parse options1741 let activeVariadicOption = null;1742 while (args.length) {1743 const arg = args.shift();17441745 // literal1746 if (arg === '--') {1747 if (dest === unknown) dest.push(arg);1748 dest.push(...args);1749 break;1750 }17511752 if (activeVariadicOption && !maybeOption(arg)) {1753 this.emit(`option:${activeVariadicOption.name()}`, arg);1754 continue;1755 }1756 activeVariadicOption = null;17571758 if (maybeOption(arg)) {1759 const option = this._findOption(arg);1760 // recognised option, call listener to assign value with possible custom processing1761 if (option) {1762 if (option.required) {1763 const value = args.shift();1764 if (value === undefined) this.optionMissingArgument(option);1765 this.emit(`option:${option.name()}`, value);1766 } else if (option.optional) {1767 let value = null;1768 // historical behaviour is optional value is following arg unless an option1769 if (args.length > 0 && !maybeOption(args[0])) {1770 value = args.shift();1771 }1772 this.emit(`option:${option.name()}`, value);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1773–1774why, one step back1773 } else {1774 // boolean flagFix dateJohn Geebefore adoption43f4743
lines 1775–1785why, one step back1775 this.emit(`option:${option.name()}`);1776 }1777 activeVariadicOption = option.variadic ? option : null;1778 continue;1779 }1780 }17811782 // Look for combo options following single dash, eat first one if known.1783 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1784 const option = this._findOption(`-${arg[1]}`);1785 if (option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1786–1789why, one step back1786 if (1787 option.required ||1788 (option.optional && this._combineFlagAndOptionalValue)1789 ) {Fix dateJohn Geebefore adoption43f4743
lines 1790–1819why, one step back1790 // option with value following in same argument1791 this.emit(`option:${option.name()}`, arg.slice(2));1792 } else {1793 // boolean option, emit and put back remainder of arg for further processing1794 this.emit(`option:${option.name()}`);1795 args.unshift(`-${arg.slice(2)}`);1796 }1797 continue;1798 }1799 }18001801 // Look for known long flag with value, like --foo=bar1802 if (/^--[^=]+=/.test(arg)) {1803 const index = arg.indexOf('=');1804 const option = this._findOption(arg.slice(0, index));1805 if (option && (option.required || option.optional)) {1806 this.emit(`option:${option.name()}`, arg.slice(index + 1));1807 continue;1808 }1809 }18101811 // Not a recognised option by this command.1812 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.18131814 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1815 if (maybeOption(arg)) {1816 dest = unknown;1817 }18181819 // If using positionalOptions, stop processing our options at subcommand.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1820–1824why, one step back1820 if (1821 (this._enablePositionalOptions || this._passThroughOptions) &&1822 operands.length === 0 &&1823 unknown.length === 01824 ) {Fix dateJohn Geebefore adoption43f4743
lines 1825–1828why, one step back1825 if (this._findCommand(arg)) {1826 operands.push(arg);1827 if (args.length > 0) unknown.push(...args);1828 break;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1829–1832why, one step back1829 } else if (1830 this._getHelpCommand() &&1831 arg === this._getHelpCommand().name()1832 ) {Fix dateJohn Geebefore adoption43f4743
lines 1833–1854why, one step back1833 operands.push(arg);1834 if (args.length > 0) operands.push(...args);1835 break;1836 } else if (this._defaultCommandName) {1837 unknown.push(arg);1838 if (args.length > 0) unknown.push(...args);1839 break;1840 }1841 }18421843 // If using passThroughOptions, stop processing options at first command-argument.1844 if (this._passThroughOptions) {1845 dest.push(arg);1846 if (args.length > 0) dest.push(...args);1847 break;1848 }18491850 // add arg1851 dest.push(arg);1852 }18531854 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1855why, one step back1855 }Fix dateJohn Geebefore adoption43f4743
lines 1856–1857why, one step back18561857 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1858why, one step back1858 * Return an object containing local option values as key-value pairs.Fix dateJohn Geebefore adoption43f4743
line 1859why, one step back1859 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1860why, one step back1860 * @return {object}Fix dateJohn Geebefore adoption43f4743
lines 1861–1869why, one step back1861 */1862 opts() {1863 if (this._storeOptionsAsProperties) {1864 // Preserve original behaviour so backwards compatible when still using properties1865 const result = {};1866 const len = this.options.length;18671868 for (let i = 0; i < len; i++) {1869 const key = this.options[i].attributeName();Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1870–1871why, one step back1870 result[key] =1871 key === this._versionOptionName ? this._version : this[key];Fix dateJohn Geebefore adoption43f4743
lines 1872–1876why, one step back1872 }1873 return result;1874 }18751876 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1877why, one step back1877 }Fix dateJohn Geebefore adoption43f4743
lines 1878–1879why, one step back18781879 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1880why, one step back1880 * Return an object containing merged local and global option values as key-value pairs.Fix dateJohn Geebefore adoption43f4743
line 1881why, one step back1881 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1882why, one step back1882 * @return {object}Fix dateJohn Geebefore adoption43f4743
line 1883why, one step back1883 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1884–1885why, one step back1884 optsWithGlobals() {1885 // globals overwrite localsIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1886why, one step back1886 return this._getCommandAndAncestors().reduce(Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1887why, one step back1887 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1888why, one step back1888 {},Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1889–1895why, one step back1889 );1890 }18911892 /**1893 * Display error message and exit (or call exitOverride).1894 *1895 * @param {string} messageFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1896why, one step back1896 * @param {object} [errorOptions]Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1897–1901why, one step back1897 * @param {string} [errorOptions.code] - an id string representing the error1898 * @param {number} [errorOptions.exitCode] - used with process.exit1899 */1900 error(message, errorOptions) {1901 // output handlingReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1902–1905why, one step back1902 this._outputConfiguration.outputError(1903 `${message}\n`,1904 this._outputConfiguration.writeErr,1905 );Fix dateJohn Geebefore adoption43f4743
lines 1906–1911why, one step back1906 if (typeof this._showHelpAfterError === 'string') {1907 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1908 } else if (this._showHelpAfterError) {1909 this._outputConfiguration.writeErr('\n');1910 this.outputHelp({ error: true });1911 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1912–1916why, one step back19121913 // exit handling1914 const config = errorOptions || {};1915 const exitCode = config.exitCode || 1;1916 const code = config.code || 'commander.error';Fix dateJohn Geebefore adoption43f4743
lines 1917–1923why, one step back1917 this._exit(exitCode, code, message);1918 }19191920 /**1921 * Apply any option related environment variables, if option does1922 * not have a value from cli or client code.1923 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1924why, one step back1924 * @privateFix dateJohn Geebefore adoption43f4743
lines 1925–1930why, one step back1925 */1926 _parseOptionsEnv() {1927 this.options.forEach((option) => {1928 if (option.envVar && option.envVar in process.env) {1929 const optionKey = option.attributeName();1930 // Priority check. Do not overwrite cli or options from unknown source (client-code).Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1931–1938why, one step back1931 if (1932 this.getOptionValue(optionKey) === undefined ||1933 ['default', 'config', 'env'].includes(1934 this.getOptionValueSource(optionKey),1935 )1936 ) {1937 if (option.required || option.optional) {1938 // option can take a valueFix dateJohn Geebefore adoption43f4743
lines 1939–1940why, one step back1939 // keep very simple, optional always takes value1940 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1941–1942why, one step back1941 } else {1942 // booleanFix dateJohn Geebefore adoption43f4743
lines 1943–1948why, one step back1943 // keep very simple, only care that envVar defined and not the value1944 this.emit(`optionEnv:${option.name()}`);1945 }1946 }1947 }1948 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1949–1953why, one step back1949 }19501951 /**1952 * Apply any implied option values, if option is undefined or default value.1953 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1954why, one step back1954 * @privateAdd Option.implies() (#1724)John Geebefore adoptiond660967
lines 1955–1958why, one step back1955 */1956 _parseOptionsImplied() {1957 const dualHelper = new DualOptions(this.options);1958 const hasCustomOptionValue = (optionKey) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1959–1962why, one step back1959 return (1960 this.getOptionValue(optionKey) !== undefined &&1961 !['default', 'implied'].includes(this.getOptionValueSource(optionKey))1962 );Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1963–1964why, one step back1963 };1964 this.optionsReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1965–1973why, one step back1965 .filter(1966 (option) =>1967 option.implied !== undefined &&1968 hasCustomOptionValue(option.attributeName()) &&1969 dualHelper.valueFromOption(1970 this.getOptionValue(option.attributeName()),1971 option,1972 ),1973 )Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1974–1975why, one step back1974 .forEach((option) => {1975 Object.keys(option.implied)Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1976–1982why, one step back1976 .filter((impliedKey) => !hasCustomOptionValue(impliedKey))1977 .forEach((impliedKey) => {1978 this.setOptionValueWithSource(1979 impliedKey,1980 option.implied[impliedKey],1981 'implied',1982 );Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1983–1984why, one step back1983 });1984 });Fix dateJohn Geebefore adoption43f4743
lines 1985–1990why, one step back1985 }19861987 /**1988 * Argument `name` is missing.1989 *1990 * @param {string} nameMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1991why, one step back1991 * @privateFix dateJohn Geebefore adoption43f4743
lines 1992–1995why, one step back1992 */19931994 missingArgument(name) {1995 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1996–1997why, one step back1996 this.error(message, { code: 'commander.missingArgument' });1997 }Fix dateJohn Geebefore adoption43f4743
lines 1998–2002why, one step back19981999 /**2000 * `Option` is missing an argument.The first 2,000 of 2,662 lines.