command.js
This file
Path
lib/command.js
2,585 lines · 79.1 KiB · JavaScript
Last changed by
Prepare for 13.0.0-0 (#2292)John Geebefore adoption53fc8a4
History of this fileTake it
The walk stopped after 200 commits: lines older than 411ca95 point at it.
Fix: Use `node`-prefixed requires for builtins (#2170)Sam Gammonbefore adoptionf7b8475
lines 1–5why, one step back1const EventEmitter = require('node:events').EventEmitter;2const childProcess = require('node:child_process');3const path = require('node:path');4const fs = require('node:fs');5const process = require('node:process');Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 6–8why, one step back67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 9why, one step back9const { Help, stripColor } = require('./help.js');Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 10why, one step back10const { Option, DualOptions } = require('./option.js');Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 11why, one step back11const { suggestSimilar } = require('./suggestSimilar');Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 12–27why, one step back1213class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();22 /** @type {Command[]} */23 this.commands = [];24 /** @type {Option[]} */25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;Disallow excess arguments (#2223)John Geebefore adoption58c28eb
line 28why, one step back28 this._allowExcessArguments = false;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 29why, one step back29 /** @type {Argument[]} */Add public Arguments property (#2010)John Geebefore adoption7d23437
lines 30–31why, one step back30 this.registeredArguments = [];31 this._args = this.registeredArguments; // deprecated old nameClarify that more than just READMEJohn Geebefore adoption411ca95
lines 32–38why, one step back32 /** @type {string[]} */33 this.args = []; // cli args with options removed34 this.rawArgs = [];35 this.processedArgs = []; // like .args but after custom processing and collecting variadic36 this._scriptPath = null;37 this._name = name || '';38 this._optionValues = {};Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 39why, one step back39 this._optionValueSources = {}; // default, env, cli etcClarify that more than just READMEJohn Geebefore adoption411ca95
lines 40–43why, one step back40 this._storeOptionsAsProperties = false;41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executableMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 44why, one step back44 this._executableDir = null; // custom search directory for subcommandsClarify that more than just READMEJohn Geebefore adoption411ca95
lines 45–49why, one step back45 this._defaultCommandName = null;46 this._exitCallback = null;47 this._aliases = [];48 this._combineFlagAndOptionalValue = true;49 this._description = '';Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 50why, one step back50 this._summary = '';Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 51–54why, one step back51 this._argsDescription = undefined; // legacy52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arraysMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 55why, one step back55 /** @type {(boolean | string)} */Clarify that more than just READMEJohn Geebefore adoption411ca95
line 56why, one step back56 this._showHelpAfterError = false;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 57why, one step back57 this._showSuggestionAfterError = true;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 58why, one step back58Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 59why, one step back59 // see configureOutput() for docsClarify that more than just READMEJohn Geebefore adoption411ca95
lines 60–62why, one step back60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 63why, one step back63 outputError: (str, write) => write(str),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 64–67why, one step back64 getOutHelpWidth: () =>65 process.stdout.isTTY ? process.stdout.columns : undefined,66 getErrHelpWidth: () =>67 process.stderr.isTTY ? process.stderr.columns : undefined,Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 68–72why, one step back68 getOutHasColors: () =>69 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),70 getErrHasColors: () =>71 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),72 stripColor: (str) => stripColor(str),Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 73–75why, one step back73 };7475 this._hidden = false;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 76–80why, one step back76 /** @type {(Option | null | undefined)} */77 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.78 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited79 /** @type {Command} */80 this._helpCommand = undefined; // lazy initialised, inheritedClarify that more than just READMEJohn Geebefore adoption411ca95
lines 81–89why, one step back81 this._helpConfiguration = {};82 }8384 /**85 * Copy settings that are useful to have in common across root command and subcommands.86 *87 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)88 *89 * @param {Command} sourceCommandMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 90why, one step back90 * @return {Command} `this` command for chainingClarify that more than just READMEJohn Geebefore adoption411ca95
lines 91–93why, one step back91 */92 copyInheritedSettings(sourceCommand) {93 this._outputConfiguration = sourceCommand._outputConfiguration;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 94–95why, one step back94 this._helpOption = sourceCommand._helpOption;95 this._helpCommand = sourceCommand._helpCommand;Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 96–98why, one step back96 this._helpConfiguration = sourceCommand._helpConfiguration;97 this._exitCallback = sourceCommand._exitCallback;98 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 99–100why, one step back99 this._combineFlagAndOptionalValue =100 sourceCommand._combineFlagAndOptionalValue;Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 101–103why, one step back101 this._allowExcessArguments = sourceCommand._allowExcessArguments;102 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;103 this._showHelpAfterError = sourceCommand._showHelpAfterError;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 104why, one step back104 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 105–109why, one step back105106 return this;107 }108109 /**Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 110why, one step back110 * @returns {Command[]}Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 111why, one step back111 * @privateIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 112–115why, one step back112 */113114 _getCommandAndAncestors() {115 const result = [];ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 116why, one step back116 // eslint-disable-next-line @typescript-eslint/no-this-aliasIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 117–123why, one step back117 for (let command = this; command; command = command.parent) {118 result.push(command);119 }120 return result;121 }122123 /**Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 124–142why, one step back124 * Define a command.125 *126 * There are two styles of command: pay attention to where to put the description.127 *128 * @example129 * // Command implemented using action handler (description is supplied separately to `.command`)130 * program131 * .command('clone <source> [destination]')132 * .description('clone a repository into a newly created directory')133 * .action((source, destination) => {134 * console.log('clone command called');135 * });136 *137 * // Command implemented using separate executable file (description is second parameter to `.command`)138 * program139 * .command('start <service>', 'start named service')140 * .command('stop [service]', 'stop named service, or all if no name supplied');141 *142 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 143–144why, one step back143 * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)144 * @param {object} [execOpts] - configuration options (for executable)Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 145–166why, one step back145 * @return {Command} returns new command for action handler, or `this` for executable command146 */147148 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {149 let desc = actionOptsOrExecDesc;150 let opts = execOpts;151 if (typeof desc === 'object' && desc !== null) {152 opts = desc;153 desc = null;154 }155 opts = opts || {};156 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);157158 const cmd = this.createCommand(name);159 if (desc) {160 cmd.description(desc);161 cmd._executableHandler = true;162 }163 if (opts.isDefault) this._defaultCommandName = cmd._name;164 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden165 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor166 if (args) cmd.arguments(args);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 167why, one step back167 this._registerCommand(cmd);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 168–172why, one step back168 cmd.parent = this;169 cmd.copyInheritedSettings(this);170171 if (desc) return this;172 return cmd;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 173why, one step back173 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 174–186why, one step back174175 /**176 * Factory routine to create a new unattached command.177 *178 * See .command() for creating an attached subcommand, which uses this routine to179 * create the command. You can override createCommand to customise subcommands.180 *181 * @param {string} [name]182 * @return {Command} new command183 */184185 createCommand(name) {186 return new Command(name);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 187why, one step back187 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 188–197why, one step back188189 /**190 * You can customise the help with a subclass of Help by overriding createHelp,191 * or by overriding Help properties using configureHelp().192 *193 * @return {Help}194 */195196 createHelp() {197 return Object.assign(new Help(), this.configureHelp());Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 198why, one step back198 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 199–203why, one step back199200 /**201 * You can customise the help by overriding Help properties using configureHelp(),202 * or with a subclass of Help by overriding createHelp().203 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 204–205why, one step back204 * @param {object} [configuration] - configuration options205 * @return {(Command | object)} `this` command for chaining, or stored configurationClarify that more than just READMEJohn Geebefore adoption411ca95
lines 206–220why, one step back206 */207208 configureHelp(configuration) {209 if (configuration === undefined) return this._helpConfiguration;210211 this._helpConfiguration = configuration;212 return this;213 }214215 /**216 * The default output goes to stdout and stderr. You can customise this for special217 * applications. You can also customise the display of errors by overriding outputError.218 *219 * The configuration properties are all functions:220 *Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 221why, one step back221 * // change how output being written, defaults to stdout and stderrClarify that more than just READMEJohn Geebefore adoption411ca95
lines 222–223why, one step back222 * writeOut(str)223 * writeErr(str)Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 224–226why, one step back224 * // change how output being written for errors, defaults to writeErr225 * outputError(str, write) // used for displaying errors and not used for displaying help226 * // specify width for wrapping helpClarify that more than just READMEJohn Geebefore adoption411ca95
lines 227–228why, one step back227 * getOutHelpWidth()228 * getErrHelpWidth()Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 229–231why, one step back229 * // color support, currently only used with Help230 * getOutHasColors()231 * getErrHasColors()Prepare for 13.0.0-0 (#2292)John Geebefore adoption53fc8a4
line 232why, one step back232 * stripColor() // used to remove ANSI escape codes if output does not have colorsClarify that more than just READMEJohn Geebefore adoption411ca95
line 233why, one step back233 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 234–235why, one step back234 * @param {object} [configuration] - configuration options235 * @return {(Command | object)} `this` command for chaining, or stored configurationClarify that more than just READMEJohn Geebefore adoption411ca95
lines 236–247why, one step back236 */237238 configureOutput(configuration) {239 if (configuration === undefined) return this._outputConfiguration;240241 Object.assign(this._outputConfiguration, configuration);242 return this;243 }244245 /**246 * Display the help or a custom message after an error occurs.247 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 248why, one step back248 * @param {(boolean|string)} [displayHelp]Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 249–257why, one step back249 * @return {Command} `this` command for chaining250 */251 showHelpAfterError(displayHelp = true) {252 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;253 this._showHelpAfterError = displayHelp;254 return this;255 }256257 /**Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 258–268why, one step back258 * Display suggestion of similar commands for unknown commands, or options for unknown options.259 *260 * @param {boolean} [displaySuggestion]261 * @return {Command} `this` command for chaining262 */263 showSuggestionAfterError(displaySuggestion = true) {264 this._showSuggestionAfterError = !!displaySuggestion;265 return this;266 }267268 /**Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 269–273why, one step back269 * Add a prepared subcommand.270 *271 * See .command() for creating an attached subcommand which inherits settings from its parent.272 *273 * @param {Command} cmd - new subcommandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 274why, one step back274 * @param {object} [opts] - configuration optionsClarify that more than just READMEJohn Geebefore adoption411ca95
lines 275–278why, one step back275 * @return {Command} `this` command for chaining276 */277278 addCommand(cmd, opts) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 279–281why, one step back279 if (!cmd._name) {280 throw new Error(`Command passed to .addCommand() must have a name281- specify the name in Command constructor or using .name()`);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 282–287why, one step back282 }283284 opts = opts || {};285 if (opts.isDefault) this._defaultCommandName = cmd._name;286 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation287Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 288why, one step back288 this._registerCommand(cmd);Clarify that more than just READMEJohn Geebefore adoption411ca95
line 289why, one step back289 cmd.parent = this;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 290–291why, one step back290 cmd._checkForBrokenPassThrough();291Clarify that more than just READMEJohn Geebefore adoption411ca95
line 292why, one step back292 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 293why, one step back293 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 294–307why, one step back294295 /**296 * Factory routine to create a new unattached argument.297 *298 * See .argument() for creating an attached argument, which uses this routine to299 * create the argument. You can override createArgument to return a custom argument.300 *301 * @param {string} name302 * @param {string} [description]303 * @return {Argument} new argument304 */305306 createArgument(name, description) {307 return new Argument(name, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 308why, one step back308 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 309–321why, one step back309310 /**311 * Define argument syntax for command.312 *313 * The default is that the argument is required, and you can explicitly314 * indicate this with <> around the name. Put [] around the name for an optional argument.315 *316 * @example317 * program.argument('<input-file>');318 * program.argument('[output-file]');319 *320 * @param {string} name321 * @param {string} [description]Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 322why, one step back322 * @param {(Function|*)} [fn] - custom argument processing functionClarify that more than just READMEJohn Geebefore adoption411ca95
lines 323–349why, one step back323 * @param {*} [defaultValue]324 * @return {Command} `this` command for chaining325 */326 argument(name, description, fn, defaultValue) {327 const argument = this.createArgument(name, description);328 if (typeof fn === 'function') {329 argument.default(defaultValue).argParser(fn);330 } else {331 argument.default(fn);332 }333 this.addArgument(argument);334 return this;335 }336337 /**338 * Define argument syntax for command, adding multiple at once (without descriptions).339 *340 * See also .argument().341 *342 * @example343 * program.arguments('<cmd> [env]');344 *345 * @param {string} names346 * @return {Command} `this` command for chaining347 */348349 arguments(names) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 350–355why, one step back350 names351 .trim()352 .split(/ +/)353 .forEach((detail) => {354 this.argument(detail);355 });Clarify that more than just READMEJohn Geebefore adoption411ca95
line 356why, one step back356 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 357why, one step back357 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 358–365why, one step back358359 /**360 * Define argument syntax for command, adding a prepared argument.361 *362 * @param {Argument} argument363 * @return {Command} `this` command for chaining364 */365 addArgument(argument) {Add public Arguments property (#2010)John Geebefore adoption7d23437
line 366why, one step back366 const previousArgument = this.registeredArguments.slice(-1)[0];Clarify that more than just READMEJohn Geebefore adoption411ca95
line 367why, one step back367 if (previousArgument && previousArgument.variadic) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 368–370why, one step back368 throw new Error(369 `only the last argument can be variadic '${previousArgument.name()}'`,370 );Clarify that more than just READMEJohn Geebefore adoption411ca95
line 371why, one step back371 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 372–379why, one step back372 if (373 argument.required &&374 argument.defaultValue !== undefined &&375 argument.parseArg === undefined376 ) {377 throw new Error(378 `a default value for a required argument is never used: '${argument.name()}'`,379 );Clarify that more than just READMEJohn Geebefore adoption411ca95
line 380why, one step back380 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 381why, one step back381 this.registeredArguments.push(argument);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 382–385why, one step back382 return this;383 }384385 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 386why, one step back386 * Customise or override default help command. By default a help command is automatically added if your command has subcommands.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 387why, one step back387 *ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 388why, one step back388 * @exampleMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 389–392why, one step back389 * program.helpCommand('help [cmd]');390 * program.helpCommand('help [cmd]', 'show help');391 * program.helpCommand(false); // suppress default help command392 * program.helpCommand(true); // add help command even if no subcommandsClarify that more than just READMEJohn Geebefore adoption411ca95
line 393why, one step back393 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 394–395why, one step back394 * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added395 * @param {string} [description] - custom descriptionClarify that more than just READMEJohn Geebefore adoption411ca95
lines 396–398why, one step back396 * @return {Command} `this` command for chaining397 */398Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 399–402why, one step back399 helpCommand(enableOrNameAndArgs, description) {400 if (typeof enableOrNameAndArgs === 'boolean') {401 this._addImplicitHelpCommand = enableOrNameAndArgs;402 return this;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 403why, one step back403 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 404–416why, one step back404405 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';406 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);407 const helpDescription = description ?? 'display help for command';408409 const helpCommand = this.createCommand(helpName);410 helpCommand.helpOption(false);411 if (helpArgs) helpCommand.arguments(helpArgs);412 if (helpDescription) helpCommand.description(helpDescription);413414 this._addImplicitHelpCommand = true;415 this._helpCommand = helpCommand;416Clarify that more than just READMEJohn Geebefore adoption411ca95
line 417why, one step back417 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 418why, one step back418 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 419–420why, one step back419420 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 421–425why, one step back421 * Add prepared custom help command.422 *423 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`424 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only425 * @return {Command} `this` command for chainingClarify that more than just READMEJohn Geebefore adoption411ca95
line 426why, one step back426 */Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 427–433why, one step back427 addHelpCommand(helpCommand, deprecatedDescription) {428 // If not passed an object, call through to helpCommand for backwards compatibility,429 // as addHelpCommand was originally used like helpCommand is now.430 if (typeof helpCommand !== 'object') {431 this.helpCommand(helpCommand, deprecatedDescription);432 return this;433 }Clarify that more than just READMEJohn Geebefore adoption411ca95
line 434why, one step back434Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 435–446why, one step back435 this._addImplicitHelpCommand = true;436 this._helpCommand = helpCommand;437 return this;438 }439440 /**441 * Lazy create help command.442 *443 * @return {(Command|null)}444 * @package445 */446 _getHelpCommand() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 447–451why, one step back447 const hasImplicitHelpCommand =448 this._addImplicitHelpCommand ??449 (this.commands.length &&450 !this._actionHandler &&451 !this._findCommand('help'));Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 452–457why, one step back452453 if (hasImplicitHelpCommand) {454 if (this._helpCommand === undefined) {455 this.helpCommand(undefined, undefined); // use default name and description456 }457 return this._helpCommand;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 458why, one step back458 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 459why, one step back459 return null;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 460why, one step back460 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 461–470why, one step back461462 /**463 * Add hook for life cycle event.464 *465 * @param {string} event466 * @param {Function} listener467 * @return {Command} `this` command for chaining468 */469470 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 471why, one step back471 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 472–503why, one step back472 if (!allowedValues.includes(event)) {473 throw new Error(`Unexpected value for event passed to hook : '${event}'.474Expecting one of '${allowedValues.join("', '")}'`);475 }476 if (this._lifeCycleHooks[event]) {477 this._lifeCycleHooks[event].push(listener);478 } else {479 this._lifeCycleHooks[event] = [listener];480 }481 return this;482 }483484 /**485 * Register callback to use as replacement for calling process.exit.486 *487 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing488 * @return {Command} `this` command for chaining489 */490491 exitOverride(fn) {492 if (fn) {493 this._exitCallback = fn;494 } else {495 this._exitCallback = (err) => {496 if (err.code !== 'commander.executeSubCommandAsync') {497 throw err;498 } else {499 // Async callback from spawn events, not useful to throw.500 }501 };502 }503 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 504why, one step back504 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 505–512why, one step back505506 /**507 * Call process.exit, and _exitCallback if defined.508 *509 * @param {number} exitCode exit code for using with process.exit510 * @param {string} code an id string representing the error511 * @param {string} message human-readable description of the error512 * @return neverMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 513why, one step back513 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 514–521why, one step back514 */515516 _exit(exitCode, code, message) {517 if (this._exitCallback) {518 this._exitCallback(new CommanderError(exitCode, code, message));519 // Expecting this line is not reached.520 }521 process.exit(exitCode);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 522why, one step back522 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 523–528why, one step back523524 /**525 * Register callback `fn` for the command.526 *527 * @example528 * programChange .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
lines 529–530why, one step back529 * .command('serve')530 * .description('start service')Clarify that more than just READMEJohn Geebefore adoption411ca95
line 531why, one step back531 * .action(function() {Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
line 532why, one step back532 * // do work hereClarify that more than just READMEJohn Geebefore adoption411ca95
lines 533–541why, one step back533 * });534 *535 * @param {Function} fn536 * @return {Command} `this` command for chaining537 */538539 action(fn) {540 const listener = (args) => {541 // The .action callback takes an extra parameter which is the command or options.Add public Arguments property (#2010)John Geebefore adoption7d23437
line 542why, one step back542 const expectedArgsCount = this.registeredArguments.length;Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 543–554why, one step back543 const actionArgs = args.slice(0, expectedArgsCount);544 if (this._storeOptionsAsProperties) {545 actionArgs[expectedArgsCount] = this; // backwards compatible "options"546 } else {547 actionArgs[expectedArgsCount] = this.opts();548 }549 actionArgs.push(this);550551 return fn.apply(this, actionArgs);552 };553 this._actionHandler = listener;554 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 555why, one step back555 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 556–569why, one step back556557 /**558 * Factory routine to create a new unattached option.559 *560 * See .option() for creating an attached option, which uses this routine to561 * create the option. You can override createOption to return a custom option.562 *563 * @param {string} flags564 * @param {string} [description]565 * @return {Option} new option566 */567568 createOption(flags, description) {569 return new Option(flags, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 570why, one step back570 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 571–572why, one step back571572 /**Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 573–574why, one step back573 * Wrap parseArgs to catch 'commander.invalidArgument'.574 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 575why, one step back575 * @param {(Option | Argument)} targetRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 576why, one step back576 * @param {string} valueReplace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6
line 577why, one step back577 * @param {*} previousRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 578why, one step back578 * @param {string} invalidArgumentMessageMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 579why, one step back579 * @privateRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 580–594why, one step back580 */581582 _callParseArg(target, value, previous, invalidArgumentMessage) {583 try {584 return target.parseArg(value, previous);585 } catch (err) {586 if (err.code === 'commander.invalidArgument') {587 const message = `${invalidArgumentMessage} ${err.message}`;588 this.error(message, { exitCode: err.exitCode, code: err.code });589 }590 throw err;591 }592 }593594 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 595–598why, one step back595 * Check for option flag conflicts.596 * Register option if no conflicts found, or throw on conflict.597 *598 * @param {Option} optionFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 599why, one step back599 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 600–602why, one step back600 */601602 _registerOption(option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 603–604why, one step back603 const matchingOption =604 (option.short && this._findOption(option.short)) ||Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 605–606why, one step back605 (option.long && this._findOption(option.long));606 if (matchingOption) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 607–610why, one step back607 const matchingFlag =608 option.long && this._findOption(option.long)609 ? option.long610 : option.short;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 611–622why, one step back611 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'612- already used by option '${matchingOption.flags}'`);613 }614615 this.options.push(option);616 }617618 /**619 * Check for command name and alias conflicts with existing commands.620 * Register command if no conflicts found, or throw on conflict.621 *622 * @param {Command} commandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 623why, one step back623 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 624–630why, one step back624 */625626 _registerCommand(command) {627 const knownBy = (cmd) => {628 return [cmd.name()].concat(cmd.aliases());629 };630Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 631–633why, one step back631 const alreadyUsed = knownBy(command).find((name) =>632 this._findCommand(name),633 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 634–636why, one step back634 if (alreadyUsed) {635 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');636 const newCmd = knownBy(command).join('|');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 637–639why, one step back637 throw new Error(638 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,639 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 640–645why, one step back640 }641642 this.commands.push(command);643 }644645 /**Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 646–651why, one step back646 * Add an option.647 *648 * @param {Option} option649 * @return {Command} `this` command for chaining650 */651 addOption(option) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 652–653why, one step back652 this._registerOption(option);653Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 654–656why, one step back654 const oname = option.name();655 const name = option.attributeName();656Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 657–661why, one step back657 // store default value658 if (option.negate) {659 // --no-foo is special and defaults foo to true, unless a --foo option is already defined660 const positiveLongFlag = option.long.replace(/^--no-/, '--');661 if (!this._findOption(positiveLongFlag)) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 662–666why, one step back662 this.setOptionValueWithSource(663 name,664 option.defaultValue === undefined ? true : option.defaultValue,665 'default',666 );Clarify that more than just READMEJohn Geebefore adoption411ca95
line 667why, one step back667 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 668–669why, one step back668 } else if (option.defaultValue !== undefined) {669 this.setOptionValueWithSource(name, option.defaultValue, 'default');Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 670–671why, one step back670 }671Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 672–673why, one step back672 // handler for cli and env supplied values673 const handleOptionValue = (val, invalidValueMessage, valueSource) => {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 674–678why, one step back674 // val is null for optional option used without an optional-argument.675 // val is undefined for boolean and negated option.676 if (val == null && option.presetArg !== undefined) {677 val = option.presetArg;678 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 679–680why, one step back679680 // custom processingMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 681why, one step back681 const oldValue = this.getOptionValue(name);Clarify that more than just READMEJohn Geebefore adoption411ca95
line 682why, one step back682 if (val !== null && option.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 683why, one step back683 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 684–687why, one step back684 } else if (val !== null && option.variadic) {685 val = option._concatValue(val, oldValue);686 }687Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 688–693why, one step back688 // Fill-in appropriate missing values. Long winded but easy to follow.689 if (val == null) {690 if (option.negate) {691 val = false;692 } else if (option.isBoolean() || option.optional) {693 val = true;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 694why, one step back694 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 695why, one step back695 val = ''; // not normal, parseArg might have failed or be a mock function for testingClarify that more than just READMEJohn Geebefore adoption411ca95
lines 696–697why, one step back696 }697 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 698why, one step back698 this.setOptionValueWithSource(name, val, valueSource);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 699–703why, one step back699 };700701 this.on('option:' + oname, (val) => {702 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;703 handleOptionValue(val, invalidValueMessage, 'cli');Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 704–705why, one step back704 });705Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 706–712why, one step back706 if (option.envVar) {707 this.on('optionEnv:' + oname, (val) => {708 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;709 handleOptionValue(val, invalidValueMessage, 'env');710 });711 }712Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 713–718why, one step back713 return this;714 }715716 /**717 * Internal implementation shared by .option() and .requiredOption()718 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 719why, one step back719 * @return {Command} `this` command for chainingMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 720why, one step back720 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 721–722why, one step back721 */722 _optionEx(config, flags, description, fn, defaultValue) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 723why, one step back723 if (typeof flags === 'object' && flags instanceof Option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 724–726why, one step back724 throw new Error(725 'To add an Option object use addOption() instead of option() or requiredOption()',726 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 727why, one step back727 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 728–747why, one step back728 const option = this.createOption(flags, description);729 option.makeOptionMandatory(!!config.mandatory);730 if (typeof fn === 'function') {731 option.default(defaultValue).argParser(fn);732 } else if (fn instanceof RegExp) {733 // deprecated734 const regex = fn;735 fn = (val, def) => {736 const m = regex.exec(val);737 return m ? m[0] : def;738 };739 option.default(defaultValue).argParser(fn);740 } else {741 option.default(fn);742 }743744 return this.addOption(option);745 }746747 /**Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 748why, one step back748 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 749why, one step back749 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 750–751why, one step back750 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required751 * option-argument is indicated by `<>` and an optional option-argument by `[]`.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 752why, one step back752 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 753why, one step back753 * See the README for more details, and see also addOption() and requiredOption().Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 754–755why, one step back754 *755 * @exampleRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 756–760why, one step back756 * program757 * .option('-p, --pepper', 'add pepper')758 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument759 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default760 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse functionClarify that more than just READMEJohn Geebefore adoption411ca95
lines 761–763why, one step back761 *762 * @param {string} flags763 * @param {string} [description]Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 764why, one step back764 * @param {(Function|*)} [parseArg] - custom option processing function or default valueClarify that more than just READMEJohn Geebefore adoption411ca95
lines 765–768why, one step back765 * @param {*} [defaultValue]766 * @return {Command} `this` command for chaining767 */768Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 769–770why, one step back769 option(flags, description, parseArg, defaultValue) {770 return this._optionEx({}, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 771why, one step back771 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 772–773why, one step back772773 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 774–784why, one step back774 * Add a required option which must have a value after parsing. This usually means775 * the option must be specified on the command line. (Otherwise the same as .option().)776 *777 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.778 *779 * @param {string} flags780 * @param {string} [description]781 * @param {(Function|*)} [parseArg] - custom option processing function or default value782 * @param {*} [defaultValue]783 * @return {Command} `this` command for chaining784 */Clarify that more than just READMEJohn Geebefore adoption411ca95
line 785why, one step back785Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 786why, one step back786 requiredOption(flags, description, parseArg, defaultValue) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 787–793why, one step back787 return this._optionEx(788 { mandatory: true },789 flags,790 description,791 parseArg,792 defaultValue,793 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 794why, one step back794 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 795–803why, one step back795796 /**797 * Alter parsing of short flags with optional values.798 *799 * @example800 * // for `.option('-f,--flag [value]'):801 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour802 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`803 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 804–805why, one step back804 * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.805 * @return {Command} `this` command for chainingClarify that more than just READMEJohn Geebefore adoption411ca95
lines 806–809why, one step back806 */807 combineFlagAndOptionalValue(combine = true) {808 this._combineFlagAndOptionalValue = !!combine;809 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 810why, one step back810 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 811–814why, one step back811812 /**813 * Allow unknown options on the command line.814 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 815–816why, one step back815 * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.816 * @return {Command} `this` command for chainingClarify that more than just READMEJohn Geebefore adoption411ca95
lines 817–820why, one step back817 */818 allowUnknownOption(allowUnknown = true) {819 this._allowUnknownOption = !!allowUnknown;820 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 821why, one step back821 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 822–825why, one step back822823 /**824 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.825 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 826–827why, one step back826 * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.827 * @return {Command} `this` command for chainingClarify that more than just READMEJohn Geebefore adoption411ca95
lines 828–831why, one step back828 */829 allowExcessArguments(allowExcess = true) {830 this._allowExcessArguments = !!allowExcess;831 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 832why, one step back832 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 833–838why, one step back833834 /**835 * Enable positional options. Positional means global options are specified before subcommands which lets836 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.837 * The default behaviour is non-positional and global options may appear anywhere on the command line.838 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 839–840why, one step back839 * @param {boolean} [positional]840 * @return {Command} `this` command for chainingClarify that more than just READMEJohn Geebefore adoption411ca95
lines 841–844why, one step back841 */842 enablePositionalOptions(positional = true) {843 this._enablePositionalOptions = !!positional;844 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 845why, one step back845 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 846–852why, one step back846847 /**848 * Pass through options that come after command-arguments rather than treat them as command-options,849 * so actual command-options come before command-arguments. Turning this on for a subcommand requires850 * positional options to have been enabled on the program (parent commands).851 * The default behaviour is non-positional and options may appear before or after command-arguments.852 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 853–854why, one step back853 * @param {boolean} [passThrough] for unknown options.854 * @return {Command} `this` command for chainingClarify that more than just READMEJohn Geebefore adoption411ca95
lines 855–857why, one step back855 */856 passThroughOptions(passThrough = true) {857 this._passThroughOptions = !!passThrough;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 858why, one step back858 this._checkForBrokenPassThrough();Clarify that more than just READMEJohn Geebefore adoption411ca95
line 859why, one step back859 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 860why, one step back860 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 861–862why, one step back861862 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 863–866why, one step back863 * @private864 */865866 _checkForBrokenPassThrough() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 867–874why, one step back867 if (868 this.parent &&869 this._passThroughOptions &&870 !this.parent._enablePositionalOptions871 ) {872 throw new Error(873 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,874 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 875–878why, one step back875 }876 }877878 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 879–884why, one step back879 * Whether to store option values as properties on command object,880 * or store separately (specify false). In both cases the option values can be accessed using .opts().881 *882 * @param {boolean} [storeAsProperties=true]883 * @return {Command} `this` command for chaining884 */Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 885–889why, one step back885886 storeOptionsAsProperties(storeAsProperties = true) {887 if (this.options.length) {888 throw new Error('call .storeOptionsAsProperties() before adding options');889 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 890why, one step back890 if (Object.keys(this._optionValues).length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 891–893why, one step back891 throw new Error(892 'call .storeOptionsAsProperties() before setting option values',893 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 894why, one step back894 }Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
line 895why, one step back895 this._storeOptionsAsProperties = !!storeAsProperties;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 896why, one step back896 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 897why, one step back897 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 898–902why, one step back898899 /**900 * Retrieve option value.901 *902 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 903why, one step back903 * @return {object} valueClarify that more than just READMEJohn Geebefore adoption411ca95
lines 904–910why, one step back904 */905906 getOptionValue(key) {907 if (this._storeOptionsAsProperties) {908 return this[key];909 }910 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 911why, one step back911 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 912–916why, one step back912913 /**914 * Store option value.915 *916 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 917why, one step back917 * @param {object} valueClarify that more than just READMEJohn Geebefore adoption411ca95
lines 918–921why, one step back918 * @return {Command} `this` command for chaining919 */920921 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 922why, one step back922 return this.setOptionValueWithSource(key, value, undefined);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 923why, one step back923 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 924–925why, one step back924925 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 926–928why, one step back926 * Store option value and where the value came from.927 *928 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 929why, one step back929 * @param {object} valueReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 930–932why, one step back930 * @param {string} source - expected values are default/config/env/cli/implied931 * @return {Command} `this` command for chaining932 */Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 933–934why, one step back933934 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 935–939why, one step back935 if (this._storeOptionsAsProperties) {936 this[key] = value;937 } else {938 this._optionValues[key] = value;939 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 940why, one step back940 this._optionValueSources[key] = source;Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 941why, one step back941 return this;Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 942–944why, one step back942 }943944 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 945–950why, one step back945 * Get source of option value.946 * Expected values are default | config | env | cli | implied947 *948 * @param {string} key949 * @return {string}950 */Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 951–953why, one step back951952 getOptionValueSource(key) {953 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 954why, one step back954 }Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 955–956why, one step back955956 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 957–962why, one step back957 * Get source of option value. See also .optsWithGlobals().958 * Expected values are default | config | env | cli | implied959 *960 * @param {string} key961 * @return {string}962 */Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 963–966why, one step back963964 getOptionValueSourceWithGlobals(key) {965 // global overwrites local, like optsWithGlobals966 let source;Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 967why, one step back967 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 968–975why, one step back968 if (cmd.getOptionValueSource(key) !== undefined) {969 source = cmd.getOptionValueSource(key);970 }971 });972 return source;973 }974975 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 976–977why, one step back976 * Get user arguments from implied or explicit arguments.977 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 978why, one step back978 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 979why, one step back979 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 980–987why, one step back980 */981982 _prepareUserArgs(argv, parseOptions) {983 if (argv !== undefined && !Array.isArray(argv)) {984 throw new Error('first parameter to parse must be array or undefined');985 }986 parseOptions = parseOptions || {};987Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 988–990why, one step back988 // auto-detect argument conventions if nothing supplied989 if (argv === undefined && parseOptions.from === undefined) {990 if (process.versions?.electron) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 991–992why, one step back991 parseOptions.from = 'electron';992 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 993–1002why, one step back993 // check node specific options for scenarios where user CLI args follow executable without scriptname994 const execArgv = process.execArgv ?? [];995 if (996 execArgv.includes('-e') ||997 execArgv.includes('--eval') ||998 execArgv.includes('-p') ||999 execArgv.includes('--print')1000 ) {1001 parseOptions.from = 'eval'; // internal usage, not documented1002 }Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1003why, one step back1003 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1004–1008why, one step back10041005 // default to using process.argv1006 if (argv === undefined) {1007 argv = process.argv;1008 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1009–1010why, one step back1009 this.rawArgs = argv.slice();1010Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1011why, one step back1011 // extract the user args and scriptPathClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1012–1019why, one step back1012 let userArgs;1013 switch (parseOptions.from) {1014 case undefined:1015 case 'node':1016 this._scriptPath = argv[1];1017 userArgs = argv.slice(2);1018 break;1019 case 'electron':ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1020why, one step back1020 // @ts-ignore: because defaultApp is an unknown propertyClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1021–1030why, one step back1021 if (process.defaultApp) {1022 this._scriptPath = argv[1];1023 userArgs = argv.slice(2);1024 } else {1025 userArgs = argv.slice(1);1026 }1027 break;1028 case 'user':1029 userArgs = argv.slice(0);1030 break;Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1031–1033why, one step back1031 case 'eval':1032 userArgs = argv.slice(1);1033 break;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1034why, one step back1034 default:Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1035–1037why, one step back1035 throw new Error(1036 `unexpected parse option { from: '${parseOptions.from}' }`,1037 );Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1038–1039why, one step back1038 }1039Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1040why, one step back1040 // Find default name for program from arguments.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1041–1042why, one step back1041 if (!this._name && this._scriptPath)1042 this.nameFromFilename(this._scriptPath);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1043why, one step back1043 this._name = this._name || 'program';Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1044–1050why, one step back10441045 return userArgs;1046 }10471048 /**1049 * Parse `argv`, setting options and invoking commands when defined.1050 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1051why, one step back1051 * Use parseAsync instead of parse if any of your action handlers are async.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1052why, one step back1052 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1053–1059why, one step back1053 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1054 *1055 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1056 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1057 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1058 * - `'user'`: just user arguments1059 *Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1060why, one step back1060 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1061–1062why, one step back1061 * program.parse(); // parse process.argv and auto-detect electron and special node flags1062 * program.parse(process.argv); // assume argv[0] is app and argv[1] is scriptClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1063–1064why, one step back1063 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1064 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 1065–1067why, one step back1065 * @param {string[]} [argv] - optional, defaults to process.argv1066 * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1067 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1068–1075why, one step back1068 * @return {Command} `this` command for chaining1069 */10701071 parse(argv, parseOptions) {1072 const userArgs = this._prepareUserArgs(argv, parseOptions);1073 this._parseCommand([], userArgs);10741075 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1076why, one step back1076 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1077–1080why, one step back10771078 /**1079 * Parse `argv`, setting options and invoking commands when defined.1080 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1081why, one step back1081 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1082why, one step back1082 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1083–1086why, one step back1083 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1084 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1085 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1086 * - `'user'`: just user argumentsClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1087–1088why, one step back1087 *1088 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1089–1090why, one step back1089 * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1090 * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is scriptClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1091–1093why, one step back1091 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1092 *1093 * @param {string[]} [argv]Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1094why, one step back1094 * @param {object} [parseOptions]Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1095why, one step back1095 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1096–1103why, one step back1096 * @return {Promise}1097 */10981099 async parseAsync(argv, parseOptions) {1100 const userArgs = this._prepareUserArgs(argv, parseOptions);1101 await this._parseCommand([], userArgs);11021103 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1104why, one step back1104 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1105–1108why, one step back11051106 /**1107 * Execute a sub-command executable.1108 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1109why, one step back1109 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1110–1116why, one step back1110 */11111112 _executeSubCommand(subcommand, args) {1113 args = args.slice();1114 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.1115 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];1116Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1117–1120why, one step back1117 function findFile(baseDir, baseName) {1118 // Look for specified file1119 const localBin = path.resolve(baseDir, baseName);1120 if (fs.existsSync(localBin)) return localBin;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1121why, one step back1121Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1122–1123why, one step back1122 // Stop looking if candidate already has an expected extension.1123 if (sourceExt.includes(path.extname(baseName))) return undefined;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1124why, one step back1124Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1125why, one step back1125 // Try all the extensions.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1126–1128why, one step back1126 const foundExt = sourceExt.find((ext) =>1127 fs.existsSync(`${localBin}${ext}`),1128 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1129–1131why, one step back1129 if (foundExt) return `${localBin}${foundExt}`;11301131 return undefined;Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1132–1133why, one step back1132 }1133Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1134–1135why, one step back1134 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1135 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1136why, one step back1136 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1137–1138why, one step back11371138 // executableFile and executableDir might be full path, or just a nameReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1139–1140why, one step back1139 let executableFile =1140 subcommand._executableFile || `${this._name}-${subcommand._name}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1141–1145why, one step back1141 let executableDir = this._executableDir || '';1142 if (this._scriptPath) {1143 let resolvedScriptPath; // resolve possible symlink for installed npm binary1144 try {1145 resolvedScriptPath = fs.realpathSync(this._scriptPath);Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585
line 1146why, one step back1146 } catch {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1147–1148why, one step back1147 resolvedScriptPath = this._scriptPath;1148 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1149–1152why, one step back1149 executableDir = path.resolve(1150 path.dirname(resolvedScriptPath),1151 executableDir,1152 );Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1153–1154why, one step back1153 }1154Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1155–1160why, one step back1155 // Look for a local file in preference to a command in PATH.1156 if (executableDir) {1157 let localFile = findFile(executableDir, executableFile);11581159 // Legacy search using prefix of script name instead of command name1160 if (!localFile && !subcommand._executableFile && this._scriptPath) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1161–1164why, one step back1161 const legacyName = path.basename(1162 this._scriptPath,1163 path.extname(this._scriptPath),1164 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1165why, one step back1165 if (legacyName !== this._name) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1166–1169why, one step back1166 localFile = findFile(1167 executableDir,1168 `${legacyName}-${subcommand._name}`,1169 );Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1170why, one step back1170 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1171–1172why, one step back1171 }1172 executableFile = localFile || executableFile;Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1173–1174why, one step back1173 }1174Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1175–1176why, one step back1175 launchWithNode = sourceExt.includes(path.extname(executableFile));1176Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1177–1179why, one step back1177 let proc;1178 if (process.platform !== 'win32') {1179 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1180why, one step back1180 args.unshift(executableFile);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1181–1185why, one step back1181 // add executable arguments to spawn1182 args = incrementNodeInspectorPort(process.execArgv).concat(args);11831184 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1185 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1186why, one step back1186 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1187–1188why, one step back1187 }1188 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1189why, one step back1189 args.unshift(executableFile);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1190–1194why, one step back1190 // add executable arguments to spawn1191 args = incrementNodeInspectorPort(process.execArgv).concat(args);1192 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1193 }1194Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1195–1196why, one step back1195 if (!proc.killed) {1196 // testing mainly to avoid leak warnings during unit tests with mocked spawnMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1197–1200why, one step back1197 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1198 signals.forEach((signal) => {1199 process.on(signal, () => {1200 if (proc.killed === false && proc.exitCode === null) {Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1201why, one step back1201 // @ts-ignore because signals not typed to known stringsMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1202–1204why, one step back1202 proc.kill(signal);1203 }1204 });Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1205why, one step back1205 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1206why, one step back1206 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1207–1209why, one step back12071208 // By default terminate process when spawned process terminates.1209 const exitCallback = this._exitCallback;ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1210why, one step back1210 proc.on('close', (code) => {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1211–1214why, one step back1211 code = code ?? 1; // code is null if spawned process terminated due to a signal1212 if (!exitCallback) {1213 process.exit(code);1214 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1215–1221why, one step back1215 exitCallback(1216 new CommanderError(1217 code,1218 'commander.executeSubCommandAsync',1219 '(close)',1220 ),1221 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1222–1223why, one step back1222 }1223 });Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1224why, one step back1224 proc.on('error', (err) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1225why, one step back1225 // @ts-ignore: because err.code is an unknown propertyClarify that more than just READMEJohn Geebefore adoption411ca95
line 1226why, one step back1226 if (err.code === 'ENOENT') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1227–1230why, one step back1227 const executableDirMessage = executableDir1228 ? `searched for local subcommand relative to directory '${executableDir}'`1229 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1230 const executableMissing = `'${executableFile}' does not existClarify that more than just READMEJohn Geebefore adoption411ca95
line 1231why, one step back1231 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' insteadMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1232–1233why, one step back1232 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1233 - ${executableDirMessage}`;Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1234why, one step back1234 throw new Error(executableMissing);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1235why, one step back1235 // @ts-ignore: because err.code is an unknown propertyClarify that more than just READMEJohn Geebefore adoption411ca95
line 1236why, one step back1236 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1237why, one step back1237 throw new Error(`'${executableFile}' not executable`);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1238–1241why, one step back1238 }1239 if (!exitCallback) {1240 process.exit(1);1241 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1242–1246why, one step back1242 const wrappedError = new CommanderError(1243 1,1244 'commander.executeSubCommandAsync',1245 '(error)',1246 );Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1247–1253why, one step back1247 wrappedError.nestedError = err;1248 exitCallback(wrappedError);1249 }1250 });12511252 // Store the reference to the child process1253 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1254why, one step back1254 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1255–1256why, one step back12551256 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1257why, one step back1257 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1258–1263why, one step back1258 */12591260 _dispatchSubcommand(commandName, operands, unknown) {1261 const subCommand = this._findCommand(commandName);1262 if (!subCommand) this.help({ error: true });1263Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1264why, one step back1264 let promiseChain;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1265–1269why, one step back1265 promiseChain = this._chainOrCallSubCommandHook(1266 promiseChain,1267 subCommand,1268 'preSubcommand',1269 );Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1270why, one step back1270 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1271–1276why, one step back1271 if (subCommand._executableHandler) {1272 this._executeSubCommand(subCommand, operands.concat(unknown));1273 } else {1274 return subCommand._parseCommand(operands, unknown);1275 }1276 });Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1277why, one step back1277 return promiseChain;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1278why, one step back1278 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1279–1280why, one step back12791280 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1281–1283why, one step back1281 * Invoke help directly if possible, or dispatch if necessary.1282 * e.g. help foo1283 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1284why, one step back1284 * @privateHave help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1285–1296why, one step back1285 */12861287 _dispatchHelpCommand(subcommandName) {1288 if (!subcommandName) {1289 this.help();1290 }1291 const subCommand = this._findCommand(subcommandName);1292 if (subCommand && !subCommand._executableHandler) {1293 subCommand.help();1294 }12951296 // Fallback to parsing the help flag to invoke the help.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1297–1301why, one step back1297 return this._dispatchSubcommand(1298 subcommandName,1299 [],1300 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1301 );Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1302–1304why, one step back1302 }13031304 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1305why, one step back1305 * Check this.args against expected this.registeredArguments.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1306why, one step back1306 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1307why, one step back1307 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1308–1311why, one step back1308 */13091310 _checkNumberOfArguments() {1311 // too fewAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1312why, one step back1312 this.registeredArguments.forEach((arg, i) => {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1313–1317why, one step back1313 if (arg.required && this.args[i] == null) {1314 this.missingArgument(arg.name());1315 }1316 });1317 // too manyReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1318–1321why, one step back1318 if (1319 this.registeredArguments.length > 0 &&1320 this.registeredArguments[this.registeredArguments.length - 1].variadic1321 ) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1322–1323why, one step back1322 return;1323 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1324why, one step back1324 if (this.args.length > this.registeredArguments.length) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1325–1326why, one step back1325 this._excessArguments(this.args);1326 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1327why, one step back1327 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1328–1329why, one step back13281329 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1330why, one step back1330 * Process this.args using this.registeredArguments and save as this.processedArgs!Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1331why, one step back1331 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1332why, one step back1332 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1333–1339why, one step back1333 */13341335 _processArguments() {1336 const myParseArg = (argument, value, previous) => {1337 // Extra processing for nice error message on parsing failure.1338 let parsedValue = value;1339 if (value !== null && argument.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 1340why, one step back1340 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1341–1346why, one step back1341 parsedValue = this._callParseArg(1342 argument,1343 value,1344 previous,1345 invalidValueMessage,1346 );Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1347–1353why, one step back1347 }1348 return parsedValue;1349 };13501351 this._checkNumberOfArguments();13521353 const processedArgs = [];Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1354why, one step back1354 this.registeredArguments.forEach((declaredArg, index) => {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1355–1381why, one step back1355 let value = declaredArg.defaultValue;1356 if (declaredArg.variadic) {1357 // Collect together remaining arguments for passing together as an array.1358 if (index < this.args.length) {1359 value = this.args.slice(index);1360 if (declaredArg.parseArg) {1361 value = value.reduce((processed, v) => {1362 return myParseArg(declaredArg, v, processed);1363 }, declaredArg.defaultValue);1364 }1365 } else if (value === undefined) {1366 value = [];1367 }1368 } else if (index < this.args.length) {1369 value = this.args[index];1370 if (declaredArg.parseArg) {1371 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1372 }1373 }1374 processedArgs[index] = value;1375 });1376 this.processedArgs = processedArgs;1377 }13781379 /**1380 * Once we have a promise we chain, but call synchronously until then.1381 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1382why, one step back1382 * @param {(Promise|undefined)} promiseClarify that more than just READMEJohn Geebefore adoption411ca95
line 1383why, one step back1383 * @param {Function} fnMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1384–1385why, one step back1384 * @return {(Promise|undefined)}1385 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1386–1399why, one step back1386 */13871388 _chainOrCall(promise, fn) {1389 // thenable1390 if (promise && promise.then && typeof promise.then === 'function') {1391 // already have a promise, chain callback1392 return promise.then(() => fn());1393 }1394 // callback might return a promise1395 return fn();1396 }13971398 /**1399 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1400why, one step back1400 * @param {(Promise|undefined)} promiseClarify that more than just READMEJohn Geebefore adoption411ca95
line 1401why, one step back1401 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1402–1403why, one step back1402 * @return {(Promise|undefined)}1403 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1404–1408why, one step back1404 */14051406 _chainOrCallHooks(promise, event) {1407 let result = promise;1408 const hooks = [];Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1409why, one step back1409 this._getCommandAndAncestors()Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1410why, one step back1410 .reverse()Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1411–1412why, one step back1411 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1412 .forEach((hookedCommand) => {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1413–1425why, one step back1413 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1414 hooks.push({ hookedCommand, callback });1415 });1416 });1417 if (event === 'postAction') {1418 hooks.reverse();1419 }14201421 hooks.forEach((hookDetail) => {1422 result = this._chainOrCall(result, () => {1423 return hookDetail.callback(hookDetail.hookedCommand, this);1424 });1425 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1426–1430why, one step back1426 return result;1427 }14281429 /**1430 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1431why, one step back1431 * @param {(Promise|undefined)} promisefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1432–1433why, one step back1432 * @param {Command} subCommand1433 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1434–1435why, one step back1434 * @return {(Promise|undefined)}1435 * @privatefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1436–1446why, one step back1436 */14371438 _chainOrCallSubCommandHook(promise, subCommand, event) {1439 let result = promise;1440 if (this._lifeCycleHooks[event] !== undefined) {1441 this._lifeCycleHooks[event].forEach((hook) => {1442 result = this._chainOrCall(result, () => {1443 return hook(this, subCommand);1444 });1445 });1446 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1447–1453why, one step back1447 return result;1448 }14491450 /**1451 * Process arguments in context of this command.1452 * Returns action result, in case it is a promise.1453 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1454why, one step back1454 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1455–1458why, one step back1455 */14561457 _parseCommand(operands, unknown) {1458 const parsed = this.parseOptions(unknown);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 1459why, one step back1459 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1460why, one step back1460 this._parseOptionsImplied();Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1461–1467why, one step back1461 operands = operands.concat(parsed.operands);1462 unknown = parsed.unknown;1463 this.args = operands.concat(unknown);14641465 if (operands && this._findCommand(operands[0])) {1466 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1467 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1468–1471why, one step back1468 if (1469 this._getHelpCommand() &&1470 operands[0] === this._getHelpCommand().name()1471 ) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1472why, one step back1472 return this._dispatchHelpCommand(operands[1]);Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1473–1474why, one step back1473 }1474 if (this._defaultCommandName) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1475why, one step back1475 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default commandReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1476–1480why, one step back1476 return this._dispatchSubcommand(1477 this._defaultCommandName,1478 operands,1479 unknown,1480 );Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1481why, one step back1481 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1482–1487why, one step back1482 if (1483 this.commands.length &&1484 this.args.length === 0 &&1485 !this._actionHandler &&1486 !this._defaultCommandName1487 ) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1488–1491why, one step back1488 // probably missing subcommand and no handler, user needs help (and exit)1489 this.help({ error: true });1490 }1491Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1492why, one step back1492 this._outputHelpIfRequested(parsed.unknown);Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1493why, one step back1493 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1494why, one step back1494 this._checkForConflictingOptions();Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1495–1507why, one step back14951496 // We do not always call this check to avoid masking a "better" error, like unknown command.1497 const checkForUnknownOptions = () => {1498 if (parsed.unknown.length > 0) {1499 this.unknownOption(parsed.unknown[0]);1500 }1501 };15021503 const commandEvent = `command:${this.name()}`;1504 if (this._actionHandler) {1505 checkForUnknownOptions();1506 this._processArguments();1507Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1508–1509why, one step back1508 let promiseChain;1509 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1510–1512why, one step back1510 promiseChain = this._chainOrCall(promiseChain, () =>1511 this._actionHandler(this.processedArgs),1512 );Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
line 1513why, one step back1513 if (this.parent) {Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1514why, one step back1514 promiseChain = this._chainOrCall(promiseChain, () => {Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1515–1517why, one step back1515 this.parent.emit(commandEvent, operands, unknown); // legacy1516 });1517 }Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1518–1519why, one step back1518 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1519 return promiseChain;Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1520–1525why, one step back1520 }1521 if (this.parent && this.parent.listenerCount(commandEvent)) {1522 checkForUnknownOptions();1523 this._processArguments();1524 this.parent.emit(commandEvent, operands, unknown); // legacy1525 } else if (operands.length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1526–1527why, one step back1526 if (this._findCommand('*')) {1527 // legacy default commandClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1528–1539why, one step back1528 return this._dispatchSubcommand('*', operands, unknown);1529 }1530 if (this.listenerCount('command:*')) {1531 // skip option check, emit event for possible misspelling suggestion1532 this.emit('command:*', operands, unknown);1533 } else if (this.commands.length) {1534 this.unknownCommand();1535 } else {1536 checkForUnknownOptions();1537 this._processArguments();1538 }1539 } else if (this.commands.length) {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 1540why, one step back1540 checkForUnknownOptions();Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1541–1547why, one step back1541 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1542 this.help({ error: true });1543 } else {1544 checkForUnknownOptions();1545 this._processArguments();1546 // fall through for caller to handle after calling .parse()1547 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1548why, one step back1548 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1549–1552why, one step back15491550 /**1551 * Find matching command.1552 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1553why, one step back1553 * @privateFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1554why, one step back1554 * @return {Command | undefined}Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1555–1557why, one step back1555 */1556 _findCommand(name) {1557 if (!name) return undefined;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1558–1560why, one step back1558 return this.commands.find(1559 (cmd) => cmd._name === name || cmd._aliases.includes(name),1560 );Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1561why, one step back1561 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1562–1567why, one step back15621563 /**1564 * Return an option matching `arg` if any.1565 *1566 * @param {string} arg1567 * @return {Option}Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1568why, one step back1568 * @packageClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1569–1571why, one step back1569 */15701571 _findOption(arg) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1572why, one step back1572 return this.options.find((option) => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1573why, one step back1573 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1574–1576why, one step back15741575 /**1576 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1577why, one step back1577 * Called after checking for help flags in leaf subcommand.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1578why, one step back1578 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1579why, one step back1579 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1580–1583why, one step back1580 */15811582 _checkForMissingMandatoryOptions() {1583 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1584why, one step back1584 this._getCommandAndAncestors().forEach((cmd) => {Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1585why, one step back1585 cmd.options.forEach((anOption) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1586–1589why, one step back1586 if (1587 anOption.mandatory &&1588 cmd.getOptionValue(anOption.attributeName()) === undefined1589 ) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1590–1592why, one step back1590 cmd.missingMandatoryOptionValue(anOption);1591 }1592 });Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1593why, one step back1593 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1594why, one step back1594 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1595–1596why, one step back15951596 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1597why, one step back1597 * 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 1598why, one step back1598 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1599why, one step back1599 * @privatefeat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1600why, one step back1600 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1601why, one step back1601 _checkForConflictingLocalOptions() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1602–1605why, one step back1602 const definedNonDefaultOptions = this.options.filter((option) => {1603 const optionKey = option.attributeName();1604 if (this.getOptionValue(optionKey) === undefined) {1605 return false;feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1606why, one step back1606 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1607–1608why, one step back1607 return this.getOptionValueSource(optionKey) !== 'default';1608 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1609–1610why, one step back16091610 const optionsWithConflicting = definedNonDefaultOptions.filter(Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1611why, one step back1611 (option) => option.conflictsWith.length > 0,feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1612–1615why, one step back1612 );16131614 optionsWithConflicting.forEach((option) => {1615 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1616why, one step back1616 option.conflictsWith.includes(defined.attributeName()),feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1617–1621why, one step back1617 );1618 if (conflictingAndDefined) {1619 this._conflictingOption(option, conflictingAndDefined);1620 }1621 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1622–1627why, one step back1622 }16231624 /**1625 * Display an error message if conflicting options are used together.1626 * Called after checking for help flags in leaf subcommand.1627 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1628why, one step back1628 * @privateCheck for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1629–1631why, one step back1629 */1630 _checkForConflictingOptions() {1631 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1632why, one step back1632 this._getCommandAndAncestors().forEach((cmd) => {Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1633why, one step back1633 cmd._checkForConflictingLocalOptions();Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1634why, one step back1634 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1635–1637why, one step back1635 }16361637 /**Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1638–1648why, one step back1638 * Parse options from `argv` removing known options,1639 * and return argv split into operands and unknown arguments.1640 *1641 * Examples:1642 *1643 * argv => operands, unknown1644 * --known kkk op => [op], []1645 * op --known kkk => [op], []1646 * sub --unknown uuu op => [sub], [--unknown uuu op]1647 * sub -- --unknown uuu op => [sub --unknown uuu op], []1648 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1649–1650why, one step back1649 * @param {string[]} argv1650 * @return {{operands: string[], unknown: string[]}}Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1651–1695why, one step back1651 */16521653 parseOptions(argv) {1654 const operands = []; // operands, not options or values1655 const unknown = []; // first unknown option and remaining unknown args1656 let dest = operands;1657 const args = argv.slice();16581659 function maybeOption(arg) {1660 return arg.length > 1 && arg[0] === '-';1661 }16621663 // parse options1664 let activeVariadicOption = null;1665 while (args.length) {1666 const arg = args.shift();16671668 // literal1669 if (arg === '--') {1670 if (dest === unknown) dest.push(arg);1671 dest.push(...args);1672 break;1673 }16741675 if (activeVariadicOption && !maybeOption(arg)) {1676 this.emit(`option:${activeVariadicOption.name()}`, arg);1677 continue;1678 }1679 activeVariadicOption = null;16801681 if (maybeOption(arg)) {1682 const option = this._findOption(arg);1683 // recognised option, call listener to assign value with possible custom processing1684 if (option) {1685 if (option.required) {1686 const value = args.shift();1687 if (value === undefined) this.optionMissingArgument(option);1688 this.emit(`option:${option.name()}`, value);1689 } else if (option.optional) {1690 let value = null;1691 // historical behaviour is optional value is following arg unless an option1692 if (args.length > 0 && !maybeOption(args[0])) {1693 value = args.shift();1694 }1695 this.emit(`option:${option.name()}`, value);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1696–1697why, one step back1696 } else {1697 // boolean flagClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1698–1708why, one step back1698 this.emit(`option:${option.name()}`);1699 }1700 activeVariadicOption = option.variadic ? option : null;1701 continue;1702 }1703 }17041705 // Look for combo options following single dash, eat first one if known.1706 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1707 const option = this._findOption(`-${arg[1]}`);1708 if (option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1709–1712why, one step back1709 if (1710 option.required ||1711 (option.optional && this._combineFlagAndOptionalValue)1712 ) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1713–1742why, one step back1713 // option with value following in same argument1714 this.emit(`option:${option.name()}`, arg.slice(2));1715 } else {1716 // boolean option, emit and put back remainder of arg for further processing1717 this.emit(`option:${option.name()}`);1718 args.unshift(`-${arg.slice(2)}`);1719 }1720 continue;1721 }1722 }17231724 // Look for known long flag with value, like --foo=bar1725 if (/^--[^=]+=/.test(arg)) {1726 const index = arg.indexOf('=');1727 const option = this._findOption(arg.slice(0, index));1728 if (option && (option.required || option.optional)) {1729 this.emit(`option:${option.name()}`, arg.slice(index + 1));1730 continue;1731 }1732 }17331734 // Not a recognised option by this command.1735 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.17361737 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1738 if (maybeOption(arg)) {1739 dest = unknown;1740 }17411742 // If using positionalOptions, stop processing our options at subcommand.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1743–1747why, one step back1743 if (1744 (this._enablePositionalOptions || this._passThroughOptions) &&1745 operands.length === 0 &&1746 unknown.length === 01747 ) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1748–1751why, one step back1748 if (this._findCommand(arg)) {1749 operands.push(arg);1750 if (args.length > 0) unknown.push(...args);1751 break;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1752–1755why, one step back1752 } else if (1753 this._getHelpCommand() &&1754 arg === this._getHelpCommand().name()1755 ) {Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1756–1777why, one step back1756 operands.push(arg);1757 if (args.length > 0) operands.push(...args);1758 break;1759 } else if (this._defaultCommandName) {1760 unknown.push(arg);1761 if (args.length > 0) unknown.push(...args);1762 break;1763 }1764 }17651766 // If using passThroughOptions, stop processing options at first command-argument.1767 if (this._passThroughOptions) {1768 dest.push(arg);1769 if (args.length > 0) dest.push(...args);1770 break;1771 }17721773 // add arg1774 dest.push(arg);1775 }17761777 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1778why, one step back1778 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1779–1780why, one step back17791780 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1781why, one step back1781 * Return an object containing local option values as key-value pairs.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1782why, one step back1782 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1783why, one step back1783 * @return {object}Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1784–1792why, one step back1784 */1785 opts() {1786 if (this._storeOptionsAsProperties) {1787 // Preserve original behaviour so backwards compatible when still using properties1788 const result = {};1789 const len = this.options.length;17901791 for (let i = 0; i < len; i++) {1792 const key = this.options[i].attributeName();Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1793–1794why, one step back1793 result[key] =1794 key === this._versionOptionName ? this._version : this[key];Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1795–1799why, one step back1795 }1796 return result;1797 }17981799 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1800why, one step back1800 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1801–1802why, one step back18011802 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1803why, one step back1803 * Return an object containing merged local and global option values as key-value pairs.Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1804why, one step back1804 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1805why, one step back1805 * @return {object}Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1806why, one step back1806 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1807–1808why, one step back1807 optsWithGlobals() {1808 // globals overwrite localsIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1809why, one step back1809 return this._getCommandAndAncestors().reduce(Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1810why, one step back1810 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1811why, one step back1811 {},Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1812–1818why, one step back1812 );1813 }18141815 /**1816 * Display error message and exit (or call exitOverride).1817 *1818 * @param {string} messageFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1819why, one step back1819 * @param {object} [errorOptions]Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1820–1824why, one step back1820 * @param {string} [errorOptions.code] - an id string representing the error1821 * @param {number} [errorOptions.exitCode] - used with process.exit1822 */1823 error(message, errorOptions) {1824 // output handlingReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1825–1828why, one step back1825 this._outputConfiguration.outputError(1826 `${message}\n`,1827 this._outputConfiguration.writeErr,1828 );Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1829–1834why, one step back1829 if (typeof this._showHelpAfterError === 'string') {1830 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1831 } else if (this._showHelpAfterError) {1832 this._outputConfiguration.writeErr('\n');1833 this.outputHelp({ error: true });1834 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1835–1839why, one step back18351836 // exit handling1837 const config = errorOptions || {};1838 const exitCode = config.exitCode || 1;1839 const code = config.code || 'commander.error';Clarify that more than just READMEJohn Geebefore adoption411ca95
line 1840why, one step back1840 this._exit(exitCode, code, message);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1841–1846why, one step back1841 }18421843 /**1844 * Apply any option related environment variables, if option does1845 * not have a value from cli or client code.1846 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1847why, one step back1847 * @privateAdd .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1848–1852why, one step back1848 */1849 _parseOptionsEnv() {1850 this.options.forEach((option) => {1851 if (option.envVar && option.envVar in process.env) {1852 const optionKey = option.attributeName();Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 1853why, one step back1853 // Priority check. Do not overwrite cli or options from unknown source (client-code).Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1854–1861why, one step back1854 if (1855 this.getOptionValue(optionKey) === undefined ||1856 ['default', 'config', 'env'].includes(1857 this.getOptionValueSource(optionKey),1858 )1859 ) {1860 if (option.required || option.optional) {1861 // option can take a valueAdd .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1862–1863why, one step back1862 // keep very simple, optional always takes value1863 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1864–1865why, one step back1864 } else {1865 // booleanAdd .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1866–1871why, one step back1866 // keep very simple, only care that envVar defined and not the value1867 this.emit(`optionEnv:${option.name()}`);1868 }1869 }1870 }1871 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1872–1876why, one step back1872 }18731874 /**1875 * Apply any implied option values, if option is undefined or default value.1876 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1877why, one step back1877 * @privateAdd Option.implies() (#1724)John Geebefore adoptiond660967
lines 1878–1881why, one step back1878 */1879 _parseOptionsImplied() {1880 const dualHelper = new DualOptions(this.options);1881 const hasCustomOptionValue = (optionKey) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1882–1885why, one step back1882 return (1883 this.getOptionValue(optionKey) !== undefined &&1884 !['default', 'implied'].includes(this.getOptionValueSource(optionKey))1885 );Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1886–1887why, one step back1886 };1887 this.optionsReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1888–1896why, one step back1888 .filter(1889 (option) =>1890 option.implied !== undefined &&1891 hasCustomOptionValue(option.attributeName()) &&1892 dualHelper.valueFromOption(1893 this.getOptionValue(option.attributeName()),1894 option,1895 ),1896 )Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1897–1898why, one step back1897 .forEach((option) => {1898 Object.keys(option.implied)Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1899–1905why, one step back1899 .filter((impliedKey) => !hasCustomOptionValue(impliedKey))1900 .forEach((impliedKey) => {1901 this.setOptionValueWithSource(1902 impliedKey,1903 option.implied[impliedKey],1904 'implied',1905 );Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1906–1907why, one step back1906 });1907 });Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1908–1913why, one step back1908 }19091910 /**1911 * Argument `name` is missing.1912 *1913 * @param {string} nameMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1914why, one step back1914 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1915–1918why, one step back1915 */19161917 missingArgument(name) {1918 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1919–1920why, one step back1919 this.error(message, { code: 'commander.missingArgument' });1920 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1921–1925why, one step back19211922 /**1923 * `Option` is missing an argument.1924 *1925 * @param {Option} optionMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1926why, one step back1926 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1927–1930why, one step back1927 */19281929 optionMissingArgument(option) {1930 const message = `error: option '${option.flags}' argument missing`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1931–1932why, one step back1931 this.error(message, { code: 'commander.optionMissingArgument' });1932 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1933–1937why, one step back19331934 /**1935 * `Option` does not have a value, and is a mandatory option.1936 *1937 * @param {Option} optionMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1938why, one step back1938 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1939–1942why, one step back1939 */19401941 missingMandatoryOptionValue(option) {1942 const message = `error: required option '${option.flags}' not specified`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1943why, one step back1943 this.error(message, { code: 'commander.missingMandatoryOptionValue' });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1944–1950why, one step back1944 }19451946 /**1947 * `Option` conflicts with another option.1948 *1949 * @param {Option} option1950 * @param {Option} conflictingOptionMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1951why, one step back1951 * @privatefeat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1952–1958why, one step back1952 */1953 _conflictingOption(option, conflictingOption) {1954 // The calling code does not know whether a negated option is the source of the1955 // value, so do some work to take an educated guess.1956 const findBestOptionFromValue = (option) => {1957 const optionKey = option.attributeName();1958 const optionValue = this.getOptionValue(optionKey);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1959–1970why, one step back1959 const negativeOption = this.options.find(1960 (target) => target.negate && optionKey === target.attributeName(),1961 );1962 const positiveOption = this.options.find(1963 (target) => !target.negate && optionKey === target.attributeName(),1964 );1965 if (1966 negativeOption &&1967 ((negativeOption.presetArg === undefined && optionValue === false) ||1968 (negativeOption.presetArg !== undefined &&1969 optionValue === negativeOption.presetArg))1970 ) {feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1971–1987why, one step back1971 return negativeOption;1972 }1973 return positiveOption || option;1974 };19751976 const getErrorMessage = (option) => {1977 const bestOption = findBestOptionFromValue(option);1978 const optionKey = bestOption.attributeName();1979 const source = this.getOptionValueSource(optionKey);1980 if (source === 'env') {1981 return `environment variable '${bestOption.envVar}'`;1982 }1983 return `option '${bestOption.flags}'`;1984 };19851986 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1987 this.error(message, { code: 'commander.conflictingOption' });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1988why, one step back1988 }Clarify that more than just READMEJohn Geebefore adoption411ca95
lines 1989–1993why, one step back19891990 /**1991 * Unknown option `flag`.1992 *1993 * @param {string} flagMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1994why, one step back1994 * @privateClarify that more than just READMEJohn Geebefore adoption411ca95
lines 1995–1998why, one step back1995 */19961997 unknownOption(flag) {1998 if (this._allowUnknownOption) return;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1999–2003why, one step back1999 let suggestion = '';2000The first 2,000 of 2,585 lines.