Skip to content
Myr

command.js

This file

Path

lib/command.js

2,301 lines · 73.1 KiB · JavaScript

Last changed by

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

History of this file

Take it

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1–4why, one step back
1const EventEmitter = require('events').EventEmitter;
2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');

Follow best practice and require process rather than use global (#1685)John Geebefore adoption47e8b20

line 5why, one step back
5const process = require('process');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 6–9why, one step back
6
7const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');

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

line 10why, one step back
10const { Option, DualOptions } = require('./option.js');

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

line 11why, one step back
11const { suggestSimilar } = require('./suggestSimilar');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 12–21why, one step back
12
13class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 22why, one step back
22 /** @type {Command[]} */

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 23why, one step back
23 this.commands = [];

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 24why, one step back
24 /** @type {Option[]} */

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 25–28why, one step back
25 this.options = [];
26 this.parent = null;27 this._allowUnknownOption = false;28 this._allowExcessArguments = true;

Support argument processing without action handler (#1529)John Geebefore adoption4663597

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

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 32–35why, one step back
32 /** @type {string[]} */
33 this.args = []; // cli args with options removed34 this.rawArgs = [];35 this.processedArgs = []; // like .args but after custom processing and collecting variadic

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 36–38why, one step back
36 this._scriptPath = null;
37 this._name = name || '';38 this._optionValues = {};

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

line 39why, one step back
39 this._optionValueSources = {}; // default, env, cli etc

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 40–43why, one step back
40 this._storeOptionsAsProperties = false;
41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executable

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 44why, one step back
44 this._executableDir = null; // custom search directory for subcommands

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 45–49why, one step back
45 this._defaultCommandName = null;
46 this._exitCallback = null;47 this._aliases = [];48 this._combineFlagAndOptionalValue = true;49 this._description = '';

Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b

line 50why, one step back
50 this._summary = '';

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 51–54why, one step back
51 this._argsDescription = undefined; // legacy
52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arrays

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

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

Add showHelpAfterError (#1534)John Geebefore adoption082717f

line 56why, one step back
56 this._showHelpAfterError = false;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 57why, one step back
57 this._showSuggestionAfterError = true;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 58–68why, one step back
58
59 // see .configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),63 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,64 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,65 outputError: (str, write) => write(str)66 };6768 this._hidden = false;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 74–77why, one step back
74 this._helpConfiguration = {};
75 }7677 /**

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 78–82why, one step back
78 * Copy settings that are useful to have in common across root command and subcommands.
79 *80 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)81 *82 * @param {Command} sourceCommand

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 84–86why, one step back
84 */
85 copyInheritedSettings(sourceCommand) {86 this._outputConfiguration = sourceCommand._outputConfiguration;

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

lines 87–88why, one step back
87 this._helpOption = sourceCommand._helpOption;
88 this._helpCommand = sourceCommand._helpCommand;

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 89–95why, one step back
89 this._helpConfiguration = sourceCommand._helpConfiguration;
90 this._exitCallback = sourceCommand._exitCallback;91 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;92 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;93 this._allowExcessArguments = sourceCommand._allowExcessArguments;94 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;95 this._showHelpAfterError = sourceCommand._showHelpAfterError;

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

line 96why, one step back
96 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

lines 97–101why, one step back
97
98 return this;99 }100101 /**

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

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

line 103why, one step back
103 * @private

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 104–107why, one step back
104 */
105106 _getCommandAndAncestors() {107 const result = [];

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

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

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

lines 109–115why, one step back
109 for (let command = this; command; command = command.parent) {
110 result.push(command);111 }112 return result;113 }114115 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 116–119why, one step back
116 * Define a command.
117 *118 * There are two styles of command: pay attention to where to put the description.119 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 120–127why, one step back
120 * @example
121 * // Command implemented using action handler (description is supplied separately to `.command`)122 * program123 * .command('clone <source> [destination]')124 * .description('clone a repository into a newly created directory')125 * .action((source, destination) => {126 * console.log('clone command called');127 * });

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 128why, one step back
128 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 129–132why, one step back
129 * // Command implemented using separate executable file (description is second parameter to `.command`)
130 * program131 * .command('start <service>', 'start named service')132 * .command('stop [service]', 'stop named service, or all if no name supplied');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 133–134why, one step back
133 *
134 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`

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

line 135why, one step back
135 * @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 136–149why, one step back
136 * @param {Object} [execOpts] - configuration options (for executable)
137 * @return {Command} returns new command for action handler, or `this` for executable command138 */139140 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {141 let desc = actionOptsOrExecDesc;142 let opts = execOpts;143 if (typeof desc === 'object' && desc !== null) {144 opts = desc;145 desc = null;146 }147 opts = opts || {};148 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);149

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

line 150why, one step back
150 const cmd = this.createCommand(name);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 151–158why, one step back
151 if (desc) {
152 cmd.description(desc);153 cmd._executableHandler = true;154 }155 if (opts.isDefault) this._defaultCommandName = cmd._name;156 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden157 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor158 if (args) cmd.arguments(args);

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

line 161why, one step back
161 cmd.copyInheritedSettings(this);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 162–164why, one step back
162
163 if (desc) return this;164 return cmd;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 165why, one step back
165 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 166–178why, one step back
166
167 /**168 * Factory routine to create a new unattached command.169 *170 * See .command() for creating an attached subcommand, which uses this routine to171 * create the command. You can override createCommand to customise subcommands.172 *173 * @param {string} [name]174 * @return {Command} new command175 */176177 createCommand(name) {178 return new Command(name);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 179why, one step back
179 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 180–189why, one step back
180
181 /**182 * You can customise the help with a subclass of Help by overriding createHelp,183 * or by overriding Help properties using configureHelp().184 *185 * @return {Help}186 */187188 createHelp() {189 return Object.assign(new Help(), this.configureHelp());

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 190why, one step back
190 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 191–196why, one step back
191
192 /**193 * You can customise the help by overriding Help properties using configureHelp(),194 * or with a subclass of Help by overriding createHelp().195 *196 * @param {Object} [configuration] - configuration options

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

line 197why, one step back
197 * @return {(Command|Object)} `this` command for chaining, or stored configuration

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 198–212why, one step back
198 */
199200 configureHelp(configuration) {201 if (configuration === undefined) return this._helpConfiguration;202203 this._helpConfiguration = configuration;204 return this;205 }206207 /**208 * The default output goes to stdout and stderr. You can customise this for special209 * applications. You can also customise the display of errors by overriding outputError.210 *211 * The configuration properties are all functions:212 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 213–220why, one step back
213 * // functions to change where being written, stdout and stderr
214 * writeOut(str)215 * writeErr(str)216 * // matching functions to specify width for wrapping help217 * getOutHelpWidth()218 * getErrHelpWidth()219 * // functions based on what is being written out220 * outputError(str, write) // used for displaying errors, and not used for displaying help

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 221–222why, one step back
221 *
222 * @param {Object} [configuration] - configuration options

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

line 223why, one step back
223 * @return {(Command|Object)} `this` command for chaining, or stored configuration

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 224–233why, one step back
224 */
225226 configureOutput(configuration) {227 if (configuration === undefined) return this._outputConfiguration;228229 Object.assign(this._outputConfiguration, configuration);230 return this;231 }232233 /**

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 234–235why, one step back
234 * Display the help or a custom message after an error occurs.
235 *

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

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

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 237–245why, one step back
237 * @return {Command} `this` command for chaining
238 */239 showHelpAfterError(displayHelp = true) {240 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;241 this._showHelpAfterError = displayHelp;242 return this;243 }244245 /**

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

lines 246–256why, one step back
246 * Display suggestion of similar commands for unknown commands, or options for unknown options.
247 *248 * @param {boolean} [displaySuggestion]249 * @return {Command} `this` command for chaining250 */251 showSuggestionAfterError(displaySuggestion = true) {252 this._showSuggestionAfterError = !!displaySuggestion;253 return this;254 }255256 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 257–266why, one step back
257 * Add a prepared subcommand.
258 *259 * See .command() for creating an attached subcommand which inherits settings from its parent.260 *261 * @param {Command} cmd - new subcommand262 * @param {Object} [opts] - configuration options263 * @return {Command} `this` command for chaining264 */265266 addCommand(cmd, opts) {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 267–269why, one step back
267 if (!cmd._name) {
268 throw new Error(`Command passed to .addCommand() must have a name269- specify the name in Command constructor or using .name()`);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 270–275why, one step back
270 }
271272 opts = opts || {};273 if (opts.isDefault) this._defaultCommandName = cmd._name;274 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation275

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 278–279why, one step back
278 cmd._checkForBrokenPassThrough();
279

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 280why, one step back
280 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 281why, one step back
281 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 282–295why, one step back
282
283 /**284 * Factory routine to create a new unattached argument.285 *286 * See .argument() for creating an attached argument, which uses this routine to287 * create the argument. You can override createArgument to return a custom argument.288 *289 * @param {string} name290 * @param {string} [description]291 * @return {Argument} new argument292 */293294 createArgument(name, description) {295 return new Argument(name, description);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 296why, one step back
296 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 297–304why, one step back
297
298 /**299 * Define argument syntax for command.300 *301 * The default is that the argument is required, and you can explicitly302 * indicate this with <> around the name. Put [] around the name for an optional argument.303 *304 * @example

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 305–306why, one step back
305 * program.argument('<input-file>');
306 * program.argument('[output-file]');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 307–309why, one step back
307 *
308 * @param {string} name309 * @param {string} [description]

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

line 310why, one step back
310 * @param {(Function|*)} [fn] - custom argument processing function

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 311–330why, one step back
311 * @param {*} [defaultValue]
312 * @return {Command} `this` command for chaining313 */314 argument(name, description, fn, defaultValue) {315 const argument = this.createArgument(name, description);316 if (typeof fn === 'function') {317 argument.default(defaultValue).argParser(fn);318 } else {319 argument.default(fn);320 }321 this.addArgument(argument);322 return this;323 }324325 /**326 * Define argument syntax for command, adding multiple at once (without descriptions).327 *328 * See also .argument().329 *330 * @example

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 331why, one step back
331 * program.arguments('<cmd> [env]');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 332–337why, one step back
332 *
333 * @param {string} names334 * @return {Command} `this` command for chaining335 */336337 arguments(names) {

trim() input string of .arguments methodАлександр Шмелевbefore adoption2f07c2a

line 338why, one step back
338 names.trim().split(/ +/).forEach((detail) => {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 339–341why, one step back
339 this.argument(detail);
340 });341 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 342why, one step back
342 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 343–350why, one step back
343
344 /**345 * Define argument syntax for command, adding a prepared argument.346 *347 * @param {Argument} argument348 * @return {Command} `this` command for chaining349 */350 addArgument(argument) {

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 352–357why, one step back
352 if (previousArgument && previousArgument.variadic) {
353 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);354 }355 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {356 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);357 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 359–362why, one step back
359 return this;
360 }361362 /**

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 364why, one step back
364 *

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

line 365why, one step back
365 * @example

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

lines 366–369why, one step back
366 * program.helpCommand('help [cmd]');
367 * program.helpCommand('help [cmd]', 'show help');368 * program.helpCommand(false); // suppress default help command369 * program.helpCommand(true); // add help command even if no subcommands

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 370why, one step back
370 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 373–375why, one step back
373 * @return {Command} `this` command for chaining
374 */375

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

lines 376–379why, one step back
376 helpCommand(enableOrNameAndArgs, description) {
377 if (typeof enableOrNameAndArgs === 'boolean') {378 this._addImplicitHelpCommand = enableOrNameAndArgs;379 return this;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 380why, one step back
380 }

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

lines 381–393why, one step back
381
382 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';383 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);384 const helpDescription = description ?? 'display help for command';385386 const helpCommand = this.createCommand(helpName);387 helpCommand.helpOption(false);388 if (helpArgs) helpCommand.arguments(helpArgs);389 if (helpDescription) helpCommand.description(helpDescription);390391 this._addImplicitHelpCommand = true;392 this._helpCommand = helpCommand;393

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 394why, one step back
394 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 395why, one step back
395 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 396–397why, one step back
396
397 /**

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

lines 398–402why, one step back
398 * Add prepared custom help command.
399 *400 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`401 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only402 * @return {Command} `this` command for chaining

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 403why, one step back
403 */

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

lines 404–410why, one step back
404 addHelpCommand(helpCommand, deprecatedDescription) {
405 // If not passed an object, call through to helpCommand for backwards compatibility,406 // as addHelpCommand was originally used like helpCommand is now.407 if (typeof helpCommand !== 'object') {408 this.helpCommand(helpCommand, deprecatedDescription);409 return this;410 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 411why, one step back
411

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

lines 412–431why, one step back
412 this._addImplicitHelpCommand = true;
413 this._helpCommand = helpCommand;414 return this;415 }416417 /**418 * Lazy create help command.419 *420 * @return {(Command|null)}421 * @package422 */423 _getHelpCommand() {424 const hasImplicitHelpCommand = this._addImplicitHelpCommand ??425 (this.commands.length && !this._actionHandler && !this._findCommand('help'));426427 if (hasImplicitHelpCommand) {428 if (this._helpCommand === undefined) {429 this.helpCommand(undefined, undefined); // use default name and description430 }431 return this._helpCommand;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 432why, one step back
432 }

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

line 433why, one step back
433 return null;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 434why, one step back
434 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 435–444why, one step back
435
436 /**437 * Add hook for life cycle event.438 *439 * @param {string} event440 * @param {Function} listener441 * @return {Command} `this` command for chaining442 */443444 hook(event, listener) {

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

line 445why, one step back
445 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 446–477why, one step back
446 if (!allowedValues.includes(event)) {
447 throw new Error(`Unexpected value for event passed to hook : '${event}'.448Expecting one of '${allowedValues.join("', '")}'`);449 }450 if (this._lifeCycleHooks[event]) {451 this._lifeCycleHooks[event].push(listener);452 } else {453 this._lifeCycleHooks[event] = [listener];454 }455 return this;456 }457458 /**459 * Register callback to use as replacement for calling process.exit.460 *461 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing462 * @return {Command} `this` command for chaining463 */464465 exitOverride(fn) {466 if (fn) {467 this._exitCallback = fn;468 } else {469 this._exitCallback = (err) => {470 if (err.code !== 'commander.executeSubCommandAsync') {471 throw err;472 } else {473 // Async callback from spawn events, not useful to throw.474 }475 };476 }477 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 478why, one step back
478 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 479–486why, one step back
479
480 /**481 * Call process.exit, and _exitCallback if defined.482 *483 * @param {number} exitCode exit code for using with process.exit484 * @param {string} code an id string representing the error485 * @param {string} message human-readable description of the error486 * @return never

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

line 487why, one step back
487 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 488–495why, one step back
488 */
489490 _exit(exitCode, code, message) {491 if (this._exitCallback) {492 this._exitCallback(new CommanderError(exitCode, code, message));493 // Expecting this line is not reached.494 }495 process.exit(exitCode);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 496why, one step back
496 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 497–500why, one step back
497
498 /**499 * Register callback `fn` for the command.500 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 501–502why, one step back
501 * @example
502 * program

Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68

lines 503–504why, one step back
503 * .command('serve')
504 * .description('start service')

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 505why, one step back
505 * .action(function() {

Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68

line 506why, one step back
506 * // do work here

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 507why, one step back
507 * });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 508–515why, one step back
508 *
509 * @param {Function} fn510 * @return {Command} `this` command for chaining511 */512513 action(fn) {514 const listener = (args) => {515 // The .action callback takes an extra parameter which is the command or options.

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 517–528why, one step back
517 const actionArgs = args.slice(0, expectedArgsCount);
518 if (this._storeOptionsAsProperties) {519 actionArgs[expectedArgsCount] = this; // backwards compatible "options"520 } else {521 actionArgs[expectedArgsCount] = this.opts();522 }523 actionArgs.push(this);524525 return fn.apply(this, actionArgs);526 };527 this._actionHandler = listener;528 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 529why, one step back
529 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 530–543why, one step back
530
531 /**532 * Factory routine to create a new unattached option.533 *534 * See .option() for creating an attached option, which uses this routine to535 * create the option. You can override createOption to return a custom option.536 *537 * @param {string} flags538 * @param {string} [description]539 * @return {Option} new option540 */541542 createOption(flags, description) {543 return new Option(flags, description);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 544why, one step back
544 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 545–546why, one step back
545
546 /**

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

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

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

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

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

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

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

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

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

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

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

line 553why, one step back
553 * @private

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

lines 554–568why, one step back
554 */
555556 _callParseArg(target, value, previous, invalidArgumentMessage) {557 try {558 return target.parseArg(value, previous);559 } catch (err) {560 if (err.code === 'commander.invalidArgument') {561 const message = `${invalidArgumentMessage} ${err.message}`;562 this.error(message, { exitCode: err.exitCode, code: err.code });563 }564 throw err;565 }566 }567568 /**

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

lines 569–611why, one step back
569 * Check for option flag conflicts.
570 * Register option if no conflicts found, or throw on conflict.571 *572 * @param {Option} option573 * @api private574 */575576 _registerOption(option) {577 const matchingOption = (option.short && this._findOption(option.short)) ||578 (option.long && this._findOption(option.long));579 if (matchingOption) {580 const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;581 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'582- already used by option '${matchingOption.flags}'`);583 }584585 this.options.push(option);586 }587588 /**589 * Check for command name and alias conflicts with existing commands.590 * Register command if no conflicts found, or throw on conflict.591 *592 * @param {Command} command593 * @api private594 */595596 _registerCommand(command) {597 const knownBy = (cmd) => {598 return [cmd.name()].concat(cmd.aliases());599 };600601 const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));602 if (alreadyUsed) {603 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');604 const newCmd = knownBy(command).join('|');605 throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);606 }607608 this.commands.push(command);609 }610611 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 612–617why, one step back
612 * Add an option.
613 *614 * @param {Option} option615 * @return {Command} `this` command for chaining616 */617 addOption(option) {

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

lines 618–619why, one step back
618 this._registerOption(option);
619

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 620–622why, one step back
620 const oname = option.name();
621 const name = option.attributeName();622

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 623–628why, one step back
623 // store default value
624 if (option.negate) {625 // --no-foo is special and defaults foo to true, unless a --foo option is already defined626 const positiveLongFlag = option.long.replace(/^--no-/, '--');627 if (!this._findOption(positiveLongFlag)) {628 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 629why, one step back
629 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 630–631why, one step back
630 } else if (option.defaultValue !== undefined) {
631 this.setOptionValueWithSource(name, option.defaultValue, 'default');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 632–633why, one step back
632 }
633

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 634–635why, one step back
634 // handler for cli and env supplied values
635 const handleOptionValue = (val, invalidValueMessage, valueSource) => {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 636–640why, one step back
636 // val is null for optional option used without an optional-argument.
637 // val is undefined for boolean and negated option.638 if (val == null && option.presetArg !== undefined) {639 val = option.presetArg;640 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 641–642why, one step back
641
642 // custom processing

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 643why, one step back
643 const oldValue = this.getOptionValue(name);

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 644why, one step back
644 if (val !== null && option.parseArg) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 646–649why, one step back
646 } else if (val !== null && option.variadic) {
647 val = option._concatValue(val, oldValue);648 }649

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 650–655why, one step back
650 // Fill-in appropriate missing values. Long winded but easy to follow.
651 if (val == null) {652 if (option.negate) {653 val = false;654 } else if (option.isBoolean() || option.optional) {655 val = true;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 656why, one step back
656 } else {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 657why, one step back
657 val = ''; // not normal, parseArg might have failed or be a mock function for testing

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 660why, one step back
660 this.setOptionValueWithSource(name, val, valueSource);

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 661–665why, one step back
661 };
662663 this.on('option:' + oname, (val) => {664 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;665 handleOptionValue(val, invalidValueMessage, 'cli');

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 666–667why, one step back
666 });
667

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 668–674why, one step back
668 if (option.envVar) {
669 this.on('optionEnv:' + oname, (val) => {670 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;671 handleOptionValue(val, invalidValueMessage, 'env');672 });673 }674

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 675–680why, one step back
675 return this;
676 }677678 /**679 * Internal implementation shared by .option() and .requiredOption()680 *

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

line 681why, one step back
681 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 682–683why, one step back
682 */
683 _optionEx(config, flags, description, fn, defaultValue) {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 684–686why, one step back
684 if (typeof flags === 'object' && flags instanceof Option) {
685 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');686 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 687–706why, one step back
687 const option = this.createOption(flags, description);
688 option.makeOptionMandatory(!!config.mandatory);689 if (typeof fn === 'function') {690 option.default(defaultValue).argParser(fn);691 } else if (fn instanceof RegExp) {692 // deprecated693 const regex = fn;694 fn = (val, def) => {695 const m = regex.exec(val);696 return m ? m[0] : def;697 };698 option.default(defaultValue).argParser(fn);699 } else {700 option.default(fn);701 }702703 return this.addOption(option);704 }705706 /**

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 708why, one step back
708 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 711why, one step back
711 *

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 713why, one step back
713 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

line 714why, one step back
714 * @example

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 715–719why, one step back
715 * program
716 * .option('-p, --pepper', 'add pepper')717 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument718 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default719 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 720–722why, one step back
720 *
721 * @param {string} flags722 * @param {string} [description]

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 724–727why, one step back
724 * @param {*} [defaultValue]
725 * @return {Command} `this` command for chaining726 */727

Rework option inline doc (#2009)John Geebefore adoptione85e05a

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 730why, one step back
730 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 731–739why, one step back
731
732 /**733 * Add a required option which must have a value after parsing. This usually means734 * the option must be specified on the command line. (Otherwise the same as .option().)735 *736 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.737 *738 * @param {string} flags739 * @param {string} [description]

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 741–744why, one step back
741 * @param {*} [defaultValue]
742 * @return {Command} `this` command for chaining743 */744

Rework option inline doc (#2009)John Geebefore adoptione85e05a

lines 745–746why, one step back
745 requiredOption(flags, description, parseArg, defaultValue) {
746 return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 747why, one step back
747 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 748–751why, one step back
748
749 /**750 * Alter parsing of short flags with optional values.751 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 752–755why, one step back
752 * @example
753 * // for `.option('-f,--flag [value]'):754 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour755 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 756why, one step back
756 *

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

line 757why, one step back
757 * @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 758–761why, one step back
758 */
759 combineFlagAndOptionalValue(combine = true) {760 this._combineFlagAndOptionalValue = !!combine;761 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 762why, one step back
762 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 763–766why, one step back
763
764 /**765 * Allow unknown options on the command line.766 *

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

line 767why, one step back
767 * @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 768–772why, one step back
768 * for unknown options.
769 */770 allowUnknownOption(allowUnknown = true) {771 this._allowUnknownOption = !!allowUnknown;772 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 773why, one step back
773 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 774–777why, one step back
774
775 /**776 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.777 *

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

line 778why, one step back
778 * @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 779–783why, one step back
779 * for excess arguments.
780 */781 allowExcessArguments(allowExcess = true) {782 this._allowExcessArguments = !!allowExcess;783 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 784why, one step back
784 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 785–790why, one step back
785
786 /**787 * Enable positional options. Positional means global options are specified before subcommands which lets788 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.789 * The default behaviour is non-positional and global options may appear anywhere on the command line.790 *

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

line 791why, one step back
791 * @param {boolean} [positional=true]

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 792–795why, one step back
792 */
793 enablePositionalOptions(positional = true) {794 this._enablePositionalOptions = !!positional;795 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 796why, one step back
796 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 797–803why, one step back
797
798 /**799 * Pass through options that come after command-arguments rather than treat them as command-options,800 * so actual command-options come before command-arguments. Turning this on for a subcommand requires801 * positional options to have been enabled on the program (parent commands).802 * The default behaviour is non-positional and options may appear before or after command-arguments.803 *

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

line 804why, one step back
804 * @param {boolean} [passThrough=true]

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 805–808why, one step back
805 * for unknown options.
806 */807 passThroughOptions(passThrough = true) {808 this._passThroughOptions = !!passThrough;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 810why, one step back
810 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 811why, one step back
811 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 812–813why, one step back
812
813 /**

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

lines 814–823why, one step back
814 * @private
815 */816817 _checkForBrokenPassThrough() {818 if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {819 throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);820 }821 }822823 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 824–834why, one step back
824 * Whether to store option values as properties on command object,
825 * or store separately (specify false). In both cases the option values can be accessed using .opts().826 *827 * @param {boolean} [storeAsProperties=true]828 * @return {Command} `this` command for chaining829 */830831 storeOptionsAsProperties(storeAsProperties = true) {832 if (this.options.length) {833 throw new Error('call .storeOptionsAsProperties() before adding options');834 }

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

lines 835–837why, one step back
835 if (Object.keys(this._optionValues).length) {
836 throw new Error('call .storeOptionsAsProperties() before setting option values');837 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 839why, one step back
839 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 840why, one step back
840 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 841–853why, one step back
841
842 /**843 * Retrieve option value.844 *845 * @param {string} key846 * @return {Object} value847 */848849 getOptionValue(key) {850 if (this._storeOptionsAsProperties) {851 return this[key];852 }853 return this._optionValues[key];

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 854why, one step back
854 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 855–864why, one step back
855
856 /**857 * Store option value.858 *859 * @param {string} key860 * @param {Object} value861 * @return {Command} `this` command for chaining862 */863864 setOptionValue(key, value) {

setOptionValue should clear option source (#1795)John Geebefore adoption84d9201

line 865why, one step back
865 return this.setOptionValueWithSource(key, value, undefined);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 866why, one step back
866 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 867–868why, one step back
867
868 /**

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

line 869why, one step back
869 * Store option value and where the value came from.

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 870–872why, one step back
870 *
871 * @param {string} key872 * @param {Object} value

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

line 873why, one step back
873 * @param {string} source - expected values are default/config/env/cli/implied

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 874–877why, one step back
874 * @return {Command} `this` command for chaining
875 */876877 setOptionValueWithSource(key, value, source) {

setOptionValue should clear option source (#1795)John Geebefore adoption84d9201

lines 878–882why, one step back
878 if (this._storeOptionsAsProperties) {
879 this[key] = value;880 } else {881 this._optionValues[key] = value;882 }

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

line 883why, one step back
883 this._optionValueSources[key] = source;

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 884why, one step back
884 return this;

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 885–887why, one step back
885 }
886887 /**

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 888why, one step back
888 * Get source of option value.

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

line 889why, one step back
889 * Expected values are default | config | env | cli | implied

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 890–896why, one step back
890 *
891 * @param {string} key892 * @return {string}893 */894895 getOptionValueSource(key) {896 return this._optionValueSources[key];

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 897why, one step back
897 }

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 898–899why, one step back
898
899 /**

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

lines 900–909why, one step back
900 * Get source of option value. See also .optsWithGlobals().
901 * Expected values are default | config | env | cli | implied902 *903 * @param {string} key904 * @return {string}905 */906907 getOptionValueSourceWithGlobals(key) {908 // global overwrites local, like optsWithGlobals909 let source;

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

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

lines 911–918why, one step back
911 if (cmd.getOptionValueSource(key) !== undefined) {
912 source = cmd.getOptionValueSource(key);913 }914 });915 return source;916 }917918 /**

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 921why, one step back
921 *

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

line 922why, one step back
922 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 923–948why, one step back
923 */
924925 _prepareUserArgs(argv, parseOptions) {926 if (argv !== undefined && !Array.isArray(argv)) {927 throw new Error('first parameter to parse must be array or undefined');928 }929 parseOptions = parseOptions || {};930931 // Default to using process.argv932 if (argv === undefined) {933 argv = process.argv;934 if (process.versions && process.versions.electron) {935 parseOptions.from = 'electron';936 }937 }938 this.rawArgs = argv.slice();939940 // make it a little easier for callers by supporting various argv conventions941 let userArgs;942 switch (parseOptions.from) {943 case undefined:944 case 'node':945 this._scriptPath = argv[1];946 userArgs = argv.slice(2);947 break;948 case 'electron':

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 950–963why, one step back
950 if (process.defaultApp) {
951 this._scriptPath = argv[1];952 userArgs = argv.slice(2);953 } else {954 userArgs = argv.slice(1);955 }956 break;957 case 'user':958 userArgs = argv.slice(0);959 break;960 default:961 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);962 }963

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 964–966why, one step back
964 // Find default name for program from arguments.
965 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);966 this._name = this._name || 'program';

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 967–976why, one step back
967
968 return userArgs;969 }970971 /**972 * Parse `argv`, setting options and invoking commands when defined.973 *974 * The default expectation is that the arguments are from node and have the application as argv[0]975 * and the script being run in argv[1], with user parameters after that.976 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 977–980why, one step back
977 * @example
978 * program.parse(process.argv);979 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions980 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 981–992why, one step back
981 *
982 * @param {string[]} [argv] - optional, defaults to process.argv983 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron984 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'985 * @return {Command} `this` command for chaining986 */987988 parse(argv, parseOptions) {989 const userArgs = this._prepareUserArgs(argv, parseOptions);990 this._parseCommand([], userArgs);991992 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 993why, one step back
993 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 994–1002why, one step back
994
995 /**996 * Parse `argv`, setting options and invoking commands when defined.997 *998 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.999 *1000 * The default expectation is that the arguments are from node and have the application as argv[0]1001 * and the script being run in argv[1], with user parameters after that.1002 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 1003–1006why, one step back
1003 * @example
1004 * await program.parseAsync(process.argv);1005 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1006 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1007–1018why, one step back
1007 *
1008 * @param {string[]} [argv]1009 * @param {Object} [parseOptions]1010 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1011 * @return {Promise}1012 */10131014 async parseAsync(argv, parseOptions) {1015 const userArgs = this._prepareUserArgs(argv, parseOptions);1016 await this._parseCommand([], userArgs);10171018 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1019why, one step back
1019 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1020–1023why, one step back
1020
1021 /**1022 * Execute a sub-command executable.1023 *

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

line 1024why, one step back
1024 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1025–1031why, one step back
1025 */
10261027 _executeSubCommand(subcommand, args) {1028 args = args.slice();1029 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1030 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];1031

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1032–1035why, one step back
1032 function findFile(baseDir, baseName) {
1033 // Look for specified file1034 const localBin = path.resolve(baseDir, baseName);1035 if (fs.existsSync(localBin)) return localBin;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1036why, one step back
1036

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1037–1038why, one step back
1037 // Stop looking if candidate already has an expected extension.
1038 if (sourceExt.includes(path.extname(baseName))) return undefined;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1039why, one step back
1039

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1040–1044why, one step back
1040 // Try all the extensions.
1041 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));1042 if (foundExt) return `${localBin}${foundExt}`;10431044 return undefined;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1045–1046why, one step back
1045 }
1046

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1047–1048why, one step back
1047 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1048 this._checkForMissingMandatoryOptions();

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

line 1049why, one step back
1049 this._checkForConflictingOptions();

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1050–1061why, one step back
1050
1051 // executableFile and executableDir might be full path, or just a name1052 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;1053 let executableDir = this._executableDir || '';1054 if (this._scriptPath) {1055 let resolvedScriptPath; // resolve possible symlink for installed npm binary1056 try {1057 resolvedScriptPath = fs.realpathSync(this._scriptPath);1058 } catch (err) {1059 resolvedScriptPath = this._scriptPath;1060 }1061 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1062–1063why, one step back
1062 }
1063

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1064–1072why, one step back
1064 // Look for a local file in preference to a command in PATH.
1065 if (executableDir) {1066 let localFile = findFile(executableDir, executableFile);10671068 // Legacy search using prefix of script name instead of command name1069 if (!localFile && !subcommand._executableFile && this._scriptPath) {1070 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));1071 if (legacyName !== this._name) {1072 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1073why, one step back
1073 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1074–1075why, one step back
1074 }
1075 executableFile = localFile || executableFile;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1076–1077why, one step back
1076 }
1077

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1078–1079why, one step back
1078 launchWithNode = sourceExt.includes(path.extname(executableFile));
1079

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1080–1082why, one step back
1080 let proc;
1081 if (process.platform !== 'win32') {1082 if (launchWithNode) {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1083why, one step back
1083 args.unshift(executableFile);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1084–1088why, one step back
1084 // add executable arguments to spawn
1085 args = incrementNodeInspectorPort(process.execArgv).concat(args);10861087 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1088 } else {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1089why, one step back
1089 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1090–1091why, one step back
1090 }
1091 } else {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1092why, one step back
1092 args.unshift(executableFile);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1093–1097why, one step back
1093 // add executable arguments to spawn
1094 args = incrementNodeInspectorPort(process.execArgv).concat(args);1095 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1096 }1097

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1098–1105why, one step back
1098 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
1099 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1100 signals.forEach((signal) => {1101 process.on(signal, () => {1102 if (proc.killed === false && proc.exitCode === null) {1103 proc.kill(signal);1104 }1105 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1106why, one step back
1106 });

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1107why, one step back
1107 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1108–1110why, one step back
1108
1109 // By default terminate process when spawned process terminates.1110 const exitCallback = this._exitCallback;

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

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

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

lines 1112–1118why, one step back
1112 code = code ?? 1; // code is null if spawned process terminated due to a signal
1113 if (!exitCallback) {1114 process.exit(code);1115 } else {1116 exitCallback(new CommanderError(code, 'commander.executeSubCommandAsync', '(close)'));1117 }1118 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1122–1125why, one step back
1122 const executableDirMessage = executableDir
1123 ? `searched for local subcommand relative to directory '${executableDir}'`1124 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1125 const executableMissing = `'${executableFile}' does not exist

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1126why, one step back
1126 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1127–1128why, one step back
1127 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1128 - ${executableDirMessage}`;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1129why, one step back
1129 throw new Error(executableMissing);

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1131why, one step back
1131 } else if (err.code === 'EACCES') {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1132why, one step back
1132 throw new Error(`'${executableFile}' not executable`);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1133–1144why, one step back
1133 }
1134 if (!exitCallback) {1135 process.exit(1);1136 } else {1137 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1138 wrappedError.nestedError = err;1139 exitCallback(wrappedError);1140 }1141 });11421143 // Store the reference to the child process1144 this.runningCommand = proc;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1145why, one step back
1145 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1146–1147why, one step back
1146
1147 /**

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

line 1148why, one step back
1148 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1149–1154why, one step back
1149 */
11501151 _dispatchSubcommand(commandName, operands, unknown) {1152 const subCommand = this._findCommand(commandName);1153 if (!subCommand) this.help({ error: true });1154

Improve chain variable name (#1958)John Geebefore adoption5740e59

lines 1155–1157why, one step back
1155 let promiseChain;
1156 promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');1157 promiseChain = this._chainOrCall(promiseChain, () => {

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

lines 1158–1163why, one step back
1158 if (subCommand._executableHandler) {
1159 this._executeSubCommand(subCommand, operands.concat(unknown));1160 } else {1161 return subCommand._parseCommand(operands, unknown);1162 }1163 });

Improve chain variable name (#1958)John Geebefore adoption5740e59

line 1164why, one step back
1164 return promiseChain;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1165why, one step back
1165 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1166–1167why, one step back
1166
1167 /**

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

lines 1168–1170why, one step back
1168 * Invoke help directly if possible, or dispatch if necessary.
1169 * e.g. help foo1170 *

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

line 1171why, one step back
1171 * @private

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

lines 1172–1183why, one step back
1172 */
11731174 _dispatchHelpCommand(subcommandName) {1175 if (!subcommandName) {1176 this.help();1177 }1178 const subCommand = this._findCommand(subcommandName);1179 if (subCommand && !subCommand._executableHandler) {1180 subCommand.help();1181 }11821183 // Fallback to parsing the help flag to invoke the help.

Fix help for commands with executable handler & only a short help flagWee Bitbefore adoptionc117172

line 1184why, one step back
1184 return this._dispatchSubcommand(subcommandName, [], [

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

line 1185why, one step back
1185 this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'

Fix help for commands with executable handler & only a short help flagWee Bitbefore adoptionc117172

line 1186why, one step back
1186 ]);

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

lines 1187–1189why, one step back
1187 }
11881189 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1191why, one step back
1191 *

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

line 1192why, one step back
1192 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1193–1194why, one step back
1193 */
1194

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1195–1196why, one step back
1195 _checkNumberOfArguments() {
1196 // too few

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1198–1202why, one step back
1198 if (arg.required && this.args[i] == null) {
1199 this.missingArgument(arg.name());1200 }1201 });1202 // too many

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1203why, one step back
1203 if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1204–1205why, one step back
1204 return;
1205 }

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1207–1208why, one step back
1207 this._excessArguments(this.args);
1208 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1209why, one step back
1209 }

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1210–1211why, one step back
1210
1211 /**

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1213why, one step back
1213 *

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

line 1214why, one step back
1214 * @private

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1215–1217why, one step back
1215 */
12161217 _processArguments() {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1218–1221why, one step back
1218 const myParseArg = (argument, value, previous) => {
1219 // Extra processing for nice error message on parsing failure.1220 let parsedValue = value;1221 if (value !== null && argument.parseArg) {

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

lines 1222–1223why, one step back
1222 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1223 parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1224–1227why, one step back
1224 }
1225 return parsedValue;1226 };1227

Support argument processing without action handler (#1529)John Geebefore adoption4663597

lines 1228–1230why, one step back
1228 this._checkNumberOfArguments();
12291230 const processedArgs = [];

Add public Arguments property (#2010)John Geebefore adoption7d23437

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1232–1250why, one step back
1232 let value = declaredArg.defaultValue;
1233 if (declaredArg.variadic) {1234 // Collect together remaining arguments for passing together as an array.1235 if (index < this.args.length) {1236 value = this.args.slice(index);1237 if (declaredArg.parseArg) {1238 value = value.reduce((processed, v) => {1239 return myParseArg(declaredArg, v, processed);1240 }, declaredArg.defaultValue);1241 }1242 } else if (value === undefined) {1243 value = [];1244 }1245 } else if (index < this.args.length) {1246 value = this.args[index];1247 if (declaredArg.parseArg) {1248 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1249 }1250 }

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1251why, one step back
1251 processedArgs[index] = value;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1252why, one step back
1252 });

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1253why, one step back
1253 this.processedArgs = processedArgs;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1254–1258why, one step back
1254 }
12551256 /**1257 * Once we have a promise we chain, but call synchronously until then.1258 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1263–1276why, one step back
1263 */
12641265 _chainOrCall(promise, fn) {1266 // thenable1267 if (promise && promise.then && typeof promise.then === 'function') {1268 // already have a promise, chain callback1269 return promise.then(() => fn());1270 }1271 // callback might return a promise1272 return fn();1273 }12741275 /**1276 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1281–1285why, one step back
1281 */
12821283 _chainOrCallHooks(promise, event) {1284 let result = promise;1285 const hooks = [];

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1287–1302why, one step back
1287 .reverse()
1288 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1289 .forEach(hookedCommand => {1290 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1291 hooks.push({ hookedCommand, callback });1292 });1293 });1294 if (event === 'postAction') {1295 hooks.reverse();1296 }12971298 hooks.forEach((hookDetail) => {1299 result = this._chainOrCall(result, () => {1300 return hookDetail.callback(hookDetail.hookedCommand, this);1301 });1302 });

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

lines 1303–1307why, one step back
1303 return result;
1304 }13051306 /**1307 *

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

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

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

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

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

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

feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687

lines 1313–1323why, one step back
1313 */
13141315 _chainOrCallSubCommandHook(promise, subCommand, event) {1316 let result = promise;1317 if (this._lifeCycleHooks[event] !== undefined) {1318 this._lifeCycleHooks[event].forEach((hook) => {1319 result = this._chainOrCall(result, () => {1320 return hook(this, subCommand);1321 });1322 });1323 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1324–1330why, one step back
1324 return result;
1325 }13261327 /**1328 * Process arguments in context of this command.1329 * Returns action result, in case it is a promise.1330 *

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

line 1331why, one step back
1331 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1332–1335why, one step back
1332 */
13331334 _parseCommand(operands, unknown) {1335 const parsed = this.parseOptions(unknown);

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

line 1336why, one step back
1336 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env

Add Option.implies() (#1724)John Geebefore adoptiond660967

line 1337why, one step back
1337 this._parseOptionsImplied();

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1338–1344why, one step back
1338 operands = operands.concat(parsed.operands);
1339 unknown = parsed.unknown;1340 this.args = operands.concat(unknown);13411342 if (operands && this._findCommand(operands[0])) {1343 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1344 }

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

line 1345why, one step back
1345 if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1347–1348why, one step back
1347 }
1348 if (this._defaultCommandName) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1350–1356why, one step back
1350 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1351 }1352 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1353 // probably missing subcommand and no handler, user needs help (and exit)1354 this.help({ error: true });1355 }1356

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1358why, one step back
1358 this._checkForMissingMandatoryOptions();

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 1359why, one step back
1359 this._checkForConflictingOptions();

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1360–1370why, one step back
1360
1361 // We do not always call this check to avoid masking a "better" error, like unknown command.1362 const checkForUnknownOptions = () => {1363 if (parsed.unknown.length > 0) {1364 this.unknownOption(parsed.unknown[0]);1365 }1366 };13671368 const commandEvent = `command:${this.name()}`;1369 if (this._actionHandler) {1370 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1371why, one step back
1371 this._processArguments();

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1372why, one step back
1372

Improve chain variable name (#1958)John Geebefore adoption5740e59

lines 1373–1375why, one step back
1373 let promiseChain;
1374 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1375 promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));

Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b

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

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b

lines 1378–1380why, one step back
1378 this.parent.emit(commandEvent, operands, unknown); // legacy
1379 });1380 }

Improve chain variable name (#1958)John Geebefore adoption5740e59

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1383–1385why, one step back
1383 }
1384 if (this.parent && this.parent.listenerCount(commandEvent)) {1385 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1386why, one step back
1386 this._processArguments();

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1387–1398why, one step back
1387 this.parent.emit(commandEvent, operands, unknown); // legacy
1388 } else if (operands.length) {1389 if (this._findCommand('*')) { // legacy default command1390 return this._dispatchSubcommand('*', operands, unknown);1391 }1392 if (this.listenerCount('command:*')) {1393 // skip option check, emit event for possible misspelling suggestion1394 this.emit('command:*', operands, unknown);1395 } else if (this.commands.length) {1396 this.unknownCommand();1397 } else {1398 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1399why, one step back
1399 this._processArguments();

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1400–1401why, one step back
1400 }
1401 } else if (this.commands.length) {

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

line 1402why, one step back
1402 checkForUnknownOptions();

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1403–1406why, one step back
1403 // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1404 this.help({ error: true });1405 } else {1406 checkForUnknownOptions();

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1407why, one step back
1407 this._processArguments();

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1408–1409why, one step back
1408 // fall through for caller to handle after calling .parse()
1409 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1410why, one step back
1410 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1411–1414why, one step back
1411
1412 /**1413 * Find matching command.1414 *

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

line 1415why, one step back
1415 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1416–1419why, one step back
1416 */
1417 _findCommand(name) {1418 if (!name) return undefined;1419 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1420why, one step back
1420 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1421–1426why, one step back
1421
1422 /**1423 * Return an option matching `arg` if any.1424 *1425 * @param {string} arg1426 * @return {Option}

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

line 1427why, one step back
1427 * @package internal use only

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1428–1431why, one step back
1428 */
14291430 _findOption(arg) {1431 return this.options.find(option => option.is(arg));

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1432why, one step back
1432 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1433–1435why, one step back
1433
1434 /**1435 * Display an error message if a mandatory option does not have a value.

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

line 1436why, one step back
1436 * Called after checking for help flags in leaf subcommand.

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1437why, one step back
1437 *

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

line 1438why, one step back
1438 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1444–1448why, one step back
1444 cmd.options.forEach((anOption) => {
1445 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1446 cmd.missingMandatoryOptionValue(anOption);1447 }1448 });

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1449why, one step back
1449 });

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1450why, one step back
1450 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1451–1452why, one step back
1451
1452 /**

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

line 1453why, one step back
1453 * Display an error message if conflicting options are used together in this.

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 1454why, one step back
1454 *

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

line 1455why, one step back
1455 * @private

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 1456why, one step back
1456 */

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

line 1457why, one step back
1457 _checkForConflictingLocalOptions() {

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1458–1479why, one step back
1458 const definedNonDefaultOptions = this.options.filter(
1459 (option) => {1460 const optionKey = option.attributeName();1461 if (this.getOptionValue(optionKey) === undefined) {1462 return false;1463 }1464 return this.getOptionValueSource(optionKey) !== 'default';1465 }1466 );14671468 const optionsWithConflicting = definedNonDefaultOptions.filter(1469 (option) => option.conflictsWith.length > 01470 );14711472 optionsWithConflicting.forEach((option) => {1473 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1474 option.conflictsWith.includes(defined.attributeName())1475 );1476 if (conflictingAndDefined) {1477 this._conflictingOption(option, conflictingAndDefined);1478 }1479 });

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

lines 1480–1485why, one step back
1480 }
14811482 /**1483 * Display an error message if conflicting options are used together.1484 * Called after checking for help flags in leaf subcommand.1485 *

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

line 1486why, one step back
1486 * @private

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

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

Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1

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

Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead

line 1492why, one step back
1492 });

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1493–1495why, one step back
1493 }
14941495 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1496–1500why, one step back
1496 * Parse options from `argv` removing known options,
1497 * and return argv split into operands and unknown arguments.1498 *1499 * Examples:1500 *

Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108

lines 1501–1505why, one step back
1501 * argv => operands, unknown
1502 * --known kkk op => [op], []1503 * op --known kkk => [op], []1504 * sub --unknown uuu op => [sub], [--unknown uuu op]1505 * sub -- --unknown uuu op => [sub --unknown uuu op], []

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1506why, one step back
1506 *

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

lines 1507–1508why, one step back
1507 * @param {string[]} argv
1508 * @return {{operands: string[], unknown: string[]}}

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1509–1601why, one step back
1509 */
15101511 parseOptions(argv) {1512 const operands = []; // operands, not options or values1513 const unknown = []; // first unknown option and remaining unknown args1514 let dest = operands;1515 const args = argv.slice();15161517 function maybeOption(arg) {1518 return arg.length > 1 && arg[0] === '-';1519 }15201521 // parse options1522 let activeVariadicOption = null;1523 while (args.length) {1524 const arg = args.shift();15251526 // literal1527 if (arg === '--') {1528 if (dest === unknown) dest.push(arg);1529 dest.push(...args);1530 break;1531 }15321533 if (activeVariadicOption && !maybeOption(arg)) {1534 this.emit(`option:${activeVariadicOption.name()}`, arg);1535 continue;1536 }1537 activeVariadicOption = null;15381539 if (maybeOption(arg)) {1540 const option = this._findOption(arg);1541 // recognised option, call listener to assign value with possible custom processing1542 if (option) {1543 if (option.required) {1544 const value = args.shift();1545 if (value === undefined) this.optionMissingArgument(option);1546 this.emit(`option:${option.name()}`, value);1547 } else if (option.optional) {1548 let value = null;1549 // historical behaviour is optional value is following arg unless an option1550 if (args.length > 0 && !maybeOption(args[0])) {1551 value = args.shift();1552 }1553 this.emit(`option:${option.name()}`, value);1554 } else { // boolean flag1555 this.emit(`option:${option.name()}`);1556 }1557 activeVariadicOption = option.variadic ? option : null;1558 continue;1559 }1560 }15611562 // Look for combo options following single dash, eat first one if known.1563 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1564 const option = this._findOption(`-${arg[1]}`);1565 if (option) {1566 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1567 // option with value following in same argument1568 this.emit(`option:${option.name()}`, arg.slice(2));1569 } else {1570 // boolean option, emit and put back remainder of arg for further processing1571 this.emit(`option:${option.name()}`);1572 args.unshift(`-${arg.slice(2)}`);1573 }1574 continue;1575 }1576 }15771578 // Look for known long flag with value, like --foo=bar1579 if (/^--[^=]+=/.test(arg)) {1580 const index = arg.indexOf('=');1581 const option = this._findOption(arg.slice(0, index));1582 if (option && (option.required || option.optional)) {1583 this.emit(`option:${option.name()}`, arg.slice(index + 1));1584 continue;1585 }1586 }15871588 // Not a recognised option by this command.1589 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15901591 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1592 if (maybeOption(arg)) {1593 dest = unknown;1594 }15951596 // If using positionalOptions, stop processing our options at subcommand.1597 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1598 if (this._findCommand(arg)) {1599 operands.push(arg);1600 if (args.length > 0) unknown.push(...args);1601 break;

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

line 1602why, one step back
1602 } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1603–1624why, one step back
1603 operands.push(arg);
1604 if (args.length > 0) operands.push(...args);1605 break;1606 } else if (this._defaultCommandName) {1607 unknown.push(arg);1608 if (args.length > 0) unknown.push(...args);1609 break;1610 }1611 }16121613 // If using passThroughOptions, stop processing options at first command-argument.1614 if (this._passThroughOptions) {1615 dest.push(arg);1616 if (args.length > 0) dest.push(...args);1617 break;1618 }16191620 // add arg1621 dest.push(arg);1622 }16231624 return { operands, unknown };

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1625why, one step back
1625 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1626–1627why, one step back
1626
1627 /**

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1628why, one step back
1628 * Return an object containing local option values as key-value pairs.

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1629–1645why, one step back
1629 *
1630 * @return {Object}1631 */1632 opts() {1633 if (this._storeOptionsAsProperties) {1634 // Preserve original behaviour so backwards compatible when still using properties1635 const result = {};1636 const len = this.options.length;16371638 for (let i = 0; i < len; i++) {1639 const key = this.options[i].attributeName();1640 result[key] = key === this._versionOptionName ? this._version : this[key];1641 }1642 return result;1643 }16441645 return this._optionValues;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1646why, one step back
1646 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1647–1648why, one step back
1647
1648 /**

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1649why, one step back
1649 * Return an object containing merged local and global option values as key-value pairs.

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1650why, one step back
1650 *

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1651why, one step back
1651 * @return {Object}

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1652why, one step back
1652 */

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1653–1654why, one step back
1653 optsWithGlobals() {
1654 // globals overwrite locals

Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11

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

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1656–1670why, one step back
1656 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
1657 {}1658 );1659 }16601661 /**1662 * Display error message and exit (or call exitOverride).1663 *1664 * @param {string} message1665 * @param {Object} [errorOptions]1666 * @param {string} [errorOptions.code] - an id string representing the error1667 * @param {number} [errorOptions.exitCode] - used with process.exit1668 */1669 error(message, errorOptions) {1670 // output handling

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1671why, one step back
1671 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);

Add showHelpAfterError (#1534)John Geebefore adoption082717f

lines 1672–1677why, one step back
1672 if (typeof this._showHelpAfterError === 'string') {
1673 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1674 } else if (this._showHelpAfterError) {1675 this._outputConfiguration.writeErr('\n');1676 this.outputHelp({ error: true });1677 }

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1678–1682why, one step back
1678
1679 // exit handling1680 const config = errorOptions || {};1681 const exitCode = config.exitCode || 1;1682 const code = config.code || 'commander.error';

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1683why, one step back
1683 this._exit(exitCode, code, message);

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 1684–1689why, one step back
1684 }
16851686 /**1687 * Apply any option related environment variables, if option does1688 * not have a value from cli or client code.1689 *

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

line 1690why, one step back
1690 * @private

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 1691–1695why, one step back
1691 */
1692 _parseOptionsEnv() {1693 this.options.forEach((option) => {1694 if (option.envVar && option.envVar in process.env) {1695 const optionKey = option.attributeName();

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 1696–1697why, one step back
1696 // Priority check. Do not overwrite cli or options from unknown source (client-code).
1697 if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 1698–1707why, one step back
1698 if (option.required || option.optional) { // option can take a value
1699 // keep very simple, optional always takes value1700 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1701 } else { // boolean1702 // keep very simple, only care that envVar defined and not the value1703 this.emit(`optionEnv:${option.name()}`);1704 }1705 }1706 }1707 });

Add Option.implies() (#1724)John Geebefore adoptiond660967

lines 1708–1712why, one step back
1708 }
17091710 /**1711 * Apply any implied option values, if option is undefined or default value.1712 *

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

line 1713why, one step back
1713 * @private

Add Option.implies() (#1724)John Geebefore adoptiond660967

lines 1714–1730why, one step back
1714 */
1715 _parseOptionsImplied() {1716 const dualHelper = new DualOptions(this.options);1717 const hasCustomOptionValue = (optionKey) => {1718 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1719 };1720 this.options1721 .filter(option => (option.implied !== undefined) &&1722 hasCustomOptionValue(option.attributeName()) &&1723 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1724 .forEach((option) => {1725 Object.keys(option.implied)1726 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1727 .forEach(impliedKey => {1728 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1729 });1730 });

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1731–1736why, one step back
1731 }
17321733 /**1734 * Argument `name` is missing.1735 *1736 * @param {string} name

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

line 1737why, one step back
1737 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1738–1741why, one step back
1738 */
17391740 missingArgument(name) {1741 const message = `error: missing required argument '${name}'`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1742–1743why, one step back
1742 this.error(message, { code: 'commander.missingArgument' });
1743 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1744–1748why, one step back
1744
1745 /**1746 * `Option` is missing an argument.1747 *1748 * @param {Option} option

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

line 1749why, one step back
1749 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1750–1753why, one step back
1750 */
17511752 optionMissingArgument(option) {1753 const message = `error: option '${option.flags}' argument missing`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1754–1755why, one step back
1754 this.error(message, { code: 'commander.optionMissingArgument' });
1755 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1756–1760why, one step back
1756
1757 /**1758 * `Option` does not have a value, and is a mandatory option.1759 *1760 * @param {Option} option

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

line 1761why, one step back
1761 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1762–1765why, one step back
1762 */
17631764 missingMandatoryOptionValue(option) {1765 const message = `error: required option '${option.flags}' not specified`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1766why, one step back
1766 this.error(message, { code: 'commander.missingMandatoryOptionValue' });

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1767–1773why, one step back
1767 }
17681769 /**1770 * `Option` conflicts with another option.1771 *1772 * @param {Option} option1773 * @param {Option} conflictingOption

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

line 1774why, one step back
1774 * @private

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 1775–1804why, one step back
1775 */
1776 _conflictingOption(option, conflictingOption) {1777 // The calling code does not know whether a negated option is the source of the1778 // value, so do some work to take an educated guess.1779 const findBestOptionFromValue = (option) => {1780 const optionKey = option.attributeName();1781 const optionValue = this.getOptionValue(optionKey);1782 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1783 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1784 if (negativeOption && (1785 (negativeOption.presetArg === undefined && optionValue === false) ||1786 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1787 )) {1788 return negativeOption;1789 }1790 return positiveOption || option;1791 };17921793 const getErrorMessage = (option) => {1794 const bestOption = findBestOptionFromValue(option);1795 const optionKey = bestOption.attributeName();1796 const source = this.getOptionValueSource(optionKey);1797 if (source === 'env') {1798 return `environment variable '${bestOption.envVar}'`;1799 }1800 return `option '${bestOption.flags}'`;1801 };18021803 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1804 this.error(message, { code: 'commander.conflictingOption' });

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1805why, one step back
1805 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1806–1810why, one step back
1806
1807 /**1808 * Unknown option `flag`.1809 *1810 * @param {string} flag

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

line 1811why, one step back
1811 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1812–1815why, one step back
1812 */
18131814 unknownOption(flag) {1815 if (this._allowUnknownOption) return;

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

lines 1816–1820why, one step back
1816 let suggestion = '';
18171818 if (flag.startsWith('--') && this._showSuggestionAfterError) {1819 // Looping to pick up the global options too1820 let candidateFlags = [];

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

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

Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734

lines 1822–1823why, one step back
1822 let command = this;
1823 do {

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

lines 1824–1827why, one step back
1824 const moreFlags = command.createHelp().visibleOptions(command)
1825 .filter(option => option.long)1826 .map(option => option.long);1827 candidateFlags = candidateFlags.concat(moreFlags);

Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734

lines 1828–1829why, one step back
1828 command = command.parent;
1829 } while (command && !command._enablePositionalOptions);

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

lines 1830–1833why, one step back
1830 suggestion = suggestSimilar(flag, candidateFlags);
1831 }18321833 const message = `error: unknown option '${flag}'${suggestion}`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1834–1835why, one step back
1834 this.error(message, { code: 'commander.unknownOption' });
1835 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1836–1840why, one step back
1836
1837 /**1838 * Excess arguments, more than expected.1839 *1840 * @param {string[]} receivedArgs

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

line 1841why, one step back
1841 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1842–1846why, one step back
1842 */
18431844 _excessArguments(receivedArgs) {1845 if (this._allowExcessArguments) return;1846

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1847why, one step back
1847 const expected = this.registeredArguments.length;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1848–1850why, one step back
1848 const s = (expected === 1) ? '' : 's';
1849 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1850 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1851–1852why, one step back
1851 this.error(message, { code: 'commander.excessArguments' });
1852 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1853–1856why, one step back
1853
1854 /**1855 * Unknown command.1856 *

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

line 1857why, one step back
1857 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1858–1860why, one step back
1858 */
18591860 unknownCommand() {

Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5

lines 1861–1874why, one step back
1861 const unknownName = this.args[0];
1862 let suggestion = '';18631864 if (this._showSuggestionAfterError) {1865 const candidateNames = [];1866 this.createHelp().visibleCommands(this).forEach((command) => {1867 candidateNames.push(command.name());1868 // just visible alias1869 if (command.alias()) candidateNames.push(command.alias());1870 });1871 suggestion = suggestSimilar(unknownName, candidateNames);1872 }18731874 const message = `error: unknown command '${unknownName}'${suggestion}`;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 1875–1876why, one step back
1875 this.error(message, { code: 'commander.unknownCommand' });
1876 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1877–1878why, one step back
1877
1878 /**

Types for version getter (#1982)John Geebefore adoptionf5413db

line 1879why, one step back
1879 * Get or set the program version.

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1880why, one step back
1880 *

Types for version getter (#1982)John Geebefore adoptionf5413db

line 1881why, one step back
1881 * This method auto-registers the "-V, --version" option which will print the version number.

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1882why, one step back
1882 *

Types for version getter (#1982)John Geebefore adoptionf5413db

line 1883why, one step back
1883 * You can optionally supply the flags and description to override the defaults.

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1884why, one step back
1884 *

Types for version getter (#1982)John Geebefore adoptionf5413db

line 1885why, one step back
1885 * @param {string} [str]

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1886–1887why, one step back
1886 * @param {string} [flags]
1887 * @param {string} [description]

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

line 1888why, one step back
1888 * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1889–1896why, one step back
1889 */
18901891 version(str, flags, description) {1892 if (str === undefined) return this._version;1893 this._version = str;1894 flags = flags || '-V, --version';1895 description = description || 'output the version number';1896 const versionOption = this.createOption(flags, description);

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

lines 1897–1899why, one step back
1897 this._versionOptionName = versionOption.attributeName();
1898 this._registerOption(versionOption);1899

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1900–1904why, one step back
1900 this.on('option:' + versionOption.name(), () => {
1901 this._outputConfiguration.writeOut(`${str}\n`);1902 this._exit(0, 'commander.version', str);1903 });1904 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1905why, one step back
1905 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1906–1907why, one step back
1906
1907 /**

Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b

line 1908why, one step back
1908 * Set the description.

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1909–1911why, one step back
1909 *
1910 * @param {string} [str]1911 * @param {Object} [argsDescription]

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

line 1912why, one step back
1912 * @return {(string|Command)}

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1913–1919why, one step back
1913 */
1914 description(str, argsDescription) {1915 if (str === undefined && argsDescription === undefined) return this._description;1916 this._description = str;1917 if (argsDescription) {1918 this._argsDescription = argsDescription;1919 }

Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b

lines 1920–1926why, one step back
1920 return this;
1921 }19221923 /**1924 * Set the summary. Used when listed as subcommand of parent.1925 *1926 * @param {string} [str]

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

line 1927why, one step back
1927 * @return {(string|Command)}

Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b

lines 1928–1931why, one step back
1928 */
1929 summary(str) {1930 if (str === undefined) return this._summary;1931 this._summary = str;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1932why, one step back
1932 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1933why, one step back
1933 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1934–1940why, one step back
1934
1935 /**1936 * Set an alias for the command.1937 *1938 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1939 *1940 * @param {string} [alias]

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

line 1941why, one step back
1941 * @return {(string|Command)}

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1942–1946why, one step back
1942 */
19431944 alias(alias) {1945 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1946

Support argument processing without action handler (#1529)John Geebefore adoption4663597

line 1947why, one step back
1947 /** @type {Command} */

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1949–1955why, one step back
1949 let command = this;
1950 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1951 // assume adding alias for last added executable subcommand, rather than this1952 command = this.commands[this.commands.length - 1];1953 }19541955 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');

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

lines 1956–1961why, one step back
1956 const matchingCommand = this.parent?._findCommand(alias);
1957 if (matchingCommand) {1958 // c.f. _registerCommand1959 const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');1960 throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);1961 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1962–1964why, one step back
1962
1963 command._aliases.push(alias);1964 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1965why, one step back
1965 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1966–1972why, one step back
1966
1967 /**1968 * Set aliases for the command.1969 *1970 * Only the first alias is shown in the auto-generated help.1971 *1972 * @param {string[]} [aliases]

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

line 1973why, one step back
1973 * @return {(string[]|Command)}

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1974–1981why, one step back
1974 */
19751976 aliases(aliases) {1977 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1978 if (aliases === undefined) return this._aliases;19791980 aliases.forEach((alias) => this.alias(alias));1981 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 1982why, one step back
1982 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1983–1987why, one step back
1983
1984 /**1985 * Set / get the command usage `str`.1986 *1987 * @param {string} [str]

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

line 1988why, one step back
1988 * @return {(string|Command)}

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1989–1994why, one step back
1989 */
19901991 usage(str) {1992 if (str === undefined) {1993 if (this._usage) return this._usage;1994

Add public Arguments property (#2010)John Geebefore adoption7d23437

line 1995why, one step back
1995 const args = this.registeredArguments.map((arg) => {

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1996–1998why, one step back
1996 return humanReadableArgName(arg);
1997 });1998 return [].concat(

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

line 1999why, one step back
1999 (this.options.length || (this._helpOption !== null) ? '[options]' : []),

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 2000why, one step back
2000 (this.commands.length ? '[command]' : []),

The first 2,000 of 2,301 lines.