command.js
This file
Path
lib/command.js
2,789 lines · 85.5 KiB · JavaScript
Last changed by
Update dependecies and lint (#2489)John Geebefore adoption0ea3bb3
History of this fileTake it
The walk stopped after 200 commits: lines older than 3e202f3 point at it.
Switching to esm-only (#2464)John Geebefore adoptionf4bd470
lines 1–5why, one step back1import { EventEmitter } from 'node:events';2import childProcess from 'node:child_process';3import path from 'node:path';4import fs from 'node:fs';5import process from 'node:process';Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 6why, one step back6Switching to esm-only (#2464)John Geebefore adoptionf4bd470
lines 7–11why, one step back7import { Argument, humanReadableArgName } from './argument.js';8import { CommanderError } from './error.js';9import { Help, stripColor } from './help.js';10import { Option, DualOptions } from './option.js';11import { suggestSimilar } from './suggestSimilar.js';Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 12why, one step back12Switching to esm-only (#2464)John Geebefore adoptionf4bd470
line 13why, one step back13export class Command extends EventEmitter {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 14–27why, one step back14 /**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;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
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 nameAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
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 etcAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 40–54why, one step back40 this._storeOptionsAsProperties = false;41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executable44 this._executableDir = null; // custom search directory for subcommands45 this._defaultCommandName = null;46 this._exitCallback = null;47 this._aliases = [];48 this._combineFlagAndOptionalValue = true;49 this._description = '';50 this._summary = '';51 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)} */Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 56–57why, one step back56 this._showHelpAfterError = false;57 this._showSuggestionAfterError = true;Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 58why, one step back58 this._savedState = null; // used in save/restoreStateBeforeParseAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 59why, one step back59Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 60why, one step back60 // see configureOutput() for docsAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 61–63why, one step back61 this._outputConfiguration = {62 writeOut: (str) => process.stdout.write(str),63 writeErr: (str) => process.stderr.write(str),Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 64why, one step back64 outputError: (str, write) => write(str),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 65–68why, one step back65 getOutHelpWidth: () =>66 process.stdout.isTTY ? process.stdout.columns : undefined,67 getErrHelpWidth: () =>68 process.stderr.isTTY ? process.stderr.columns : undefined,Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 69–73why, one step back69 getOutHasColors: () =>70 useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),71 getErrHasColors: () =>72 useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),73 stripColor: (str) => stripColor(str),Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 74–76why, one step back74 };7576 this._hidden = false;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 77–81why, one step back77 /** @type {(Option | null | undefined)} */78 this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.79 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited80 /** @type {Command} */81 this._helpCommand = undefined; // lazy initialised, inheritedAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 82why, one step back82 this._helpConfiguration = {};Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 83–88why, one step back83 /** @type {string | undefined} */84 this._helpGroupHeading = undefined; // soft initialised when added to parent85 /** @type {string | undefined} */86 this._defaultCommandGroup = undefined;87 /** @type {string | undefined} */88 this._defaultOptionGroup = undefined;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 89–100why, one step back89 }9091 /**92 * Copy settings that are useful to have in common across root command and subcommands.93 *94 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)95 *96 * @param {Command} sourceCommand97 * @return {Command} `this` command for chaining98 */99 copyInheritedSettings(sourceCommand) {100 this._outputConfiguration = sourceCommand._outputConfiguration;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 101–102why, one step back101 this._helpOption = sourceCommand._helpOption;102 this._helpCommand = sourceCommand._helpCommand;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 103–105why, one step back103 this._helpConfiguration = sourceCommand._helpConfiguration;104 this._exitCallback = sourceCommand._exitCallback;105 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 106–107why, one step back106 this._combineFlagAndOptionalValue =107 sourceCommand._combineFlagAndOptionalValue;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 108–116why, one step back108 this._allowExcessArguments = sourceCommand._allowExcessArguments;109 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;110 this._showHelpAfterError = sourceCommand._showHelpAfterError;111 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;112113 return this;114 }115116 /**Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 117why, one step back117 * @returns {Command[]}Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 118why, one step back118 * @privateIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 119–122why, one step back119 */120121 _getCommandAndAncestors() {122 const result = [];ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 123why, one step back123 // eslint-disable-next-line @typescript-eslint/no-this-aliasIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 124–130why, one step back124 for (let command = this; command; command = command.parent) {125 result.push(command);126 }127 return result;128 }129130 /**Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 131–149why, one step back131 * Define a command.132 *133 * There are two styles of command: pay attention to where to put the description.134 *135 * @example136 * // Command implemented using action handler (description is supplied separately to `.command`)137 * program138 * .command('clone <source> [destination]')139 * .description('clone a repository into a newly created directory')140 * .action((source, destination) => {141 * console.log('clone command called');142 * });143 *144 * // Command implemented using separate executable file (description is second parameter to `.command`)145 * program146 * .command('start <service>', 'start named service')147 * .command('stop [service]', 'stop named service, or all if no name supplied');148 *149 * @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 150–151why, one step back150 * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)151 * @param {object} [execOpts] - configuration options (for executable)Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 152–173why, one step back152 * @return {Command} returns new command for action handler, or `this` for executable command153 */154155 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {156 let desc = actionOptsOrExecDesc;157 let opts = execOpts;158 if (typeof desc === 'object' && desc !== null) {159 opts = desc;160 desc = null;161 }162 opts = opts || {};163 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);164165 const cmd = this.createCommand(name);166 if (desc) {167 cmd.description(desc);168 cmd._executableHandler = true;169 }170 if (opts.isDefault) this._defaultCommandName = cmd._name;171 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden172 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor173 if (args) cmd.arguments(args);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 174why, one step back174 this._registerCommand(cmd);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 175–210why, one step back175 cmd.parent = this;176 cmd.copyInheritedSettings(this);177178 if (desc) return this;179 return cmd;180 }181182 /**183 * Factory routine to create a new unattached command.184 *185 * See .command() for creating an attached subcommand, which uses this routine to186 * create the command. You can override createCommand to customise subcommands.187 *188 * @param {string} [name]189 * @return {Command} new command190 */191192 createCommand(name) {193 return new Command(name);194 }195196 /**197 * You can customise the help with a subclass of Help by overriding createHelp,198 * or by overriding Help properties using configureHelp().199 *200 * @return {Help}201 */202203 createHelp() {204 return Object.assign(new Help(), this.configureHelp());205 }206207 /**208 * You can customise the help by overriding Help properties using configureHelp(),209 * or with a subclass of Help by overriding createHelp().210 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 211–212why, one step back211 * @param {object} [configuration] - configuration options212 * @return {(Command | object)} `this` command for chaining, or stored configurationAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 213–227why, one step back213 */214215 configureHelp(configuration) {216 if (configuration === undefined) return this._helpConfiguration;217218 this._helpConfiguration = configuration;219 return this;220 }221222 /**223 * The default output goes to stdout and stderr. You can customise this for special224 * applications. You can also customise the display of errors by overriding outputError.225 *226 * The configuration properties are all functions:227 *Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
line 228why, one step back228 * // change how output being written, defaults to stdout and stderrAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 229–230why, one step back229 * writeOut(str)230 * writeErr(str)Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 231–233why, one step back231 * // change how output being written for errors, defaults to writeErr232 * outputError(str, write) // used for displaying errors and not used for displaying help233 * // specify width for wrapping helpAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 234–235why, one step back234 * getOutHelpWidth()235 * getErrHelpWidth()Support color ansi code sequences in custom help (#2251)John Geebefore adoption5629947
lines 236–238why, one step back236 * // color support, currently only used with Help237 * getOutHasColors()238 * getErrHasColors()Prepare for 13.0.0-0 (#2292)John Geebefore adoption53fc8a4
line 239why, one step back239 * stripColor() // used to remove ANSI escape codes if output does not have colorsAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 240why, one step back240 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 241–242why, one step back241 * @param {object} [configuration] - configuration options242 * @return {(Command | object)} `this` command for chaining, or stored configurationAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 243–247why, one step back243 */244245 configureOutput(configuration) {246 if (configuration === undefined) return this._outputConfiguration;247Merge from develop (#2482)John Geebefore adoptionb51c0ea
lines 248–251why, one step back248 this._outputConfiguration = {249 ...this._outputConfiguration,250 ...configuration,251 };Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 252–257why, one step back252 return this;253 }254255 /**256 * Display the help or a custom message after an error occurs.257 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 258why, one step back258 * @param {(boolean|string)} [displayHelp]Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 259–283why, one step back259 * @return {Command} `this` command for chaining260 */261 showHelpAfterError(displayHelp = true) {262 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;263 this._showHelpAfterError = displayHelp;264 return this;265 }266267 /**268 * Display suggestion of similar commands for unknown commands, or options for unknown options.269 *270 * @param {boolean} [displaySuggestion]271 * @return {Command} `this` command for chaining272 */273 showSuggestionAfterError(displaySuggestion = true) {274 this._showSuggestionAfterError = !!displaySuggestion;275 return this;276 }277278 /**279 * Add a prepared subcommand.280 *281 * See .command() for creating an attached subcommand which inherits settings from its parent.282 *283 * @param {Command} cmd - new subcommandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 284why, one step back284 * @param {object} [opts] - configuration optionsAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 285–297why, one step back285 * @return {Command} `this` command for chaining286 */287288 addCommand(cmd, opts) {289 if (!cmd._name) {290 throw new Error(`Command passed to .addCommand() must have a name291- specify the name in Command constructor or using .name()`);292 }293294 opts = opts || {};295 if (opts.isDefault) this._defaultCommandName = cmd._name;296 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation297Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 298why, one step back298 this._registerCommand(cmd);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 299why, one step back299 cmd.parent = this;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 300–301why, one step back300 cmd._checkForBrokenPassThrough();301Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 302–331why, one step back302 return this;303 }304305 /**306 * Factory routine to create a new unattached argument.307 *308 * See .argument() for creating an attached argument, which uses this routine to309 * create the argument. You can override createArgument to return a custom argument.310 *311 * @param {string} name312 * @param {string} [description]313 * @return {Argument} new argument314 */315316 createArgument(name, description) {317 return new Argument(name, description);318 }319320 /**321 * Define argument syntax for command.322 *323 * The default is that the argument is required, and you can explicitly324 * indicate this with <> around the name. Put [] around the name for an optional argument.325 *326 * @example327 * program.argument('<input-file>');328 * program.argument('[output-file]');329 *330 * @param {string} name331 * @param {string} [description]Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
line 332why, one step back332 * @param {(Function|*)} [parseArg] - custom argument processing function or default valueAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 333–335why, one step back333 * @param {*} [defaultValue]334 * @return {Command} `this` command for chaining335 */Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
line 336why, one step back336 argument(name, description, parseArg, defaultValue) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 337why, one step back337 const argument = this.createArgument(name, description);Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
lines 338–339why, one step back338 if (typeof parseArg === 'function') {339 argument.default(defaultValue).argParser(parseArg);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 340why, one step back340 } else {Merge branch 'develop' into release/14.xJohn Geebefore adoption00af603
line 341why, one step back341 argument.default(parseArg);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 342–359why, one step back342 }343 this.addArgument(argument);344 return this;345 }346347 /**348 * Define argument syntax for command, adding multiple at once (without descriptions).349 *350 * See also .argument().351 *352 * @example353 * program.arguments('<cmd> [env]');354 *355 * @param {string} names356 * @return {Command} `this` command for chaining357 */358359 arguments(names) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 360–365why, one step back360 names361 .trim()362 .split(/ +/)363 .forEach((detail) => {364 this.argument(detail);365 });Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 366–375why, one step back366 return this;367 }368369 /**370 * Define argument syntax for command, adding a prepared argument.371 *372 * @param {Argument} argument373 * @return {Command} `this` command for chaining374 */375 addArgument(argument) {Add public Arguments property (#2010)John Geebefore adoption7d23437
line 376why, one step back376 const previousArgument = this.registeredArguments.slice(-1)[0];Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 377why, one step back377 if (previousArgument?.variadic) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 378–380why, one step back378 throw new Error(379 `only the last argument can be variadic '${previousArgument.name()}'`,380 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 381why, one step back381 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 382–389why, one step back382 if (383 argument.required &&384 argument.defaultValue !== undefined &&385 argument.parseArg === undefined386 ) {387 throw new Error(388 `a default value for a required argument is never used: '${argument.name()}'`,389 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 390why, one step back390 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 391why, one step back391 this.registeredArguments.push(argument);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 392–395why, one step back392 return this;393 }394395 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 396why, one step back396 * Customise or override default help command. By default a help command is automatically added if your command has subcommands.Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 397why, one step back397 *ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 398why, one step back398 * @exampleMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 399–402why, one step back399 * program.helpCommand('help [cmd]');400 * program.helpCommand('help [cmd]', 'show help');401 * program.helpCommand(false); // suppress default help command402 * program.helpCommand(true); // add help command even if no subcommandsAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 403why, one step back403 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 404–405why, one step back404 * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added405 * @param {string} [description] - custom descriptionAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 406–408why, one step back406 * @return {Command} `this` command for chaining407 */408Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 409–411why, one step back409 helpCommand(enableOrNameAndArgs, description) {410 if (typeof enableOrNameAndArgs === 'boolean') {411 this._addImplicitHelpCommand = enableOrNameAndArgs;Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 412–415why, one step back412 if (enableOrNameAndArgs && this._defaultCommandGroup) {413 // make the command to store the group414 this._initCommandGroup(this._getHelpCommand());415 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 416why, one step back416 return this;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 417why, one step back417 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 418why, one step back418Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 419–420why, one step back419 const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';420 const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 421–429why, one step back421 const helpDescription = description ?? 'display help for command';422423 const helpCommand = this.createCommand(helpName);424 helpCommand.helpOption(false);425 if (helpArgs) helpCommand.arguments(helpArgs);426 if (helpDescription) helpCommand.description(helpDescription);427428 this._addImplicitHelpCommand = true;429 this._helpCommand = helpCommand;Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
lines 430–431why, one step back430 // init group unless lazy create431 if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 432why, one step back432Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 433–436why, one step back433 return this;434 }435436 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 437–441why, one step back437 * Add prepared custom help command.438 *439 * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`440 * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only441 * @return {Command} `this` command for chainingAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 442why, one step back442 */Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 443–449why, one step back443 addHelpCommand(helpCommand, deprecatedDescription) {444 // If not passed an object, call through to helpCommand for backwards compatibility,445 // as addHelpCommand was originally used like helpCommand is now.446 if (typeof helpCommand !== 'object') {447 this.helpCommand(helpCommand, deprecatedDescription);448 return this;449 }Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 450why, one step back450Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 451–452why, one step back451 this._addImplicitHelpCommand = true;452 this._helpCommand = helpCommand;Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
line 453why, one step back453 this._initCommandGroup(helpCommand);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 454–463why, one step back454 return this;455 }456457 /**458 * Lazy create help command.459 *460 * @return {(Command|null)}461 * @package462 */463 _getHelpCommand() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 464–468why, one step back464 const hasImplicitHelpCommand =465 this._addImplicitHelpCommand ??466 (this.commands.length &&467 !this._actionHandler &&468 !this._findCommand('help'));Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 469–474why, one step back469470 if (hasImplicitHelpCommand) {471 if (this._helpCommand === undefined) {472 this.helpCommand(undefined, undefined); // use default name and description473 }474 return this._helpCommand;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 475why, one step back475 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 476why, one step back476 return null;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 477–487why, one step back477 }478479 /**480 * Add hook for life cycle event.481 *482 * @param {string} event483 * @param {Function} listener484 * @return {Command} `this` command for chaining485 */486487 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 488why, one step back488 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 489–529why, one step back489 if (!allowedValues.includes(event)) {490 throw new Error(`Unexpected value for event passed to hook : '${event}'.491Expecting one of '${allowedValues.join("', '")}'`);492 }493 if (this._lifeCycleHooks[event]) {494 this._lifeCycleHooks[event].push(listener);495 } else {496 this._lifeCycleHooks[event] = [listener];497 }498 return this;499 }500501 /**502 * Register callback to use as replacement for calling process.exit.503 *504 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing505 * @return {Command} `this` command for chaining506 */507508 exitOverride(fn) {509 if (fn) {510 this._exitCallback = fn;511 } else {512 this._exitCallback = (err) => {513 if (err.code !== 'commander.executeSubCommandAsync') {514 throw err;515 } else {516 // Async callback from spawn events, not useful to throw.517 }518 };519 }520 return this;521 }522523 /**524 * Call process.exit, and _exitCallback if defined.525 *526 * @param {number} exitCode exit code for using with process.exit527 * @param {string} code an id string representing the error528 * @param {string} message human-readable description of the error529 * @return neverMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 530why, one step back530 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 531–558why, one step back531 */532533 _exit(exitCode, code, message) {534 if (this._exitCallback) {535 this._exitCallback(new CommanderError(exitCode, code, message));536 // Expecting this line is not reached.537 }538 process.exit(exitCode);539 }540541 /**542 * Register callback `fn` for the command.543 *544 * @example545 * program546 * .command('serve')547 * .description('start service')548 * .action(function() {549 * // do work here550 * });551 *552 * @param {Function} fn553 * @return {Command} `this` command for chaining554 */555556 action(fn) {557 const listener = (args) => {558 // The .action callback takes an extra parameter which is the command or options.Add public Arguments property (#2010)John Geebefore adoption7d23437
line 559why, one step back559 const expectedArgsCount = this.registeredArguments.length;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 560–589why, one step back560 const actionArgs = args.slice(0, expectedArgsCount);561 if (this._storeOptionsAsProperties) {562 actionArgs[expectedArgsCount] = this; // backwards compatible "options"563 } else {564 actionArgs[expectedArgsCount] = this.opts();565 }566 actionArgs.push(this);567568 return fn.apply(this, actionArgs);569 };570 this._actionHandler = listener;571 return this;572 }573574 /**575 * Factory routine to create a new unattached option.576 *577 * See .option() for creating an attached option, which uses this routine to578 * create the option. You can override createOption to return a custom option.579 *580 * @param {string} flags581 * @param {string} [description]582 * @return {Option} new option583 */584585 createOption(flags, description) {586 return new Option(flags, description);587 }588589 /**Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 590–591why, one step back590 * Wrap parseArgs to catch 'commander.invalidArgument'.591 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 592why, one step back592 * @param {(Option | Argument)} targetRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 593why, one step back593 * @param {string} valueReplace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6
line 594why, one step back594 * @param {*} previousRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 595why, one step back595 * @param {string} invalidArgumentMessageMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 596why, one step back596 * @privateRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 597–611why, one step back597 */598599 _callParseArg(target, value, previous, invalidArgumentMessage) {600 try {601 return target.parseArg(value, previous);602 } catch (err) {603 if (err.code === 'commander.invalidArgument') {604 const message = `${invalidArgumentMessage} ${err.message}`;605 this.error(message, { exitCode: err.exitCode, code: err.code });606 }607 throw err;608 }609 }610611 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 612–615why, one step back612 * Check for option flag conflicts.613 * Register option if no conflicts found, or throw on conflict.614 *615 * @param {Option} optionFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 616why, one step back616 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 617–619why, one step back617 */618619 _registerOption(option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 620–621why, one step back620 const matchingOption =621 (option.short && this._findOption(option.short)) ||Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 622–623why, one step back622 (option.long && this._findOption(option.long));623 if (matchingOption) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 624–627why, one step back624 const matchingFlag =625 option.long && this._findOption(option.long)626 ? option.long627 : option.short;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 628–631why, one step back628 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'629- already used by option '${matchingOption.flags}'`);630 }631Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
line 632why, one step back632 this._initOptionGroup(option);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 633–640why, one step back633 this.options.push(option);634 }635636 /**637 * Check for command name and alias conflicts with existing commands.638 * Register command if no conflicts found, or throw on conflict.639 *640 * @param {Command} commandFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 641why, one step back641 * @privateMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 642–648why, one step back642 */643644 _registerCommand(command) {645 const knownBy = (cmd) => {646 return [cmd.name()].concat(cmd.aliases());647 };648Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 649–651why, one step back649 const alreadyUsed = knownBy(command).find((name) =>650 this._findCommand(name),651 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 652–654why, one step back652 if (alreadyUsed) {653 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');654 const newCmd = knownBy(command).join('|');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 655–657why, one step back655 throw new Error(656 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,657 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 658–659why, one step back658 }659Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3
line 660why, one step back660 this._initCommandGroup(command);Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 661–664why, one step back661 this.commands.push(command);662 }663664 /**Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 665–670why, one step back665 * Add an option.666 *667 * @param {Option} option668 * @return {Command} `this` command for chaining669 */670 addOption(option) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 671–672why, one step back671 this._registerOption(option);672Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 673–676why, one step back673 const oname = option.name();674 const name = option.attributeName();675676 // store default valueMake order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a
line 677why, one step back677 if (option.defaultValue !== undefined) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 678–691why, one step back678 this.setOptionValueWithSource(name, option.defaultValue, 'default');679 }680681 // handler for cli and env supplied values682 const handleOptionValue = (val, invalidValueMessage, valueSource) => {683 // val is null for optional option used without an optional-argument.684 // val is undefined for boolean and negated option.685 if (val == null && option.presetArg !== undefined) {686 val = option.presetArg;687 }688689 // custom processing690 const oldValue = this.getOptionValue(name);691 if (val !== null && option.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 692why, one step back692 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 693why, one step back693 } else if (val !== null && option.variadic) {Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 694why, one step back694 val = option._collectValue(val, oldValue);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 695–727why, one step back695 }696697 // Fill-in appropriate missing values. Long winded but easy to follow.698 if (val == null) {699 if (option.negate) {700 val = false;701 } else if (option.isBoolean() || option.optional) {702 val = true;703 } else {704 val = ''; // not normal, parseArg might have failed or be a mock function for testing705 }706 }707 this.setOptionValueWithSource(name, val, valueSource);708 };709710 this.on('option:' + oname, (val) => {711 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;712 handleOptionValue(val, invalidValueMessage, 'cli');713 });714715 if (option.envVar) {716 this.on('optionEnv:' + oname, (val) => {717 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;718 handleOptionValue(val, invalidValueMessage, 'env');719 });720 }721722 return this;723 }724725 /**726 * Internal implementation shared by .option() and .requiredOption()727 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 728why, one step back728 * @return {Command} `this` command for chainingMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 729why, one step back729 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 730–732why, one step back730 */731 _optionEx(config, flags, description, fn, defaultValue) {732 if (typeof flags === 'object' && flags instanceof Option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 733–735why, one step back733 throw new Error(734 'To add an Option object use addOption() instead of option() or requiredOption()',735 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 736–756why, one step back736 }737 const option = this.createOption(flags, description);738 option.makeOptionMandatory(!!config.mandatory);739 if (typeof fn === 'function') {740 option.default(defaultValue).argParser(fn);741 } else if (fn instanceof RegExp) {742 // deprecated743 const regex = fn;744 fn = (val, def) => {745 const m = regex.exec(val);746 return m ? m[0] : def;747 };748 option.default(defaultValue).argParser(fn);749 } else {750 option.default(fn);751 }752753 return this.addOption(option);754 }755756 /**Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 757why, one step back757 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 758why, one step back758 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 759–760why, one step back759 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required760 * option-argument is indicated by `<>` and an optional option-argument by `[]`.Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 761why, one step back761 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 762why, one step back762 * See the README for more details, and see also addOption() and requiredOption().Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 763–764why, one step back763 *764 * @exampleRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 765–766why, one step back765 * program766 * .option('-p, --pepper', 'add pepper')Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f
line 767why, one step back767 * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argumentRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 768–769why, one step back768 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default769 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse functionAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 770–772why, one step back770 *771 * @param {string} flags772 * @param {string} [description]Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 773why, one step back773 * @param {(Function|*)} [parseArg] - custom option processing function or default valueAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 774–777why, one step back774 * @param {*} [defaultValue]775 * @return {Command} `this` command for chaining776 */777Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 778–779why, one step back778 option(flags, description, parseArg, defaultValue) {779 return this._optionEx({}, flags, description, parseArg, defaultValue);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 780–782why, one step back780 }781782 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 783–793why, one step back783 * Add a required option which must have a value after parsing. This usually means784 * the option must be specified on the command line. (Otherwise the same as .option().)785 *786 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.787 *788 * @param {string} flags789 * @param {string} [description]790 * @param {(Function|*)} [parseArg] - custom option processing function or default value791 * @param {*} [defaultValue]792 * @return {Command} `this` command for chaining793 */Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 794why, one step back794Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 795why, one step back795 requiredOption(flags, description, parseArg, defaultValue) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 796–802why, one step back796 return this._optionEx(797 { mandatory: true },798 flags,799 description,800 parseArg,801 defaultValue,802 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 803–812why, one step back803 }804805 /**806 * Alter parsing of short flags with optional values.807 *808 * @example809 * // for `.option('-f,--flag [value]'):810 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour811 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`812 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 813–814why, one step back813 * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.814 * @return {Command} `this` command for chainingAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 815–823why, one step back815 */816 combineFlagAndOptionalValue(combine = true) {817 this._combineFlagAndOptionalValue = !!combine;818 return this;819 }820821 /**822 * Allow unknown options on the command line.823 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 824–825why, one step back824 * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.825 * @return {Command} `this` command for chainingAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 826–834why, one step back826 */827 allowUnknownOption(allowUnknown = true) {828 this._allowUnknownOption = !!allowUnknown;829 return this;830 }831832 /**833 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.834 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 835–836why, one step back835 * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.836 * @return {Command} `this` command for chainingAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 837–847why, one step back837 */838 allowExcessArguments(allowExcess = true) {839 this._allowExcessArguments = !!allowExcess;840 return this;841 }842843 /**844 * Enable positional options. Positional means global options are specified before subcommands which lets845 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.846 * The default behaviour is non-positional and global options may appear anywhere on the command line.847 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 848–849why, one step back848 * @param {boolean} [positional]849 * @return {Command} `this` command for chainingAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 850–861why, one step back850 */851 enablePositionalOptions(positional = true) {852 this._enablePositionalOptions = !!positional;853 return this;854 }855856 /**857 * Pass through options that come after command-arguments rather than treat them as command-options,858 * so actual command-options come before command-arguments. Turning this on for a subcommand requires859 * positional options to have been enabled on the program (parent commands).860 * The default behaviour is non-positional and options may appear before or after command-arguments.861 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 862–863why, one step back862 * @param {boolean} [passThrough] for unknown options.863 * @return {Command} `this` command for chainingAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 864–866why, one step back864 */865 passThroughOptions(passThrough = true) {866 this._passThroughOptions = !!passThrough;Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 867why, one step back867 this._checkForBrokenPassThrough();Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 868–871why, one step back868 return this;869 }870871 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 872–875why, one step back872 * @private873 */874875 _checkForBrokenPassThrough() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 876–883why, one step back876 if (877 this.parent &&878 this._passThroughOptions &&879 !this.parent._enablePositionalOptions880 ) {881 throw new Error(882 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,883 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 884–887why, one step back884 }885 }886887 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 888–893why, one step back888 * Whether to store option values as properties on command object,889 * or store separately (specify false). In both cases the option values can be accessed using .opts().890 *891 * @param {boolean} [storeAsProperties=true]892 * @return {Command} `this` command for chaining893 */Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 894–898why, one step back894895 storeOptionsAsProperties(storeAsProperties = true) {896 if (this.options.length) {897 throw new Error('call .storeOptionsAsProperties() before adding options');898 }Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 899why, one step back899 if (Object.keys(this._optionValues).length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 900–902why, one step back900 throw new Error(901 'call .storeOptionsAsProperties() before setting option values',902 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 903why, one step back903 }Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
line 904why, one step back904 this._storeOptionsAsProperties = !!storeAsProperties;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 905–911why, one step back905 return this;906 }907908 /**909 * Retrieve option value.910 *911 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 912why, one step back912 * @return {object} valueAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 913–925why, one step back913 */914915 getOptionValue(key) {916 if (this._storeOptionsAsProperties) {917 return this[key];918 }919 return this._optionValues[key];920 }921922 /**923 * Store option value.924 *925 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 926why, one step back926 * @param {object} valueAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 927–930why, one step back927 * @return {Command} `this` command for chaining928 */929930 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 931why, one step back931 return this.setOptionValueWithSource(key, value, undefined);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 932–934why, one step back932 }933934 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 935–937why, one step back935 * Store option value and where the value came from.936 *937 * @param {string} keyFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 938why, one step back938 * @param {object} valueReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 939–941why, one step back939 * @param {string} source - expected values are default/config/env/cli/implied940 * @return {Command} `this` command for chaining941 */Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 942–943why, one step back942943 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 944–948why, one step back944 if (this._storeOptionsAsProperties) {945 this[key] = value;946 } else {947 this._optionValues[key] = value;948 }Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 949–953why, one step back949 this._optionValueSources[key] = source;950 return this;951 }952953 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 954–959why, one step back954 * Get source of option value.955 * Expected values are default | config | env | cli | implied956 *957 * @param {string} key958 * @return {string}959 */Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 960–965why, one step back960961 getOptionValueSource(key) {962 return this._optionValueSources[key];963 }964965 /**Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 966–971why, one step back966 * Get source of option value. See also .optsWithGlobals().967 * Expected values are default | config | env | cli | implied968 *969 * @param {string} key970 * @return {string}971 */Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 972–975why, one step back972973 getOptionValueSourceWithGlobals(key) {974 // global overwrites local, like optsWithGlobals975 let source;Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 976why, one step back976 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 977–984why, one step back977 if (cmd.getOptionValueSource(key) !== undefined) {978 source = cmd.getOptionValueSource(key);979 }980 });981 return source;982 }983984 /**Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 985–987why, one step back985 * Get user arguments from implied or explicit arguments.986 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.987 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 988why, one step back988 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 989–996why, one step back989 */990991 _prepareUserArgs(argv, parseOptions) {992 if (argv !== undefined && !Array.isArray(argv)) {993 throw new Error('first parameter to parse must be array or undefined');994 }995 parseOptions = parseOptions || {};996Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 997–999why, one step back997 // auto-detect argument conventions if nothing supplied998 if (argv === undefined && parseOptions.from === undefined) {999 if (process.versions?.electron) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1000–1001why, one step back1000 parseOptions.from = 'electron';1001 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1002–1011why, one step back1002 // check node specific options for scenarios where user CLI args follow executable without scriptname1003 const execArgv = process.execArgv ?? [];1004 if (1005 execArgv.includes('-e') ||1006 execArgv.includes('--eval') ||1007 execArgv.includes('-p') ||1008 execArgv.includes('--print')1009 ) {1010 parseOptions.from = 'eval'; // internal usage, not documented1011 }Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1012why, one step back1012 }Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1013–1017why, one step back10131014 // default to using process.argv1015 if (argv === undefined) {1016 argv = process.argv;1017 }Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1018–1019why, one step back1018 this.rawArgs = argv.slice();1019Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1020why, one step back1020 // extract the user args and scriptPathAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1021–1028why, one step back1021 let userArgs;1022 switch (parseOptions.from) {1023 case undefined:1024 case 'node':1025 this._scriptPath = argv[1];1026 userArgs = argv.slice(2);1027 break;1028 case 'electron':ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1029why, one step back1029 // @ts-ignore: because defaultApp is an unknown propertyAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1030–1039why, one step back1030 if (process.defaultApp) {1031 this._scriptPath = argv[1];1032 userArgs = argv.slice(2);1033 } else {1034 userArgs = argv.slice(1);1035 }1036 break;1037 case 'user':1038 userArgs = argv.slice(0);1039 break;Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1040–1042why, one step back1040 case 'eval':1041 userArgs = argv.slice(1);1042 break;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1043why, one step back1043 default:Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1044–1046why, one step back1044 throw new Error(1045 `unexpected parse option { from: '${parseOptions.from}' }`,1046 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1047–1049why, one step back1047 }10481049 // Find default name for program from arguments.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1050–1051why, one step back1050 if (!this._name && this._scriptPath)1051 this.nameFromFilename(this._scriptPath);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1052–1059why, one step back1052 this._name = this._name || 'program';10531054 return userArgs;1055 }10561057 /**1058 * Parse `argv`, setting options and invoking commands when defined.1059 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1060why, one step back1060 * Use parseAsync instead of parse if any of your action handlers are async.Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1061why, one step back1061 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1062–1068why, one step back1062 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!1063 *1064 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1065 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1066 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1067 * - `'user'`: just user arguments1068 *Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1069why, one step back1069 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1070–1071why, one step back1070 * program.parse(); // parse process.argv and auto-detect electron and special node flags1071 * program.parse(process.argv); // assume argv[0] is app and argv[1] is scriptAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1072–1073why, one step back1072 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1073 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
lines 1074–1076why, one step back1074 * @param {string[]} [argv] - optional, defaults to process.argv1075 * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron1076 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1077–1080why, one step back1077 * @return {Command} `this` command for chaining1078 */10791080 parse(argv, parseOptions) {Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1081why, one step back1081 this._prepareForParse();Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1082–1090why, one step back1082 const userArgs = this._prepareUserArgs(argv, parseOptions);1083 this._parseCommand([], userArgs);10841085 return this;1086 }10871088 /**1089 * Parse `argv`, setting options and invoking commands when defined.1090 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1091why, one step back1091 * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1092why, one step back1092 *Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1093–1096why, one step back1093 * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:1094 * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that1095 * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged1096 * - `'user'`: just user argumentsAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1097–1098why, one step back1097 *1098 * @exampleAdd auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
lines 1099–1100why, one step back1099 * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags1100 * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is scriptAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1101–1103why, one step back1101 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]1102 *1103 * @param {string[]} [argv]Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390
line 1104why, one step back1104 * @param {object} [parseOptions]Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1105why, one step back1105 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1106–1109why, one step back1106 * @return {Promise}1107 */11081109 async parseAsync(argv, parseOptions) {Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1110why, one step back1110 this._prepareForParse();Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1111–1116why, one step back1111 const userArgs = this._prepareUserArgs(argv, parseOptions);1112 await this._parseCommand([], userArgs);11131114 return this;1115 }1116Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1117why, one step back1117 _prepareForParse() {Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a
line 1118why, one step back1118 // Save the state the first time, then restore the state before each subsequent parse.Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1119why, one step back1119 if (this._savedState === null) {Make order not matter for adding combo positive/negative options (#2405)John Geebefore adoption63eed4a
lines 1120–1140why, one step back1120 // Do the special default of lone negated option to true, now that we have all the options.1121 // Filter for negated options that have not been processed already.1122 this.options1123 .filter(1124 (option) =>1125 option.negate &&1126 option.defaultValue === undefined &&1127 this.getOptionValue(option.attributeName()) === undefined,1128 )1129 .forEach((option) => {1130 // check for lone negated option: --no-foo without a --foo option1131 const positiveLongFlag = option.long.replace(/^--no-/, '--');1132 if (!this._findOption(positiveLongFlag)) {1133 this.setOptionValueWithSource(1134 option.attributeName(),1135 true,1136 'default',1137 );1138 }1139 });1140Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1141–1146why, one step back1141 this.saveStateBeforeParse();1142 } else {1143 this.restoreStateBeforeParse();1144 }1145 }1146Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1147why, one step back1147 /**Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1148–1188why, one step back1148 * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.1149 * Not usually called directly, but available for subclasses to save their custom state.1150 *1151 * This is called in a lazy way. Only commands used in parsing chain will have state saved.1152 */1153 saveStateBeforeParse() {1154 this._savedState = {1155 // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing1156 _name: this._name,1157 // option values before parse have default values (including false for negated options)1158 // shallow clones1159 _optionValues: { ...this._optionValues },1160 _optionValueSources: { ...this._optionValueSources },1161 };1162 }11631164 /**1165 * Restore state before parse for calls after the first.1166 * Not usually called directly, but available for subclasses to save their custom state.1167 *1168 * This is called in a lazy way. Only commands used in parsing chain will have state restored.1169 */1170 restoreStateBeforeParse() {1171 if (this._storeOptionsAsProperties)1172 throw new Error(`Can not call parse again when storeOptionsAsProperties is true.1173- either make a new Command for each call to parse, or stop storing options as properties`);11741175 // clear state from _prepareUserArgs1176 this._name = this._savedState._name;1177 this._scriptPath = null;1178 this.rawArgs = [];1179 // clear state from setOptionValueWithSource1180 this._optionValues = { ...this._savedState._optionValues };1181 this._optionValueSources = { ...this._savedState._optionValueSources };1182 // clear state from _parseCommand1183 this.args = [];1184 // clear state from _processArguments1185 this.processedArgs = [];1186 }11871188 /**Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1189–1208why, one step back1189 * Throw if expected executable is missing. Add lots of help for author.1190 *1191 * @param {string} executableFile1192 * @param {string} executableDir1193 * @param {string} subcommandName1194 */1195 _checkForMissingExecutable(executableFile, executableDir, subcommandName) {1196 if (fs.existsSync(executableFile)) return;11971198 const executableDirMessage = executableDir1199 ? `searched for local subcommand relative to directory '${executableDir}'`1200 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1201 const executableMissing = `'${executableFile}' does not exist1202 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1203 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1204 - ${executableDirMessage}`;1205 throw new Error(executableMissing);1206 }12071208 /**Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1209–1210why, one step back1209 * Execute a sub-command executable.1210 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1211why, one step back1211 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1212–1226why, one step back1212 */12131214 _executeSubCommand(subcommand, args) {1215 args = args.slice();1216 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];12171218 function findFile(baseDir, baseName) {1219 // Look for specified file1220 const localBin = path.resolve(baseDir, baseName);1221 if (fs.existsSync(localBin)) return localBin;12221223 // Stop looking if candidate already has an expected extension.1224 if (sourceExt.includes(path.extname(baseName))) return undefined;12251226 // Try all the extensions.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1227–1229why, one step back1227 const foundExt = sourceExt.find((ext) =>1228 fs.existsSync(`${localBin}${ext}`),1229 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1230–1239why, one step back1230 if (foundExt) return `${localBin}${foundExt}`;12311232 return undefined;1233 }12341235 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.1236 this._checkForMissingMandatoryOptions();1237 this._checkForConflictingOptions();12381239 // executableFile and executableDir might be full path, or just a nameReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1240–1241why, one step back1240 let executableFile =1241 subcommand._executableFile || `${this._name}-${subcommand._name}`;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1242–1246why, one step back1242 let executableDir = this._executableDir || '';1243 if (this._scriptPath) {1244 let resolvedScriptPath; // resolve possible symlink for installed npm binary1245 try {1246 resolvedScriptPath = fs.realpathSync(this._scriptPath);Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585
line 1247why, one step back1247 } catch {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1248–1249why, one step back1248 resolvedScriptPath = this._scriptPath;1249 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1250–1253why, one step back1250 executableDir = path.resolve(1251 path.dirname(resolvedScriptPath),1252 executableDir,1253 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1254–1261why, one step back1254 }12551256 // Look for a local file in preference to a command in PATH.1257 if (executableDir) {1258 let localFile = findFile(executableDir, executableFile);12591260 // Legacy search using prefix of script name instead of command name1261 if (!localFile && !subcommand._executableFile && this._scriptPath) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1262–1265why, one step back1262 const legacyName = path.basename(1263 this._scriptPath,1264 path.extname(this._scriptPath),1265 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1266why, one step back1266 if (legacyName !== this._name) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1267–1270why, one step back1267 localFile = findFile(1268 executableDir,1269 `${legacyName}-${subcommand._name}`,1270 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1271–1275why, one step back1271 }1272 }1273 executableFile = localFile || executableFile;1274 }1275Update dependecies and lint (#2489)John Geebefore adoption0ea3bb3
line 1276why, one step back1276 const launchWithNode = sourceExt.includes(path.extname(executableFile));Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1277–1289why, one step back12771278 let proc;1279 if (process.platform !== 'win32') {1280 if (launchWithNode) {1281 args.unshift(executableFile);1282 // add executable arguments to spawn1283 args = incrementNodeInspectorPort(process.execArgv).concat(args);12841285 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1286 } else {1287 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });1288 }1289 } else {Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1290–1294why, one step back1290 this._checkForMissingExecutable(1291 executableFile,1292 executableDir,1293 subcommand._name,1294 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1295–1300why, one step back1295 args.unshift(executableFile);1296 // add executable arguments to spawn1297 args = incrementNodeInspectorPort(process.execArgv).concat(args);1298 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1299 }1300Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1301–1302why, one step back1301 if (!proc.killed) {1302 // testing mainly to avoid leak warnings during unit tests with mocked spawnAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1303–1306why, one step back1303 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1304 signals.forEach((signal) => {1305 process.on(signal, () => {1306 if (proc.killed === false && proc.exitCode === null) {Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1307why, one step back1307 // @ts-ignore because signals not typed to known stringsAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1308–1315why, one step back1308 proc.kill(signal);1309 }1310 });1311 });1312 }13131314 // By default terminate process when spawned process terminates.1315 const exitCallback = this._exitCallback;ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 1316why, one step back1316 proc.on('close', (code) => {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1317–1320why, one step back1317 code = code ?? 1; // code is null if spawned process terminated due to a signal1318 if (!exitCallback) {1319 process.exit(code);1320 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1321–1327why, one step back1321 exitCallback(1322 new CommanderError(1323 code,1324 'commander.executeSubCommandAsync',1325 '(close)',1326 ),1327 );Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1328–1329why, one step back1328 }1329 });Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1330why, one step back1330 proc.on('error', (err) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1331why, one step back1331 // @ts-ignore: because err.code is an unknown propertyAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1332why, one step back1332 if (err.code === 'ENOENT') {Add informative message for missing executable on Windows (#2291)John Geebefore adoptiona8ef5cf
lines 1333–1337why, one step back1333 this._checkForMissingExecutable(1334 executableFile,1335 executableDir,1336 subcommand._name,1337 );Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1338why, one step back1338 // @ts-ignore: because err.code is an unknown propertyAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1339–1344why, one step back1339 } else if (err.code === 'EACCES') {1340 throw new Error(`'${executableFile}' not executable`);1341 }1342 if (!exitCallback) {1343 process.exit(1);1344 } else {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1345–1349why, one step back1345 const wrappedError = new CommanderError(1346 1,1347 'commander.executeSubCommandAsync',1348 '(error)',1349 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1350–1359why, one step back1350 wrappedError.nestedError = err;1351 exitCallback(wrappedError);1352 }1353 });13541355 // Store the reference to the child process1356 this.runningCommand = proc;1357 }13581359 /**Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1360why, one step back1360 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1361–1366why, one step back1361 */13621363 _dispatchSubcommand(commandName, operands, unknown) {1364 const subCommand = this._findCommand(commandName);1365 if (!subCommand) this.help({ error: true });1366Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
line 1367why, one step back1367 subCommand._prepareForParse();Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1368why, one step back1368 let promiseChain;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1369–1373why, one step back1369 promiseChain = this._chainOrCallSubCommandHook(1370 promiseChain,1371 subCommand,1372 'preSubcommand',1373 );Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1374why, one step back1374 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1375–1380why, one step back1375 if (subCommand._executableHandler) {1376 this._executeSubCommand(subCommand, operands.concat(unknown));1377 } else {1378 return subCommand._parseCommand(operands, unknown);1379 }1380 });Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1381why, one step back1381 return promiseChain;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1382–1384why, one step back1382 }13831384 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1385–1387why, one step back1385 * Invoke help directly if possible, or dispatch if necessary.1386 * e.g. help foo1387 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1388why, one step back1388 * @privateHave help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1389–1400why, one step back1389 */13901391 _dispatchHelpCommand(subcommandName) {1392 if (!subcommandName) {1393 this.help();1394 }1395 const subCommand = this._findCommand(subcommandName);1396 if (subCommand && !subCommand._executableHandler) {1397 subCommand.help();1398 }13991400 // Fallback to parsing the help flag to invoke the help.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1401–1405why, one step back1401 return this._dispatchSubcommand(1402 subcommandName,1403 [],1404 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1405 );Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1406–1408why, one step back1406 }14071408 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1409why, one step back1409 * Check this.args against expected this.registeredArguments.Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1410why, one step back1410 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1411why, one step back1411 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1412–1415why, one step back1412 */14131414 _checkNumberOfArguments() {1415 // too fewAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1416why, one step back1416 this.registeredArguments.forEach((arg, i) => {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1417–1421why, one step back1417 if (arg.required && this.args[i] == null) {1418 this.missingArgument(arg.name());1419 }1420 });1421 // too manyReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1422–1425why, one step back1422 if (1423 this.registeredArguments.length > 0 &&1424 this.registeredArguments[this.registeredArguments.length - 1].variadic1425 ) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1426–1427why, one step back1426 return;1427 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1428why, one step back1428 if (this.args.length > this.registeredArguments.length) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1429–1433why, one step back1429 this._excessArguments(this.args);1430 }1431 }14321433 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1434why, one step back1434 * Process this.args using this.registeredArguments and save as this.processedArgs!Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1435why, one step back1435 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1436why, one step back1436 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1437–1443why, one step back1437 */14381439 _processArguments() {1440 const myParseArg = (argument, value, previous) => {1441 // Extra processing for nice error message on parsing failure.1442 let parsedValue = value;1443 if (value !== null && argument.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 1444why, one step back1444 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1445–1450why, one step back1445 parsedValue = this._callParseArg(1446 argument,1447 value,1448 previous,1449 invalidValueMessage,1450 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1451–1457why, one step back1451 }1452 return parsedValue;1453 };14541455 this._checkNumberOfArguments();14561457 const processedArgs = [];Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1458why, one step back1458 this.registeredArguments.forEach((declaredArg, index) => {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1459–1485why, one step back1459 let value = declaredArg.defaultValue;1460 if (declaredArg.variadic) {1461 // Collect together remaining arguments for passing together as an array.1462 if (index < this.args.length) {1463 value = this.args.slice(index);1464 if (declaredArg.parseArg) {1465 value = value.reduce((processed, v) => {1466 return myParseArg(declaredArg, v, processed);1467 }, declaredArg.defaultValue);1468 }1469 } else if (value === undefined) {1470 value = [];1471 }1472 } else if (index < this.args.length) {1473 value = this.args[index];1474 if (declaredArg.parseArg) {1475 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1476 }1477 }1478 processedArgs[index] = value;1479 });1480 this.processedArgs = processedArgs;1481 }14821483 /**1484 * Once we have a promise we chain, but call synchronously until then.1485 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1486why, one step back1486 * @param {(Promise|undefined)} promiseAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1487why, one step back1487 * @param {Function} fnMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1488–1489why, one step back1488 * @return {(Promise|undefined)}1489 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1490–1493why, one step back1490 */14911492 _chainOrCall(promise, fn) {1493 // thenableMerge from develop (#2482)John Geebefore adoptionb51c0ea
line 1494why, one step back1494 if (promise?.then && typeof promise.then === 'function') {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1495–1503why, one step back1495 // already have a promise, chain callback1496 return promise.then(() => fn());1497 }1498 // callback might return a promise1499 return fn();1500 }15011502 /**1503 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1504why, one step back1504 * @param {(Promise|undefined)} promiseAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1505why, one step back1505 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1506–1507why, one step back1506 * @return {(Promise|undefined)}1507 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1508–1512why, one step back1508 */15091510 _chainOrCallHooks(promise, event) {1511 let result = promise;1512 const hooks = [];Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1513why, one step back1513 this._getCommandAndAncestors()Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1514why, one step back1514 .reverse()Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1515–1516why, one step back1515 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1516 .forEach((hookedCommand) => {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1517–1529why, one step back1517 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1518 hooks.push({ hookedCommand, callback });1519 });1520 });1521 if (event === 'postAction') {1522 hooks.reverse();1523 }15241525 hooks.forEach((hookDetail) => {1526 result = this._chainOrCall(result, () => {1527 return hookDetail.callback(hookDetail.hookedCommand, this);1528 });1529 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1530–1534why, one step back1530 return result;1531 }15321533 /**1534 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1535why, one step back1535 * @param {(Promise|undefined)} promisefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1536–1537why, one step back1536 * @param {Command} subCommand1537 * @param {string} eventMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
lines 1538–1539why, one step back1538 * @return {(Promise|undefined)}1539 * @privatefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1540–1550why, one step back1540 */15411542 _chainOrCallSubCommandHook(promise, subCommand, event) {1543 let result = promise;1544 if (this._lifeCycleHooks[event] !== undefined) {1545 this._lifeCycleHooks[event].forEach((hook) => {1546 result = this._chainOrCall(result, () => {1547 return hook(this, subCommand);1548 });1549 });1550 }Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1551–1557why, one step back1551 return result;1552 }15531554 /**1555 * Process arguments in context of this command.1556 * Returns action result, in case it is a promise.1557 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1558why, one step back1558 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1559–1571why, one step back1559 */15601561 _parseCommand(operands, unknown) {1562 const parsed = this.parseOptions(unknown);1563 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env1564 this._parseOptionsImplied();1565 operands = operands.concat(parsed.operands);1566 unknown = parsed.unknown;1567 this.args = operands.concat(unknown);15681569 if (operands && this._findCommand(operands[0])) {1570 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1571 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1572–1575why, one step back1572 if (1573 this._getHelpCommand() &&1574 operands[0] === this._getHelpCommand().name()1575 ) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1576why, one step back1576 return this._dispatchHelpCommand(operands[1]);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1577–1578why, one step back1577 }1578 if (this._defaultCommandName) {Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1579why, one step back1579 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 1580–1584why, one step back1580 return this._dispatchSubcommand(1581 this._defaultCommandName,1582 operands,1583 unknown,1584 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1585why, one step back1585 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1586–1591why, one step back1586 if (1587 this.commands.length &&1588 this.args.length === 0 &&1589 !this._actionHandler &&1590 !this._defaultCommandName1591 ) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1592–1595why, one step back1592 // probably missing subcommand and no handler, user needs help (and exit)1593 this.help({ error: true });1594 }1595Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1596why, one step back1596 this._outputHelpIfRequested(parsed.unknown);Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1597–1611why, one step back1597 this._checkForMissingMandatoryOptions();1598 this._checkForConflictingOptions();15991600 // We do not always call this check to avoid masking a "better" error, like unknown command.1601 const checkForUnknownOptions = () => {1602 if (parsed.unknown.length > 0) {1603 this.unknownOption(parsed.unknown[0]);1604 }1605 };16061607 const commandEvent = `command:${this.name()}`;1608 if (this._actionHandler) {1609 checkForUnknownOptions();1610 this._processArguments();1611Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1612–1613why, one step back1612 let promiseChain;1613 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1614–1616why, one step back1614 promiseChain = this._chainOrCall(promiseChain, () =>1615 this._actionHandler(this.processedArgs),1616 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1617why, one step back1617 if (this.parent) {Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1618why, one step back1618 promiseChain = this._chainOrCall(promiseChain, () => {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1619–1621why, one step back1619 this.parent.emit(commandEvent, operands, unknown); // legacy1620 });1621 }Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1622–1623why, one step back1622 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1623 return promiseChain;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1624why, one step back1624 }Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1625why, one step back1625 if (this.parent?.listenerCount(commandEvent)) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1626–1629why, one step back1626 checkForUnknownOptions();1627 this._processArguments();1628 this.parent.emit(commandEvent, operands, unknown); // legacy1629 } else if (operands.length) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1630–1631why, one step back1630 if (this._findCommand('*')) {1631 // legacy default commandAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1632–1656why, one step back1632 return this._dispatchSubcommand('*', operands, unknown);1633 }1634 if (this.listenerCount('command:*')) {1635 // skip option check, emit event for possible misspelling suggestion1636 this.emit('command:*', operands, unknown);1637 } else if (this.commands.length) {1638 this.unknownCommand();1639 } else {1640 checkForUnknownOptions();1641 this._processArguments();1642 }1643 } else if (this.commands.length) {1644 checkForUnknownOptions();1645 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1646 this.help({ error: true });1647 } else {1648 checkForUnknownOptions();1649 this._processArguments();1650 // fall through for caller to handle after calling .parse()1651 }1652 }16531654 /**1655 * Find matching command.1656 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1657why, one step back1657 * @privateFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1658why, one step back1658 * @return {Command | undefined}Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1659–1661why, one step back1659 */1660 _findCommand(name) {1661 if (!name) return undefined;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1662–1664why, one step back1662 return this.commands.find(1663 (cmd) => cmd._name === name || cmd._aliases.includes(name),1664 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1665–1671why, one step back1665 }16661667 /**1668 * Return an option matching `arg` if any.1669 *1670 * @param {string} arg1671 * @return {Option}Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1672why, one step back1672 * @packageAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1673–1675why, one step back1673 */16741675 _findOption(arg) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1676why, one step back1676 return this.options.find((option) => option.is(arg));Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1677–1682why, one step back1677 }16781679 /**1680 * Display an error message if a mandatory option does not have a value.1681 * Called after checking for help flags in leaf subcommand.1682 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1683why, one step back1683 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1684–1687why, one step back1684 */16851686 _checkForMissingMandatoryOptions() {1687 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1688why, one step back1688 this._getCommandAndAncestors().forEach((cmd) => {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1689why, one step back1689 cmd.options.forEach((anOption) => {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1690–1693why, one step back1690 if (1691 anOption.mandatory &&1692 cmd.getOptionValue(anOption.attributeName()) === undefined1693 ) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1694–1696why, one step back1694 cmd.missingMandatoryOptionValue(anOption);1695 }1696 });Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1697why, one step back1697 });Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1698–1702why, one step back1698 }16991700 /**1701 * Display an error message if conflicting options are used together in this.1702 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1703why, one step back1703 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1704–1705why, one step back1704 */1705 _checkForConflictingLocalOptions() {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1706–1709why, one step back1706 const definedNonDefaultOptions = this.options.filter((option) => {1707 const optionKey = option.attributeName();1708 if (this.getOptionValue(optionKey) === undefined) {1709 return false;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1710why, one step back1710 }Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1711–1712why, one step back1711 return this.getOptionValueSource(optionKey) !== 'default';1712 });Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1713–1714why, one step back17131714 const optionsWithConflicting = definedNonDefaultOptions.filter(Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1715why, one step back1715 (option) => option.conflictsWith.length > 0,Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1716–1719why, one step back1716 );17171718 optionsWithConflicting.forEach((option) => {1719 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1720why, one step back1720 option.conflictsWith.includes(defined.attributeName()),Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1721–1731why, one step back1721 );1722 if (conflictingAndDefined) {1723 this._conflictingOption(option, conflictingAndDefined);1724 }1725 });1726 }17271728 /**1729 * Display an error message if conflicting options are used together.1730 * Called after checking for help flags in leaf subcommand.1731 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1732why, one step back1732 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1733–1735why, one step back1733 */1734 _checkForConflictingOptions() {1735 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1736why, one step back1736 this._getCommandAndAncestors().forEach((cmd) => {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1737why, one step back1737 cmd._checkForConflictingLocalOptions();Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1738why, one step back1738 });Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1739–1743why, one step back1739 }17401741 /**1742 * Parse options from `argv` removing known options,1743 * and return argv split into operands and unknown arguments.Add save/restore state to allow multiple calls to parse (#2299)John Geebefore adoption49423a2
lines 1744–1745why, one step back1744 *1745 * Side effects: modifies command by storing options. Does not reset state if called again.Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1746–1754why, one step back1746 *1747 * Examples:1748 *1749 * argv => operands, unknown1750 * --known kkk op => [op], []1751 * op --known kkk => [op], []1752 * sub --unknown uuu op => [sub], [--unknown uuu op]1753 * sub -- --unknown uuu op => [sub --unknown uuu op], []1754 *Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1755why, one step back1755 * @param {string[]} argsMerge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1756why, one step back1756 * @return {{operands: string[], unknown: string[]}}Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1757–1758why, one step back1757 */1758Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1759why, one step back1759 parseOptions(args) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1760–1767why, one step back1760 const operands = []; // operands, not options or values1761 const unknown = []; // first unknown option and remaining unknown args1762 let dest = operands;17631764 function maybeOption(arg) {1765 return arg.length > 1 && arg[0] === '-';1766 }1767Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1768–1769why, one step back1768 const negativeNumberArg = (arg) => {1769 // return false if not a negative numberMerge from develop (#2482)John Geebefore adoptionb51c0ea
line 1770why, one step back1770 if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1771–1778why, one step back1771 // negative number is ok unless digit used as an option in command hierarchy1772 return !this._getCommandAndAncestors().some((cmd) =>1773 cmd.options1774 .map((opt) => opt.short)1775 .some((short) => /^-\d$/.test(short)),1776 );1777 };1778Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1779–1780why, one step back1779 // parse options1780 let activeVariadicOption = null;Merge from develop (#2482)John Geebefore adoptionb51c0ea
lines 1781–1785why, one step back1781 let activeGroup = null; // working through group of short options, like -abc1782 let i = 0;1783 while (i < args.length || activeGroup) {1784 const arg = activeGroup ?? args[i++];1785 activeGroup = null;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1786–1789why, one step back17861787 // literal1788 if (arg === '--') {1789 if (dest === unknown) dest.push(arg);Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1790why, one step back1790 dest.push(...args.slice(i));Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1791–1793why, one step back1791 break;1792 }1793Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1794–1797why, one step back1794 if (1795 activeVariadicOption &&1796 (!maybeOption(arg) || negativeNumberArg(arg))1797 ) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1798–1807why, one step back1798 this.emit(`option:${activeVariadicOption.name()}`, arg);1799 continue;1800 }1801 activeVariadicOption = null;18021803 if (maybeOption(arg)) {1804 const option = this._findOption(arg);1805 // recognised option, call listener to assign value with possible custom processing1806 if (option) {1807 if (option.required) {Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1808why, one step back1808 const value = args[i++];Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1809–1813why, one step back1809 if (value === undefined) this.optionMissingArgument(option);1810 this.emit(`option:${option.name()}`, value);1811 } else if (option.optional) {1812 let value = null;1813 // historical behaviour is optional value is following arg unless an optionAllow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
line 1814why, one step back1814 if (Merge from develop (#2482)John Geebefore adoptionb51c0ea
lines 1815–1816why, one step back1815 i < args.length &&1816 (!maybeOption(args[i]) || negativeNumberArg(args[i]))Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
line 1817why, one step back1817 ) {Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1818why, one step back1818 value = args[i++];Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1819–1820why, one step back1819 }1820 this.emit(`option:${option.name()}`, value);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1821–1822why, one step back1821 } else {1822 // boolean flagAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1823–1833why, one step back1823 this.emit(`option:${option.name()}`);1824 }1825 activeVariadicOption = option.variadic ? option : null;1826 continue;1827 }1828 }18291830 // Look for combo options following single dash, eat first one if known.1831 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1832 const option = this._findOption(`-${arg[1]}`);1833 if (option) {Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1834–1837why, one step back1834 if (1835 option.required ||1836 (option.optional && this._combineFlagAndOptionalValue)1837 ) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1838–1840why, one step back1838 // option with value following in same argument1839 this.emit(`option:${option.name()}`, arg.slice(2));1840 } else {Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1841why, one step back1841 // boolean optionAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1842why, one step back1842 this.emit(`option:${option.name()}`);Merge from develop (#2482)John Geebefore adoptionb51c0ea
lines 1843–1844why, one step back1843 // remove the processed option and keep processing group1844 activeGroup = `-${arg.slice(2)}`;Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1845–1863why, one step back1845 }1846 continue;1847 }1848 }18491850 // Look for known long flag with value, like --foo=bar1851 if (/^--[^=]+=/.test(arg)) {1852 const index = arg.indexOf('=');1853 const option = this._findOption(arg.slice(0, index));1854 if (option && (option.required || option.optional)) {1855 this.emit(`option:${option.name()}`, arg.slice(index + 1));1856 continue;1857 }1858 }18591860 // Not a recognised option by this command.1861 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.18621863 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de
lines 1864–1869why, one step back1864 // A negative number in a leaf command is not an unknown option.1865 if (1866 dest === operands &&1867 maybeOption(arg) &&1868 !(this.commands.length === 0 && negativeNumberArg(arg))1869 ) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1870–1873why, one step back1870 dest = unknown;1871 }18721873 // If using positionalOptions, stop processing our options at subcommand.Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1874–1878why, one step back1874 if (1875 (this._enablePositionalOptions || this._passThroughOptions) &&1876 operands.length === 0 &&1877 unknown.length === 01878 ) {Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1879–1880why, one step back1879 if (this._findCommand(arg)) {1880 operands.push(arg);Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1881why, one step back1881 unknown.push(...args.slice(i));Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1882why, one step back1882 break;Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1883–1886why, one step back1883 } else if (1884 this._getHelpCommand() &&1885 arg === this._getHelpCommand().name()1886 ) {Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1887why, one step back1887 operands.push(arg, ...args.slice(i));Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1888–1889why, one step back1888 break;1889 } else if (this._defaultCommandName) {Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1890why, one step back1890 unknown.push(arg, ...args.slice(i));Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1891–1896why, one step back1891 break;1892 }1893 }18941895 // If using passThroughOptions, stop processing options at first command-argument.1896 if (this._passThroughOptions) {Merge from develop (#2482)John Geebefore adoptionb51c0ea
line 1897why, one step back1897 dest.push(arg, ...args.slice(i));Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1898–1910why, one step back1898 break;1899 }19001901 // add arg1902 dest.push(arg);1903 }19041905 return { operands, unknown };1906 }19071908 /**1909 * Return an object containing local option values as key-value pairs.1910 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1911why, one step back1911 * @return {object}Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1912–1920why, one step back1912 */1913 opts() {1914 if (this._storeOptionsAsProperties) {1915 // Preserve original behaviour so backwards compatible when still using properties1916 const result = {};1917 const len = this.options.length;19181919 for (let i = 0; i < len; i++) {1920 const key = this.options[i].attributeName();Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1921–1922why, one step back1921 result[key] =1922 key === this._versionOptionName ? this._version : this[key];Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1923–1932why, one step back1923 }1924 return result;1925 }19261927 return this._optionValues;1928 }19291930 /**1931 * Return an object containing merged local and global option values as key-value pairs.1932 *Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1933why, one step back1933 * @return {object}Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1934–1936why, one step back1934 */1935 optsWithGlobals() {1936 // globals overwrite localsIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1937why, one step back1937 return this._getCommandAndAncestors().reduce(Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
line 1938why, one step back1938 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
line 1939why, one step back1939 {},Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1940–1946why, one step back1940 );1941 }19421943 /**1944 * Display error message and exit (or call exitOverride).1945 *1946 * @param {string} messageFix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44
line 1947why, one step back1947 * @param {object} [errorOptions]Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1948–1952why, one step back1948 * @param {string} [errorOptions.code] - an id string representing the error1949 * @param {number} [errorOptions.exitCode] - used with process.exit1950 */1951 error(message, errorOptions) {1952 // output handlingReformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1953–1956why, one step back1953 this._outputConfiguration.outputError(1954 `${message}\n`,1955 this._outputConfiguration.writeErr,1956 );Add develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1957–1974why, one step back1957 if (typeof this._showHelpAfterError === 'string') {1958 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1959 } else if (this._showHelpAfterError) {1960 this._outputConfiguration.writeErr('\n');1961 this.outputHelp({ error: true });1962 }19631964 // exit handling1965 const config = errorOptions || {};1966 const exitCode = config.exitCode || 1;1967 const code = config.code || 'commander.error';1968 this._exit(exitCode, code, message);1969 }19701971 /**1972 * Apply any option related environment variables, if option does1973 * not have a value from cli or client code.1974 *Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1
line 1975why, one step back1975 * @privateAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1976–1981why, one step back1976 */1977 _parseOptionsEnv() {1978 this.options.forEach((option) => {1979 if (option.envVar && option.envVar in process.env) {1980 const optionKey = option.attributeName();1981 // Priority check. Do not overwrite cli or options from unknown source (client-code).Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1982–1989why, one step back1982 if (1983 this.getOptionValue(optionKey) === undefined ||1984 ['default', 'config', 'env'].includes(1985 this.getOptionValueSource(optionKey),1986 )1987 ) {1988 if (option.required || option.optional) {1989 // option can take a valueAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1990–1991why, one step back1990 // keep very simple, optional always takes value1991 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 1992–1993why, one step back1992 } else {1993 // booleanAdd develop branch for earlier warningsJohn Geebefore adoption3e202f3
lines 1994–2004why, one step back1994 // keep very simple, only care that envVar defined and not the value1995 this.emit(`optionEnv:${option.name()}`);1996 }1997 }1998 }1999 });2000 }The first 2,000 of 2,789 lines.