Skip to content
Myr

command.js

This file

Path

lib/command.js

2,790 lines · 85.6 KiB · JavaScript

Last changed by

Use node:util stripVTControlCharacters instead of own code (#2486)John Geebefore adoption373f660

History of this file

Take it

The walk stopped after 200 commits: lines older than 471ec40 point at it.

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

lines 1–5why, one step back
1import { EventEmitter } from 'node:events';
2import childProcess from 'node:child_process';3import path from 'node:path';4import fs from 'node:fs';5import process from 'node:process';

Use node:util stripVTControlCharacters instead of own code (#2486)John Geebefore adoption373f660

line 6why, one step back
6import { stripVTControlCharacters } from 'node:util';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 7why, one step back
7

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

lines 8–9why, one step back
8import { Argument, humanReadableArgName } from './argument.js';
9import { CommanderError } from './error.js';

Use node:util stripVTControlCharacters instead of own code (#2486)John Geebefore adoption373f660

line 10why, one step back
10import { Help } from './help.js';

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

lines 11–12why, one step back
11import { Option, DualOptions } from './option.js';
12import { suggestSimilar } from './suggestSimilar.js';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 13why, one step back
13

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 14why, one step back
14export class Command extends EventEmitter {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 15–28why, one step back
15 /**
16 * Initialize a new `Command`.17 *18 * @param {string} [name]19 */2021 constructor(name) {22 super();23 /** @type {Command[]} */24 this.commands = [];25 /** @type {Option[]} */26 this.options = [];27 this.parent = null;28 this._allowUnknownOption = false;

Disallow excess arguments (#2223)John Geebefore adoption58c28eb

line 29why, one step back
29 this._allowExcessArguments = false;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 30why, one step back
30 /** @type {Argument[]} */

Add public Arguments property (#2010)John Geebefore adoption7d23437

lines 31–32why, one step back
31 this.registeredArguments = [];
32 this._args = this.registeredArguments; // deprecated old name

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 33–55why, one step back
33 /** @type {string[]} */
34 this.args = []; // cli args with options removed35 this.rawArgs = [];36 this.processedArgs = []; // like .args but after custom processing and collecting variadic37 this._scriptPath = null;38 this._name = name || '';39 this._optionValues = {};40 this._optionValueSources = {}; // default, env, cli etc41 this._storeOptionsAsProperties = false;42 this._actionHandler = null;43 this._executableHandler = false;44 this._executableFile = null; // custom name for executable45 this._executableDir = null; // custom search directory for subcommands46 this._defaultCommandName = null;47 this._exitCallback = null;48 this._aliases = [];49 this._combineFlagAndOptionalValue = true;50 this._description = '';51 this._summary = '';52 this._argsDescription = undefined; // legacy53 this._enablePositionalOptions = false;54 this._passThroughOptions = false;55 this._lifeCycleHooks = {}; // a hash of arrays

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 56why, one step back
56 /** @type {(boolean | string)} */

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 57–58why, one step back
57 this._showHelpAfterError = false;
58 this._showSuggestionAfterError = true;

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 59why, one step back
59 this._savedState = null; // used in save/restoreStateBeforeParse

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 60why, one step back
60

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

line 61why, one step back
61 // see configureOutput() for docs

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 62–64why, one step back
62 this._outputConfiguration = {
63 writeOut: (str) => process.stdout.write(str),64 writeErr: (str) => process.stderr.write(str),

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

line 65why, one step back
65 outputError: (str, write) => write(str),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 66–69why, one step back
66 getOutHelpWidth: () =>
67 process.stdout.isTTY ? process.stdout.columns : undefined,68 getErrHelpWidth: () =>69 process.stderr.isTTY ? process.stderr.columns : undefined,

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 70–73why, one step back
70 getOutHasColors: () =>
71 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),72 getErrHasColors: () =>73 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),

Use node:util stripVTControlCharacters instead of own code (#2486)John Geebefore adoption373f660

line 74why, one step back
74 stripColor: (str) => stripVTControlCharacters(str),

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 75–77why, one step back
75 };
7677 this._hidden = false;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 78–82why, one step back
78 /** @type {(Option | null | undefined)} */
79 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.80 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited81 /** @type {Command} */82 this._helpCommand = undefined; // lazy initialised, inherited

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 83why, one step back
83 this._helpConfiguration = {};

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 84–89why, one step back
84 /** @type {string | undefined} */
85 this._helpGroupHeading = undefined; // soft initialised when added to parent86 /** @type {string | undefined} */87 this._defaultCommandGroup = undefined;88 /** @type {string | undefined} */89 this._defaultOptionGroup = undefined;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 90–101why, one step back
90 }
9192 /**93 * Copy settings that are useful to have in common across root command and subcommands.94 *95 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)96 *97 * @param {Command} sourceCommand98 * @return {Command} `this` command for chaining99 */100 copyInheritedSettings(sourceCommand) {101 this._outputConfiguration = sourceCommand._outputConfiguration;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 102–103why, one step back
102 this._helpOption = sourceCommand._helpOption;
103 this._helpCommand = sourceCommand._helpCommand;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 104–106why, one step back
104 this._helpConfiguration = sourceCommand._helpConfiguration;
105 this._exitCallback = sourceCommand._exitCallback;106 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 107–108why, one step back
107 this._combineFlagAndOptionalValue =
108 sourceCommand._combineFlagAndOptionalValue;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 109–117why, one step back
109 this._allowExcessArguments = sourceCommand._allowExcessArguments;
110 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;111 this._showHelpAfterError = sourceCommand._showHelpAfterError;112 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;113114 return this;115 }116117 /**

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 118why, one step back
118 * @returns {Command[]}

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 119why, one step back
119 * @private

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 120–123why, one step back
120 */
121122 _getCommandAndAncestors() {123 const result = [];

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 124why, one step back
124 // eslint-disable-next-line @typescript-eslint/no-this-alias

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 125–131why, one step back
125 for (let command = this; command; command = command.parent) {
126 result.push(command);127 }128 return result;129 }130131 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 132–150why, one step back
132 * Define a command.
133 *134 * There are two styles of command: pay attention to where to put the description.135 *136 * @example137 * // Command implemented using action handler (description is supplied separately to `.command`)138 * program139 * .command('clone <source> [destination]')140 * .description('clone a repository into a newly created directory')141 * .action((source, destination) => {142 * console.log('clone command called');143 * });144 *145 * // Command implemented using separate executable file (description is second parameter to `.command`)146 * program147 * .command('start <service>', 'start named service')148 * .command('stop [service]', 'stop named service, or all if no name supplied');149 *150 * @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 151–152why, one step back
151 * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
152 * @param {object} [execOpts] - configuration options (for executable)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 153–174why, one step back
153 * @return {Command} returns new command for action handler, or `this` for executable command
154 */155156 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {157 let desc = actionOptsOrExecDesc;158 let opts = execOpts;159 if (typeof desc === 'object' && desc !== null) {160 opts = desc;161 desc = null;162 }163 opts = opts || {};164 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);165166 const cmd = this.createCommand(name);167 if (desc) {168 cmd.description(desc);169 cmd._executableHandler = true;170 }171 if (opts.isDefault) this._defaultCommandName = cmd._name;172 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden173 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor174 if (args) cmd.arguments(args);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 175why, one step back
175 this._registerCommand(cmd);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 176–211why, one step back
176 cmd.parent = this;
177 cmd.copyInheritedSettings(this);178179 if (desc) return this;180 return cmd;181 }182183 /**184 * Factory routine to create a new unattached command.185 *186 * See .command() for creating an attached subcommand, which uses this routine to187 * create the command. You can override createCommand to customise subcommands.188 *189 * @param {string} [name]190 * @return {Command} new command191 */192193 createCommand(name) {194 return new Command(name);195 }196197 /**198 * You can customise the help with a subclass of Help by overriding createHelp,199 * or by overriding Help properties using configureHelp().200 *201 * @return {Help}202 */203204 createHelp() {205 return Object.assign(new Help(), this.configureHelp());206 }207208 /**209 * You can customise the help by overriding Help properties using configureHelp(),210 * or with a subclass of Help by overriding createHelp().211 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 212–213why, one step back
212 * @param {object} [configuration] - configuration options
213 * @return {(Command | object)} `this` command for chaining, or stored configuration

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 214–228why, one step back
214 */
215216 configureHelp(configuration) {217 if (configuration === undefined) return this._helpConfiguration;218219 this._helpConfiguration = configuration;220 return this;221 }222223 /**224 * The default output goes to stdout and stderr. You can customise this for special225 * applications. You can also customise the display of errors by overriding outputError.226 *227 * The configuration properties are all functions:228 *

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

line 229why, one step back
229 * // change how output being written, defaults to stdout and stderr

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 230–231why, one step back
230 * writeOut(str)
231 * writeErr(str)

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 232–234why, one step back
232 * // change how output being written for errors, defaults to writeErr
233 * outputError(str, write) // used for displaying errors and not used for displaying help234 * // specify width for wrapping help

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 235–236why, one step back
235 * getOutHelpWidth()
236 * getErrHelpWidth()

Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947

lines 237–239why, one step back
237 * // color support, currently only used with Help
238 * getOutHasColors()239 * getErrHasColors()

Prepare for 13.0.0-0 (#2292)John Geebefore adoption53fc8a4

line 240why, one step back
240 * stripColor() // used to remove ANSI escape codes if output does not have colors

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 241why, one step back
241 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 242–243why, one step back
242 * @param {object} [configuration] - configuration options
243 * @return {(Command | object)} `this` command for chaining, or stored configuration

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 244–248why, one step back
244 */
245246 configureOutput(configuration) {247 if (configuration === undefined) return this._outputConfiguration;248

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 249–252why, one step back
249 this._outputConfiguration = {
250 ...this._outputConfiguration,251 ...configuration,252 };

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 253–258why, one step back
253 return this;
254 }255256 /**257 * Display the help or a custom message after an error occurs.258 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 259why, one step back
259 * @param {(boolean|string)} [displayHelp]

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 260–284why, one step back
260 * @return {Command} `this` command for chaining
261 */262 showHelpAfterError(displayHelp = true) {263 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;264 this._showHelpAfterError = displayHelp;265 return this;266 }267268 /**269 * Display suggestion of similar commands for unknown commands, or options for unknown options.270 *271 * @param {boolean} [displaySuggestion]272 * @return {Command} `this` command for chaining273 */274 showSuggestionAfterError(displaySuggestion = true) {275 this._showSuggestionAfterError = !!displaySuggestion;276 return this;277 }278279 /**280 * Add a prepared subcommand.281 *282 * See .command() for creating an attached subcommand which inherits settings from its parent.283 *284 * @param {Command} cmd - new subcommand

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 285why, one step back
285 * @param {object} [opts] - configuration options

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 286–298why, one step back
286 * @return {Command} `this` command for chaining
287 */288289 addCommand(cmd, opts) {290 if (!cmd._name) {291 throw new Error(`Command passed to .addCommand() must have a name292- specify the name in Command constructor or using .name()`);293 }294295 opts = opts || {};296 if (opts.isDefault) this._defaultCommandName = cmd._name;297 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation298

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 299why, one step back
299 this._registerCommand(cmd);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 300why, one step back
300 cmd.parent = this;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 301–302why, one step back
301 cmd._checkForBrokenPassThrough();
302

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 303–332why, one step back
303 return this;
304 }305306 /**307 * Factory routine to create a new unattached argument.308 *309 * See .argument() for creating an attached argument, which uses this routine to310 * create the argument. You can override createArgument to return a custom argument.311 *312 * @param {string} name313 * @param {string} [description]314 * @return {Argument} new argument315 */316317 createArgument(name, description) {318 return new Argument(name, description);319 }320321 /**322 * Define argument syntax for command.323 *324 * The default is that the argument is required, and you can explicitly325 * indicate this with <> around the name. Put [] around the name for an optional argument.326 *327 * @example328 * program.argument('<input-file>');329 * program.argument('[output-file]');330 *331 * @param {string} name332 * @param {string} [description]

Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603

line 333why, one step back
333 * @param {(Function|*)} [parseArg] - custom argument processing function or default value

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 334–336why, one step back
334 * @param {*} [defaultValue]
335 * @return {Command} `this` command for chaining336 */

Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603

line 337why, one step back
337 argument(name, description, parseArg, defaultValue) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 338why, one step back
338 const argument = this.createArgument(name, description);

Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603

lines 339–340why, one step back
339 if (typeof parseArg === 'function') {
340 argument.default(defaultValue).argParser(parseArg);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 341why, one step back
341 } else {

Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603

line 342why, one step back
342 argument.default(parseArg);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 343–360why, one step back
343 }
344 this.addArgument(argument);345 return this;346 }347348 /**349 * Define argument syntax for command, adding multiple at once (without descriptions).350 *351 * See also .argument().352 *353 * @example354 * program.arguments('<cmd> [env]');355 *356 * @param {string} names357 * @return {Command} `this` command for chaining358 */359360 arguments(names) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 361–366why, one step back
361 names
362 .trim()363 .split(/ +/)364 .forEach((detail) => {365 this.argument(detail);366 });

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 367–376why, one step back
367 return this;
368 }369370 /**371 * Define argument syntax for command, adding a prepared argument.372 *373 * @param {Argument} argument374 * @return {Command} `this` command for chaining375 */376 addArgument(argument) {

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 377why, one step back
377 const previousArgument = this.registeredArguments.slice(-1)[0];

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 378why, one step back
378 if (previousArgument?.variadic) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 379–381why, one step back
379 throw new Error(
380 `only the last argument can be variadic '${previousArgument.name()}'`,381 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 382why, one step back
382 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 383–390why, one step back
383 if (
384 argument.required &&385 argument.defaultValue !== undefined &&386 argument.parseArg === undefined387 ) {388 throw new Error(389 `a default value for a required argument is never used: '${argument.name()}'`,390 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 391why, one step back
391 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 392why, one step back
392 this.registeredArguments.push(argument);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 393–396why, one step back
393 return this;
394 }395396 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 397why, one step back
397 * Customise or override default help command. By default a help command is automatically added if your command has subcommands.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 398why, one step back
398 *

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 399why, one step back
399 * @example

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 400–403why, one step back
400 * program.helpCommand('help [cmd]');
401 * program.helpCommand('help [cmd]', 'show help');402 * program.helpCommand(false); // suppress default help command403 * program.helpCommand(true); // add help command even if no subcommands

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 404why, one step back
404 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 405–406why, one step back
405 * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
406 * @param {string} [description] - custom description

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 407–409why, one step back
407 * @return {Command} `this` command for chaining
408 */409

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 410–412why, one step back
410 helpCommand(enableOrNameAndArgs, description) {
411 if (typeof enableOrNameAndArgs === 'boolean') {412 this._addImplicitHelpCommand = enableOrNameAndArgs;

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 413–416why, one step back
413 if (enableOrNameAndArgs && this._defaultCommandGroup) {
414 // make the command to store the group415 this._initCommandGroup(this._getHelpCommand());416 }

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 417why, one step back
417 return this;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 418why, one step back
418 }

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 419why, one step back
419

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 420–421why, one step back
420 const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';
421 const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 422–430why, one step back
422 const helpDescription = description ?? 'display help for command';
423424 const helpCommand = this.createCommand(helpName);425 helpCommand.helpOption(false);426 if (helpArgs) helpCommand.arguments(helpArgs);427 if (helpDescription) helpCommand.description(helpDescription);428429 this._addImplicitHelpCommand = true;430 this._helpCommand = helpCommand;

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 431–432why, one step back
431 // init group unless lazy create
432 if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 433why, one step back
433

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 434–437why, one step back
434 return this;
435 }436437 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 438–442why, one step back
438 * Add prepared custom help command.
439 *440 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`441 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only442 * @return {Command} `this` command for chaining

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 443why, one step back
443 */

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 444–450why, one step back
444 addHelpCommand(helpCommand, deprecatedDescription) {
445 // If not passed an object, call through to helpCommand for backwards compatibility,446 // as addHelpCommand was originally used like helpCommand is now.447 if (typeof helpCommand !== 'object') {448 this.helpCommand(helpCommand, deprecatedDescription);449 return this;450 }

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 451why, one step back
451

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 452–453why, one step back
452 this._addImplicitHelpCommand = true;
453 this._helpCommand = helpCommand;

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

line 454why, one step back
454 this._initCommandGroup(helpCommand);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 455–464why, one step back
455 return this;
456 }457458 /**459 * Lazy create help command.460 *461 * @return {(Command|null)}462 * @package463 */464 _getHelpCommand() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 465–469why, one step back
465 const hasImplicitHelpCommand =
466 this._addImplicitHelpCommand ??467 (this.commands.length &&468 !this._actionHandler &&469 !this._findCommand('help'));

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 470–475why, one step back
470
471 if (hasImplicitHelpCommand) {472 if (this._helpCommand === undefined) {473 this.helpCommand(undefined, undefined); // use default name and description474 }475 return this._helpCommand;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 476why, one step back
476 }

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 477why, one step back
477 return null;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 478–530why, one step back
478 }
479480 /**481 * Add hook for life cycle event.482 *483 * @param {string} event484 * @param {Function} listener485 * @return {Command} `this` command for chaining486 */487488 hook(event, listener) {489 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];490 if (!allowedValues.includes(event)) {491 throw new Error(`Unexpected value for event passed to hook : '${event}'.492Expecting one of '${allowedValues.join("', '")}'`);493 }494 if (this._lifeCycleHooks[event]) {495 this._lifeCycleHooks[event].push(listener);496 } else {497 this._lifeCycleHooks[event] = [listener];498 }499 return this;500 }501502 /**503 * Register callback to use as replacement for calling process.exit.504 *505 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing506 * @return {Command} `this` command for chaining507 */508509 exitOverride(fn) {510 if (fn) {511 this._exitCallback = fn;512 } else {513 this._exitCallback = (err) => {514 if (err.code !== 'commander.executeSubCommandAsync') {515 throw err;516 } else {517 // Async callback from spawn events, not useful to throw.518 }519 };520 }521 return this;522 }523524 /**525 * Call process.exit, and _exitCallback if defined.526 *527 * @param {number} exitCode exit code for using with process.exit528 * @param {string} code an id string representing the error529 * @param {string} message human-readable description of the error530 * @return never

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 531why, one step back
531 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 532–559why, one step back
532 */
533534 _exit(exitCode, code, message) {535 if (this._exitCallback) {536 this._exitCallback(new CommanderError(exitCode, code, message));537 // Expecting this line is not reached.538 }539 process.exit(exitCode);540 }541542 /**543 * Register callback `fn` for the command.544 *545 * @example546 * program547 * .command('serve')548 * .description('start service')549 * .action(function() {550 * // do work here551 * });552 *553 * @param {Function} fn554 * @return {Command} `this` command for chaining555 */556557 action(fn) {558 const listener = (args) => {559 // The .action callback takes an extra parameter which is the command or options.

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 560why, one step back
560 const expectedArgsCount = this.registeredArguments.length;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 561–590why, one step back
561 const actionArgs = args.slice(0, expectedArgsCount);
562 if (this._storeOptionsAsProperties) {563 actionArgs[expectedArgsCount] = this; // backwards compatible "options"564 } else {565 actionArgs[expectedArgsCount] = this.opts();566 }567 actionArgs.push(this);568569 return fn.apply(this, actionArgs);570 };571 this._actionHandler = listener;572 return this;573 }574575 /**576 * Factory routine to create a new unattached option.577 *578 * See .option() for creating an attached option, which uses this routine to579 * create the option. You can override createOption to return a custom option.580 *581 * @param {string} flags582 * @param {string} [description]583 * @return {Option} new option584 */585586 createOption(flags, description) {587 return new Option(flags, description);588 }589590 /**

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

lines 591–592why, one step back
591 * Wrap parseArgs to catch 'commander.invalidArgument'.
592 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 593why, one step back
593 * @param {(Option | Argument)} target

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 594why, one step back
594 * @param {string} value

Replace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6

line 595why, one step back
595 * @param {*} previous

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 596why, one step back
596 * @param {string} invalidArgumentMessage

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 597why, one step back
597 * @private

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

lines 598–612why, one step back
598 */
599600 _callParseArg(target, value, previous, invalidArgumentMessage) {601 try {602 return target.parseArg(value, previous);603 } catch (err) {604 if (err.code === 'commander.invalidArgument') {605 const message = `${invalidArgumentMessage} ${err.message}`;606 this.error(message, { exitCode: err.exitCode, code: err.code });607 }608 throw err;609 }610 }611612 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 613–616why, one step back
613 * Check for option flag conflicts.
614 * Register option if no conflicts found, or throw on conflict.615 *616 * @param {Option} option

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 617why, one step back
617 * @private

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 618–620why, one step back
618 */
619620 _registerOption(option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 621–622why, one step back
621 const matchingOption =
622 (option.short && this._findOption(option.short)) ||

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 623–624why, one step back
623 (option.long && this._findOption(option.long));
624 if (matchingOption) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 625–628why, one step back
625 const matchingFlag =
626 option.long && this._findOption(option.long)627 ? option.long628 : option.short;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 629–632why, one step back
629 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
630- already used by option '${matchingOption.flags}'`);631 }632

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

line 633why, one step back
633 this._initOptionGroup(option);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 634–641why, one step back
634 this.options.push(option);
635 }636637 /**638 * Check for command name and alias conflicts with existing commands.639 * Register command if no conflicts found, or throw on conflict.640 *641 * @param {Command} command

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 642why, one step back
642 * @private

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 643–649why, one step back
643 */
644645 _registerCommand(command) {646 const knownBy = (cmd) => {647 return [cmd.name()].concat(cmd.aliases());648 };649

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 650–652why, one step back
650 const alreadyUsed = knownBy(command).find((name) =>
651 this._findCommand(name),652 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 653–655why, one step back
653 if (alreadyUsed) {
654 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');655 const newCmd = knownBy(command).join('|');

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 656–658why, one step back
656 throw new Error(
657 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,658 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 659–660why, one step back
659 }
660

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

line 661why, one step back
661 this._initCommandGroup(command);

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 662–665why, one step back
662 this.commands.push(command);
663 }664665 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 666–671why, one step back
666 * Add an option.
667 *668 * @param {Option} option669 * @return {Command} `this` command for chaining670 */671 addOption(option) {

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 672–673why, one step back
672 this._registerOption(option);
673

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 674–677why, one step back
674 const oname = option.name();
675 const name = option.attributeName();676677 // store default value

Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a

line 678why, one step back
678 if (option.defaultValue !== undefined) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 679–692why, one step back
679 this.setOptionValueWithSource(name, option.defaultValue, 'default');
680 }681682 // handler for cli and env supplied values683 const handleOptionValue = (val, invalidValueMessage, valueSource) => {684 // val is null for optional option used without an optional-argument.685 // val is undefined for boolean and negated option.686 if (val == null && option.presetArg !== undefined) {687 val = option.presetArg;688 }689690 // custom processing691 const oldValue = this.getOptionValue(name);692 if (val !== null && option.parseArg) {

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 693why, one step back
693 val = this._callParseArg(option, val, oldValue, invalidValueMessage);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 694why, one step back
694 } else if (val !== null && option.variadic) {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 695why, one step back
695 val = option._collectValue(val, oldValue);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 696–728why, one step back
696 }
697698 // Fill-in appropriate missing values. Long winded but easy to follow.699 if (val == null) {700 if (option.negate) {701 val = false;702 } else if (option.isBoolean() || option.optional) {703 val = true;704 } else {705 val = ''; // not normal, parseArg might have failed or be a mock function for testing706 }707 }708 this.setOptionValueWithSource(name, val, valueSource);709 };710711 this.on('option:' + oname, (val) => {712 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;713 handleOptionValue(val, invalidValueMessage, 'cli');714 });715716 if (option.envVar) {717 this.on('optionEnv:' + oname, (val) => {718 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;719 handleOptionValue(val, invalidValueMessage, 'env');720 });721 }722723 return this;724 }725726 /**727 * Internal implementation shared by .option() and .requiredOption()728 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 729why, one step back
729 * @return {Command} `this` command for chaining

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 730why, one step back
730 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 731–733why, one step back
731 */
732 _optionEx(config, flags, description, fn, defaultValue) {733 if (typeof flags === 'object' && flags instanceof Option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 734–736why, one step back
734 throw new Error(
735 'To add an Option object use addOption() instead of option() or requiredOption()',736 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 737–757why, one step back
737 }
738 const option = this.createOption(flags, description);739 option.makeOptionMandatory(!!config.mandatory);740 if (typeof fn === 'function') {741 option.default(defaultValue).argParser(fn);742 } else if (fn instanceof RegExp) {743 // deprecated744 const regex = fn;745 fn = (val, def) => {746 const m = regex.exec(val);747 return m ? m[0] : def;748 };749 option.default(defaultValue).argParser(fn);750 } else {751 option.default(fn);752 }753754 return this.addOption(option);755 }756757 /**

Rework option inline doc (#2009)John Geebefore adoptione85e05a

line 758why, one step back
758 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 759why, one step back
759 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 760–761why, one step back
760 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
761 * option-argument is indicated by `<>` and an optional option-argument by `[]`.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 762why, one step back
762 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

line 763why, one step back
763 * See the README for more details, and see also addOption() and requiredOption().

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 764–765why, one step back
764 *
765 * @example

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 766–767why, one step back
766 * program
767 * .option('-p, --pepper', 'add pepper')

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

line 768why, one step back
768 * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 769–770why, one step back
769 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
770 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 771–773why, one step back
771 *
772 * @param {string} flags773 * @param {string} [description]

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 774why, one step back
774 * @param {(Function|*)} [parseArg] - custom option processing function or default value

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 775–778why, one step back
775 * @param {*} [defaultValue]
776 * @return {Command} `this` command for chaining777 */778

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 779–780why, one step back
779 option(flags, description, parseArg, defaultValue) {
780 return this._optionEx({}, flags, description, parseArg, defaultValue);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 781–783why, one step back
781 }
782783 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 784–794why, one step back
784 * Add a required option which must have a value after parsing. This usually means
785 * the option must be specified on the command line. (Otherwise the same as .option().)786 *787 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.788 *789 * @param {string} flags790 * @param {string} [description]791 * @param {(Function|*)} [parseArg] - custom option processing function or default value792 * @param {*} [defaultValue]793 * @return {Command} `this` command for chaining794 */

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 795why, one step back
795

Rework option inline doc (#2009)John Geebefore adoptione85e05a

line 796why, one step back
796 requiredOption(flags, description, parseArg, defaultValue) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 797–803why, one step back
797 return this._optionEx(
798 { mandatory: true },799 flags,800 description,801 parseArg,802 defaultValue,803 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 804–813why, one step back
804 }
805806 /**807 * Alter parsing of short flags with optional values.808 *809 * @example810 * // for `.option('-f,--flag [value]'):811 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour812 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`813 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 814–815why, one step back
814 * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
815 * @return {Command} `this` command for chaining

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 816–824why, one step back
816 */
817 combineFlagAndOptionalValue(combine = true) {818 this._combineFlagAndOptionalValue = !!combine;819 return this;820 }821822 /**823 * Allow unknown options on the command line.824 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 825–826why, one step back
825 * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
826 * @return {Command} `this` command for chaining

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 827–835why, one step back
827 */
828 allowUnknownOption(allowUnknown = true) {829 this._allowUnknownOption = !!allowUnknown;830 return this;831 }832833 /**834 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.835 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 836–837why, one step back
836 * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
837 * @return {Command} `this` command for chaining

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 838–848why, one step back
838 */
839 allowExcessArguments(allowExcess = true) {840 this._allowExcessArguments = !!allowExcess;841 return this;842 }843844 /**845 * Enable positional options. Positional means global options are specified before subcommands which lets846 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.847 * The default behaviour is non-positional and global options may appear anywhere on the command line.848 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 849–850why, one step back
849 * @param {boolean} [positional]
850 * @return {Command} `this` command for chaining

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 851–862why, one step back
851 */
852 enablePositionalOptions(positional = true) {853 this._enablePositionalOptions = !!positional;854 return this;855 }856857 /**858 * Pass through options that come after command-arguments rather than treat them as command-options,859 * so actual command-options come before command-arguments. Turning this on for a subcommand requires860 * positional options to have been enabled on the program (parent commands).861 * The default behaviour is non-positional and options may appear before or after command-arguments.862 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 863–864why, one step back
863 * @param {boolean} [passThrough] for unknown options.
864 * @return {Command} `this` command for chaining

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 865–867why, one step back
865 */
866 passThroughOptions(passThrough = true) {867 this._passThroughOptions = !!passThrough;

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 868why, one step back
868 this._checkForBrokenPassThrough();

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 869–872why, one step back
869 return this;
870 }871872 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 873–876why, one step back
873 * @private
874 */875876 _checkForBrokenPassThrough() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 877–884why, one step back
877 if (
878 this.parent &&879 this._passThroughOptions &&880 !this.parent._enablePositionalOptions881 ) {882 throw new Error(883 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,884 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 885–888why, one step back
885 }
886 }887888 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 889–894why, one step back
889 * Whether to store option values as properties on command object,
890 * or store separately (specify false). In both cases the option values can be accessed using .opts().891 *892 * @param {boolean} [storeAsProperties=true]893 * @return {Command} `this` command for chaining894 */

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 895–899why, one step back
895
896 storeOptionsAsProperties(storeAsProperties = true) {897 if (this.options.length) {898 throw new Error('call .storeOptionsAsProperties() before adding options');899 }

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 900why, one step back
900 if (Object.keys(this._optionValues).length) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 901–903why, one step back
901 throw new Error(
902 'call .storeOptionsAsProperties() before setting option values',903 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 904why, one step back
904 }

Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e

line 905why, one step back
905 this._storeOptionsAsProperties = !!storeAsProperties;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 906–912why, one step back
906 return this;
907 }908909 /**910 * Retrieve option value.911 *912 * @param {string} key

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 913why, one step back
913 * @return {object} value

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 914–926why, one step back
914 */
915916 getOptionValue(key) {917 if (this._storeOptionsAsProperties) {918 return this[key];919 }920 return this._optionValues[key];921 }922923 /**924 * Store option value.925 *926 * @param {string} key

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 927why, one step back
927 * @param {object} value

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 928–935why, one step back
928 * @return {Command} `this` command for chaining
929 */930931 setOptionValue(key, value) {932 return this.setOptionValueWithSource(key, value, undefined);933 }934935 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 936–938why, one step back
936 * Store option value and where the value came from.
937 *938 * @param {string} key

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 939why, one step back
939 * @param {object} value

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 940–942why, one step back
940 * @param {string} source - expected values are default/config/env/cli/implied
941 * @return {Command} `this` command for chaining942 */

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 943–954why, one step back
943
944 setOptionValueWithSource(key, value, source) {945 if (this._storeOptionsAsProperties) {946 this[key] = value;947 } else {948 this._optionValues[key] = value;949 }950 this._optionValueSources[key] = source;951 return this;952 }953954 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 955–960why, one step back
955 * Get source of option value.
956 * Expected values are default | config | env | cli | implied957 *958 * @param {string} key959 * @return {string}960 */

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 961–966why, one step back
961
962 getOptionValueSource(key) {963 return this._optionValueSources[key];964 }965966 /**

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 967–972why, one step back
967 * Get source of option value. See also .optsWithGlobals().
968 * Expected values are default | config | env | cli | implied969 *970 * @param {string} key971 * @return {string}972 */

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 973–976why, one step back
973
974 getOptionValueSourceWithGlobals(key) {975 // global overwrites local, like optsWithGlobals976 let source;

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 977why, one step back
977 this._getCommandAndAncestors().forEach((cmd) => {

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

lines 978–985why, one step back
978 if (cmd.getOptionValueSource(key) !== undefined) {
979 source = cmd.getOptionValueSource(key);980 }981 });982 return source;983 }984985 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 986–988why, one step back
986 * Get user arguments from implied or explicit arguments.
987 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.988 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 989why, one step back
989 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 990–997why, one step back
990 */
991992 _prepareUserArgs(argv, parseOptions) {993 if (argv !== undefined && !Array.isArray(argv)) {994 throw new Error('first parameter to parse must be array or undefined');995 }996 parseOptions = parseOptions || {};997

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 998–1000why, one step back
998 // auto-detect argument conventions if nothing supplied
999 if (argv === undefined && parseOptions.from === undefined) {1000 if (process.versions?.electron) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1001–1002why, one step back
1001 parseOptions.from = 'electron';
1002 }

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1003–1012why, one step back
1003 // check node specific options for scenarios where user CLI args follow executable without scriptname
1004 const execArgv = process.execArgv ?? [];1005 if (1006 execArgv.includes('-e') ||1007 execArgv.includes('--eval') ||1008 execArgv.includes('-p') ||1009 execArgv.includes('--print')1010 ) {1011 parseOptions.from = 'eval'; // internal usage, not documented1012 }

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1013why, one step back
1013 }

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1014–1018why, one step back
1014
1015 // default to using process.argv1016 if (argv === undefined) {1017 argv = process.argv;1018 }

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1019–1020why, one step back
1019 this.rawArgs = argv.slice();
1020

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1021why, one step back
1021 // extract the user args and scriptPath

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1022–1029why, one step back
1022 let userArgs;
1023 switch (parseOptions.from) {1024 case undefined:1025 case 'node':1026 this._scriptPath = argv[1];1027 userArgs = argv.slice(2);1028 break;1029 case 'electron':

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 1030why, one step back
1030 // @ts-ignore: because defaultApp is an unknown property

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1031–1040why, one step back
1031 if (process.defaultApp) {
1032 this._scriptPath = argv[1];1033 userArgs = argv.slice(2);1034 } else {1035 userArgs = argv.slice(1);1036 }1037 break;1038 case 'user':1039 userArgs = argv.slice(0);1040 break;

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1041–1043why, one step back
1041 case 'eval':
1042 userArgs = argv.slice(1);1043 break;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1044why, one step back
1044 default:

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1045–1047why, one step back
1045 throw new Error(
1046 `unexpected parse option { from: '${parseOptions.from}' }`,1047 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1048–1050why, one step back
1048 }
10491050 // Find default name for program from arguments.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1051–1052why, one step back
1051 if (!this._name && this._scriptPath)
1052 this.nameFromFilename(this._scriptPath);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1053–1060why, one step back
1053 this._name = this._name || 'program';
10541055 return userArgs;1056 }10571058 /**1059 * Parse `argv`, setting options and invoking commands when defined.1060 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1061why, one step back
1061 * Use parseAsync instead of parse if any of your action handlers are async.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1062why, one step back
1062 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1063–1069why, one step back
1063 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1064 *1065 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1066 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1067 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1068 * - `'user'`: just user arguments1069 *

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1070why, one step back
1070 * @example

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1071–1072why, one step back
1071 * program.parse(); // parse process.argv and auto-detect electron and special node flags
1072 * program.parse(process.argv); // assume argv[0] is app and argv[1] is script

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1073–1074why, one step back
1073 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1074 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

lines 1075–1077why, one step back
1075 * @param {string[]} [argv] - optional, defaults to process.argv
1076 * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1077 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1078–1081why, one step back
1078 * @return {Command} `this` command for chaining
1079 */10801081 parse(argv, parseOptions) {

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1082why, one step back
1082 this._prepareForParse();

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1083–1091why, one step back
1083 const userArgs = this._prepareUserArgs(argv, parseOptions);
1084 this._parseCommand([], userArgs);10851086 return this;1087 }10881089 /**1090 * Parse `argv`, setting options and invoking commands when defined.1091 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1092why, one step back
1092 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1093why, one step back
1093 *

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1094–1097why, one step back
1094 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1095 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1096 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1097 * - `'user'`: just user arguments

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1098–1099why, one step back
1098 *
1099 * @example

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 1100–1101why, one step back
1100 * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1101 * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1102–1104why, one step back
1102 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1103 *1104 * @param {string[]} [argv]

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 1105why, one step back
1105 * @param {object} [parseOptions]

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1106why, one step back
1106 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1107–1110why, one step back
1107 * @return {Promise}
1108 */11091110 async parseAsync(argv, parseOptions) {

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1111why, one step back
1111 this._prepareForParse();

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1112–1117why, one step back
1112 const userArgs = this._prepareUserArgs(argv, parseOptions);
1113 await this._parseCommand([], userArgs);11141115 return this;1116 }1117

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1118why, one step back
1118 _prepareForParse() {

Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a

line 1119why, one step back
1119 // Save the state the first time, then restore the state before each subsequent parse.

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1120why, one step back
1120 if (this._savedState === null) {

Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a

lines 1121–1141why, one step back
1121 // Do the special default of lone negated option to true, now that we have all the options.
1122 // Filter for negated options that have not been processed already.1123 this.options1124 .filter(1125 (option) =>1126 option.negate &&1127 option.defaultValue === undefined &&1128 this.getOptionValue(option.attributeName()) === undefined,1129 )1130 .forEach((option) => {1131 // check for lone negated option: --no-foo without a --foo option1132 const positiveLongFlag = option.long.replace(/^--no-/, '--');1133 if (!this._findOption(positiveLongFlag)) {1134 this.setOptionValueWithSource(1135 option.attributeName(),1136 true,1137 'default',1138 );1139 }1140 });1141

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

lines 1142–1147why, one step back
1142 this.saveStateBeforeParse();
1143 } else {1144 this.restoreStateBeforeParse();1145 }1146 }1147

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1148why, one step back
1148 /**

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

lines 1149–1189why, one step back
1149 * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1150 * Not usually called directly, but available for subclasses to save their custom state.1151 *1152 * This is called in a lazy way. Only commands used in parsing chain will have state saved.1153 */1154 saveStateBeforeParse() {1155 this._savedState = {1156 // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing1157 _name: this._name,1158 // option values before parse have default values (including false for negated options)1159 // shallow clones1160 _optionValues: { ...this._optionValues },1161 _optionValueSources: { ...this._optionValueSources },1162 };1163 }11641165 /**1166 * Restore state before parse for calls after the first.1167 * Not usually called directly, but available for subclasses to save their custom state.1168 *1169 * This is called in a lazy way. Only commands used in parsing chain will have state restored.1170 */1171 restoreStateBeforeParse() {1172 if (this._storeOptionsAsProperties)1173 throw new Error(`Can not call parse again when storeOptionsAsProperties is true.1174- either make a new Command for each call to parse, or stop storing options as properties`);11751176 // clear state from _prepareUserArgs1177 this._name = this._savedState._name;1178 this._scriptPath = null;1179 this.rawArgs = [];1180 // clear state from setOptionValueWithSource1181 this._optionValues = { ...this._savedState._optionValues };1182 this._optionValueSources = { ...this._savedState._optionValueSources };1183 // clear state from _parseCommand1184 this.args = [];1185 // clear state from _processArguments1186 this.processedArgs = [];1187 }11881189 /**

Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf

lines 1190–1209why, one step back
1190 * Throw if expected executable is missing. Add lots of help for author.
1191 *1192 * @param {string} executableFile1193 * @param {string} executableDir1194 * @param {string} subcommandName1195 */1196 _checkForMissingExecutable(executableFile, executableDir, subcommandName) {1197 if (fs.existsSync(executableFile)) return;11981199 const executableDirMessage = executableDir1200 ? `searched for local subcommand relative to directory '${executableDir}'`1201 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1202 const executableMissing = `'${executableFile}' does not exist1203 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1204 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1205 - ${executableDirMessage}`;1206 throw new Error(executableMissing);1207 }12081209 /**

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1210–1211why, one step back
1210 * Execute a sub-command executable.
1211 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1212why, one step back
1212 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1213–1227why, one step back
1213 */
12141215 _executeSubCommand(subcommand, args) {1216 args = args.slice();1217 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];12181219 function findFile(baseDir, baseName) {1220 // Look for specified file1221 const localBin = path.resolve(baseDir, baseName);1222 if (fs.existsSync(localBin)) return localBin;12231224 // Stop looking if candidate already has an expected extension.1225 if (sourceExt.includes(path.extname(baseName))) return undefined;12261227 // Try all the extensions.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1228–1230why, one step back
1228 const foundExt = sourceExt.find((ext) =>
1229 fs.existsSync(`${localBin}${ext}`),1230 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1231–1240why, one step back
1231 if (foundExt) return `${localBin}${foundExt}`;
12321233 return undefined;1234 }12351236 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1237 this._checkForMissingMandatoryOptions();1238 this._checkForConflictingOptions();12391240 // executableFile and executableDir might be full path, or just a name

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1241–1242why, one step back
1241 let executableFile =
1242 subcommand._executableFile || `${this._name}-${subcommand._name}`;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1243–1247why, one step back
1243 let executableDir = this._executableDir || '';
1244 if (this._scriptPath) {1245 let resolvedScriptPath; // resolve possible symlink for installed npm binary1246 try {1247 resolvedScriptPath = fs.realpathSync(this._scriptPath);

Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585

line 1248why, one step back
1248 } catch {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1249–1250why, one step back
1249 resolvedScriptPath = this._scriptPath;
1250 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1251–1254why, one step back
1251 executableDir = path.resolve(
1252 path.dirname(resolvedScriptPath),1253 executableDir,1254 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1255–1262why, one step back
1255 }
12561257 // Look for a local file in preference to a command in PATH.1258 if (executableDir) {1259 let localFile = findFile(executableDir, executableFile);12601261 // Legacy search using prefix of script name instead of command name1262 if (!localFile && !subcommand._executableFile && this._scriptPath) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1263–1266why, one step back
1263 const legacyName = path.basename(
1264 this._scriptPath,1265 path.extname(this._scriptPath),1266 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1267why, one step back
1267 if (legacyName !== this._name) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1268–1271why, one step back
1268 localFile = findFile(
1269 executableDir,1270 `${legacyName}-${subcommand._name}`,1271 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1272–1276why, one step back
1272 }
1273 }1274 executableFile = localFile || executableFile;1275 }1276

Update dependecies and lint (#2489)John Geebefore adoption0ea3bb3

line 1277why, one step back
1277 const launchWithNode = sourceExt.includes(path.extname(executableFile));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1278–1290why, one step back
1278
1279 let proc;1280 if (process.platform !== 'win32') {1281 if (launchWithNode) {1282 args.unshift(executableFile);1283 // add executable arguments to spawn1284 args = incrementNodeInspectorPort(process.execArgv).concat(args);12851286 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1287 } else {1288 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1289 }1290 } else {

Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf

lines 1291–1295why, one step back
1291 this._checkForMissingExecutable(
1292 executableFile,1293 executableDir,1294 subcommand._name,1295 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1296–1301why, one step back
1296 args.unshift(executableFile);
1297 // add executable arguments to spawn1298 args = incrementNodeInspectorPort(process.execArgv).concat(args);1299 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1300 }1301

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1302–1303why, one step back
1302 if (!proc.killed) {
1303 // testing mainly to avoid leak warnings during unit tests with mocked spawn

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1304–1307why, one step back
1304 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1305 signals.forEach((signal) => {1306 process.on(signal, () => {1307 if (proc.killed === false && proc.exitCode === null) {

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1308why, one step back
1308 // @ts-ignore because signals not typed to known strings

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1309–1316why, one step back
1309 proc.kill(signal);
1310 }1311 });1312 });1313 }13141315 // By default terminate process when spawned process terminates.1316 const exitCallback = this._exitCallback;

ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e

line 1317why, one step back
1317 proc.on('close', (code) => {

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1318–1321why, one step back
1318 code = code ?? 1; // code is null if spawned process terminated due to a signal
1319 if (!exitCallback) {1320 process.exit(code);1321 } else {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1322–1328why, one step back
1322 exitCallback(
1323 new CommanderError(1324 code,1325 'commander.executeSubCommandAsync',1326 '(close)',1327 ),1328 );

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1329–1330why, one step back
1329 }
1330 });

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1331why, one step back
1331 proc.on('error', (err) => {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1332why, one step back
1332 // @ts-ignore: because err.code is an unknown property

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1333why, one step back
1333 if (err.code === 'ENOENT') {

Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf

lines 1334–1338why, one step back
1334 this._checkForMissingExecutable(
1335 executableFile,1336 executableDir,1337 subcommand._name,1338 );

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1339why, one step back
1339 // @ts-ignore: because err.code is an unknown property

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1340–1345why, one step back
1340 } else if (err.code === 'EACCES') {
1341 throw new Error(`'${executableFile}' not executable`);1342 }1343 if (!exitCallback) {1344 process.exit(1);1345 } else {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1346–1350why, one step back
1346 const wrappedError = new CommanderError(
1347 1,1348 'commander.executeSubCommandAsync',1349 '(error)',1350 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1351–1360why, one step back
1351 wrappedError.nestedError = err;
1352 exitCallback(wrappedError);1353 }1354 });13551356 // Store the reference to the child process1357 this.runningCommand = proc;1358 }13591360 /**

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1361why, one step back
1361 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1362–1367why, one step back
1362 */
13631364 _dispatchSubcommand(commandName, operands, unknown) {1365 const subCommand = this._findCommand(commandName);1366 if (!subCommand) this.help({ error: true });1367

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

line 1368why, one step back
1368 subCommand._prepareForParse();

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1369why, one step back
1369 let promiseChain;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1370–1374why, one step back
1370 promiseChain = this._chainOrCallSubCommandHook(
1371 promiseChain,1372 subCommand,1373 'preSubcommand',1374 );

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1375why, one step back
1375 promiseChain = this._chainOrCall(promiseChain, () => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1376–1381why, one step back
1376 if (subCommand._executableHandler) {
1377 this._executeSubCommand(subCommand, operands.concat(unknown));1378 } else {1379 return subCommand._parseCommand(operands, unknown);1380 }1381 });

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1382why, one step back
1382 return promiseChain;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1383–1385why, one step back
1383 }
13841385 /**

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

lines 1386–1388why, one step back
1386 * Invoke help directly if possible, or dispatch if necessary.
1387 * e.g. help foo1388 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1389why, one step back
1389 * @private

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

lines 1390–1401why, one step back
1390 */
13911392 _dispatchHelpCommand(subcommandName) {1393 if (!subcommandName) {1394 this.help();1395 }1396 const subCommand = this._findCommand(subcommandName);1397 if (subCommand && !subCommand._executableHandler) {1398 subCommand.help();1399 }14001401 // Fallback to parsing the help flag to invoke the help.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1402–1406why, one step back
1402 return this._dispatchSubcommand(
1403 subcommandName,1404 [],1405 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1406 );

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

lines 1407–1409why, one step back
1407 }
14081409 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1410why, one step back
1410 * Check this.args against expected this.registeredArguments.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1411why, one step back
1411 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1412why, one step back
1412 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1413–1416why, one step back
1413 */
14141415 _checkNumberOfArguments() {1416 // too few

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1417why, one step back
1417 this.registeredArguments.forEach((arg, i) => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1418–1422why, one step back
1418 if (arg.required && this.args[i] == null) {
1419 this.missingArgument(arg.name());1420 }1421 });1422 // too many

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1423–1426why, one step back
1423 if (
1424 this.registeredArguments.length > 0 &&1425 this.registeredArguments[this.registeredArguments.length - 1].variadic1426 ) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1427–1428why, one step back
1427 return;
1428 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1429why, one step back
1429 if (this.args.length > this.registeredArguments.length) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1430–1434why, one step back
1430 this._excessArguments(this.args);
1431 }1432 }14331434 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1435why, one step back
1435 * Process this.args using this.registeredArguments and save as this.processedArgs!

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1436why, one step back
1436 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1437why, one step back
1437 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1438–1444why, one step back
1438 */
14391440 _processArguments() {1441 const myParseArg = (argument, value, previous) => {1442 // Extra processing for nice error message on parsing failure.1443 let parsedValue = value;1444 if (value !== null && argument.parseArg) {

Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1

line 1445why, one step back
1445 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1446–1451why, one step back
1446 parsedValue = this._callParseArg(
1447 argument,1448 value,1449 previous,1450 invalidValueMessage,1451 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1452–1458why, one step back
1452 }
1453 return parsedValue;1454 };14551456 this._checkNumberOfArguments();14571458 const processedArgs = [];

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1459why, one step back
1459 this.registeredArguments.forEach((declaredArg, index) => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1460–1486why, one step back
1460 let value = declaredArg.defaultValue;
1461 if (declaredArg.variadic) {1462 // Collect together remaining arguments for passing together as an array.1463 if (index < this.args.length) {1464 value = this.args.slice(index);1465 if (declaredArg.parseArg) {1466 value = value.reduce((processed, v) => {1467 return myParseArg(declaredArg, v, processed);1468 }, declaredArg.defaultValue);1469 }1470 } else if (value === undefined) {1471 value = [];1472 }1473 } else if (index < this.args.length) {1474 value = this.args[index];1475 if (declaredArg.parseArg) {1476 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1477 }1478 }1479 processedArgs[index] = value;1480 });1481 this.processedArgs = processedArgs;1482 }14831484 /**1485 * Once we have a promise we chain, but call synchronously until then.1486 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1487why, one step back
1487 * @param {(Promise|undefined)} promise

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1488why, one step back
1488 * @param {Function} fn

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1489–1490why, one step back
1489 * @return {(Promise|undefined)}
1490 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1491–1494why, one step back
1491 */
14921493 _chainOrCall(promise, fn) {1494 // thenable

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1495why, one step back
1495 if (promise?.then && typeof promise.then === 'function') {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1496–1504why, one step back
1496 // already have a promise, chain callback
1497 return promise.then(() => fn());1498 }1499 // callback might return a promise1500 return fn();1501 }15021503 /**1504 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1505why, one step back
1505 * @param {(Promise|undefined)} promise

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1506why, one step back
1506 * @param {string} event

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1507–1508why, one step back
1507 * @return {(Promise|undefined)}
1508 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1509–1513why, one step back
1509 */
15101511 _chainOrCallHooks(promise, event) {1512 let result = promise;1513 const hooks = [];

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 1514why, one step back
1514 this._getCommandAndAncestors()

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1515why, one step back
1515 .reverse()

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1516–1517why, one step back
1516 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
1517 .forEach((hookedCommand) => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1518–1535why, one step back
1518 hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1519 hooks.push({ hookedCommand, callback });1520 });1521 });1522 if (event === 'postAction') {1523 hooks.reverse();1524 }15251526 hooks.forEach((hookDetail) => {1527 result = this._chainOrCall(result, () => {1528 return hookDetail.callback(hookDetail.hookedCommand, this);1529 });1530 });1531 return result;1532 }15331534 /**1535 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1536why, one step back
1536 * @param {(Promise|undefined)} promise

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1537–1538why, one step back
1537 * @param {Command} subCommand
1538 * @param {string} event

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

lines 1539–1540why, one step back
1539 * @return {(Promise|undefined)}
1540 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1541–1558why, one step back
1541 */
15421543 _chainOrCallSubCommandHook(promise, subCommand, event) {1544 let result = promise;1545 if (this._lifeCycleHooks[event] !== undefined) {1546 this._lifeCycleHooks[event].forEach((hook) => {1547 result = this._chainOrCall(result, () => {1548 return hook(this, subCommand);1549 });1550 });1551 }1552 return result;1553 }15541555 /**1556 * Process arguments in context of this command.1557 * Returns action result, in case it is a promise.1558 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1559why, one step back
1559 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1560–1572why, one step back
1560 */
15611562 _parseCommand(operands, unknown) {1563 const parsed = this.parseOptions(unknown);1564 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1565 this._parseOptionsImplied();1566 operands = operands.concat(parsed.operands);1567 unknown = parsed.unknown;1568 this.args = operands.concat(unknown);15691570 if (operands && this._findCommand(operands[0])) {1571 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1572 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1573–1576why, one step back
1573 if (
1574 this._getHelpCommand() &&1575 operands[0] === this._getHelpCommand().name()1576 ) {

Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac

line 1577why, one step back
1577 return this._dispatchHelpCommand(operands[1]);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1578–1579why, one step back
1578 }
1579 if (this._defaultCommandName) {

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1580why, one step back
1580 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1581–1585why, one step back
1581 return this._dispatchSubcommand(
1582 this._defaultCommandName,1583 operands,1584 unknown,1585 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1586why, one step back
1586 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1587–1592why, one step back
1587 if (
1588 this.commands.length &&1589 this.args.length === 0 &&1590 !this._actionHandler &&1591 !this._defaultCommandName1592 ) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1593–1596why, one step back
1593 // probably missing subcommand and no handler, user needs help (and exit)
1594 this.help({ error: true });1595 }1596

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1597why, one step back
1597 this._outputHelpIfRequested(parsed.unknown);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1598–1612why, one step back
1598 this._checkForMissingMandatoryOptions();
1599 this._checkForConflictingOptions();16001601 // We do not always call this check to avoid masking a "better" error, like unknown command.1602 const checkForUnknownOptions = () => {1603 if (parsed.unknown.length > 0) {1604 this.unknownOption(parsed.unknown[0]);1605 }1606 };16071608 const commandEvent = `command:${this.name()}`;1609 if (this._actionHandler) {1610 checkForUnknownOptions();1611 this._processArguments();1612

Improve chain variable name (#1958)John Geebefore adoption5740e59

lines 1613–1614why, one step back
1613 let promiseChain;
1614 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1615–1617why, one step back
1615 promiseChain = this._chainOrCall(promiseChain, () =>
1616 this._actionHandler(this.processedArgs),1617 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1618why, one step back
1618 if (this.parent) {

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1619why, one step back
1619 promiseChain = this._chainOrCall(promiseChain, () => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1620–1622why, one step back
1620 this.parent.emit(commandEvent, operands, unknown); // legacy
1621 });1622 }

Improve chain variable name (#1958)John Geebefore adoption5740e59

lines 1623–1624why, one step back
1623 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
1624 return promiseChain;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1625why, one step back
1625 }

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1626why, one step back
1626 if (this.parent?.listenerCount(commandEvent)) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1627–1630why, one step back
1627 checkForUnknownOptions();
1628 this._processArguments();1629 this.parent.emit(commandEvent, operands, unknown); // legacy1630 } else if (operands.length) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1631–1632why, one step back
1631 if (this._findCommand('*')) {
1632 // legacy default command

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1633–1657why, one step back
1633 return this._dispatchSubcommand('*', operands, unknown);
1634 }1635 if (this.listenerCount('command:*')) {1636 // skip option check, emit event for possible misspelling suggestion1637 this.emit('command:*', operands, unknown);1638 } else if (this.commands.length) {1639 this.unknownCommand();1640 } else {1641 checkForUnknownOptions();1642 this._processArguments();1643 }1644 } else if (this.commands.length) {1645 checkForUnknownOptions();1646 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1647 this.help({ error: true });1648 } else {1649 checkForUnknownOptions();1650 this._processArguments();1651 // fall through for caller to handle after calling .parse()1652 }1653 }16541655 /**1656 * Find matching command.1657 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1658why, one step back
1658 * @private

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1659why, one step back
1659 * @return {Command | undefined}

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1660–1662why, one step back
1660 */
1661 _findCommand(name) {1662 if (!name) return undefined;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1663–1665why, one step back
1663 return this.commands.find(
1664 (cmd) => cmd._name === name || cmd._aliases.includes(name),1665 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1666–1672why, one step back
1666 }
16671668 /**1669 * Return an option matching `arg` if any.1670 *1671 * @param {string} arg1672 * @return {Option}

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1673why, one step back
1673 * @package

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1674–1676why, one step back
1674 */
16751676 _findOption(arg) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1677why, one step back
1677 return this.options.find((option) => option.is(arg));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1678–1683why, one step back
1678 }
16791680 /**1681 * Display an error message if a mandatory option does not have a value.1682 * Called after checking for help flags in leaf subcommand.1683 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1684why, one step back
1684 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1685–1688why, one step back
1685 */
16861687 _checkForMissingMandatoryOptions() {1688 // Walk up hierarchy so can call in subcommand after checking for displaying help.

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1689why, one step back
1689 this._getCommandAndAncestors().forEach((cmd) => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1690why, one step back
1690 cmd.options.forEach((anOption) => {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1691–1694why, one step back
1691 if (
1692 anOption.mandatory &&1693 cmd.getOptionValue(anOption.attributeName()) === undefined1694 ) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1695–1697why, one step back
1695 cmd.missingMandatoryOptionValue(anOption);
1696 }1697 });

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1698why, one step back
1698 });

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1699–1703why, one step back
1699 }
17001701 /**1702 * Display an error message if conflicting options are used together in this.1703 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1704why, one step back
1704 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1705–1706why, one step back
1705 */
1706 _checkForConflictingLocalOptions() {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1707–1710why, one step back
1707 const definedNonDefaultOptions = this.options.filter((option) => {
1708 const optionKey = option.attributeName();1709 if (this.getOptionValue(optionKey) === undefined) {1710 return false;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1711why, one step back
1711 }

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1712–1713why, one step back
1712 return this.getOptionValueSource(optionKey) !== 'default';
1713 });

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1714–1715why, one step back
1714
1715 const optionsWithConflicting = definedNonDefaultOptions.filter(

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1716why, one step back
1716 (option) => option.conflictsWith.length > 0,

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1717–1720why, one step back
1717 );
17181719 optionsWithConflicting.forEach((option) => {1720 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1721why, one step back
1721 option.conflictsWith.includes(defined.attributeName()),

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1722–1732why, one step back
1722 );
1723 if (conflictingAndDefined) {1724 this._conflictingOption(option, conflictingAndDefined);1725 }1726 });1727 }17281729 /**1730 * Display an error message if conflicting options are used together.1731 * Called after checking for help flags in leaf subcommand.1732 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1733why, one step back
1733 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1734–1736why, one step back
1734 */
1735 _checkForConflictingOptions() {1736 // Walk up hierarchy so can call in subcommand after checking for displaying help.

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1737why, one step back
1737 this._getCommandAndAncestors().forEach((cmd) => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1738why, one step back
1738 cmd._checkForConflictingLocalOptions();

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1739why, one step back
1739 });

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1740–1744why, one step back
1740 }
17411742 /**1743 * Parse options from `argv` removing known options,1744 * and return argv split into operands and unknown arguments.

Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2

lines 1745–1746why, one step back
1745 *
1746 * Side effects: modifies command by storing options. Does not reset state if called again.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1747–1755why, one step back
1747 *
1748 * Examples:1749 *1750 * argv => operands, unknown1751 * --known kkk op => [op], []1752 * op --known kkk => [op], []1753 * sub --unknown uuu op => [sub], [--unknown uuu op]1754 * sub -- --unknown uuu op => [sub --unknown uuu op], []1755 *

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1756why, one step back
1756 * @param {string[]} args

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1757why, one step back
1757 * @return {{operands: string[], unknown: string[]}}

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1758–1759why, one step back
1758 */
1759

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1760why, one step back
1760 parseOptions(args) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1761–1768why, one step back
1761 const operands = []; // operands, not options or values
1762 const unknown = []; // first unknown option and remaining unknown args1763 let dest = operands;17641765 function maybeOption(arg) {1766 return arg.length > 1 && arg[0] === '-';1767 }1768

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1769–1770why, one step back
1769 const negativeNumberArg = (arg) => {
1770 // return false if not a negative number

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1771why, one step back
1771 if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1772–1779why, one step back
1772 // negative number is ok unless digit used as an option in command hierarchy
1773 return !this._getCommandAndAncestors().some((cmd) =>1774 cmd.options1775 .map((opt) => opt.short)1776 .some((short) => /^-\d$/.test(short)),1777 );1778 };1779

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1780–1781why, one step back
1780 // parse options
1781 let activeVariadicOption = null;

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1782–1786why, one step back
1782 let activeGroup = null; // working through group of short options, like -abc
1783 let i = 0;1784 while (i < args.length || activeGroup) {1785 const arg = activeGroup ?? args[i++];1786 activeGroup = null;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1787–1790why, one step back
1787
1788 // literal1789 if (arg === '--') {1790 if (dest === unknown) dest.push(arg);

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1791why, one step back
1791 dest.push(...args.slice(i));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1792–1794why, one step back
1792 break;
1793 }1794

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1795–1798why, one step back
1795 if (
1796 activeVariadicOption &&1797 (!maybeOption(arg) || negativeNumberArg(arg))1798 ) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1799–1808why, one step back
1799 this.emit(`option:${activeVariadicOption.name()}`, arg);
1800 continue;1801 }1802 activeVariadicOption = null;18031804 if (maybeOption(arg)) {1805 const option = this._findOption(arg);1806 // recognised option, call listener to assign value with possible custom processing1807 if (option) {1808 if (option.required) {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1809why, one step back
1809 const value = args[i++];

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1810–1814why, one step back
1810 if (value === undefined) this.optionMissingArgument(option);
1811 this.emit(`option:${option.name()}`, value);1812 } else if (option.optional) {1813 let value = null;1814 // historical behaviour is optional value is following arg unless an option

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

line 1815why, one step back
1815 if (

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1816–1817why, one step back
1816 i < args.length &&
1817 (!maybeOption(args[i]) || negativeNumberArg(args[i]))

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

line 1818why, one step back
1818 ) {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1819why, one step back
1819 value = args[i++];

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1820–1821why, one step back
1820 }
1821 this.emit(`option:${option.name()}`, value);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1822–1823why, one step back
1822 } else {
1823 // boolean flag

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1824–1834why, one step back
1824 this.emit(`option:${option.name()}`);
1825 }1826 activeVariadicOption = option.variadic ? option : null;1827 continue;1828 }1829 }18301831 // Look for combo options following single dash, eat first one if known.1832 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1833 const option = this._findOption(`-${arg[1]}`);1834 if (option) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1835–1838why, one step back
1835 if (
1836 option.required ||1837 (option.optional && this._combineFlagAndOptionalValue)1838 ) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1839–1841why, one step back
1839 // option with value following in same argument
1840 this.emit(`option:${option.name()}`, arg.slice(2));1841 } else {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1842why, one step back
1842 // boolean option

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1843why, one step back
1843 this.emit(`option:${option.name()}`);

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1844–1845why, one step back
1844 // remove the processed option and keep processing group
1845 activeGroup = `-${arg.slice(2)}`;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1846–1864why, one step back
1846 }
1847 continue;1848 }1849 }18501851 // Look for known long flag with value, like --foo=bar1852 if (/^--[^=]+=/.test(arg)) {1853 const index = arg.indexOf('=');1854 const option = this._findOption(arg.slice(0, index));1855 if (option && (option.required || option.optional)) {1856 this.emit(`option:${option.name()}`, arg.slice(index + 1));1857 continue;1858 }1859 }18601861 // Not a recognised option by this command.1862 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.18631864 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 1865–1870why, one step back
1865 // A negative number in a leaf command is not an unknown option.
1866 if (1867 dest === operands &&1868 maybeOption(arg) &&1869 !(this.commands.length === 0 && negativeNumberArg(arg))1870 ) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1871–1874why, one step back
1871 dest = unknown;
1872 }18731874 // If using positionalOptions, stop processing our options at subcommand.

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1875–1879why, one step back
1875 if (
1876 (this._enablePositionalOptions || this._passThroughOptions) &&1877 operands.length === 0 &&1878 unknown.length === 01879 ) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1880–1881why, one step back
1880 if (this._findCommand(arg)) {
1881 operands.push(arg);

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1882why, one step back
1882 unknown.push(...args.slice(i));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1883why, one step back
1883 break;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1884–1887why, one step back
1884 } else if (
1885 this._getHelpCommand() &&1886 arg === this._getHelpCommand().name()1887 ) {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1888why, one step back
1888 operands.push(arg, ...args.slice(i));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1889–1890why, one step back
1889 break;
1890 } else if (this._defaultCommandName) {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1891why, one step back
1891 unknown.push(arg, ...args.slice(i));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1892–1897why, one step back
1892 break;
1893 }1894 }18951896 // If using passThroughOptions, stop processing options at first command-argument.1897 if (this._passThroughOptions) {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1898why, one step back
1898 dest.push(arg, ...args.slice(i));

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1899–1911why, one step back
1899 break;
1900 }19011902 // add arg1903 dest.push(arg);1904 }19051906 return { operands, unknown };1907 }19081909 /**1910 * Return an object containing local option values as key-value pairs.1911 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1912why, one step back
1912 * @return {object}

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1913–1921why, one step back
1913 */
1914 opts() {1915 if (this._storeOptionsAsProperties) {1916 // Preserve original behaviour so backwards compatible when still using properties1917 const result = {};1918 const len = this.options.length;19191920 for (let i = 0; i < len; i++) {1921 const key = this.options[i].attributeName();

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1922–1923why, one step back
1922 result[key] =
1923 key === this._versionOptionName ? this._version : this[key];

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1924–1933why, one step back
1924 }
1925 return result;1926 }19271928 return this._optionValues;1929 }19301931 /**1932 * Return an object containing merged local and global option values as key-value pairs.1933 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1934why, one step back
1934 * @return {object}

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1935–1937why, one step back
1935 */
1936 optsWithGlobals() {1937 // globals overwrite locals

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

line 1938why, one step back
1938 return this._getCommandAndAncestors().reduce(

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1939why, one step back
1939 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 1940why, one step back
1940 {},

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1941–1947why, one step back
1941 );
1942 }19431944 /**1945 * Display error message and exit (or call exitOverride).1946 *1947 * @param {string} message

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 1948why, one step back
1948 * @param {object} [errorOptions]

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1949–1953why, one step back
1949 * @param {string} [errorOptions.code] - an id string representing the error
1950 * @param {number} [errorOptions.exitCode] - used with process.exit1951 */1952 error(message, errorOptions) {1953 // output handling

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1954–1957why, one step back
1954 this._outputConfiguration.outputError(
1955 `${message}\n`,1956 this._outputConfiguration.writeErr,1957 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1958–1975why, one step back
1958 if (typeof this._showHelpAfterError === 'string') {
1959 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1960 } else if (this._showHelpAfterError) {1961 this._outputConfiguration.writeErr('\n');1962 this.outputHelp({ error: true });1963 }19641965 // exit handling1966 const config = errorOptions || {};1967 const exitCode = config.exitCode || 1;1968 const code = config.code || 'commander.error';1969 this._exit(exitCode, code, message);1970 }19711972 /**1973 * Apply any option related environment variables, if option does1974 * not have a value from cli or client code.1975 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 1976why, one step back
1976 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1977–1982why, one step back
1977 */
1978 _parseOptionsEnv() {1979 this.options.forEach((option) => {1980 if (option.envVar && option.envVar in process.env) {1981 const optionKey = option.attributeName();1982 // Priority check. Do not overwrite cli or options from unknown source (client-code).

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1983–1990why, one step back
1983 if (
1984 this.getOptionValue(optionKey) === undefined ||1985 ['default', 'config', 'env'].includes(1986 this.getOptionValueSource(optionKey),1987 )1988 ) {1989 if (option.required || option.optional) {1990 // option can take a value

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1991–1992why, one step back
1991 // keep very simple, optional always takes value
1992 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 1993–1994why, one step back
1993 } else {
1994 // boolean

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1995–2005why, one step back
1995 // keep very simple, only care that envVar defined and not the value
1996 this.emit(`optionEnv:${option.name()}`);1997 }1998 }1999 }2000 });

The first 2,000 of 2,790 lines.