command.js
This file
Path
lib/command.js
2,207 lines · 69.8 KiB · JavaScript
Last changed by
Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40
History of this fileTake it
Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1–4why, one step back1const EventEmitter = require('events').EventEmitter;2const childProcess = require('child_process');3const path = require('path');4const fs = require('fs');Follow best practice and require process rather than use global (#1685)John Geebefore adoption47e8b20
line 5why, one step back5const process = require('process');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 6–9why, one step back67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help } = require('./help.js');Add Option.implies() (#1724)John Geebefore adoptiond660967
line 10why, one step back10const { Option, splitOptionFlags, DualOptions } = require('./option.js');Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 11why, one step back11const { suggestSimilar } = require('./suggestSimilar');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 12–21why, one step back1213class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]18 */1920 constructor(name) {21 super();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 22why, one step back22 /** @type {Command[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
line 23why, one step back23 this.commands = [];Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 24why, one step back24 /** @type {Option[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 25–28why, one step back25 this.options = [];26 this.parent = null;27 this._allowUnknownOption = false;28 this._allowExcessArguments = true;Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 29why, one step back29 /** @type {Argument[]} */Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
lines 30–31why, one step back30 this.registeredArguments = [];31 this._args = this.registeredArguments; // deprecated old nameSupport argument processing without action handler (#1529)John Geebefore adoption4663597
lines 32–35why, 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 variadicRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 36–38why, one step back36 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 etcRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 40–43why, one step back40 this._storeOptionsAsProperties = false;41 this._actionHandler = null;42 this._executableHandler = false;43 this._executableFile = null; // custom name for executableMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 44why, one step back44 this._executableDir = null; // custom search directory for subcommandsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 45–49why, one step back45 this._defaultCommandName = null;46 this._exitCallback = null;47 this._aliases = [];48 this._combineFlagAndOptionalValue = true;49 this._description = '';Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 50why, one step back50 this._summary = '';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 51–54why, one step back51 this._argsDescription = undefined; // legacy52 this._enablePositionalOptions = false;53 this._passThroughOptions = false;54 this._lifeCycleHooks = {}; // a hash of arraysAdd showHelpAfterError (#1534)John Geebefore adoption082717f
lines 55–56why, one step back55 /** @type {boolean | string} */56 this._showHelpAfterError = false;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 57why, one step back57 this._showSuggestionAfterError = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 58–81why, one step back5859 // see .configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),63 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,64 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,65 outputError: (str, write) => write(str)66 };6768 this._hidden = false;69 this._hasHelpOption = true;70 this._helpFlags = '-h, --help';71 this._helpDescription = 'display help for command';72 this._helpShortFlag = '-h';73 this._helpLongFlag = '--help';74 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false75 this._helpCommandName = 'help';76 this._helpCommandnameAndArgs = 'help [command]';77 this._helpCommandDescription = 'display help for command';78 this._helpConfiguration = {};79 }8081 /**Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 82–86why, one step back82 * Copy settings that are useful to have in common across root command and subcommands.83 *84 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)85 *86 * @param {Command} sourceCommandMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 87why, one step back87 * @return {Command} `this` command for chainingAdd copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 88–105why, one step back88 */89 copyInheritedSettings(sourceCommand) {90 this._outputConfiguration = sourceCommand._outputConfiguration;91 this._hasHelpOption = sourceCommand._hasHelpOption;92 this._helpFlags = sourceCommand._helpFlags;93 this._helpDescription = sourceCommand._helpDescription;94 this._helpShortFlag = sourceCommand._helpShortFlag;95 this._helpLongFlag = sourceCommand._helpLongFlag;96 this._helpCommandName = sourceCommand._helpCommandName;97 this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;98 this._helpCommandDescription = sourceCommand._helpCommandDescription;99 this._helpConfiguration = sourceCommand._helpConfiguration;100 this._exitCallback = sourceCommand._exitCallback;101 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;102 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;103 this._allowExcessArguments = sourceCommand._allowExcessArguments;104 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;105 this._showHelpAfterError = sourceCommand._showHelpAfterError;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 106why, one step back106 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 107–111why, one step back107108 return this;109 }110111 /**Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 112why, one step back112 * @returns {Command[]}Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 113why, one step back113 * @privateMerge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 114–124why, one step back114 */115116 _getCommandAndAncestors() {117 const result = [];118 for (let command = this; command; command = command.parent) {119 result.push(command);120 }121 return result;122 }123124 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 125–128why, one step back125 * Define a command.126 *127 * There are two styles of command: pay attention to where to put the description.128 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 129–136why, one step back129 * @example130 * // Command implemented using action handler (description is supplied separately to `.command`)131 * program132 * .command('clone <source> [destination]')133 * .description('clone a repository into a newly created directory')134 * .action((source, destination) => {135 * console.log('clone command called');136 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 137why, one step back137 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 138–141why, one step back138 * // Command implemented using separate executable file (description is second parameter to `.command`)139 * program140 * .command('start <service>', 'start named service')141 * .command('stop [service]', 'stop named service, or all if no name supplied');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 142–158why, one step back142 *143 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`144 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)145 * @param {Object} [execOpts] - configuration options (for executable)146 * @return {Command} returns new command for action handler, or `this` for executable command147 */148149 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {150 let desc = actionOptsOrExecDesc;151 let opts = execOpts;152 if (typeof desc === 'object' && desc !== null) {153 opts = desc;154 desc = null;155 }156 opts = opts || {};157 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);158Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
line 159why, one step back159 const cmd = this.createCommand(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 160–169why, one step back160 if (desc) {161 cmd.description(desc);162 cmd._executableHandler = true;163 }164 if (opts.isDefault) this._defaultCommandName = cmd._name;165 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden166 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor167 if (args) cmd.arguments(args);168 this.commands.push(cmd);169 cmd.parent = this;Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
line 170why, one step back170 cmd.copyInheritedSettings(this);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 171–173why, one step back171172 if (desc) return this;173 return cmd;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 174why, one step back174 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 175–187why, one step back175176 /**177 * Factory routine to create a new unattached command.178 *179 * See .command() for creating an attached subcommand, which uses this routine to180 * create the command. You can override createCommand to customise subcommands.181 *182 * @param {string} [name]183 * @return {Command} new command184 */185186 createCommand(name) {187 return new Command(name);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 188why, one step back188 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 189–198why, one step back189190 /**191 * You can customise the help with a subclass of Help by overriding createHelp,192 * or by overriding Help properties using configureHelp().193 *194 * @return {Help}195 */196197 createHelp() {198 return Object.assign(new Help(), this.configureHelp());Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 199why, one step back199 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 200–221why, one step back200201 /**202 * You can customise the help by overriding Help properties using configureHelp(),203 * or with a subclass of Help by overriding createHelp().204 *205 * @param {Object} [configuration] - configuration options206 * @return {Command|Object} `this` command for chaining, or stored configuration207 */208209 configureHelp(configuration) {210 if (configuration === undefined) return this._helpConfiguration;211212 this._helpConfiguration = configuration;213 return this;214 }215216 /**217 * The default output goes to stdout and stderr. You can customise this for special218 * applications. You can also customise the display of errors by overriding outputError.219 *220 * The configuration properties are all functions:221 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 222–229why, one step back222 * // functions to change where being written, stdout and stderr223 * writeOut(str)224 * writeErr(str)225 * // matching functions to specify width for wrapping help226 * getOutHelpWidth()227 * getErrHelpWidth()228 * // functions based on what is being written out229 * outputError(str, write) // used for displaying errors, and not used for displaying helpRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 230–242why, one step back230 *231 * @param {Object} [configuration] - configuration options232 * @return {Command|Object} `this` command for chaining, or stored configuration233 */234235 configureOutput(configuration) {236 if (configuration === undefined) return this._outputConfiguration;237238 Object.assign(this._outputConfiguration, configuration);239 return this;240 }241242 /**Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 243–254why, one step back243 * Display the help or a custom message after an error occurs.244 *245 * @param {boolean|string} [displayHelp]246 * @return {Command} `this` command for chaining247 */248 showHelpAfterError(displayHelp = true) {249 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;250 this._showHelpAfterError = displayHelp;251 return this;252 }253254 /**Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 255–265why, one step back255 * Display suggestion of similar commands for unknown commands, or options for unknown options.256 *257 * @param {boolean} [displaySuggestion]258 * @return {Command} `this` command for chaining259 */260 showSuggestionAfterError(displaySuggestion = true) {261 this._showSuggestionAfterError = !!displaySuggestion;262 return this;263 }264265 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 266–275why, one step back266 * Add a prepared subcommand.267 *268 * See .command() for creating an attached subcommand which inherits settings from its parent.269 *270 * @param {Command} cmd - new subcommand271 * @param {Object} [opts] - configuration options272 * @return {Command} `this` command for chaining273 */274275 addCommand(cmd, opts) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 276–278why, one step back276 if (!cmd._name) {277 throw new Error(`Command passed to .addCommand() must have a name278- specify the name in Command constructor or using .name()`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 279–286why, one step back279 }280281 opts = opts || {};282 if (opts.isDefault) this._defaultCommandName = cmd._name;283 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation284285 this.commands.push(cmd);286 cmd.parent = this;Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a
line 287why, one step back287 cmd._checkForBrokenPassThrough();Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4
line 288why, one step back288Refactor classes into files (#1522)John Geebefore adoption08245cc
line 289why, one step back289 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 290why, one step back290 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 291–304why, one step back291292 /**293 * Factory routine to create a new unattached argument.294 *295 * See .argument() for creating an attached argument, which uses this routine to296 * create the argument. You can override createArgument to return a custom argument.297 *298 * @param {string} name299 * @param {string} [description]300 * @return {Argument} new argument301 */302303 createArgument(name, description) {304 return new Argument(name, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 305why, one step back305 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 306–313why, one step back306307 /**308 * Define argument syntax for command.309 *310 * The default is that the argument is required, and you can explicitly311 * indicate this with <> around the name. Put [] around the name for an optional argument.312 *313 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 314–315why, one step back314 * program.argument('<input-file>');315 * program.argument('[output-file]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 316–339why, one step back316 *317 * @param {string} name318 * @param {string} [description]319 * @param {Function|*} [fn] - custom argument processing function320 * @param {*} [defaultValue]321 * @return {Command} `this` command for chaining322 */323 argument(name, description, fn, defaultValue) {324 const argument = this.createArgument(name, description);325 if (typeof fn === 'function') {326 argument.default(defaultValue).argParser(fn);327 } else {328 argument.default(fn);329 }330 this.addArgument(argument);331 return this;332 }333334 /**335 * Define argument syntax for command, adding multiple at once (without descriptions).336 *337 * See also .argument().338 *339 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 340why, one step back340 * program.arguments('<cmd> [env]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 341–346why, one step back341 *342 * @param {string} names343 * @return {Command} `this` command for chaining344 */345346 arguments(names) {trim() input string of .arguments methodАлександр Шмелевbefore adoption2f07c2a
line 347why, one step back347 names.trim().split(/ +/).forEach((detail) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 348–350why, one step back348 this.argument(detail);349 });350 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 351why, one step back351 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 352–359why, one step back352353 /**354 * Define argument syntax for command, adding a prepared argument.355 *356 * @param {Argument} argument357 * @return {Command} `this` command for chaining358 */359 addArgument(argument) {Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 360why, one step back360 const previousArgument = this.registeredArguments.slice(-1)[0];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 361–366why, one step back361 if (previousArgument && previousArgument.variadic) {362 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);363 }364 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {365 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);366 }Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 367why, one step back367 this.registeredArguments.push(argument);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 368–392why, one step back368 return this;369 }370371 /**372 * Override default decision whether to add implicit help command.373 *374 * addHelpCommand() // force on375 * addHelpCommand(false); // force off376 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details377 *378 * @return {Command} `this` command for chaining379 */380381 addHelpCommand(enableOrNameAndArgs, description) {382 if (enableOrNameAndArgs === false) {383 this._addImplicitHelpCommand = false;384 } else {385 this._addImplicitHelpCommand = true;386 if (typeof enableOrNameAndArgs === 'string') {387 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];388 this._helpCommandnameAndArgs = enableOrNameAndArgs;389 }390 this._helpCommandDescription = description || this._helpCommandDescription;391 }392 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 393why, one step back393 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 394–396why, one step back394395 /**396 * @return {boolean}Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 397why, one step back397 * @package internal use onlyRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 398–404why, one step back398 */399400 _hasImplicitHelpCommand() {401 if (this._addImplicitHelpCommand === undefined) {402 return this.commands.length && !this._actionHandler && !this._findCommand('help');403 }404 return this._addImplicitHelpCommand;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 405why, one step back405 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 406–415why, one step back406407 /**408 * Add hook for life cycle event.409 *410 * @param {string} event411 * @param {Function} listener412 * @return {Command} `this` command for chaining413 */414415 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 416why, one step back416 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 417–448why, one step back417 if (!allowedValues.includes(event)) {418 throw new Error(`Unexpected value for event passed to hook : '${event}'.419Expecting one of '${allowedValues.join("', '")}'`);420 }421 if (this._lifeCycleHooks[event]) {422 this._lifeCycleHooks[event].push(listener);423 } else {424 this._lifeCycleHooks[event] = [listener];425 }426 return this;427 }428429 /**430 * Register callback to use as replacement for calling process.exit.431 *432 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing433 * @return {Command} `this` command for chaining434 */435436 exitOverride(fn) {437 if (fn) {438 this._exitCallback = fn;439 } else {440 this._exitCallback = (err) => {441 if (err.code !== 'commander.executeSubCommandAsync') {442 throw err;443 } else {444 // Async callback from spawn events, not useful to throw.445 }446 };447 }448 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 449why, one step back449 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 450–457why, one step back450451 /**452 * Call process.exit, and _exitCallback if defined.453 *454 * @param {number} exitCode exit code for using with process.exit455 * @param {string} code an id string representing the error456 * @param {string} message human-readable description of the error457 * @return neverSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 458why, one step back458 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 459–466why, one step back459 */460461 _exit(exitCode, code, message) {462 if (this._exitCallback) {463 this._exitCallback(new CommanderError(exitCode, code, message));464 // Expecting this line is not reached.465 }466 process.exit(exitCode);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 467why, one step back467 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 468–471why, one step back468469 /**470 * Register callback `fn` for the command.471 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 472–473why, one step back472 * @example473 * programChange .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
lines 474–475why, one step back474 * .command('serve')475 * .description('start service')Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 476why, one step back476 * .action(function() {Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
line 477why, one step back477 * // do work hereFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 478why, one step back478 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 479–486why, one step back479 *480 * @param {Function} fn481 * @return {Command} `this` command for chaining482 */483484 action(fn) {485 const listener = (args) => {486 // The .action callback takes an extra parameter which is the command or options.Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 487why, one step back487 const expectedArgsCount = this.registeredArguments.length;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 488–499why, one step back488 const actionArgs = args.slice(0, expectedArgsCount);489 if (this._storeOptionsAsProperties) {490 actionArgs[expectedArgsCount] = this; // backwards compatible "options"491 } else {492 actionArgs[expectedArgsCount] = this.opts();493 }494 actionArgs.push(this);495496 return fn.apply(this, actionArgs);497 };498 this._actionHandler = listener;499 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 500why, one step back500 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 501–514why, one step back501502 /**503 * Factory routine to create a new unattached option.504 *505 * See .option() for creating an attached option, which uses this routine to506 * create the option. You can override createOption to return a custom option.507 *508 * @param {string} flags509 * @param {string} [description]510 * @return {Option} new option511 */512513 createOption(flags, description) {514 return new Option(flags, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 515why, one step back515 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 516–517why, one step back516517 /**Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
lines 518–521why, one step back518 * Wrap parseArgs to catch 'commander.invalidArgument'.519 *520 * @param {Option | Argument} target521 * @param {string} valueMerge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 522why, one step back522 * @param {*} previousMerge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 523why, one step back523 * @param {string} invalidArgumentMessageSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 524why, one step back524 * @privateMerge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
lines 525–537why, one step back525 */526527 _callParseArg(target, value, previous, invalidArgumentMessage) {528 try {529 return target.parseArg(value, previous);530 } catch (err) {531 if (err.code === 'commander.invalidArgument') {532 const message = `${invalidArgumentMessage} ${err.message}`;533 this.error(message, { exitCode: err.exitCode, code: err.code });534 }535 throw err;536 }537 }Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40
lines 538–545why, one step back538 /**539 * Check for option flag conflicts.540 * Register option if no conflicts found.541 * Throw otherwise.542 *543 * @param {Option} option544 * @api private545 */Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 546why, one step back546Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40
lines 547–557why, one step back547 _registerOption(option) {548 const matchingOption = (option.short && this._findOption(option.short)) ||549 (option.long && this._findOption(option.long));550 if (matchingOption) {551 const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;552 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'553- already used by option '${matchingOption.flags}'`);554 }555 this.options.push(option);556 }557Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 558why, one step back558 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 559–564why, one step back559 * Add an option.560 *561 * @param {Option} option562 * @return {Command} `this` command for chaining563 */564 addOption(option) {Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40
lines 565–566why, one step back565 this._registerOption(option);566Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 567–569why, one step back567 const oname = option.name();568 const name = option.attributeName();569Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 570–575why, one step back570 // store default value571 if (option.negate) {572 // --no-foo is special and defaults foo to true, unless a --foo option is already defined573 const positiveLongFlag = option.long.replace(/^--no-/, '--');574 if (!this._findOption(positiveLongFlag)) {575 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 576why, one step back576 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 577–578why, one step back577 } else if (option.defaultValue !== undefined) {578 this.setOptionValueWithSource(name, option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 579–580why, one step back579 }580Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 581–582why, one step back581 // handler for cli and env supplied values582 const handleOptionValue = (val, invalidValueMessage, valueSource) => {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 583–587why, one step back583 // val is null for optional option used without an optional-argument.584 // val is undefined for boolean and negated option.585 if (val == null && option.presetArg !== undefined) {586 val = option.presetArg;587 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 588–589why, one step back588589 // custom processingMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 590why, one step back590 const oldValue = this.getOptionValue(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 591why, one step back591 if (val !== null && option.parseArg) {Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 592why, one step back592 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 593–596why, one step back593 } else if (val !== null && option.variadic) {594 val = option._concatValue(val, oldValue);595 }596Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 597–602why, one step back597 // Fill-in appropriate missing values. Long winded but easy to follow.598 if (val == null) {599 if (option.negate) {600 val = false;601 } else if (option.isBoolean() || option.optional) {602 val = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 603why, one step back603 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 604why, one step back604 val = ''; // not normal, parseArg might have failed or be a mock function for testingRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 605–606why, one step back605 }606 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 607why, one step back607 this.setOptionValueWithSource(name, val, valueSource);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 608–612why, one step back608 };609610 this.on('option:' + oname, (val) => {611 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;612 handleOptionValue(val, invalidValueMessage, 'cli');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 613–614why, one step back613 });614Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 615–621why, one step back615 if (option.envVar) {616 this.on('optionEnv:' + oname, (val) => {617 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;618 handleOptionValue(val, invalidValueMessage, 'env');619 });620 }621Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 622–627why, one step back622 return this;623 }624625 /**626 * Internal implementation shared by .option() and .requiredOption()627 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 628why, one step back628 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 629–630why, one step back629 */630 _optionEx(config, flags, description, fn, defaultValue) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 631–633why, one step back631 if (typeof flags === 'object' && flags instanceof Option) {632 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');633 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 634–653why, one step back634 const option = this.createOption(flags, description);635 option.makeOptionMandatory(!!config.mandatory);636 if (typeof fn === 'function') {637 option.default(defaultValue).argParser(fn);638 } else if (fn instanceof RegExp) {639 // deprecated640 const regex = fn;641 fn = (val, def) => {642 const m = regex.exec(val);643 return m ? m[0] : def;644 };645 option.default(defaultValue).argParser(fn);646 } else {647 option.default(fn);648 }649650 return this.addOption(option);651 }652653 /**Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 654why, one step back654 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 655why, one step back655 *Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
lines 656–657why, one step back656 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required657 * option-argument is indicated by `<>` and an optional option-argument by `[]`.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 658why, one step back658 *Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 659why, one step back659 * See the README for more details, and see also addOption() and requiredOption().Refactor classes into files (#1522)John Geebefore adoption08245cc
line 660why, one step back660 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 661why, one step back661 * @exampleMerge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
lines 662–666why, one step back662 * program663 * .option('-p, --pepper', 'add pepper')664 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument665 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default666 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse functionRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 667–669why, one step back667 *668 * @param {string} flags669 * @param {string} [description]Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 670why, one step back670 * @param {Function|*} [parseArg] - custom option processing function or default valueRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 671–674why, one step back671 * @param {*} [defaultValue]672 * @return {Command} `this` command for chaining673 */674Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
lines 675–676why, one step back675 option(flags, description, parseArg, defaultValue) {676 return this._optionEx({}, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 677why, one step back677 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 678–686why, one step back678679 /**680 * Add a required option which must have a value after parsing. This usually means681 * the option must be specified on the command line. (Otherwise the same as .option().)682 *683 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.684 *685 * @param {string} flags686 * @param {string} [description]Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 687why, one step back687 * @param {Function|*} [parseArg] - custom option processing function or default valueRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 688–691why, one step back688 * @param {*} [defaultValue]689 * @return {Command} `this` command for chaining690 */691Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
lines 692–693why, one step back692 requiredOption(flags, description, parseArg, defaultValue) {693 return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 694why, one step back694 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 695–698why, one step back695696 /**697 * Alter parsing of short flags with optional values.698 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 699–702why, one step back699 * @example700 * // for `.option('-f,--flag [value]'):701 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour702 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 703–708why, one step back703 *704 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.705 */706 combineFlagAndOptionalValue(combine = true) {707 this._combineFlagAndOptionalValue = !!combine;708 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 709why, one step back709 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 710–719why, one step back710711 /**712 * Allow unknown options on the command line.713 *714 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown715 * for unknown options.716 */717 allowUnknownOption(allowUnknown = true) {718 this._allowUnknownOption = !!allowUnknown;719 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 720why, one step back720 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 721–730why, one step back721722 /**723 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.724 *725 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown726 * for excess arguments.727 */728 allowExcessArguments(allowExcess = true) {729 this._allowExcessArguments = !!allowExcess;730 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 731why, one step back731 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 732–742why, one step back732733 /**734 * Enable positional options. Positional means global options are specified before subcommands which lets735 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.736 * The default behaviour is non-positional and global options may appear anywhere on the command line.737 *738 * @param {Boolean} [positional=true]739 */740 enablePositionalOptions(positional = true) {741 this._enablePositionalOptions = !!positional;742 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 743why, one step back743 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 744–755why, one step back744745 /**746 * Pass through options that come after command-arguments rather than treat them as command-options,747 * so actual command-options come before command-arguments. Turning this on for a subcommand requires748 * positional options to have been enabled on the program (parent commands).749 * The default behaviour is non-positional and options may appear before or after command-arguments.750 *751 * @param {Boolean} [passThrough=true]752 * for unknown options.753 */754 passThroughOptions(passThrough = true) {755 this._passThroughOptions = !!passThrough;Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a
line 756why, one step back756 this._checkForBrokenPassThrough();Refactor classes into files (#1522)John Geebefore adoption08245cc
line 757why, one step back757 return this;Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4
lines 758–760why, one step back758 }759760 /**Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 761why, one step back761 * @privateAdd missing checks for passThroughOptionsWee Bitbefore adoption681a7e4
lines 762–763why, one step back762 */763Refactor _checkForBrokenPassThrough() to make it instance-awareWee Bitbefore adoptionac8db3a
lines 764–766why, one step back764 _checkForBrokenPassThrough() {765 if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {766 throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);Add missing checks for passThroughOptionsWee Bitbefore adoption681a7e4
line 767why, one step back767 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 768why, one step back768 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 769–781why, one step back769770 /**771 * Whether to store option values as properties on command object,772 * or store separately (specify false). In both cases the option values can be accessed using .opts().773 *774 * @param {boolean} [storeAsProperties=true]775 * @return {Command} `this` command for chaining776 */777778 storeOptionsAsProperties(storeAsProperties = true) {779 if (this.options.length) {780 throw new Error('call .storeOptionsAsProperties() before adding options');781 }Restore extra sanity check when enabling storeOptionsAsProperties (#2029)John Geebefore adoptiond90c59c
lines 782–784why, one step back782 if (Object.keys(this._optionValues).length) {783 throw new Error('call .storeOptionsAsProperties() before setting option values');784 }Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 785why, one step back785 this._storeOptionsAsProperties = !!storeAsProperties;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 786why, one step back786 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 787why, one step back787 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 788–800why, one step back788789 /**790 * Retrieve option value.791 *792 * @param {string} key793 * @return {Object} value794 */795796 getOptionValue(key) {797 if (this._storeOptionsAsProperties) {798 return this[key];799 }800 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 801why, one step back801 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 802–811why, one step back802803 /**804 * Store option value.805 *806 * @param {string} key807 * @param {Object} value808 * @return {Command} `this` command for chaining809 */810811 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 812why, one step back812 return this.setOptionValueWithSource(key, value, undefined);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 813why, one step back813 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 814–815why, one step back814815 /**Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 816why, one step back816 * Store option value and where the value came from.Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 817–819why, one step back817 *818 * @param {string} key819 * @param {Object} valueAdd implied to option value sources (#1794)John Geebefore adoption72be61c
line 820why, one step back820 * @param {string} source - expected values are default/config/env/cli/impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 821–824why, one step back821 * @return {Command} `this` command for chaining822 */823824 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 825–829why, one step back825 if (this._storeOptionsAsProperties) {826 this[key] = value;827 } else {828 this._optionValues[key] = value;829 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 830why, one step back830 this._optionValueSources[key] = source;Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 831why, one step back831 return this;Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 832–834why, one step back832 }833834 /**Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 835why, one step back835 * Get source of option value.Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 836why, one step back836 * Expected values are default | config | env | cli | impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 837–843why, one step back837 *838 * @param {string} key839 * @return {string}840 */841842 getOptionValueSource(key) {843 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 844why, one step back844 }Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 845–846why, one step back845846 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 847–856why, one step back847 * Get source of option value. See also .optsWithGlobals().848 * Expected values are default | config | env | cli | implied849 *850 * @param {string} key851 * @return {string}852 */853854 getOptionValueSourceWithGlobals(key) {855 // global overwrites local, like optsWithGlobals856 let source;Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 857why, one step back857 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 858–865why, one step back858 if (cmd.getOptionValueSource(key) !== undefined) {859 source = cmd.getOptionValueSource(key);860 }861 });862 return source;863 }864865 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 866–867why, one step back866 * Get user arguments from implied or explicit arguments.867 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 868why, one step back868 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 869why, one step back869 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 870–911why, one step back870 */871872 _prepareUserArgs(argv, parseOptions) {873 if (argv !== undefined && !Array.isArray(argv)) {874 throw new Error('first parameter to parse must be array or undefined');875 }876 parseOptions = parseOptions || {};877878 // Default to using process.argv879 if (argv === undefined) {880 argv = process.argv;881 // @ts-ignore: unknown property882 if (process.versions && process.versions.electron) {883 parseOptions.from = 'electron';884 }885 }886 this.rawArgs = argv.slice();887888 // make it a little easier for callers by supporting various argv conventions889 let userArgs;890 switch (parseOptions.from) {891 case undefined:892 case 'node':893 this._scriptPath = argv[1];894 userArgs = argv.slice(2);895 break;896 case 'electron':897 // @ts-ignore: unknown property898 if (process.defaultApp) {899 this._scriptPath = argv[1];900 userArgs = argv.slice(2);901 } else {902 userArgs = argv.slice(1);903 }904 break;905 case 'user':906 userArgs = argv.slice(0);907 break;908 default:909 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);910 }911Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 912–914why, one step back912 // Find default name for program from arguments.913 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);914 this._name = this._name || 'program';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 915–924why, one step back915916 return userArgs;917 }918919 /**920 * Parse `argv`, setting options and invoking commands when defined.921 *922 * The default expectation is that the arguments are from node and have the application as argv[0]923 * and the script being run in argv[1], with user parameters after that.924 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 925–928why, one step back925 * @example926 * program.parse(process.argv);927 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions928 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 929–940why, one step back929 *930 * @param {string[]} [argv] - optional, defaults to process.argv931 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron932 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'933 * @return {Command} `this` command for chaining934 */935936 parse(argv, parseOptions) {937 const userArgs = this._prepareUserArgs(argv, parseOptions);938 this._parseCommand([], userArgs);939940 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 941why, one step back941 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 942–950why, one step back942943 /**944 * Parse `argv`, setting options and invoking commands when defined.945 *946 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.947 *948 * The default expectation is that the arguments are from node and have the application as argv[0]949 * and the script being run in argv[1], with user parameters after that.950 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 951–954why, one step back951 * @example952 * await program.parseAsync(process.argv);953 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions954 * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 955–966why, one step back955 *956 * @param {string[]} [argv]957 * @param {Object} [parseOptions]958 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'959 * @return {Promise}960 */961962 async parseAsync(argv, parseOptions) {963 const userArgs = this._prepareUserArgs(argv, parseOptions);964 await this._parseCommand([], userArgs);965966 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 967why, one step back967 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 968–971why, one step back968969 /**970 * Execute a sub-command executable.971 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 972why, one step back972 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 973–979why, one step back973 */974975 _executeSubCommand(subcommand, args) {976 args = args.slice();977 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.978 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];979Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 980–983why, one step back980 function findFile(baseDir, baseName) {981 // Look for specified file982 const localBin = path.resolve(baseDir, baseName);983 if (fs.existsSync(localBin)) return localBin;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 984why, one step back984Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 985–986why, one step back985 // Stop looking if candidate already has an expected extension.986 if (sourceExt.includes(path.extname(baseName))) return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 987why, one step back987Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 988–992why, one step back988 // Try all the extensions.989 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));990 if (foundExt) return `${localBin}${foundExt}`;991992 return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 993–994why, one step back993 }994Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 995–996why, one step back995 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.996 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 997why, one step back997 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 998–1009why, one step back998999 // executableFile and executableDir might be full path, or just a name1000 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;1001 let executableDir = this._executableDir || '';1002 if (this._scriptPath) {1003 let resolvedScriptPath; // resolve possible symlink for installed npm binary1004 try {1005 resolvedScriptPath = fs.realpathSync(this._scriptPath);1006 } catch (err) {1007 resolvedScriptPath = this._scriptPath;1008 }1009 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1010–1011why, one step back1010 }1011Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1012–1020why, one step back1012 // Look for a local file in preference to a command in PATH.1013 if (executableDir) {1014 let localFile = findFile(executableDir, executableFile);10151016 // Legacy search using prefix of script name instead of command name1017 if (!localFile && !subcommand._executableFile && this._scriptPath) {1018 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));1019 if (legacyName !== this._name) {1020 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1021why, one step back1021 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1022–1023why, one step back1022 }1023 executableFile = localFile || executableFile;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1024–1025why, one step back1024 }1025Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1026–1027why, one step back1026 launchWithNode = sourceExt.includes(path.extname(executableFile));1027Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1028–1030why, one step back1028 let proc;1029 if (process.platform !== 'win32') {1030 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1031why, one step back1031 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1032–1036why, one step back1032 // add executable arguments to spawn1033 args = incrementNodeInspectorPort(process.execArgv).concat(args);10341035 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1036 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1037why, one step back1037 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1038–1039why, one step back1038 }1039 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1040why, one step back1040 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1041–1045why, one step back1041 // add executable arguments to spawn1042 args = incrementNodeInspectorPort(process.execArgv).concat(args);1043 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1044 }1045Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1046–1054why, one step back1046 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1047 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1048 signals.forEach((signal) => {1049 // @ts-ignore1050 process.on(signal, () => {1051 if (proc.killed === false && proc.exitCode === null) {1052 proc.kill(signal);1053 }1054 });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1055why, one step back1055 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1056why, one step back1056 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1057–1059why, one step back10571058 // By default terminate process when spawned process terminates.1059 const exitCallback = this._exitCallback;Exit with non-zero code when subprocess terminated by signal (#2023)John Geebefore adoption5aaca0d
lines 1060–1067why, one step back1060 proc.on('close', (code, _signal) => {1061 code = code ?? 1; // code is null if spawned process terminated due to a signal1062 if (!exitCallback) {1063 process.exit(code);1064 } else {1065 exitCallback(new CommanderError(code, 'commander.executeSubCommandAsync', '(close)'));1066 }1067 });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1068–1070why, one step back1068 proc.on('error', (err) => {1069 // @ts-ignore1070 if (err.code === 'ENOENT') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1071–1074why, one step back1071 const executableDirMessage = executableDir1072 ? `searched for local subcommand relative to directory '${executableDir}'`1073 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1074 const executableMissing = `'${executableFile}' does not existRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1075why, one step back1075 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' insteadMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1076–1077why, one step back1076 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1077 - ${executableDirMessage}`;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1078–1080why, one step back1078 throw new Error(executableMissing);1079 // @ts-ignore1080 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1081why, one step back1081 throw new Error(`'${executableFile}' not executable`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1082–1093why, one step back1082 }1083 if (!exitCallback) {1084 process.exit(1);1085 } else {1086 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1087 wrappedError.nestedError = err;1088 exitCallback(wrappedError);1089 }1090 });10911092 // Store the reference to the child process1093 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1094why, one step back1094 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1095–1096why, one step back10951096 /**Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1097why, one step back1097 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1098–1103why, one step back1098 */10991100 _dispatchSubcommand(commandName, operands, unknown) {1101 const subCommand = this._findCommand(commandName);1102 if (!subCommand) this.help({ error: true });1103Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1104–1106why, one step back1104 let promiseChain;1105 promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');1106 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1107–1112why, one step back1107 if (subCommand._executableHandler) {1108 this._executeSubCommand(subCommand, operands.concat(unknown));1109 } else {1110 return subCommand._parseCommand(operands, unknown);1111 }1112 });Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1113why, one step back1113 return promiseChain;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1114why, one step back1114 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1115–1116why, one step back11151116 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1117–1119why, one step back1117 * Invoke help directly if possible, or dispatch if necessary.1118 * e.g. help foo1119 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1120why, one step back1120 * @privateHave help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1121–1132why, one step back1121 */11221123 _dispatchHelpCommand(subcommandName) {1124 if (!subcommandName) {1125 this.help();1126 }1127 const subCommand = this._findCommand(subcommandName);1128 if (subCommand && !subCommand._executableHandler) {1129 subCommand.help();1130 }11311132 // Fallback to parsing the help flag to invoke the help.Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1133–1135why, one step back1133 return this._dispatchSubcommand(subcommandName, [], [1134 this._helpLongFlag || this._helpShortFlag1135 ]);Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1136–1138why, one step back1136 }11371138 /**Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1139why, one step back1139 * Check this.args against expected this.registeredArguments.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1140why, one step back1140 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1141why, one step back1141 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1142–1143why, one step back1142 */1143Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1144–1145why, one step back1144 _checkNumberOfArguments() {1145 // too fewMerge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1146why, one step back1146 this.registeredArguments.forEach((arg, i) => {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1147–1151why, one step back1147 if (arg.required && this.args[i] == null) {1148 this.missingArgument(arg.name());1149 }1150 });1151 // too manyMerge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1152why, one step back1152 if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1153–1154why, one step back1153 return;1154 }Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1155why, one step back1155 if (this.args.length > this.registeredArguments.length) {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1156–1157why, one step back1156 this._excessArguments(this.args);1157 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1158why, one step back1158 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1159–1160why, one step back11591160 /**Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1161why, one step back1161 * Process this.args using this.registeredArguments and save as this.processedArgs!Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1162why, one step back1162 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1163why, one step back1163 * @privateSupport argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1164–1166why, one step back1164 */11651166 _processArguments() {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1167–1170why, one step back1167 const myParseArg = (argument, value, previous) => {1168 // Extra processing for nice error message on parsing failure.1169 let parsedValue = value;1170 if (value !== null && argument.parseArg) {Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
lines 1171–1172why, one step back1171 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1172 parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1173–1176why, one step back1173 }1174 return parsedValue;1175 };1176Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1177–1179why, one step back1177 this._checkNumberOfArguments();11781179 const processedArgs = [];Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1180why, one step back1180 this.registeredArguments.forEach((declaredArg, index) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1181–1199why, one step back1181 let value = declaredArg.defaultValue;1182 if (declaredArg.variadic) {1183 // Collect together remaining arguments for passing together as an array.1184 if (index < this.args.length) {1185 value = this.args.slice(index);1186 if (declaredArg.parseArg) {1187 value = value.reduce((processed, v) => {1188 return myParseArg(declaredArg, v, processed);1189 }, declaredArg.defaultValue);1190 }1191 } else if (value === undefined) {1192 value = [];1193 }1194 } else if (index < this.args.length) {1195 value = this.args[index];1196 if (declaredArg.parseArg) {1197 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1198 }1199 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1200why, one step back1200 processedArgs[index] = value;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1201why, one step back1201 });Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1202why, one step back1202 this.processedArgs = processedArgs;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1203–1210why, one step back1203 }12041205 /**1206 * Once we have a promise we chain, but call synchronously until then.1207 *1208 * @param {Promise|undefined} promise1209 * @param {Function} fn1210 * @return {Promise|undefined}Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1211why, one step back1211 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1212–1228why, one step back1212 */12131214 _chainOrCall(promise, fn) {1215 // thenable1216 if (promise && promise.then && typeof promise.then === 'function') {1217 // already have a promise, chain callback1218 return promise.then(() => fn());1219 }1220 // callback might return a promise1221 return fn();1222 }12231224 /**1225 *1226 * @param {Promise|undefined} promise1227 * @param {string} event1228 * @return {Promise|undefined}Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1229why, one step back1229 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1230–1234why, one step back1230 */12311232 _chainOrCallHooks(promise, event) {1233 let result = promise;1234 const hooks = [];Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1235why, one step back1235 this._getCommandAndAncestors()Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1236–1251why, one step back1236 .reverse()1237 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1238 .forEach(hookedCommand => {1239 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1240 hooks.push({ hookedCommand, callback });1241 });1242 });1243 if (event === 'postAction') {1244 hooks.reverse();1245 }12461247 hooks.forEach((hookDetail) => {1248 result = this._chainOrCall(result, () => {1249 return hookDetail.callback(hookDetail.hookedCommand, this);1250 });1251 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1252–1260why, one step back1252 return result;1253 }12541255 /**1256 *1257 * @param {Promise|undefined} promise1258 * @param {Command} subCommand1259 * @param {string} event1260 * @return {Promise|undefined}Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1261why, one step back1261 * @privatefeat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1262–1272why, one step back1262 */12631264 _chainOrCallSubCommandHook(promise, subCommand, event) {1265 let result = promise;1266 if (this._lifeCycleHooks[event] !== undefined) {1267 this._lifeCycleHooks[event].forEach((hook) => {1268 result = this._chainOrCall(result, () => {1269 return hook(this, subCommand);1270 });1271 });1272 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1273–1279why, one step back1273 return result;1274 }12751276 /**1277 * Process arguments in context of this command.1278 * Returns action result, in case it is a promise.1279 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1280why, one step back1280 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1281–1284why, one step back1281 */12821283 _parseCommand(operands, unknown) {1284 const parsed = this.parseOptions(unknown);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 1285why, one step back1285 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1286why, one step back1286 this._parseOptionsImplied();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1287–1294why, one step back1287 operands = operands.concat(parsed.operands);1288 unknown = parsed.unknown;1289 this.args = operands.concat(unknown);12901291 if (operands && this._findCommand(operands[0])) {1292 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1293 }1294 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1295why, one step back1295 return this._dispatchHelpCommand(operands[1]);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1296–1297why, one step back1296 }1297 if (this._defaultCommandName) {Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1298why, one step back1298 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default commandRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1299–1305why, one step back1299 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1300 }1301 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1302 // probably missing subcommand and no handler, user needs help (and exit)1303 this.help({ error: true });1304 }1305Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1306why, one step back1306 this._outputHelpIfRequested(parsed.unknown);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1307why, one step back1307 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1308why, one step back1308 this._checkForConflictingOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1309–1319why, one step back13091310 // We do not always call this check to avoid masking a "better" error, like unknown command.1311 const checkForUnknownOptions = () => {1312 if (parsed.unknown.length > 0) {1313 this.unknownOption(parsed.unknown[0]);1314 }1315 };13161317 const commandEvent = `command:${this.name()}`;1318 if (this._actionHandler) {1319 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1320why, one step back1320 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1321why, one step back1321Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1322–1324why, one step back1322 let promiseChain;1323 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1324 promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
line 1325why, one step back1325 if (this.parent) {Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1326why, one step back1326 promiseChain = this._chainOrCall(promiseChain, () => {Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1327–1329why, one step back1327 this.parent.emit(commandEvent, operands, unknown); // legacy1328 });1329 }Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
lines 1330–1331why, one step back1330 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1331 return promiseChain;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1332–1334why, one step back1332 }1333 if (this.parent && this.parent.listenerCount(commandEvent)) {1334 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1335why, one step back1335 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1336–1347why, one step back1336 this.parent.emit(commandEvent, operands, unknown); // legacy1337 } else if (operands.length) {1338 if (this._findCommand('*')) { // legacy default command1339 return this._dispatchSubcommand('*', operands, unknown);1340 }1341 if (this.listenerCount('command:*')) {1342 // skip option check, emit event for possible misspelling suggestion1343 this.emit('command:*', operands, unknown);1344 } else if (this.commands.length) {1345 this.unknownCommand();1346 } else {1347 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1348why, one step back1348 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1349–1350why, one step back1349 }1350 } else if (this.commands.length) {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 1351why, one step back1351 checkForUnknownOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1352–1355why, one step back1352 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1353 this.help({ error: true });1354 } else {1355 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1356why, one step back1356 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1357–1358why, one step back1357 // fall through for caller to handle after calling .parse()1358 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1359why, one step back1359 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1360–1363why, one step back13601361 /**1362 * Find matching command.1363 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1364why, one step back1364 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1365–1368why, one step back1365 */1366 _findCommand(name) {1367 if (!name) return undefined;1368 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1369why, one step back1369 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1370–1375why, one step back13701371 /**1372 * Return an option matching `arg` if any.1373 *1374 * @param {string} arg1375 * @return {Option}Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1376why, one step back1376 * @package internal use onlyRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1377–1380why, one step back1377 */13781379 _findOption(arg) {1380 return this.options.find(option => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1381why, one step back1381 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1382–1384why, one step back13821383 /**1384 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1385why, one step back1385 * Called after checking for help flags in leaf subcommand.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1386why, one step back1386 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1387why, one step back1387 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1388–1391why, one step back1388 */13891390 _checkForMissingMandatoryOptions() {1391 // Walk up hierarchy so can call in subcommand after checking for displaying help.Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1392why, one step back1392 this._getCommandAndAncestors().forEach((cmd) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1393–1397why, one step back1393 cmd.options.forEach((anOption) => {1394 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1395 cmd.missingMandatoryOptionValue(anOption);1396 }1397 });Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1398why, one step back1398 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1399why, one step back1399 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1400–1401why, one step back14001401 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1402why, one step back1402 * Display an error message if conflicting options are used together in this.feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1403why, one step back1403 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1404why, one step back1404 * @privatefeat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1405why, one step back1405 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1406why, one step back1406 _checkForConflictingLocalOptions() {feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1407–1428why, one step back1407 const definedNonDefaultOptions = this.options.filter(1408 (option) => {1409 const optionKey = option.attributeName();1410 if (this.getOptionValue(optionKey) === undefined) {1411 return false;1412 }1413 return this.getOptionValueSource(optionKey) !== 'default';1414 }1415 );14161417 const optionsWithConflicting = definedNonDefaultOptions.filter(1418 (option) => option.conflictsWith.length > 01419 );14201421 optionsWithConflicting.forEach((option) => {1422 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1423 option.conflictsWith.includes(defined.attributeName())1424 );1425 if (conflictingAndDefined) {1426 this._conflictingOption(option, conflictingAndDefined);1427 }1428 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1429–1434why, one step back1429 }14301431 /**1432 * Display an error message if conflicting options are used together.1433 * Called after checking for help flags in leaf subcommand.1434 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1435why, one step back1435 * @privateCheck for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1436–1438why, one step back1436 */1437 _checkForConflictingOptions() {1438 // Walk up hierarchy so can call in subcommand after checking for displaying help.Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1439why, one step back1439 this._getCommandAndAncestors().forEach((cmd) => {Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1440why, one step back1440 cmd._checkForConflictingLocalOptions();Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1441why, one step back1441 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1442–1444why, one step back1442 }14431444 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1445–1449why, one step back1445 * Parse options from `argv` removing known options,1446 * and return argv split into operands and unknown arguments.1447 *1448 * Examples:1449 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 1450–1454why, one step back1450 * argv => operands, unknown1451 * --known kkk op => [op], []1452 * op --known kkk => [op], []1453 * sub --unknown uuu op => [sub], [--unknown uuu op]1454 * sub -- --unknown uuu op => [sub --unknown uuu op], []Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1455–1573why, one step back1455 *1456 * @param {String[]} argv1457 * @return {{operands: String[], unknown: String[]}}1458 */14591460 parseOptions(argv) {1461 const operands = []; // operands, not options or values1462 const unknown = []; // first unknown option and remaining unknown args1463 let dest = operands;1464 const args = argv.slice();14651466 function maybeOption(arg) {1467 return arg.length > 1 && arg[0] === '-';1468 }14691470 // parse options1471 let activeVariadicOption = null;1472 while (args.length) {1473 const arg = args.shift();14741475 // literal1476 if (arg === '--') {1477 if (dest === unknown) dest.push(arg);1478 dest.push(...args);1479 break;1480 }14811482 if (activeVariadicOption && !maybeOption(arg)) {1483 this.emit(`option:${activeVariadicOption.name()}`, arg);1484 continue;1485 }1486 activeVariadicOption = null;14871488 if (maybeOption(arg)) {1489 const option = this._findOption(arg);1490 // recognised option, call listener to assign value with possible custom processing1491 if (option) {1492 if (option.required) {1493 const value = args.shift();1494 if (value === undefined) this.optionMissingArgument(option);1495 this.emit(`option:${option.name()}`, value);1496 } else if (option.optional) {1497 let value = null;1498 // historical behaviour is optional value is following arg unless an option1499 if (args.length > 0 && !maybeOption(args[0])) {1500 value = args.shift();1501 }1502 this.emit(`option:${option.name()}`, value);1503 } else { // boolean flag1504 this.emit(`option:${option.name()}`);1505 }1506 activeVariadicOption = option.variadic ? option : null;1507 continue;1508 }1509 }15101511 // Look for combo options following single dash, eat first one if known.1512 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1513 const option = this._findOption(`-${arg[1]}`);1514 if (option) {1515 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1516 // option with value following in same argument1517 this.emit(`option:${option.name()}`, arg.slice(2));1518 } else {1519 // boolean option, emit and put back remainder of arg for further processing1520 this.emit(`option:${option.name()}`);1521 args.unshift(`-${arg.slice(2)}`);1522 }1523 continue;1524 }1525 }15261527 // Look for known long flag with value, like --foo=bar1528 if (/^--[^=]+=/.test(arg)) {1529 const index = arg.indexOf('=');1530 const option = this._findOption(arg.slice(0, index));1531 if (option && (option.required || option.optional)) {1532 this.emit(`option:${option.name()}`, arg.slice(index + 1));1533 continue;1534 }1535 }15361537 // Not a recognised option by this command.1538 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15391540 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1541 if (maybeOption(arg)) {1542 dest = unknown;1543 }15441545 // If using positionalOptions, stop processing our options at subcommand.1546 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1547 if (this._findCommand(arg)) {1548 operands.push(arg);1549 if (args.length > 0) unknown.push(...args);1550 break;1551 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1552 operands.push(arg);1553 if (args.length > 0) operands.push(...args);1554 break;1555 } else if (this._defaultCommandName) {1556 unknown.push(arg);1557 if (args.length > 0) unknown.push(...args);1558 break;1559 }1560 }15611562 // If using passThroughOptions, stop processing options at first command-argument.1563 if (this._passThroughOptions) {1564 dest.push(arg);1565 if (args.length > 0) dest.push(...args);1566 break;1567 }15681569 // add arg1570 dest.push(arg);1571 }15721573 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1574why, one step back1574 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1575–1576why, one step back15751576 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1577why, one step back1577 * Return an object containing local option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1578–1594why, one step back1578 *1579 * @return {Object}1580 */1581 opts() {1582 if (this._storeOptionsAsProperties) {1583 // Preserve original behaviour so backwards compatible when still using properties1584 const result = {};1585 const len = this.options.length;15861587 for (let i = 0; i < len; i++) {1588 const key = this.options[i].attributeName();1589 result[key] = key === this._versionOptionName ? this._version : this[key];1590 }1591 return result;1592 }15931594 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1595why, one step back1595 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1596–1597why, one step back15961597 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1598why, one step back1598 * Return an object containing merged local and global option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1599why, one step back1599 *Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1600why, one step back1600 * @return {Object}Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1601why, one step back1601 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1602–1603why, one step back1602 optsWithGlobals() {1603 // globals overwrite localsMerge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1604why, one step back1604 return this._getCommandAndAncestors().reduce(Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1605–1619why, one step back1605 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1606 {}1607 );1608 }16091610 /**1611 * Display error message and exit (or call exitOverride).1612 *1613 * @param {string} message1614 * @param {Object} [errorOptions]1615 * @param {string} [errorOptions.code] - an id string representing the error1616 * @param {number} [errorOptions.exitCode] - used with process.exit1617 */1618 error(message, errorOptions) {1619 // output handlingRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1620why, one step back1620 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 1621–1626why, one step back1621 if (typeof this._showHelpAfterError === 'string') {1622 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1623 } else if (this._showHelpAfterError) {1624 this._outputConfiguration.writeErr('\n');1625 this.outputHelp({ error: true });1626 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1627–1631why, one step back16271628 // exit handling1629 const config = errorOptions || {};1630 const exitCode = config.exitCode || 1;1631 const code = config.code || 'commander.error';Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1632why, one step back1632 this._exit(exitCode, code, message);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1633–1638why, one step back1633 }16341635 /**1636 * Apply any option related environment variables, if option does1637 * not have a value from cli or client code.1638 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1639why, one step back1639 * @privateAdd .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1640–1644why, one step back1640 */1641 _parseOptionsEnv() {1642 this.options.forEach((option) => {1643 if (option.envVar && option.envVar in process.env) {1644 const optionKey = option.attributeName();Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 1645–1646why, one step back1645 // Priority check. Do not overwrite cli or options from unknown source (client-code).1646 if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1647–1656why, one step back1647 if (option.required || option.optional) { // option can take a value1648 // keep very simple, optional always takes value1649 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1650 } else { // boolean1651 // keep very simple, only care that envVar defined and not the value1652 this.emit(`optionEnv:${option.name()}`);1653 }1654 }1655 }1656 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1657–1661why, one step back1657 }16581659 /**1660 * Apply any implied option values, if option is undefined or default value.1661 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1662why, one step back1662 * @privateAdd Option.implies() (#1724)John Geebefore adoptiond660967
lines 1663–1679why, one step back1663 */1664 _parseOptionsImplied() {1665 const dualHelper = new DualOptions(this.options);1666 const hasCustomOptionValue = (optionKey) => {1667 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1668 };1669 this.options1670 .filter(option => (option.implied !== undefined) &&1671 hasCustomOptionValue(option.attributeName()) &&1672 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1673 .forEach((option) => {1674 Object.keys(option.implied)1675 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1676 .forEach(impliedKey => {1677 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1678 });1679 });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1680–1685why, one step back1680 }16811682 /**1683 * Argument `name` is missing.1684 *1685 * @param {string} nameSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1686why, one step back1686 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1687–1690why, one step back1687 */16881689 missingArgument(name) {1690 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1691–1692why, one step back1691 this.error(message, { code: 'commander.missingArgument' });1692 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1693–1697why, one step back16931694 /**1695 * `Option` is missing an argument.1696 *1697 * @param {Option} optionSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1698why, one step back1698 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1699–1702why, one step back1699 */17001701 optionMissingArgument(option) {1702 const message = `error: option '${option.flags}' argument missing`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1703–1704why, one step back1703 this.error(message, { code: 'commander.optionMissingArgument' });1704 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1705–1709why, one step back17051706 /**1707 * `Option` does not have a value, and is a mandatory option.1708 *1709 * @param {Option} optionSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1710why, one step back1710 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1711–1714why, one step back1711 */17121713 missingMandatoryOptionValue(option) {1714 const message = `error: required option '${option.flags}' not specified`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1715why, one step back1715 this.error(message, { code: 'commander.missingMandatoryOptionValue' });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1716–1722why, one step back1716 }17171718 /**1719 * `Option` conflicts with another option.1720 *1721 * @param {Option} option1722 * @param {Option} conflictingOptionSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1723why, one step back1723 * @privatefeat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1724–1753why, one step back1724 */1725 _conflictingOption(option, conflictingOption) {1726 // The calling code does not know whether a negated option is the source of the1727 // value, so do some work to take an educated guess.1728 const findBestOptionFromValue = (option) => {1729 const optionKey = option.attributeName();1730 const optionValue = this.getOptionValue(optionKey);1731 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1732 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1733 if (negativeOption && (1734 (negativeOption.presetArg === undefined && optionValue === false) ||1735 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1736 )) {1737 return negativeOption;1738 }1739 return positiveOption || option;1740 };17411742 const getErrorMessage = (option) => {1743 const bestOption = findBestOptionFromValue(option);1744 const optionKey = bestOption.attributeName();1745 const source = this.getOptionValueSource(optionKey);1746 if (source === 'env') {1747 return `environment variable '${bestOption.envVar}'`;1748 }1749 return `option '${bestOption.flags}'`;1750 };17511752 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1753 this.error(message, { code: 'commander.conflictingOption' });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1754why, one step back1754 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1755–1759why, one step back17551756 /**1757 * Unknown option `flag`.1758 *1759 * @param {string} flagSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1760why, one step back1760 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1761–1764why, one step back1761 */17621763 unknownOption(flag) {1764 if (this._allowUnknownOption) return;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1765–1781why, one step back1765 let suggestion = '';17661767 if (flag.startsWith('--') && this._showSuggestionAfterError) {1768 // Looping to pick up the global options too1769 let candidateFlags = [];1770 let command = this;1771 do {1772 const moreFlags = command.createHelp().visibleOptions(command)1773 .filter(option => option.long)1774 .map(option => option.long);1775 candidateFlags = candidateFlags.concat(moreFlags);1776 command = command.parent;1777 } while (command && !command._enablePositionalOptions);1778 suggestion = suggestSimilar(flag, candidateFlags);1779 }17801781 const message = `error: unknown option '${flag}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1782–1783why, one step back1782 this.error(message, { code: 'commander.unknownOption' });1783 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1784–1788why, one step back17841785 /**1786 * Excess arguments, more than expected.1787 *1788 * @param {string[]} receivedArgsSwitch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1789why, one step back1789 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1790–1794why, one step back1790 */17911792 _excessArguments(receivedArgs) {1793 if (this._allowExcessArguments) return;1794Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1795why, one step back1795 const expected = this.registeredArguments.length;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1796–1798why, one step back1796 const s = (expected === 1) ? '' : 's';1797 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1798 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1799–1800why, one step back1799 this.error(message, { code: 'commander.excessArguments' });1800 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1801–1804why, one step back18011802 /**1803 * Unknown command.1804 *Switch @api private to official JSDoc (#2018)John Geebefore adoption37c9398
line 1805why, one step back1805 * @privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1806–1808why, one step back1806 */18071808 unknownCommand() {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1809–1822why, one step back1809 const unknownName = this.args[0];1810 let suggestion = '';18111812 if (this._showSuggestionAfterError) {1813 const candidateNames = [];1814 this.createHelp().visibleCommands(this).forEach((command) => {1815 candidateNames.push(command.name());1816 // just visible alias1817 if (command.alias()) candidateNames.push(command.alias());1818 });1819 suggestion = suggestSimilar(unknownName, candidateNames);1820 }18211822 const message = `error: unknown command '${unknownName}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1823–1824why, one step back1823 this.error(message, { code: 'commander.unknownCommand' });1824 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1825–1826why, one step back18251826 /**Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1827why, one step back1827 * Get or set the program version.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1828why, one step back1828 *Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1829why, one step back1829 * This method auto-registers the "-V, --version" option which will print the version number.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1830why, one step back1830 *Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1831why, one step back1831 * You can optionally supply the flags and description to override the defaults.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1832why, one step back1832 *Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1833why, one step back1833 * @param {string} [str]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1834–1835why, one step back1834 * @param {string} [flags]1835 * @param {string} [description]Merge branch 'develop' into release/12.xJohn Geebefore adoptionf570b08
line 1836why, one step back1836 * @return {this | string | undefined} `this` command for chaining, or version string if no argumentsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1837–1844why, one step back1837 */18381839 version(str, flags, description) {1840 if (str === undefined) return this._version;1841 this._version = str;1842 flags = flags || '-V, --version';1843 description = description || 'output the version number';1844 const versionOption = this.createOption(flags, description);Throw error when add option with clashing flags (#2055)John Geebefore adoptionb96af40
lines 1845–1847why, one step back1845 this._versionOptionName = versionOption.attributeName();1846 this._registerOption(versionOption);1847Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1848–1852why, one step back1848 this.on('option:' + versionOption.name(), () => {1849 this._outputConfiguration.writeOut(`${str}\n`);1850 this._exit(0, 'commander.version', str);1851 });1852 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1853why, one step back1853 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1854–1855why, one step back18541855 /**Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 1856why, one step back1856 * Set the description.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1857–1867why, one step back1857 *1858 * @param {string} [str]1859 * @param {Object} [argsDescription]1860 * @return {string|Command}1861 */1862 description(str, argsDescription) {1863 if (str === undefined && argsDescription === undefined) return this._description;1864 this._description = str;1865 if (argsDescription) {1866 this._argsDescription = argsDescription;1867 }Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 1868–1879why, one step back1868 return this;1869 }18701871 /**1872 * Set the summary. Used when listed as subcommand of parent.1873 *1874 * @param {string} [str]1875 * @return {string|Command}1876 */1877 summary(str) {1878 if (str === undefined) return this._summary;1879 this._summary = str;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1880why, one step back1880 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1881why, one step back1881 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1882–1894why, one step back18821883 /**1884 * Set an alias for the command.1885 *1886 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1887 *1888 * @param {string} [alias]1889 * @return {string|Command}1890 */18911892 alias(alias) {1893 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1894Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1895why, one step back1895 /** @type {Command} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1896–1905why, one step back1896 let command = this;1897 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1898 // assume adding alias for last added executable subcommand, rather than this1899 command = this.commands[this.commands.length - 1];1900 }19011902 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');19031904 command._aliases.push(alias);1905 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1906why, one step back1906 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1907–1922why, one step back19071908 /**1909 * Set aliases for the command.1910 *1911 * Only the first alias is shown in the auto-generated help.1912 *1913 * @param {string[]} [aliases]1914 * @return {string[]|Command}1915 */19161917 aliases(aliases) {1918 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1919 if (aliases === undefined) return this._aliases;19201921 aliases.forEach((alias) => this.alias(alias));1922 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1923why, one step back1923 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1924–1935why, one step back19241925 /**1926 * Set / get the command usage `str`.1927 *1928 * @param {string} [str]1929 * @return {String|Command}1930 */19311932 usage(str) {1933 if (str === undefined) {1934 if (this._usage) return this._usage;1935Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1936why, one step back1936 const args = this.registeredArguments.map((arg) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1937–1941why, one step back1937 return humanReadableArgName(arg);1938 });1939 return [].concat(1940 (this.options.length || this._hasHelpOption ? '[options]' : []),1941 (this.commands.length ? '[command]' : []),Merge remote-tracking branch 'origin/develop' into release/12.xJohn Geebefore adoption9afbabd
line 1942why, one step back1942 (this.registeredArguments.length ? args : [])Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1943–1947why, one step back1943 ).join(' ');1944 }19451946 this._usage = str;1947 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1948why, one step back1948 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1949–1950why, one step back19491950 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1951why, one step back1951 * Get or set the name of the command.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1952–1960why, one step back1952 *1953 * @param {string} [str]1954 * @return {string|Command}1955 */19561957 name(str) {1958 if (str === undefined) return this._name;1959 this._name = str;1960 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1961why, one step back1961 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1962–1963why, one step back19621963 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1964–1990why, one step back1964 * Set the name of the command from script filename, such as process.argv[1],1965 * or require.main.filename, or __filename.1966 *1967 * (Used internally and public although not documented in README.)1968 *1969 * @example1970 * program.nameFromFilename(require.main.filename);1971 *1972 * @param {string} filename1973 * @return {Command}1974 */19751976 nameFromFilename(filename) {1977 this._name = path.basename(filename, path.extname(filename));19781979 return this;1980 }19811982 /**1983 * Get or set the directory for searching for executable subcommands of this command.1984 *1985 * @example1986 * program.executableDir(__dirname);1987 * // or1988 * program.executableDir('subcommands');1989 *1990 * @param {string} [path]Merge branch 'develop' into release/12.xJohn Geebefore adoption95d54c3
line 1991why, one step back1991 * @return {string|null|Command}Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1992–2000why, one step back1992 */19931994 executableDir(path) {1995 if (path === undefined) return this._executableDir;1996 this._executableDir = path;1997 return this;1998 }19992000 /**The first 2,000 of 2,207 lines.