Skip to content
Myr

command.js

This file

Path

lib/command.js

2,299 lines · 72.9 KiB · JavaScript

Last changed by

Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af

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');

Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af

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[]} */

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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;

Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af

lines 69–70why, one step back
69 /** @type {(Option | null | undefined)} */
70 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

lines 71–73why, one step back
71 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
72 /** @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;

Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af

line 87why, one step back
87 this._helpOption = sourceCommand._helpOption;

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

line 88why, one step back
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 /**

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 103why, one step back
103 * @private

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

lines 104–114why, one step back
104 */
105106 _getCommandAndAncestors() {107 const result = [];108 for (let command = this; command; command = command.parent) {109 result.push(command);110 }111 return result;112 }113114 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 127why, one step back
127 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add check for overlapping command names or aliases (#2059)John Geebefore adoption1d3dd47

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add copyInheritedSettings (#1557)John Geebefore adoption5517d25

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 164why, one step back
164 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 178why, one step back
178 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 189why, one step back
189 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 197–211why, one step back
197 */
198199 configureHelp(configuration) {200 if (configuration === undefined) return this._helpConfiguration;201202 this._helpConfiguration = configuration;203 return this;204 }205206 /**207 * The default output goes to stdout and stderr. You can customise this for special208 * applications. You can also customise the display of errors by overriding outputError.209 *210 * The configuration properties are all functions:211 *

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 223–232why, one step back
223 */
224225 configureOutput(configuration) {226 if (configuration === undefined) return this._outputConfiguration;227228 Object.assign(this._outputConfiguration, configuration);229 return this;230 }231232 /**

Add showHelpAfterError (#1534)John Geebefore adoption082717f

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Add showHelpAfterError (#1534)John Geebefore adoption082717f

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add check for overlapping command names or aliases (#2059)John Geebefore adoption1d3dd47

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a

line 277why, one step back
277 cmd._checkForBrokenPassThrough();

Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4

line 278why, one step back
278

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 279why, one step back
279 return this;

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

line 280why, one step back
280 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 281–294why, one step back
281
282 /**283 * Factory routine to create a new unattached argument.284 *285 * See .argument() for creating an attached argument, which uses this routine to286 * create the argument. You can override createArgument to return a custom argument.287 *288 * @param {string} name289 * @param {string} [description]290 * @return {Argument} new argument291 */292293 createArgument(name, description) {294 return new Argument(name, description);

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

line 295why, one step back
295 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 331–336why, one step back
331 *
332 * @param {string} names333 * @return {Command} `this` command for chaining334 */335336 arguments(names) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 341why, one step back
341 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 358–361why, one step back
358 return this;
359 }360361 /**

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

line 362why, one step back
362 * 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 363why, one step back
363 *

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 368why, one step back
368 *

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 378why, one step back
378 }

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

lines 379–391why, one step back
379
380 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';381 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);382 const helpDescription = description ?? 'display help for command';383384 const helpCommand = this.createCommand(helpName);385 helpCommand.helpOption(false);386 if (helpArgs) helpCommand.arguments(helpArgs);387 if (helpDescription) helpCommand.description(helpDescription);388389 this._addImplicitHelpCommand = true;390 this._helpCommand = helpCommand;391

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 392why, one step back
392 return this;

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

line 393why, one step back
393 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 394–395why, one step back
394
395 /**

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 401why, one step back
401 */

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 409why, one step back
409

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

lines 410–429why, one step back
410 this._addImplicitHelpCommand = true;
411 this._helpCommand = helpCommand;412 return this;413 }414415 /**416 * Lazy create help command.417 *418 * @return {(Command|null)}419 * @package420 */421 _getHelpCommand() {422 const hasImplicitHelpCommand = this._addImplicitHelpCommand ??423 (this.commands.length && !this._actionHandler && !this._findCommand('help'));424425 if (hasImplicitHelpCommand) {426 if (this._helpCommand === undefined) {427 this.helpCommand(undefined, undefined); // use default name and description428 }429 return this._helpCommand;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 430why, one step back
430 }

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

line 431why, one step back
431 return null;

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

line 432why, one step back
432 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 433–442why, one step back
433
434 /**435 * Add hook for life cycle event.436 *437 * @param {string} event438 * @param {Function} listener439 * @return {Command} `this` command for chaining440 */441442 hook(event, listener) {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 476why, one step back
476 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 477–484why, one step back
477
478 /**479 * Call process.exit, and _exitCallback if defined.480 *481 * @param {number} exitCode exit code for using with process.exit482 * @param {string} code an id string representing the error483 * @param {string} message human-readable description of the error484 * @return never

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 485why, one step back
485 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 494why, one step back
494 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 499–500why, one step back
499 * @example
500 * program

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

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

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

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

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 506–513why, one step back
506 *
507 * @param {Function} fn508 * @return {Command} `this` command for chaining509 */510511 action(fn) {512 const listener = (args) => {513 // The .action callback takes an extra parameter which is the command or options.

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 527why, one step back
527 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 528–541why, one step back
528
529 /**530 * Factory routine to create a new unattached option.531 *532 * See .option() for creating an attached option, which uses this routine to533 * create the option. You can override createOption to return a custom option.534 *535 * @param {string} flags536 * @param {string} [description]537 * @return {Option} new option538 */539540 createOption(flags, description) {541 return new Option(flags, description);

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

line 542why, one step back
542 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 543–544why, one step back
543
544 /**

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 551why, one step back
551 * @private

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Add check for overlapping command names or aliases (#2059)John Geebefore adoption1d3dd47

line 565why, one step back
565

Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40

lines 566–567why, one step back
566 /**
567 * Check for option flag conflicts.

Add check for overlapping command names or aliases (#2059)John Geebefore adoption1d3dd47

line 568why, one step back
568 * Register option if no conflicts found, or throw on conflict.

Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40

lines 569–572why, one step back
569 *
570 * @param {Option} option571 * @api private572 */

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

line 573why, one step back
573

Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40

lines 574–581why, one step back
574 _registerOption(option) {
575 const matchingOption = (option.short && this._findOption(option.short)) ||576 (option.long && this._findOption(option.long));577 if (matchingOption) {578 const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;579 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'580- already used by option '${matchingOption.flags}'`);581 }

Add check for overlapping command names or aliases (#2059)John Geebefore adoption1d3dd47

line 582why, one step back
582

Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40

lines 583–585why, one step back
583 this.options.push(option);
584 }585

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

line 586why, one step back
586 /**

Add check for overlapping command names or aliases (#2059)John Geebefore adoption1d3dd47

lines 587–609why, one step back
587 * Check for command name and alias conflicts with existing commands.
588 * Register command if no conflicts found, or throw on conflict.589 *590 * @param {Command} command591 * @api private592 */593594 _registerCommand(command) {595 const knownBy = (cmd) => {596 return [cmd.name()].concat(cmd.aliases());597 };598599 const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));600 if (alreadyUsed) {601 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');602 const newCmd = knownBy(command).join('|');603 throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);604 }605606 this.commands.push(command);607 }608609 /**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 610–615why, one step back
610 * Add an option.
611 *612 * @param {Option} option613 * @return {Command} `this` command for chaining614 */615 addOption(option) {

Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40

lines 616–617why, one step back
616 this._registerOption(option);
617

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 627why, one step back
627 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 630–631why, one step back
630 }
631

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 639–640why, one step back
639
640 // custom processing

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 654why, one step back
654 } else {

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 656–657why, one step back
656 }
657 }

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 664–665why, one step back
664 });
665

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 673–678why, one step back
673 return this;
674 }675676 /**677 * Internal implementation shared by .option() and .requiredOption()678 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 679why, one step back
679 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 706why, one step back
706 *

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 709why, one step back
709 *

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 711why, one step back
711 *

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

line 712why, one step back
712 * @example

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 718–720why, one step back
718 *
719 * @param {string} flags720 * @param {string} [description]

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 722–725why, one step back
722 * @param {*} [defaultValue]
723 * @return {Command} `this` command for chaining724 */725

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

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

line 728why, one step back
728 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 739–742why, one step back
739 * @param {*} [defaultValue]
740 * @return {Command} `this` command for chaining741 */742

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

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

line 745why, one step back
745 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 754why, one step back
754 *

Improve JSDoc (#2103)John Geebefore adoption32c05a8

line 755why, one step back
755 * @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 756–759why, one step back
756 */
757 combineFlagAndOptionalValue(combine = true) {758 this._combineFlagAndOptionalValue = !!combine;759 return this;

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

line 760why, one step back
760 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 771why, one step back
771 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 782why, one step back
782 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 794why, one step back
794 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 808why, one step back
808 return this;

Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4

lines 809–811why, one step back
809 }
810811 /**

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 812why, one step back
812 * @private

Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4

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

Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a

lines 815–817why, one step back
815 _checkForBrokenPassThrough() {
816 if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {817 throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);

Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4

line 818why, one step back
818 }

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

line 819why, one step back
819 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Restore extra sanity check when enabling storeOptionsAsProperties (#2029)John Geebefore adoptiond90c59c

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

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 837why, one step back
837 return this;

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

line 838why, one step back
838 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 839–851why, one step back
839
840 /**841 * Retrieve option value.842 *843 * @param {string} key844 * @return {Object} value845 */846847 getOptionValue(key) {848 if (this._storeOptionsAsProperties) {849 return this[key];850 }851 return this._optionValues[key];

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

line 852why, one step back
852 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 853–862why, one step back
853
854 /**855 * Store option value.856 *857 * @param {string} key858 * @param {Object} value859 * @return {Command} `this` command for chaining860 */861862 setOptionValue(key, value) {

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

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

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

line 864why, one step back
864 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 865–866why, one step back
865
866 /**

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

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

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 868–870why, one step back
868 *
869 * @param {string} key870 * @param {Object} value

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

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

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

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

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

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

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

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

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

line 882why, one step back
882 return this;

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

lines 883–885why, one step back
883 }
884885 /**

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

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

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

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

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 888–894why, one step back
888 *
889 * @param {string} key890 * @return {string}891 */892893 getOptionValueSource(key) {894 return this._optionValueSources[key];

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

line 895why, one step back
895 }

Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44

lines 896–897why, one step back
896
897 /**

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

lines 898–907why, one step back
898 * Get source of option value. See also .optsWithGlobals().
899 * Expected values are default | config | env | cli | implied900 *901 * @param {string} key902 * @return {string}903 */904905 getOptionValueSourceWithGlobals(key) {906 // global overwrites local, like optsWithGlobals907 let source;

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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

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

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

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

lines 917–918why, one step back
917 * Get user arguments from implied or explicit arguments.
918 * 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 919why, one step back
919 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 920why, one step back
920 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 921–962why, one step back
921 */
922923 _prepareUserArgs(argv, parseOptions) {924 if (argv !== undefined && !Array.isArray(argv)) {925 throw new Error('first parameter to parse must be array or undefined');926 }927 parseOptions = parseOptions || {};928929 // Default to using process.argv930 if (argv === undefined) {931 argv = process.argv;932 // @ts-ignore: unknown property933 if (process.versions && process.versions.electron) {934 parseOptions.from = 'electron';935 }936 }937 this.rawArgs = argv.slice();938939 // make it a little easier for callers by supporting various argv conventions940 let userArgs;941 switch (parseOptions.from) {942 case undefined:943 case 'node':944 this._scriptPath = argv[1];945 userArgs = argv.slice(2);946 break;947 case 'electron':948 // @ts-ignore: unknown property949 if (process.defaultApp) {950 this._scriptPath = argv[1];951 userArgs = argv.slice(2);952 } else {953 userArgs = argv.slice(1);954 }955 break;956 case 'user':957 userArgs = argv.slice(0);958 break;959 default:960 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);961 }962

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 980–991why, one step back
980 *
981 * @param {string[]} [argv] - optional, defaults to process.argv982 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron983 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'984 * @return {Command} `this` command for chaining985 */986987 parse(argv, parseOptions) {988 const userArgs = this._prepareUserArgs(argv, parseOptions);989 this._parseCommand([], userArgs);990991 return this;

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

line 992why, one step back
992 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1002–1005why, one step back
1002 * @example
1003 * await program.parseAsync(process.argv);1004 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions1005 * 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 1006–1017why, one step back
1006 *
1007 * @param {string[]} [argv]1008 * @param {Object} [parseOptions]1009 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1010 * @return {Promise}1011 */10121013 async parseAsync(argv, parseOptions) {1014 const userArgs = this._prepareUserArgs(argv, parseOptions);1015 await this._parseCommand([], userArgs);10161017 return this;

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

line 1018why, one step back
1018 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 1023why, one step back
1023 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1035why, one step back
1035

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1038why, one step back
1038

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

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

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1072why, one step back
1072 }

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

lines 1097–1105why, one step back
1097 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
1098 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1099 signals.forEach((signal) => {1100 // @ts-ignore1101 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;

Exit with non-zero code when subprocess terminated by signal (#2023)John Geebefore adoption5aaca0d

lines 1111–1118why, one step back
1111 proc.on('close', (code, _signal) => {
1112 code = code ?? 1; // code is null if spawned process terminated due to a signal1113 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

lines 1119–1121why, one step back
1119 proc.on('error', (err) => {
1120 // @ts-ignore1121 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

lines 1129–1131why, one step back
1129 throw new Error(executableMissing);
1130 // @ts-ignore1131 } 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 /**

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 });

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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.

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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

Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af

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

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 /**

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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 }

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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 /**

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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) {

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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 = [];

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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 *

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

line 1261why, one step back
1261 * @return {(Promise|undefined)}

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 1262why, one step back
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 *

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

line 1279why, one step back
1279 * @return {(Promise|undefined)}

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 1280why, one step back
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 = [];

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 *

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

line 1311why, one step back
1311 * @return {(Promise|undefined)}

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 1312why, one step back
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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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 }

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

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) {

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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) {

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 }

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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}

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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.

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 });

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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.

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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();

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 *

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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;

Refactor help command implementation to hold actual Command (#2087)John Geebefore adoptionff08a02

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

Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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 *

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

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–1832why, one step back
1816 let suggestion = '';
18171818 if (flag.startsWith('--') && this._showSuggestionAfterError) {1819 // Looping to pick up the global options too1820 let candidateFlags = [];1821 let command = this;1822 do {1823 const moreFlags = command.createHelp().visibleOptions(command)1824 .filter(option => option.long)1825 .map(option => option.long);1826 candidateFlags = candidateFlags.concat(moreFlags);1827 command = command.parent;1828 } while (command && !command._enablePositionalOptions);1829 suggestion = suggestSimilar(flag, candidateFlags);1830 }18311832 const message = `error: unknown option '${flag}'${suggestion}`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 1840why, one step back
1840 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1841–1845why, one step back
1841 */
18421843 _excessArguments(receivedArgs) {1844 if (this._allowExcessArguments) return;1845

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1847–1849why, one step back
1847 const s = (expected === 1) ? '' : 's';
1848 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1849 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 1850–1851why, one step back
1850 this.error(message, { code: 'commander.excessArguments' });
1851 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398

line 1856why, one step back
1856 * @private

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1857–1859why, one step back
1857 */
18581859 unknownCommand() {

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

lines 1860–1873why, one step back
1860 const unknownName = this.args[0];
1861 let suggestion = '';18621863 if (this._showSuggestionAfterError) {1864 const candidateNames = [];1865 this.createHelp().visibleCommands(this).forEach((command) => {1866 candidateNames.push(command.name());1867 // just visible alias1868 if (command.alias()) candidateNames.push(command.alias());1869 });1870 suggestion = suggestSimilar(unknownName, candidateNames);1871 }18721873 const message = `error: unknown command '${unknownName}'${suggestion}`;

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1879why, one step back
1879 *

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1881why, one step back
1881 *

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1883why, one step back
1883 *

Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 1904why, one step back
1904 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 1931why, one step back
1931 return this;

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

line 1932why, one step back
1932 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1941–1945why, one step back
1941 */
19421943 alias(alias) {1944 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1945

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

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Add check for overlapping command names or aliases (#2059)John Geebefore adoption1d3dd47

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

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

line 1963why, one step back
1963 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1972–1979why, one step back
1972 */
19731974 aliases(aliases) {1975 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1976 if (aliases === undefined) return this._aliases;19771978 aliases.forEach((alias) => this.alias(alias));1979 return this;

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

line 1980why, one step back
1980 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Improve JSDoc (#2103)John Geebefore adoption32c05a8

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1987–1992why, one step back
1987 */
19881989 usage(str) {1990 if (str === undefined) {1991 if (this._usage) return this._usage;1992

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Refactor help option implementation to hold actual Option (#2006)John Geebefore adoption09244af

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

Refactor classes into files (#1522)John Geebefore adoption08245cc

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

Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd

line 1999why, one step back
1999 (this.registeredArguments.length ? args : [])

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 2000–2004why, one step back
2000 ).join(' ');

The first 2,000 of 2,299 lines.