command.js
This file
Path
lib/command.js
2,179 lines · 69.3 KiB · JavaScript
Last changed by
Comment out new misuse check until a major version (#2026)John Geebefore adoption67c9180
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[]} */Add public Arguments property (#2010)John Geebefore adoption7d23437
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 /**Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 112–124why, one step back112 * @returns {Command[]}113 * @api private114 */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–287why, 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;287 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 288why, one step back288 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 289–302why, one step back289290 /**291 * Factory routine to create a new unattached argument.292 *293 * See .argument() for creating an attached argument, which uses this routine to294 * create the argument. You can override createArgument to return a custom argument.295 *296 * @param {string} name297 * @param {string} [description]298 * @return {Argument} new argument299 */300301 createArgument(name, description) {302 return new Argument(name, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 303why, one step back303 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 304–311why, one step back304305 /**306 * Define argument syntax for command.307 *308 * The default is that the argument is required, and you can explicitly309 * indicate this with <> around the name. Put [] around the name for an optional argument.310 *311 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 312–313why, one step back312 * program.argument('<input-file>');313 * program.argument('[output-file]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 314–337why, one step back314 *315 * @param {string} name316 * @param {string} [description]317 * @param {Function|*} [fn] - custom argument processing function318 * @param {*} [defaultValue]319 * @return {Command} `this` command for chaining320 */321 argument(name, description, fn, defaultValue) {322 const argument = this.createArgument(name, description);323 if (typeof fn === 'function') {324 argument.default(defaultValue).argParser(fn);325 } else {326 argument.default(fn);327 }328 this.addArgument(argument);329 return this;330 }331332 /**333 * Define argument syntax for command, adding multiple at once (without descriptions).334 *335 * See also .argument().336 *337 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 338why, one step back338 * program.arguments('<cmd> [env]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 339–344why, one step back339 *340 * @param {string} names341 * @return {Command} `this` command for chaining342 */343344 arguments(names) {trim() input string of .arguments methodАлександр Шмелевbefore adoption2f07c2a
line 345why, one step back345 names.trim().split(/ +/).forEach((detail) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 346–348why, one step back346 this.argument(detail);347 });348 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 349why, one step back349 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 350–357why, one step back350351 /**352 * Define argument syntax for command, adding a prepared argument.353 *354 * @param {Argument} argument355 * @return {Command} `this` command for chaining356 */357 addArgument(argument) {Add public Arguments property (#2010)John Geebefore adoption7d23437
line 358why, one step back358 const previousArgument = this.registeredArguments.slice(-1)[0];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 359–364why, one step back359 if (previousArgument && previousArgument.variadic) {360 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);361 }362 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {363 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);364 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 365why, one step back365 this.registeredArguments.push(argument);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 366–390why, one step back366 return this;367 }368369 /**370 * Override default decision whether to add implicit help command.371 *372 * addHelpCommand() // force on373 * addHelpCommand(false); // force off374 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details375 *376 * @return {Command} `this` command for chaining377 */378379 addHelpCommand(enableOrNameAndArgs, description) {380 if (enableOrNameAndArgs === false) {381 this._addImplicitHelpCommand = false;382 } else {383 this._addImplicitHelpCommand = true;384 if (typeof enableOrNameAndArgs === 'string') {385 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];386 this._helpCommandnameAndArgs = enableOrNameAndArgs;387 }388 this._helpCommandDescription = description || this._helpCommandDescription;389 }390 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 391why, one step back391 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 392–402why, one step back392393 /**394 * @return {boolean}395 * @api private396 */397398 _hasImplicitHelpCommand() {399 if (this._addImplicitHelpCommand === undefined) {400 return this.commands.length && !this._actionHandler && !this._findCommand('help');401 }402 return this._addImplicitHelpCommand;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 403why, one step back403 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 404–413why, one step back404405 /**406 * Add hook for life cycle event.407 *408 * @param {string} event409 * @param {Function} listener410 * @return {Command} `this` command for chaining411 */412413 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 414why, one step back414 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 415–446why, one step back415 if (!allowedValues.includes(event)) {416 throw new Error(`Unexpected value for event passed to hook : '${event}'.417Expecting one of '${allowedValues.join("', '")}'`);418 }419 if (this._lifeCycleHooks[event]) {420 this._lifeCycleHooks[event].push(listener);421 } else {422 this._lifeCycleHooks[event] = [listener];423 }424 return this;425 }426427 /**428 * Register callback to use as replacement for calling process.exit.429 *430 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing431 * @return {Command} `this` command for chaining432 */433434 exitOverride(fn) {435 if (fn) {436 this._exitCallback = fn;437 } else {438 this._exitCallback = (err) => {439 if (err.code !== 'commander.executeSubCommandAsync') {440 throw err;441 } else {442 // Async callback from spawn events, not useful to throw.443 }444 };445 }446 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 447why, one step back447 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 448–464why, one step back448449 /**450 * Call process.exit, and _exitCallback if defined.451 *452 * @param {number} exitCode exit code for using with process.exit453 * @param {string} code an id string representing the error454 * @param {string} message human-readable description of the error455 * @return never456 * @api private457 */458459 _exit(exitCode, code, message) {460 if (this._exitCallback) {461 this._exitCallback(new CommanderError(exitCode, code, message));462 // Expecting this line is not reached.463 }464 process.exit(exitCode);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 465why, one step back465 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 466–469why, one step back466467 /**468 * Register callback `fn` for the command.469 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 470–471why, one step back470 * @example471 * programChange .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
lines 472–473why, one step back472 * .command('serve')473 * .description('start service')Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 474why, one step back474 * .action(function() {Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
line 475why, one step back475 * // do work hereFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 476why, one step back476 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 477–484why, one step back477 *478 * @param {Function} fn479 * @return {Command} `this` command for chaining480 */481482 action(fn) {483 const listener = (args) => {484 // The .action callback takes an extra parameter which is the command or options.Add public Arguments property (#2010)John Geebefore adoption7d23437
line 485why, one step back485 const expectedArgsCount = this.registeredArguments.length;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 486–497why, one step back486 const actionArgs = args.slice(0, expectedArgsCount);487 if (this._storeOptionsAsProperties) {488 actionArgs[expectedArgsCount] = this; // backwards compatible "options"489 } else {490 actionArgs[expectedArgsCount] = this.opts();491 }492 actionArgs.push(this);493494 return fn.apply(this, actionArgs);495 };496 this._actionHandler = listener;497 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 498why, one step back498 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 499–512why, one step back499500 /**501 * Factory routine to create a new unattached option.502 *503 * See .option() for creating an attached option, which uses this routine to504 * create the option. You can override createOption to return a custom option.505 *506 * @param {string} flags507 * @param {string} [description]508 * @return {Option} new option509 */510511 createOption(flags, description) {512 return new Option(flags, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 513why, one step back513 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 514–515why, one step back514515 /**Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 516–519why, one step back516 * Wrap parseArgs to catch 'commander.invalidArgument'.517 *518 * @param {Option | Argument} target519 * @param {string} valueReplace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6
line 520why, one step back520 * @param {*} previousRefactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 521–537why, one step back521 * @param {string} invalidArgumentMessage522 * @api private523 */524525 _callParseArg(target, value, previous, invalidArgumentMessage) {526 try {527 return target.parseArg(value, previous);528 } catch (err) {529 if (err.code === 'commander.invalidArgument') {530 const message = `${invalidArgumentMessage} ${err.message}`;531 this.error(message, { exitCode: err.exitCode, code: err.code });532 }533 throw err;534 }535 }536537 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 538–546why, one step back538 * Add an option.539 *540 * @param {Option} option541 * @return {Command} `this` command for chaining542 */543 addOption(option) {544 const oname = option.name();545 const name = option.attributeName();546Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 547–552why, one step back547 // store default value548 if (option.negate) {549 // --no-foo is special and defaults foo to true, unless a --foo option is already defined550 const positiveLongFlag = option.long.replace(/^--no-/, '--');551 if (!this._findOption(positiveLongFlag)) {552 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 553why, one step back553 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 554–555why, one step back554 } else if (option.defaultValue !== undefined) {555 this.setOptionValueWithSource(name, option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 556–560why, one step back556 }557558 // register the option559 this.options.push(option);560Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 561–562why, one step back561 // handler for cli and env supplied values562 const handleOptionValue = (val, invalidValueMessage, valueSource) => {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 563–567why, one step back563 // val is null for optional option used without an optional-argument.564 // val is undefined for boolean and negated option.565 if (val == null && option.presetArg !== undefined) {566 val = option.presetArg;567 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 568–569why, one step back568569 // custom processingMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 570why, one step back570 const oldValue = this.getOptionValue(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 571why, one step back571 if (val !== null && option.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 572why, one step back572 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 573–576why, one step back573 } else if (val !== null && option.variadic) {574 val = option._concatValue(val, oldValue);575 }576Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 577–582why, one step back577 // Fill-in appropriate missing values. Long winded but easy to follow.578 if (val == null) {579 if (option.negate) {580 val = false;581 } else if (option.isBoolean() || option.optional) {582 val = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 583why, one step back583 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 584why, one step back584 val = ''; // not normal, parseArg might have failed or be a mock function for testingRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 585–586why, one step back585 }586 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 587why, one step back587 this.setOptionValueWithSource(name, val, valueSource);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 588–592why, one step back588 };589590 this.on('option:' + oname, (val) => {591 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;592 handleOptionValue(val, invalidValueMessage, 'cli');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 593–594why, one step back593 });594Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 595–601why, one step back595 if (option.envVar) {596 this.on('optionEnv:' + oname, (val) => {597 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;598 handleOptionValue(val, invalidValueMessage, 'env');599 });600 }601Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 602–610why, one step back602 return this;603 }604605 /**606 * Internal implementation shared by .option() and .requiredOption()607 *608 * @api private609 */610 _optionEx(config, flags, description, fn, defaultValue) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 611–613why, one step back611 if (typeof flags === 'object' && flags instanceof Option) {612 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');613 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 614–633why, one step back614 const option = this.createOption(flags, description);615 option.makeOptionMandatory(!!config.mandatory);616 if (typeof fn === 'function') {617 option.default(defaultValue).argParser(fn);618 } else if (fn instanceof RegExp) {619 // deprecated620 const regex = fn;621 fn = (val, def) => {622 const m = regex.exec(val);623 return m ? m[0] : def;624 };625 option.default(defaultValue).argParser(fn);626 } else {627 option.default(fn);628 }629630 return this.addOption(option);631 }632633 /**Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 634why, one step back634 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 635why, one step back635 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 636–637why, one step back636 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required637 * option-argument is indicated by `<>` and an optional option-argument by `[]`.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 638why, one step back638 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 639why, one step back639 * See the README for more details, and see also addOption() and requiredOption().Refactor classes into files (#1522)John Geebefore adoption08245cc
line 640why, one step back640 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 641why, one step back641 * @exampleRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 642–646why, one step back642 * program643 * .option('-p, --pepper', 'add pepper')644 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument645 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default646 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse functionRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 647–649why, one step back647 *648 * @param {string} flags649 * @param {string} [description]Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 650why, one step back650 * @param {Function|*} [parseArg] - custom option processing function or default valueRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 651–654why, one step back651 * @param {*} [defaultValue]652 * @return {Command} `this` command for chaining653 */654Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 655–656why, one step back655 option(flags, description, parseArg, defaultValue) {656 return this._optionEx({}, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 657why, one step back657 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 658–666why, one step back658659 /**660 * Add a required option which must have a value after parsing. This usually means661 * the option must be specified on the command line. (Otherwise the same as .option().)662 *663 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.664 *665 * @param {string} flags666 * @param {string} [description]Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 667why, one step back667 * @param {Function|*} [parseArg] - custom option processing function or default valueRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 668–671why, one step back668 * @param {*} [defaultValue]669 * @return {Command} `this` command for chaining670 */671Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 672–673why, one step back672 requiredOption(flags, description, parseArg, defaultValue) {673 return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 674why, one step back674 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 675–678why, one step back675676 /**677 * Alter parsing of short flags with optional values.678 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 679–682why, one step back679 * @example680 * // for `.option('-f,--flag [value]'):681 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour682 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 683–688why, one step back683 *684 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.685 */686 combineFlagAndOptionalValue(combine = true) {687 this._combineFlagAndOptionalValue = !!combine;688 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 689why, one step back689 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 690–699why, one step back690691 /**692 * Allow unknown options on the command line.693 *694 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown695 * for unknown options.696 */697 allowUnknownOption(allowUnknown = true) {698 this._allowUnknownOption = !!allowUnknown;699 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 700why, one step back700 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 701–710why, one step back701702 /**703 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.704 *705 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown706 * for excess arguments.707 */708 allowExcessArguments(allowExcess = true) {709 this._allowExcessArguments = !!allowExcess;710 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 711why, one step back711 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 712–722why, one step back712713 /**714 * Enable positional options. Positional means global options are specified before subcommands which lets715 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.716 * The default behaviour is non-positional and global options may appear anywhere on the command line.717 *718 * @param {Boolean} [positional=true]719 */720 enablePositionalOptions(positional = true) {721 this._enablePositionalOptions = !!positional;722 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 723why, one step back723 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 724–739why, one step back724725 /**726 * Pass through options that come after command-arguments rather than treat them as command-options,727 * so actual command-options come before command-arguments. Turning this on for a subcommand requires728 * positional options to have been enabled on the program (parent commands).729 * The default behaviour is non-positional and options may appear before or after command-arguments.730 *731 * @param {Boolean} [passThrough=true]732 * for unknown options.733 */734 passThroughOptions(passThrough = true) {735 this._passThroughOptions = !!passThrough;736 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {737 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');738 }739 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 740why, one step back740 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 741–753why, one step back741742 /**743 * Whether to store option values as properties on command object,744 * or store separately (specify false). In both cases the option values can be accessed using .opts().745 *746 * @param {boolean} [storeAsProperties=true]747 * @return {Command} `this` command for chaining748 */749750 storeOptionsAsProperties(storeAsProperties = true) {751 if (this.options.length) {752 throw new Error('call .storeOptionsAsProperties() before adding options');753 }Comment out new misuse check until a major version (#2026)John Geebefore adoption67c9180
lines 754–756why, one step back754 // if (Object.keys(this._optionValues).length) {755 // throw new Error('call .storeOptionsAsProperties() before setting option values');756 // }Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
line 757why, one step back757 this._storeOptionsAsProperties = !!storeAsProperties;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 758why, one step back758 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 759why, one step back759 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 760–772why, one step back760761 /**762 * Retrieve option value.763 *764 * @param {string} key765 * @return {Object} value766 */767768 getOptionValue(key) {769 if (this._storeOptionsAsProperties) {770 return this[key];771 }772 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 773why, one step back773 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 774–783why, one step back774775 /**776 * Store option value.777 *778 * @param {string} key779 * @param {Object} value780 * @return {Command} `this` command for chaining781 */782783 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 784why, one step back784 return this.setOptionValueWithSource(key, value, undefined);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 785why, one step back785 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 786–787why, one step back786787 /**Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 788why, one step back788 * Store option value and where the value came from.Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 789–791why, one step back789 *790 * @param {string} key791 * @param {Object} valueAdd implied to option value sources (#1794)John Geebefore adoption72be61c
line 792why, one step back792 * @param {string} source - expected values are default/config/env/cli/impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 793–796why, one step back793 * @return {Command} `this` command for chaining794 */795796 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 797–801why, one step back797 if (this._storeOptionsAsProperties) {798 this[key] = value;799 } else {800 this._optionValues[key] = value;801 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 802why, one step back802 this._optionValueSources[key] = source;Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 803why, one step back803 return this;Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 804–806why, one step back804 }805806 /**Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 807why, one step back807 * Get source of option value.Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 808why, one step back808 * Expected values are default | config | env | cli | impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 809–815why, one step back809 *810 * @param {string} key811 * @return {string}812 */813814 getOptionValueSource(key) {815 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 816why, one step back816 }Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 817–818why, one step back817818 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 819–828why, one step back819 * Get source of option value. See also .optsWithGlobals().820 * Expected values are default | config | env | cli | implied821 *822 * @param {string} key823 * @return {string}824 */825826 getOptionValueSourceWithGlobals(key) {827 // global overwrites local, like optsWithGlobals828 let source;Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 829why, one step back829 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 830–837why, one step back830 if (cmd.getOptionValueSource(key) !== undefined) {831 source = cmd.getOptionValueSource(key);832 }833 });834 return source;835 }836837 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 838–839why, one step back838 * Get user arguments from implied or explicit arguments.839 * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 840–883why, one step back840 *841 * @api private842 */843844 _prepareUserArgs(argv, parseOptions) {845 if (argv !== undefined && !Array.isArray(argv)) {846 throw new Error('first parameter to parse must be array or undefined');847 }848 parseOptions = parseOptions || {};849850 // Default to using process.argv851 if (argv === undefined) {852 argv = process.argv;853 // @ts-ignore: unknown property854 if (process.versions && process.versions.electron) {855 parseOptions.from = 'electron';856 }857 }858 this.rawArgs = argv.slice();859860 // make it a little easier for callers by supporting various argv conventions861 let userArgs;862 switch (parseOptions.from) {863 case undefined:864 case 'node':865 this._scriptPath = argv[1];866 userArgs = argv.slice(2);867 break;868 case 'electron':869 // @ts-ignore: unknown property870 if (process.defaultApp) {871 this._scriptPath = argv[1];872 userArgs = argv.slice(2);873 } else {874 userArgs = argv.slice(1);875 }876 break;877 case 'user':878 userArgs = argv.slice(0);879 break;880 default:881 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);882 }883Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 884–886why, one step back884 // Find default name for program from arguments.885 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);886 this._name = this._name || 'program';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 887–896why, one step back887888 return userArgs;889 }890891 /**892 * Parse `argv`, setting options and invoking commands when defined.893 *894 * The default expectation is that the arguments are from node and have the application as argv[0]895 * and the script being run in argv[1], with user parameters after that.896 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 897–900why, one step back897 * @example898 * program.parse(process.argv);899 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions900 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 901–912why, one step back901 *902 * @param {string[]} [argv] - optional, defaults to process.argv903 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron904 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'905 * @return {Command} `this` command for chaining906 */907908 parse(argv, parseOptions) {909 const userArgs = this._prepareUserArgs(argv, parseOptions);910 this._parseCommand([], userArgs);911912 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 913why, one step back913 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 914–922why, one step back914915 /**916 * Parse `argv`, setting options and invoking commands when defined.917 *918 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.919 *920 * The default expectation is that the arguments are from node and have the application as argv[0]921 * and the script being run in argv[1], with user parameters after that.922 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 923–926why, one step back923 * @example924 * await program.parseAsync(process.argv);925 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions926 * 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 927–938why, one step back927 *928 * @param {string[]} [argv]929 * @param {Object} [parseOptions]930 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'931 * @return {Promise}932 */933934 async parseAsync(argv, parseOptions) {935 const userArgs = this._prepareUserArgs(argv, parseOptions);936 await this._parseCommand([], userArgs);937938 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 939why, one step back939 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 940–951why, one step back940941 /**942 * Execute a sub-command executable.943 *944 * @api private945 */946947 _executeSubCommand(subcommand, args) {948 args = args.slice();949 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.950 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];951Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 952–955why, one step back952 function findFile(baseDir, baseName) {953 // Look for specified file954 const localBin = path.resolve(baseDir, baseName);955 if (fs.existsSync(localBin)) return localBin;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 956why, one step back956Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 957–958why, one step back957 // Stop looking if candidate already has an expected extension.958 if (sourceExt.includes(path.extname(baseName))) return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 959why, one step back959Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 960–964why, one step back960 // Try all the extensions.961 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));962 if (foundExt) return `${localBin}${foundExt}`;963964 return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 965–966why, one step back965 }966Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 967–968why, one step back967 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.968 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 969why, one step back969 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 970–981why, one step back970971 // executableFile and executableDir might be full path, or just a name972 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;973 let executableDir = this._executableDir || '';974 if (this._scriptPath) {975 let resolvedScriptPath; // resolve possible symlink for installed npm binary976 try {977 resolvedScriptPath = fs.realpathSync(this._scriptPath);978 } catch (err) {979 resolvedScriptPath = this._scriptPath;980 }981 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 982–983why, one step back982 }983Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 984–992why, one step back984 // Look for a local file in preference to a command in PATH.985 if (executableDir) {986 let localFile = findFile(executableDir, executableFile);987988 // Legacy search using prefix of script name instead of command name989 if (!localFile && !subcommand._executableFile && this._scriptPath) {990 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));991 if (legacyName !== this._name) {992 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 993why, one step back993 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 994–995why, one step back994 }995 executableFile = localFile || executableFile;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 996–997why, one step back996 }997Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 998–999why, one step back998 launchWithNode = sourceExt.includes(path.extname(executableFile));999Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1000–1002why, one step back1000 let proc;1001 if (process.platform !== 'win32') {1002 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1003why, one step back1003 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1004–1008why, one step back1004 // add executable arguments to spawn1005 args = incrementNodeInspectorPort(process.execArgv).concat(args);10061007 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1008 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1009why, one step back1009 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1010–1011why, one step back1010 }1011 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1012why, one step back1012 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1013–1017why, one step back1013 // add executable arguments to spawn1014 args = incrementNodeInspectorPort(process.execArgv).concat(args);1015 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1016 }1017Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1018–1026why, one step back1018 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1019 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1020 signals.forEach((signal) => {1021 // @ts-ignore1022 process.on(signal, () => {1023 if (proc.killed === false && proc.exitCode === null) {1024 proc.kill(signal);1025 }1026 });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1027why, one step back1027 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1028why, one step back1028 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1029–1042why, one step back10291030 // By default terminate process when spawned process terminates.1031 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1032 const exitCallback = this._exitCallback;1033 if (!exitCallback) {1034 proc.on('close', process.exit.bind(process));1035 } else {1036 proc.on('close', () => {1037 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1038 });1039 }1040 proc.on('error', (err) => {1041 // @ts-ignore1042 if (err.code === 'ENOENT') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1043–1046why, one step back1043 const executableDirMessage = executableDir1044 ? `searched for local subcommand relative to directory '${executableDir}'`1045 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1046 const executableMissing = `'${executableFile}' does not existRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1047why, one step back1047 - 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 1048–1049why, one step back1048 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1049 - ${executableDirMessage}`;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1050–1052why, one step back1050 throw new Error(executableMissing);1051 // @ts-ignore1052 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1053why, one step back1053 throw new Error(`'${executableFile}' not executable`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1054–1065why, one step back1054 }1055 if (!exitCallback) {1056 process.exit(1);1057 } else {1058 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1059 wrappedError.nestedError = err;1060 exitCallback(wrappedError);1061 }1062 });10631064 // Store the reference to the child process1065 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1066why, one step back1066 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1067–1075why, one step back10671068 /**1069 * @api private1070 */10711072 _dispatchSubcommand(commandName, operands, unknown) {1073 const subCommand = this._findCommand(commandName);1074 if (!subCommand) this.help({ error: true });1075Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1076–1078why, one step back1076 let promiseChain;1077 promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');1078 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1079–1084why, one step back1079 if (subCommand._executableHandler) {1080 this._executeSubCommand(subCommand, operands.concat(unknown));1081 } else {1082 return subCommand._parseCommand(operands, unknown);1083 }1084 });Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1085why, one step back1085 return promiseChain;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1086why, one step back1086 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1087–1088why, one step back10871088 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1089–1104why, one step back1089 * Invoke help directly if possible, or dispatch if necessary.1090 * e.g. help foo1091 *1092 * @api private1093 */10941095 _dispatchHelpCommand(subcommandName) {1096 if (!subcommandName) {1097 this.help();1098 }1099 const subCommand = this._findCommand(subcommandName);1100 if (subCommand && !subCommand._executableHandler) {1101 subCommand.help();1102 }11031104 // Fallback to parsing the help flag to invoke the help.Fix help for commands with executable handler & only a short help flagWee Bitbefore adoptionc117172
lines 1105–1107why, one step back1105 return this._dispatchSubcommand(subcommandName, [], [1106 this._helpLongFlag || this._helpShortFlag1107 ]);Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1108–1110why, one step back1108 }11091110 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1111why, one step back1111 * Check this.args against expected this.registeredArguments.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1112–1115why, one step back1112 *1113 * @api private1114 */1115Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1116–1117why, one step back1116 _checkNumberOfArguments() {1117 // too fewAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1118why, one step back1118 this.registeredArguments.forEach((arg, i) => {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1119–1123why, one step back1119 if (arg.required && this.args[i] == null) {1120 this.missingArgument(arg.name());1121 }1122 });1123 // too manyAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1124why, one step back1124 if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1125–1126why, one step back1125 return;1126 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1127why, one step back1127 if (this.args.length > this.registeredArguments.length) {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1128–1129why, one step back1128 this._excessArguments(this.args);1129 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1130why, one step back1130 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1131–1132why, one step back11311132 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1133why, one step back1133 * Process this.args using this.registeredArguments and save as this.processedArgs!Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1134–1138why, one step back1134 *1135 * @api private1136 */11371138 _processArguments() {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1139–1142why, one step back1139 const myParseArg = (argument, value, previous) => {1140 // Extra processing for nice error message on parsing failure.1141 let parsedValue = value;1142 if (value !== null && argument.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 1143–1144why, one step back1143 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1144 parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1145–1148why, one step back1145 }1146 return parsedValue;1147 };1148Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1149–1151why, one step back1149 this._checkNumberOfArguments();11501151 const processedArgs = [];Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1152why, one step back1152 this.registeredArguments.forEach((declaredArg, index) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1153–1171why, one step back1153 let value = declaredArg.defaultValue;1154 if (declaredArg.variadic) {1155 // Collect together remaining arguments for passing together as an array.1156 if (index < this.args.length) {1157 value = this.args.slice(index);1158 if (declaredArg.parseArg) {1159 value = value.reduce((processed, v) => {1160 return myParseArg(declaredArg, v, processed);1161 }, declaredArg.defaultValue);1162 }1163 } else if (value === undefined) {1164 value = [];1165 }1166 } else if (index < this.args.length) {1167 value = this.args[index];1168 if (declaredArg.parseArg) {1169 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1170 }1171 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1172why, one step back1172 processedArgs[index] = value;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1173why, one step back1173 });Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1174why, one step back1174 this.processedArgs = processedArgs;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1175–1182why, one step back1175 }11761177 /**1178 * Once we have a promise we chain, but call synchronously until then.1179 *1180 * @param {Promise|undefined} promise1181 * @param {Function} fn1182 * @return {Promise|undefined}Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 1183why, one step back1183 * @api privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1184–1206why, one step back1184 */11851186 _chainOrCall(promise, fn) {1187 // thenable1188 if (promise && promise.then && typeof promise.then === 'function') {1189 // already have a promise, chain callback1190 return promise.then(() => fn());1191 }1192 // callback might return a promise1193 return fn();1194 }11951196 /**1197 *1198 * @param {Promise|undefined} promise1199 * @param {string} event1200 * @return {Promise|undefined}1201 * @api private1202 */12031204 _chainOrCallHooks(promise, event) {1205 let result = promise;1206 const hooks = [];Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1207why, one step back1207 this._getCommandAndAncestors()Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1208–1223why, one step back1208 .reverse()1209 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1210 .forEach(hookedCommand => {1211 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1212 hooks.push({ hookedCommand, callback });1213 });1214 });1215 if (event === 'postAction') {1216 hooks.reverse();1217 }12181219 hooks.forEach((hookDetail) => {1220 result = this._chainOrCall(result, () => {1221 return hookDetail.callback(hookDetail.hookedCommand, this);1222 });1223 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1224–1244why, one step back1224 return result;1225 }12261227 /**1228 *1229 * @param {Promise|undefined} promise1230 * @param {Command} subCommand1231 * @param {string} event1232 * @return {Promise|undefined}1233 * @api private1234 */12351236 _chainOrCallSubCommandHook(promise, subCommand, event) {1237 let result = promise;1238 if (this._lifeCycleHooks[event] !== undefined) {1239 this._lifeCycleHooks[event].forEach((hook) => {1240 result = this._chainOrCall(result, () => {1241 return hook(this, subCommand);1242 });1243 });1244 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1245–1256why, one step back1245 return result;1246 }12471248 /**1249 * Process arguments in context of this command.1250 * Returns action result, in case it is a promise.1251 *1252 * @api private1253 */12541255 _parseCommand(operands, unknown) {1256 const parsed = this.parseOptions(unknown);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 1257why, one step back1257 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1258why, one step back1258 this._parseOptionsImplied();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1259–1266why, one step back1259 operands = operands.concat(parsed.operands);1260 unknown = parsed.unknown;1261 this.args = operands.concat(unknown);12621263 if (operands && this._findCommand(operands[0])) {1264 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1265 }1266 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1267why, one step back1267 return this._dispatchHelpCommand(operands[1]);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1268–1279why, one step back1268 }1269 if (this._defaultCommandName) {1270 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1271 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1272 }1273 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1274 // probably missing subcommand and no handler, user needs help (and exit)1275 this.help({ error: true });1276 }12771278 outputHelpIfRequested(this, parsed.unknown);1279 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1280why, one step back1280 this._checkForConflictingOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1281–1291why, one step back12811282 // We do not always call this check to avoid masking a "better" error, like unknown command.1283 const checkForUnknownOptions = () => {1284 if (parsed.unknown.length > 0) {1285 this.unknownOption(parsed.unknown[0]);1286 }1287 };12881289 const commandEvent = `command:${this.name()}`;1290 if (this._actionHandler) {1291 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1292why, one step back1292 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1293why, one step back1293Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1294–1296why, one step back1294 let promiseChain;1295 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1296 promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
line 1297why, one step back1297 if (this.parent) {Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1298why, one step back1298 promiseChain = this._chainOrCall(promiseChain, () => {Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1299–1301why, one step back1299 this.parent.emit(commandEvent, operands, unknown); // legacy1300 });1301 }Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1302–1303why, one step back1302 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1303 return promiseChain;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1304–1306why, one step back1304 }1305 if (this.parent && this.parent.listenerCount(commandEvent)) {1306 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1307why, one step back1307 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1308–1319why, one step back1308 this.parent.emit(commandEvent, operands, unknown); // legacy1309 } else if (operands.length) {1310 if (this._findCommand('*')) { // legacy default command1311 return this._dispatchSubcommand('*', operands, unknown);1312 }1313 if (this.listenerCount('command:*')) {1314 // skip option check, emit event for possible misspelling suggestion1315 this.emit('command:*', operands, unknown);1316 } else if (this.commands.length) {1317 this.unknownCommand();1318 } else {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
lines 1321–1322why, one step back1321 }1322 } else if (this.commands.length) {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 1323why, one step back1323 checkForUnknownOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1324–1327why, one step back1324 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1325 this.help({ error: true });1326 } else {1327 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1328why, one step back1328 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1329–1330why, one step back1329 // fall through for caller to handle after calling .parse()1330 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1331why, one step back1331 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1332–1340why, one step back13321333 /**1334 * Find matching command.1335 *1336 * @api private1337 */1338 _findCommand(name) {1339 if (!name) return undefined;1340 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1341why, one step back1341 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1342–1352why, one step back13421343 /**1344 * Return an option matching `arg` if any.1345 *1346 * @param {string} arg1347 * @return {Option}1348 * @api private1349 */13501351 _findOption(arg) {1352 return this.options.find(option => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1353why, one step back1353 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1354–1356why, one step back13541355 /**1356 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1357why, one step back1357 * Called after checking for help flags in leaf subcommand.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1358–1363why, one step back1358 *1359 * @api private1360 */13611362 _checkForMissingMandatoryOptions() {1363 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1364why, one step back1364 this._getCommandAndAncestors().forEach((cmd) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1365–1369why, one step back1365 cmd.options.forEach((anOption) => {1366 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1367 cmd.missingMandatoryOptionValue(anOption);1368 }1369 });Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1370why, one step back1370 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1371why, one step back1371 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1372–1373why, one step back13721373 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1374why, one step back1374 * Display an error message if conflicting options are used together in this.feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1375–1377why, one step back1375 *1376 * @api private1377 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1378why, one step back1378 _checkForConflictingLocalOptions() {feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1379–1400why, one step back1379 const definedNonDefaultOptions = this.options.filter(1380 (option) => {1381 const optionKey = option.attributeName();1382 if (this.getOptionValue(optionKey) === undefined) {1383 return false;1384 }1385 return this.getOptionValueSource(optionKey) !== 'default';1386 }1387 );13881389 const optionsWithConflicting = definedNonDefaultOptions.filter(1390 (option) => option.conflictsWith.length > 01391 );13921393 optionsWithConflicting.forEach((option) => {1394 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1395 option.conflictsWith.includes(defined.attributeName())1396 );1397 if (conflictingAndDefined) {1398 this._conflictingOption(option, conflictingAndDefined);1399 }1400 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1401–1410why, one step back1401 }14021403 /**1404 * Display an error message if conflicting options are used together.1405 * Called after checking for help flags in leaf subcommand.1406 *1407 * @api private1408 */1409 _checkForConflictingOptions() {1410 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1411why, one step back1411 this._getCommandAndAncestors().forEach((cmd) => {Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1412why, one step back1412 cmd._checkForConflictingLocalOptions();Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1413why, one step back1413 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1414–1416why, one step back1414 }14151416 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1417–1421why, one step back1417 * Parse options from `argv` removing known options,1418 * and return argv split into operands and unknown arguments.1419 *1420 * Examples:1421 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 1422–1426why, one step back1422 * argv => operands, unknown1423 * --known kkk op => [op], []1424 * op --known kkk => [op], []1425 * sub --unknown uuu op => [sub], [--unknown uuu op]1426 * sub -- --unknown uuu op => [sub --unknown uuu op], []Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1427–1545why, one step back1427 *1428 * @param {String[]} argv1429 * @return {{operands: String[], unknown: String[]}}1430 */14311432 parseOptions(argv) {1433 const operands = []; // operands, not options or values1434 const unknown = []; // first unknown option and remaining unknown args1435 let dest = operands;1436 const args = argv.slice();14371438 function maybeOption(arg) {1439 return arg.length > 1 && arg[0] === '-';1440 }14411442 // parse options1443 let activeVariadicOption = null;1444 while (args.length) {1445 const arg = args.shift();14461447 // literal1448 if (arg === '--') {1449 if (dest === unknown) dest.push(arg);1450 dest.push(...args);1451 break;1452 }14531454 if (activeVariadicOption && !maybeOption(arg)) {1455 this.emit(`option:${activeVariadicOption.name()}`, arg);1456 continue;1457 }1458 activeVariadicOption = null;14591460 if (maybeOption(arg)) {1461 const option = this._findOption(arg);1462 // recognised option, call listener to assign value with possible custom processing1463 if (option) {1464 if (option.required) {1465 const value = args.shift();1466 if (value === undefined) this.optionMissingArgument(option);1467 this.emit(`option:${option.name()}`, value);1468 } else if (option.optional) {1469 let value = null;1470 // historical behaviour is optional value is following arg unless an option1471 if (args.length > 0 && !maybeOption(args[0])) {1472 value = args.shift();1473 }1474 this.emit(`option:${option.name()}`, value);1475 } else { // boolean flag1476 this.emit(`option:${option.name()}`);1477 }1478 activeVariadicOption = option.variadic ? option : null;1479 continue;1480 }1481 }14821483 // Look for combo options following single dash, eat first one if known.1484 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1485 const option = this._findOption(`-${arg[1]}`);1486 if (option) {1487 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1488 // option with value following in same argument1489 this.emit(`option:${option.name()}`, arg.slice(2));1490 } else {1491 // boolean option, emit and put back remainder of arg for further processing1492 this.emit(`option:${option.name()}`);1493 args.unshift(`-${arg.slice(2)}`);1494 }1495 continue;1496 }1497 }14981499 // Look for known long flag with value, like --foo=bar1500 if (/^--[^=]+=/.test(arg)) {1501 const index = arg.indexOf('=');1502 const option = this._findOption(arg.slice(0, index));1503 if (option && (option.required || option.optional)) {1504 this.emit(`option:${option.name()}`, arg.slice(index + 1));1505 continue;1506 }1507 }15081509 // Not a recognised option by this command.1510 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15111512 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1513 if (maybeOption(arg)) {1514 dest = unknown;1515 }15161517 // If using positionalOptions, stop processing our options at subcommand.1518 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1519 if (this._findCommand(arg)) {1520 operands.push(arg);1521 if (args.length > 0) unknown.push(...args);1522 break;1523 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1524 operands.push(arg);1525 if (args.length > 0) operands.push(...args);1526 break;1527 } else if (this._defaultCommandName) {1528 unknown.push(arg);1529 if (args.length > 0) unknown.push(...args);1530 break;1531 }1532 }15331534 // If using passThroughOptions, stop processing options at first command-argument.1535 if (this._passThroughOptions) {1536 dest.push(arg);1537 if (args.length > 0) dest.push(...args);1538 break;1539 }15401541 // add arg1542 dest.push(arg);1543 }15441545 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1546why, one step back1546 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1547–1548why, one step back15471548 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1549why, one step back1549 * Return an object containing local option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1550–1566why, one step back1550 *1551 * @return {Object}1552 */1553 opts() {1554 if (this._storeOptionsAsProperties) {1555 // Preserve original behaviour so backwards compatible when still using properties1556 const result = {};1557 const len = this.options.length;15581559 for (let i = 0; i < len; i++) {1560 const key = this.options[i].attributeName();1561 result[key] = key === this._versionOptionName ? this._version : this[key];1562 }1563 return result;1564 }15651566 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1567why, one step back1567 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1568–1569why, one step back15681569 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1570why, one step back1570 * Return an object containing merged local and global option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1571why, one step back1571 *Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1572why, one step back1572 * @return {Object}Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1573why, one step back1573 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1574–1575why, one step back1574 optsWithGlobals() {1575 // globals overwrite localsIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1576why, one step back1576 return this._getCommandAndAncestors().reduce(Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1577–1591why, one step back1577 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1578 {}1579 );1580 }15811582 /**1583 * Display error message and exit (or call exitOverride).1584 *1585 * @param {string} message1586 * @param {Object} [errorOptions]1587 * @param {string} [errorOptions.code] - an id string representing the error1588 * @param {number} [errorOptions.exitCode] - used with process.exit1589 */1590 error(message, errorOptions) {1591 // output handlingRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1592why, one step back1592 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 1593–1598why, one step back1593 if (typeof this._showHelpAfterError === 'string') {1594 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1595 } else if (this._showHelpAfterError) {1596 this._outputConfiguration.writeErr('\n');1597 this.outputHelp({ error: true });1598 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1599–1603why, one step back15991600 // exit handling1601 const config = errorOptions || {};1602 const exitCode = config.exitCode || 1;1603 const code = config.code || 'commander.error';Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1604why, one step back1604 this._exit(exitCode, code, message);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1605–1616why, one step back1605 }16061607 /**1608 * Apply any option related environment variables, if option does1609 * not have a value from cli or client code.1610 *1611 * @api private1612 */1613 _parseOptionsEnv() {1614 this.options.forEach((option) => {1615 if (option.envVar && option.envVar in process.env) {1616 const optionKey = option.attributeName();Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 1617–1618why, one step back1617 // Priority check. Do not overwrite cli or options from unknown source (client-code).1618 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 1619–1628why, one step back1619 if (option.required || option.optional) { // option can take a value1620 // keep very simple, optional always takes value1621 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1622 } else { // boolean1623 // keep very simple, only care that envVar defined and not the value1624 this.emit(`optionEnv:${option.name()}`);1625 }1626 }1627 }1628 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1629–1651why, one step back1629 }16301631 /**1632 * Apply any implied option values, if option is undefined or default value.1633 *1634 * @api private1635 */1636 _parseOptionsImplied() {1637 const dualHelper = new DualOptions(this.options);1638 const hasCustomOptionValue = (optionKey) => {1639 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1640 };1641 this.options1642 .filter(option => (option.implied !== undefined) &&1643 hasCustomOptionValue(option.attributeName()) &&1644 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1645 .forEach((option) => {1646 Object.keys(option.implied)1647 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1648 .forEach(impliedKey => {1649 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1650 });1651 });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1652–1662why, one step back1652 }16531654 /**1655 * Argument `name` is missing.1656 *1657 * @param {string} name1658 * @api private1659 */16601661 missingArgument(name) {1662 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1663–1664why, one step back1663 this.error(message, { code: 'commander.missingArgument' });1664 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1665–1674why, one step back16651666 /**1667 * `Option` is missing an argument.1668 *1669 * @param {Option} option1670 * @api private1671 */16721673 optionMissingArgument(option) {1674 const message = `error: option '${option.flags}' argument missing`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1675–1676why, one step back1675 this.error(message, { code: 'commander.optionMissingArgument' });1676 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1677–1686why, one step back16771678 /**1679 * `Option` does not have a value, and is a mandatory option.1680 *1681 * @param {Option} option1682 * @api private1683 */16841685 missingMandatoryOptionValue(option) {1686 const message = `error: required option '${option.flags}' not specified`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1687why, one step back1687 this.error(message, { code: 'commander.missingMandatoryOptionValue' });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1688–1725why, one step back1688 }16891690 /**1691 * `Option` conflicts with another option.1692 *1693 * @param {Option} option1694 * @param {Option} conflictingOption1695 * @api private1696 */1697 _conflictingOption(option, conflictingOption) {1698 // The calling code does not know whether a negated option is the source of the1699 // value, so do some work to take an educated guess.1700 const findBestOptionFromValue = (option) => {1701 const optionKey = option.attributeName();1702 const optionValue = this.getOptionValue(optionKey);1703 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1704 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1705 if (negativeOption && (1706 (negativeOption.presetArg === undefined && optionValue === false) ||1707 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1708 )) {1709 return negativeOption;1710 }1711 return positiveOption || option;1712 };17131714 const getErrorMessage = (option) => {1715 const bestOption = findBestOptionFromValue(option);1716 const optionKey = bestOption.attributeName();1717 const source = this.getOptionValueSource(optionKey);1718 if (source === 'env') {1719 return `environment variable '${bestOption.envVar}'`;1720 }1721 return `option '${bestOption.flags}'`;1722 };17231724 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1725 this.error(message, { code: 'commander.conflictingOption' });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1726why, one step back1726 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1727–1736why, one step back17271728 /**1729 * Unknown option `flag`.1730 *1731 * @param {string} flag1732 * @api private1733 */17341735 unknownOption(flag) {1736 if (this._allowUnknownOption) return;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1737–1741why, one step back1737 let suggestion = '';17381739 if (flag.startsWith('--') && this._showSuggestionAfterError) {1740 // Looping to pick up the global options too1741 let candidateFlags = [];Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734
lines 1742–1743why, one step back1742 let command = this;1743 do {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1744–1747why, one step back1744 const moreFlags = command.createHelp().visibleOptions(command)1745 .filter(option => option.long)1746 .map(option => option.long);1747 candidateFlags = candidateFlags.concat(moreFlags);Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734
lines 1748–1749why, one step back1748 command = command.parent;1749 } while (command && !command._enablePositionalOptions);Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1750–1753why, one step back1750 suggestion = suggestSimilar(flag, candidateFlags);1751 }17521753 const message = `error: unknown option '${flag}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1754–1755why, one step back1754 this.error(message, { code: 'commander.unknownOption' });1755 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1756–1766why, one step back17561757 /**1758 * Excess arguments, more than expected.1759 *1760 * @param {string[]} receivedArgs1761 * @api private1762 */17631764 _excessArguments(receivedArgs) {1765 if (this._allowExcessArguments) return;1766Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1767why, one step back1767 const expected = this.registeredArguments.length;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1768–1770why, one step back1768 const s = (expected === 1) ? '' : 's';1769 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1770 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 1771–1772why, one step back1771 this.error(message, { code: 'commander.excessArguments' });1772 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1773–1780why, one step back17731774 /**1775 * Unknown command.1776 *1777 * @api private1778 */17791780 unknownCommand() {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1781–1794why, one step back1781 const unknownName = this.args[0];1782 let suggestion = '';17831784 if (this._showSuggestionAfterError) {1785 const candidateNames = [];1786 this.createHelp().visibleCommands(this).forEach((command) => {1787 candidateNames.push(command.name());1788 // just visible alias1789 if (command.alias()) candidateNames.push(command.alias());1790 });1791 suggestion = suggestSimilar(unknownName, candidateNames);1792 }17931794 const message = `error: unknown command '${unknownName}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1795–1796why, one step back1795 this.error(message, { code: 'commander.unknownCommand' });1796 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1797–1798why, one step back17971798 /**Types for version getter (#1982)John Geebefore adoptionf5413db
line 1799why, one step back1799 * Get or set the program version.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1800why, one step back1800 *Types for version getter (#1982)John Geebefore adoptionf5413db
line 1801why, one step back1801 * This method auto-registers the "-V, --version" option which will print the version number.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1802why, one step back1802 *Types for version getter (#1982)John Geebefore adoptionf5413db
line 1803why, one step back1803 * You can optionally supply the flags and description to override the defaults.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1804why, one step back1804 *Types for version getter (#1982)John Geebefore adoptionf5413db
line 1805why, one step back1805 * @param {string} [str]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1806–1807why, one step back1806 * @param {string} [flags]1807 * @param {string} [description]Types for version getter (#1982)John Geebefore adoptionf5413db
line 1808why, one step back1808 * @return {this | string | undefined} `this` command for chaining, or version string if no argumentsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1809–1816why, one step back1809 */18101811 version(str, flags, description) {1812 if (str === undefined) return this._version;1813 this._version = str;1814 flags = flags || '-V, --version';1815 description = description || 'output the version number';1816 const versionOption = this.createOption(flags, description);Types for version getter (#1982)John Geebefore adoptionf5413db
line 1817why, one step back1817 this._versionOptionName = versionOption.attributeName(); // [sic] not defined in constructor, partly legacy, partly only needed at rootRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1818–1823why, one step back1818 this.options.push(versionOption);1819 this.on('option:' + versionOption.name(), () => {1820 this._outputConfiguration.writeOut(`${str}\n`);1821 this._exit(0, 'commander.version', str);1822 });1823 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1824why, one step back1824 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1825–1826why, one step back18251826 /**Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 1827why, one step back1827 * Set the description.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1828–1838why, one step back1828 *1829 * @param {string} [str]1830 * @param {Object} [argsDescription]1831 * @return {string|Command}1832 */1833 description(str, argsDescription) {1834 if (str === undefined && argsDescription === undefined) return this._description;1835 this._description = str;1836 if (argsDescription) {1837 this._argsDescription = argsDescription;1838 }Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 1839–1850why, one step back1839 return this;1840 }18411842 /**1843 * Set the summary. Used when listed as subcommand of parent.1844 *1845 * @param {string} [str]1846 * @return {string|Command}1847 */1848 summary(str) {1849 if (str === undefined) return this._summary;1850 this._summary = str;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1851why, one step back1851 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1852why, one step back1852 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1853–1865why, one step back18531854 /**1855 * Set an alias for the command.1856 *1857 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1858 *1859 * @param {string} [alias]1860 * @return {string|Command}1861 */18621863 alias(alias) {1864 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1865Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1866why, one step back1866 /** @type {Command} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1867–1876why, one step back1867 let command = this;1868 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1869 // assume adding alias for last added executable subcommand, rather than this1870 command = this.commands[this.commands.length - 1];1871 }18721873 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');18741875 command._aliases.push(alias);1876 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1877why, one step back1877 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1878–1893why, one step back18781879 /**1880 * Set aliases for the command.1881 *1882 * Only the first alias is shown in the auto-generated help.1883 *1884 * @param {string[]} [aliases]1885 * @return {string[]|Command}1886 */18871888 aliases(aliases) {1889 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1890 if (aliases === undefined) return this._aliases;18911892 aliases.forEach((alias) => this.alias(alias));1893 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1894why, one step back1894 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1895–1906why, one step back18951896 /**1897 * Set / get the command usage `str`.1898 *1899 * @param {string} [str]1900 * @return {String|Command}1901 */19021903 usage(str) {1904 if (str === undefined) {1905 if (this._usage) return this._usage;1906Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1907why, one step back1907 const args = this.registeredArguments.map((arg) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1908–1912why, one step back1908 return humanReadableArgName(arg);1909 });1910 return [].concat(1911 (this.options.length || this._hasHelpOption ? '[options]' : []),1912 (this.commands.length ? '[command]' : []),Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1913why, one step back1913 (this.registeredArguments.length ? args : [])Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1914–1918why, one step back1914 ).join(' ');1915 }19161917 this._usage = str;1918 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1919why, one step back1919 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1920–1921why, one step back19201921 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1922why, one step back1922 * Get or set the name of the command.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1923–1931why, one step back1923 *1924 * @param {string} [str]1925 * @return {string|Command}1926 */19271928 name(str) {1929 if (str === undefined) return this._name;1930 this._name = str;1931 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1932why, one step back1932 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1933–1934why, one step back19331934 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1935–1961why, one step back1935 * Set the name of the command from script filename, such as process.argv[1],1936 * or require.main.filename, or __filename.1937 *1938 * (Used internally and public although not documented in README.)1939 *1940 * @example1941 * program.nameFromFilename(require.main.filename);1942 *1943 * @param {string} filename1944 * @return {Command}1945 */19461947 nameFromFilename(filename) {1948 this._name = path.basename(filename, path.extname(filename));19491950 return this;1951 }19521953 /**1954 * Get or set the directory for searching for executable subcommands of this command.1955 *1956 * @example1957 * program.executableDir(__dirname);1958 * // or1959 * program.executableDir('subcommands');1960 *1961 * @param {string} [path]Fix executableDir() return typeWee Bitbefore adoption68a4276
line 1962why, one step back1962 * @return {string|null|Command}Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1963–1971why, one step back1963 */19641965 executableDir(path) {1966 if (path === undefined) return this._executableDir;1967 this._executableDir = path;1968 return this;1969 }19701971 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1972–1983why, one step back1972 * Return program help documentation.1973 *1974 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1975 * @return {string}1976 */19771978 helpInformation(contextOptions) {1979 const helper = this.createHelp();1980 if (helper.helpWidth === undefined) {1981 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1982 }1983 return helper.formatHelp(this, helper);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1984why, one step back1984 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1985–2019why, one step back19851986 /**1987 * @api private1988 */19891990 _getHelpContext(contextOptions) {1991 contextOptions = contextOptions || {};1992 const context = { error: !!contextOptions.error };1993 let write;1994 if (context.error) {1995 write = (arg) => this._outputConfiguration.writeErr(arg);1996 } else {1997 write = (arg) => this._outputConfiguration.writeOut(arg);1998 }1999 context.write = contextOptions.write || write;2000 context.command = this;The first 2,000 of 2,179 lines.