command.js
This file
Path
lib/command.js
2,181 lines · 69.3 KiB · JavaScript
Last changed by
Add public Arguments property (#2010)John Geebefore adoption7d23437
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–23why, one step back1213// @ts-check1415class Command extends EventEmitter {16 /**17 * Initialize a new `Command`.18 *19 * @param {string} [name]20 */2122 constructor(name) {23 super();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 24why, one step back24 /** @type {Command[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
line 25why, one step back25 this.commands = [];Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 26why, one step back26 /** @type {Option[]} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 27–30why, one step back27 this.options = [];28 this.parent = null;29 this._allowUnknownOption = false;30 this._allowExcessArguments = true;Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 31why, one step back31 /** @type {Argument[]} */Add public Arguments property (#2010)John Geebefore adoption7d23437
lines 32–33why, one step back32 this.registeredArguments = [];33 this._args = this.registeredArguments; // deprecated old nameSupport argument processing without action handler (#1529)John Geebefore adoption4663597
lines 34–37why, one step back34 /** @type {string[]} */35 this.args = []; // cli args with options removed36 this.rawArgs = [];37 this.processedArgs = []; // like .args but after custom processing and collecting variadicRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 38–40why, one step back38 this._scriptPath = null;39 this._name = name || '';40 this._optionValues = {};Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 41why, one step back41 this._optionValueSources = {}; // default, env, cli etcRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 42–45why, one step back42 this._storeOptionsAsProperties = false;43 this._actionHandler = null;44 this._executableHandler = false;45 this._executableFile = null; // custom name for executableMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 46why, one step back46 this._executableDir = null; // custom search directory for subcommandsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 47–51why, one step back47 this._defaultCommandName = null;48 this._exitCallback = null;49 this._aliases = [];50 this._combineFlagAndOptionalValue = true;51 this._description = '';Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 52why, one step back52 this._summary = '';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 53–56why, one step back53 this._argsDescription = undefined; // legacy54 this._enablePositionalOptions = false;55 this._passThroughOptions = false;56 this._lifeCycleHooks = {}; // a hash of arraysAdd showHelpAfterError (#1534)John Geebefore adoption082717f
lines 57–58why, one step back57 /** @type {boolean | string} */58 this._showHelpAfterError = false;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 59why, one step back59 this._showSuggestionAfterError = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 60–83why, one step back6061 // see .configureOutput() for docs62 this._outputConfiguration = {63 writeOut: (str) => process.stdout.write(str),64 writeErr: (str) => process.stderr.write(str),65 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,66 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,67 outputError: (str, write) => write(str)68 };6970 this._hidden = false;71 this._hasHelpOption = true;72 this._helpFlags = '-h, --help';73 this._helpDescription = 'display help for command';74 this._helpShortFlag = '-h';75 this._helpLongFlag = '--help';76 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false77 this._helpCommandName = 'help';78 this._helpCommandnameAndArgs = 'help [command]';79 this._helpCommandDescription = 'display help for command';80 this._helpConfiguration = {};81 }8283 /**Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 84–88why, one step back84 * Copy settings that are useful to have in common across root command and subcommands.85 *86 * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)87 *88 * @param {Command} sourceCommandMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 89why, one step back89 * @return {Command} `this` command for chainingAdd copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 90–107why, one step back90 */91 copyInheritedSettings(sourceCommand) {92 this._outputConfiguration = sourceCommand._outputConfiguration;93 this._hasHelpOption = sourceCommand._hasHelpOption;94 this._helpFlags = sourceCommand._helpFlags;95 this._helpDescription = sourceCommand._helpDescription;96 this._helpShortFlag = sourceCommand._helpShortFlag;97 this._helpLongFlag = sourceCommand._helpLongFlag;98 this._helpCommandName = sourceCommand._helpCommandName;99 this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;100 this._helpCommandDescription = sourceCommand._helpCommandDescription;101 this._helpConfiguration = sourceCommand._helpConfiguration;102 this._exitCallback = sourceCommand._exitCallback;103 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;104 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;105 this._allowExcessArguments = sourceCommand._allowExcessArguments;106 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;107 this._showHelpAfterError = sourceCommand._showHelpAfterError;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 108why, one step back108 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
lines 109–113why, one step back109110 return this;111 }112113 /**Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
lines 114–126why, one step back114 * @returns {Command[]}115 * @api private116 */117118 _getCommandAndAncestors() {119 const result = [];120 for (let command = this; command; command = command.parent) {121 result.push(command);122 }123 return result;124 }125126 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 127–130why, one step back127 * Define a command.128 *129 * There are two styles of command: pay attention to where to put the description.130 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 131–138why, one step back131 * @example132 * // Command implemented using action handler (description is supplied separately to `.command`)133 * program134 * .command('clone <source> [destination]')135 * .description('clone a repository into a newly created directory')136 * .action((source, destination) => {137 * console.log('clone command called');138 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 139why, one step back139 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 140–143why, one step back140 * // Command implemented using separate executable file (description is second parameter to `.command`)141 * program142 * .command('start <service>', 'start named service')143 * .command('stop [service]', 'stop named service, or all if no name supplied');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 144–160why, one step back144 *145 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`146 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)147 * @param {Object} [execOpts] - configuration options (for executable)148 * @return {Command} returns new command for action handler, or `this` for executable command149 */150151 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {152 let desc = actionOptsOrExecDesc;153 let opts = execOpts;154 if (typeof desc === 'object' && desc !== null) {155 opts = desc;156 desc = null;157 }158 opts = opts || {};159 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);160Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
line 161why, one step back161 const cmd = this.createCommand(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 162–171why, one step back162 if (desc) {163 cmd.description(desc);164 cmd._executableHandler = true;165 }166 if (opts.isDefault) this._defaultCommandName = cmd._name;167 cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden168 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor169 if (args) cmd.arguments(args);170 this.commands.push(cmd);171 cmd.parent = this;Add copyInheritedSettings (#1557)John Geebefore adoption5517d25
line 172why, one step back172 cmd.copyInheritedSettings(this);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 173–175why, one step back173174 if (desc) return this;175 return cmd;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 176why, one step back176 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 177–189why, one step back177178 /**179 * Factory routine to create a new unattached command.180 *181 * See .command() for creating an attached subcommand, which uses this routine to182 * create the command. You can override createCommand to customise subcommands.183 *184 * @param {string} [name]185 * @return {Command} new command186 */187188 createCommand(name) {189 return new Command(name);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 190why, one step back190 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 191–200why, one step back191192 /**193 * You can customise the help with a subclass of Help by overriding createHelp,194 * or by overriding Help properties using configureHelp().195 *196 * @return {Help}197 */198199 createHelp() {200 return Object.assign(new Help(), this.configureHelp());Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 201why, one step back201 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 202–223why, one step back202203 /**204 * You can customise the help by overriding Help properties using configureHelp(),205 * or with a subclass of Help by overriding createHelp().206 *207 * @param {Object} [configuration] - configuration options208 * @return {Command|Object} `this` command for chaining, or stored configuration209 */210211 configureHelp(configuration) {212 if (configuration === undefined) return this._helpConfiguration;213214 this._helpConfiguration = configuration;215 return this;216 }217218 /**219 * The default output goes to stdout and stderr. You can customise this for special220 * applications. You can also customise the display of errors by overriding outputError.221 *222 * The configuration properties are all functions:223 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 224–231why, one step back224 * // functions to change where being written, stdout and stderr225 * writeOut(str)226 * writeErr(str)227 * // matching functions to specify width for wrapping help228 * getOutHelpWidth()229 * getErrHelpWidth()230 * // functions based on what is being written out231 * outputError(str, write) // used for displaying errors, and not used for displaying helpRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 232–244why, one step back232 *233 * @param {Object} [configuration] - configuration options234 * @return {Command|Object} `this` command for chaining, or stored configuration235 */236237 configureOutput(configuration) {238 if (configuration === undefined) return this._outputConfiguration;239240 Object.assign(this._outputConfiguration, configuration);241 return this;242 }243244 /**Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 245–256why, one step back245 * Display the help or a custom message after an error occurs.246 *247 * @param {boolean|string} [displayHelp]248 * @return {Command} `this` command for chaining249 */250 showHelpAfterError(displayHelp = true) {251 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;252 this._showHelpAfterError = displayHelp;253 return this;254 }255256 /**Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 257–267why, one step back257 * Display suggestion of similar commands for unknown commands, or options for unknown options.258 *259 * @param {boolean} [displaySuggestion]260 * @return {Command} `this` command for chaining261 */262 showSuggestionAfterError(displaySuggestion = true) {263 this._showSuggestionAfterError = !!displaySuggestion;264 return this;265 }266267 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 268–277why, one step back268 * Add a prepared subcommand.269 *270 * See .command() for creating an attached subcommand which inherits settings from its parent.271 *272 * @param {Command} cmd - new subcommand273 * @param {Object} [opts] - configuration options274 * @return {Command} `this` command for chaining275 */276277 addCommand(cmd, opts) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 278–280why, one step back278 if (!cmd._name) {279 throw new Error(`Command passed to .addCommand() must have a name280- specify the name in Command constructor or using .name()`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 281–289why, one step back281 }282283 opts = opts || {};284 if (opts.isDefault) this._defaultCommandName = cmd._name;285 if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation286287 this.commands.push(cmd);288 cmd.parent = this;289 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 290why, one step back290 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 291–304why, one step back291292 /**293 * Factory routine to create a new unattached argument.294 *295 * See .argument() for creating an attached argument, which uses this routine to296 * create the argument. You can override createArgument to return a custom argument.297 *298 * @param {string} name299 * @param {string} [description]300 * @return {Argument} new argument301 */302303 createArgument(name, description) {304 return new Argument(name, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 305why, one step back305 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 306–313why, one step back306307 /**308 * Define argument syntax for command.309 *310 * The default is that the argument is required, and you can explicitly311 * indicate this with <> around the name. Put [] around the name for an optional argument.312 *313 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 314–315why, one step back314 * program.argument('<input-file>');315 * program.argument('[output-file]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 316–339why, one step back316 *317 * @param {string} name318 * @param {string} [description]319 * @param {Function|*} [fn] - custom argument processing function320 * @param {*} [defaultValue]321 * @return {Command} `this` command for chaining322 */323 argument(name, description, fn, defaultValue) {324 const argument = this.createArgument(name, description);325 if (typeof fn === 'function') {326 argument.default(defaultValue).argParser(fn);327 } else {328 argument.default(fn);329 }330 this.addArgument(argument);331 return this;332 }333334 /**335 * Define argument syntax for command, adding multiple at once (without descriptions).336 *337 * See also .argument().338 *339 * @exampleFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 340why, one step back340 * program.arguments('<cmd> [env]');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 341–346why, one step back341 *342 * @param {string} names343 * @return {Command} `this` command for chaining344 */345346 arguments(names) {trim() input string of .arguments methodАлександр Шмелевbefore adoption2f07c2a
line 347why, one step back347 names.trim().split(/ +/).forEach((detail) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 348–350why, one step back348 this.argument(detail);349 });350 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 351why, one step back351 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 352–359why, one step back352353 /**354 * Define argument syntax for command, adding a prepared argument.355 *356 * @param {Argument} argument357 * @return {Command} `this` command for chaining358 */359 addArgument(argument) {Add public Arguments property (#2010)John Geebefore adoption7d23437
line 360why, one step back360 const previousArgument = this.registeredArguments.slice(-1)[0];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 361–366why, one step back361 if (previousArgument && previousArgument.variadic) {362 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);363 }364 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {365 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);366 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 367why, one step back367 this.registeredArguments.push(argument);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 368–392why, one step back368 return this;369 }370371 /**372 * Override default decision whether to add implicit help command.373 *374 * addHelpCommand() // force on375 * addHelpCommand(false); // force off376 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details377 *378 * @return {Command} `this` command for chaining379 */380381 addHelpCommand(enableOrNameAndArgs, description) {382 if (enableOrNameAndArgs === false) {383 this._addImplicitHelpCommand = false;384 } else {385 this._addImplicitHelpCommand = true;386 if (typeof enableOrNameAndArgs === 'string') {387 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];388 this._helpCommandnameAndArgs = enableOrNameAndArgs;389 }390 this._helpCommandDescription = description || this._helpCommandDescription;391 }392 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 393why, one step back393 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 394–404why, one step back394395 /**396 * @return {boolean}397 * @api private398 */399400 _hasImplicitHelpCommand() {401 if (this._addImplicitHelpCommand === undefined) {402 return this.commands.length && !this._actionHandler && !this._findCommand('help');403 }404 return this._addImplicitHelpCommand;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 405why, one step back405 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 406–415why, one step back406407 /**408 * Add hook for life cycle event.409 *410 * @param {string} event411 * @param {Function} listener412 * @return {Command} `this` command for chaining413 */414415 hook(event, listener) {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
line 416why, one step back416 const allowedValues = ['preSubcommand', 'preAction', 'postAction'];Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 417–448why, one step back417 if (!allowedValues.includes(event)) {418 throw new Error(`Unexpected value for event passed to hook : '${event}'.419Expecting one of '${allowedValues.join("', '")}'`);420 }421 if (this._lifeCycleHooks[event]) {422 this._lifeCycleHooks[event].push(listener);423 } else {424 this._lifeCycleHooks[event] = [listener];425 }426 return this;427 }428429 /**430 * Register callback to use as replacement for calling process.exit.431 *432 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing433 * @return {Command} `this` command for chaining434 */435436 exitOverride(fn) {437 if (fn) {438 this._exitCallback = fn;439 } else {440 this._exitCallback = (err) => {441 if (err.code !== 'commander.executeSubCommandAsync') {442 throw err;443 } else {444 // Async callback from spawn events, not useful to throw.445 }446 };447 }448 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 449why, one step back449 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 450–466why, one step back450451 /**452 * Call process.exit, and _exitCallback if defined.453 *454 * @param {number} exitCode exit code for using with process.exit455 * @param {string} code an id string representing the error456 * @param {string} message human-readable description of the error457 * @return never458 * @api private459 */460461 _exit(exitCode, code, message) {462 if (this._exitCallback) {463 this._exitCallback(new CommanderError(exitCode, code, message));464 // Expecting this line is not reached.465 }466 process.exit(exitCode);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 467why, one step back467 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 468–471why, one step back468469 /**470 * Register callback `fn` for the command.471 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 472–473why, one step back472 * @example473 * programChange .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
lines 474–475why, one step back474 * .command('serve')475 * .description('start service')Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 476why, one step back476 * .action(function() {Change .action() JSDoc/TSDoc example (#1614)John Geebefore adoption36c2f68
line 477why, one step back477 * // do work hereFollow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 478why, one step back478 * });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 479–486why, one step back479 *480 * @param {Function} fn481 * @return {Command} `this` command for chaining482 */483484 action(fn) {485 const listener = (args) => {486 // The .action callback takes an extra parameter which is the command or options.Add public Arguments property (#2010)John Geebefore adoption7d23437
line 487why, one step back487 const expectedArgsCount = this.registeredArguments.length;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 488–499why, one step back488 const actionArgs = args.slice(0, expectedArgsCount);489 if (this._storeOptionsAsProperties) {490 actionArgs[expectedArgsCount] = this; // backwards compatible "options"491 } else {492 actionArgs[expectedArgsCount] = this.opts();493 }494 actionArgs.push(this);495496 return fn.apply(this, actionArgs);497 };498 this._actionHandler = listener;499 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 500why, one step back500 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 501–514why, one step back501502 /**503 * Factory routine to create a new unattached option.504 *505 * See .option() for creating an attached option, which uses this routine to506 * create the option. You can override createOption to return a custom option.507 *508 * @param {string} flags509 * @param {string} [description]510 * @return {Option} new option511 */512513 createOption(flags, description) {514 return new Option(flags, description);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 515why, one step back515 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 516–517why, one step back516517 /**Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 518–539why, one step back518 * Wrap parseArgs to catch 'commander.invalidArgument'.519 *520 * @param {Option | Argument} target521 * @param {string} value522 * @param {any} previous523 * @param {string} invalidArgumentMessage524 * @api private525 */526527 _callParseArg(target, value, previous, invalidArgumentMessage) {528 try {529 return target.parseArg(value, previous);530 } catch (err) {531 if (err.code === 'commander.invalidArgument') {532 const message = `${invalidArgumentMessage} ${err.message}`;533 this.error(message, { exitCode: err.exitCode, code: err.code });534 }535 throw err;536 }537 }538539 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 540–548why, one step back540 * Add an option.541 *542 * @param {Option} option543 * @return {Command} `this` command for chaining544 */545 addOption(option) {546 const oname = option.name();547 const name = option.attributeName();548Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 549–554why, one step back549 // store default value550 if (option.negate) {551 // --no-foo is special and defaults foo to true, unless a --foo option is already defined552 const positiveLongFlag = option.long.replace(/^--no-/, '--');553 if (!this._findOption(positiveLongFlag)) {554 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
line 555why, one step back555 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 556–557why, one step back556 } else if (option.defaultValue !== undefined) {557 this.setOptionValueWithSource(name, option.defaultValue, 'default');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 558–562why, one step back558 }559560 // register the option561 this.options.push(option);562Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 563–564why, one step back563 // handler for cli and env supplied values564 const handleOptionValue = (val, invalidValueMessage, valueSource) => {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 565–569why, one step back565 // val is null for optional option used without an optional-argument.566 // val is undefined for boolean and negated option.567 if (val == null && option.presetArg !== undefined) {568 val = option.presetArg;569 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 570–571why, one step back570571 // custom processingMerge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 572why, one step back572 const oldValue = this.getOptionValue(name);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 573why, one step back573 if (val !== null && option.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
line 574why, one step back574 val = this._callParseArg(option, val, oldValue, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 575–578why, one step back575 } else if (val !== null && option.variadic) {576 val = option._concatValue(val, oldValue);577 }578Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 579–584why, one step back579 // Fill-in appropriate missing values. Long winded but easy to follow.580 if (val == null) {581 if (option.negate) {582 val = false;583 } else if (option.isBoolean() || option.optional) {584 val = true;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 585why, one step back585 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 586why, one step back586 val = ''; // not normal, parseArg might have failed or be a mock function for testingRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 587–588why, one step back587 }588 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 589why, one step back589 this.setOptionValueWithSource(name, val, valueSource);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 590–594why, one step back590 };591592 this.on('option:' + oname, (val) => {593 const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;594 handleOptionValue(val, invalidValueMessage, 'cli');Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 595–596why, one step back595 });596Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 597–603why, one step back597 if (option.envVar) {598 this.on('optionEnv:' + oname, (val) => {599 const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;600 handleOptionValue(val, invalidValueMessage, 'env');601 });602 }603Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 604–612why, one step back604 return this;605 }606607 /**608 * Internal implementation shared by .option() and .requiredOption()609 *610 * @api private611 */612 _optionEx(config, flags, description, fn, defaultValue) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 613–615why, one step back613 if (typeof flags === 'object' && flags instanceof Option) {614 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');615 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 616–635why, one step back616 const option = this.createOption(flags, description);617 option.makeOptionMandatory(!!config.mandatory);618 if (typeof fn === 'function') {619 option.default(defaultValue).argParser(fn);620 } else if (fn instanceof RegExp) {621 // deprecated622 const regex = fn;623 fn = (val, def) => {624 const m = regex.exec(val);625 return m ? m[0] : def;626 };627 option.default(defaultValue).argParser(fn);628 } else {629 option.default(fn);630 }631632 return this.addOption(option);633 }634635 /**Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 636why, one step back636 * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 637why, one step back637 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 638–639why, one step back638 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required639 * option-argument is indicated by `<>` and an optional option-argument by `[]`.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 640why, one step back640 *Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 641why, one step back641 * See the README for more details, and see also addOption() and requiredOption().Refactor classes into files (#1522)John Geebefore adoption08245cc
line 642why, one step back642 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
line 643why, one step back643 * @exampleRework option inline doc (#2009)John Geebefore adoptione85e05a
lines 644–648why, one step back644 * program645 * .option('-p, --pepper', 'add pepper')646 * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument647 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default648 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse functionRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 649–651why, one step back649 *650 * @param {string} flags651 * @param {string} [description]Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 652why, one step back652 * @param {Function|*} [parseArg] - custom option processing function or default valueRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 653–656why, one step back653 * @param {*} [defaultValue]654 * @return {Command} `this` command for chaining655 */656Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 657–658why, one step back657 option(flags, description, parseArg, defaultValue) {658 return this._optionEx({}, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 659why, one step back659 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 660–668why, one step back660661 /**662 * Add a required option which must have a value after parsing. This usually means663 * the option must be specified on the command line. (Otherwise the same as .option().)664 *665 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.666 *667 * @param {string} flags668 * @param {string} [description]Rework option inline doc (#2009)John Geebefore adoptione85e05a
line 669why, one step back669 * @param {Function|*} [parseArg] - custom option processing function or default valueRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 670–673why, one step back670 * @param {*} [defaultValue]671 * @return {Command} `this` command for chaining672 */673Rework option inline doc (#2009)John Geebefore adoptione85e05a
lines 674–675why, one step back674 requiredOption(flags, description, parseArg, defaultValue) {675 return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 676why, one step back676 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 677–680why, one step back677678 /**679 * Alter parsing of short flags with optional values.680 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 681–684why, one step back681 * @example682 * // for `.option('-f,--flag [value]'):683 * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour684 * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 685–690why, one step back685 *686 * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.687 */688 combineFlagAndOptionalValue(combine = true) {689 this._combineFlagAndOptionalValue = !!combine;690 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 691why, one step back691 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 692–701why, one step back692693 /**694 * Allow unknown options on the command line.695 *696 * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown697 * for unknown options.698 */699 allowUnknownOption(allowUnknown = true) {700 this._allowUnknownOption = !!allowUnknown;701 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 702why, one step back702 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 703–712why, one step back703704 /**705 * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.706 *707 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown708 * for excess arguments.709 */710 allowExcessArguments(allowExcess = true) {711 this._allowExcessArguments = !!allowExcess;712 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 713why, one step back713 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 714–724why, one step back714715 /**716 * Enable positional options. Positional means global options are specified before subcommands which lets717 * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.718 * The default behaviour is non-positional and global options may appear anywhere on the command line.719 *720 * @param {Boolean} [positional=true]721 */722 enablePositionalOptions(positional = true) {723 this._enablePositionalOptions = !!positional;724 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 725why, one step back725 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 726–741why, one step back726727 /**728 * Pass through options that come after command-arguments rather than treat them as command-options,729 * so actual command-options come before command-arguments. Turning this on for a subcommand requires730 * positional options to have been enabled on the program (parent commands).731 * The default behaviour is non-positional and options may appear before or after command-arguments.732 *733 * @param {Boolean} [passThrough=true]734 * for unknown options.735 */736 passThroughOptions(passThrough = true) {737 this._passThroughOptions = !!passThrough;738 if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {739 throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');740 }741 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 742why, one step back742 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 743–755why, one step back743744 /**745 * Whether to store option values as properties on command object,746 * or store separately (specify false). In both cases the option values can be accessed using .opts().747 *748 * @param {boolean} [storeAsProperties=true]749 * @return {Command} `this` command for chaining750 */751752 storeOptionsAsProperties(storeAsProperties = true) {753 if (this.options.length) {754 throw new Error('call .storeOptionsAsProperties() before adding options');755 }Throw error on options-as-properties config after setting option valuesWee Bitbefore adoptionff0fd9e
lines 756–759why, one step back756 if (Object.keys(this._optionValues).length) {757 throw new Error('call .storeOptionsAsProperties() before setting option values');758 }759 this._storeOptionsAsProperties = !!storeAsProperties;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 760why, one step back760 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 761why, one step back761 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 762–774why, one step back762763 /**764 * Retrieve option value.765 *766 * @param {string} key767 * @return {Object} value768 */769770 getOptionValue(key) {771 if (this._storeOptionsAsProperties) {772 return this[key];773 }774 return this._optionValues[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 775why, one step back775 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 776–785why, one step back776777 /**778 * Store option value.779 *780 * @param {string} key781 * @param {Object} value782 * @return {Command} `this` command for chaining783 */784785 setOptionValue(key, value) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
line 786why, one step back786 return this.setOptionValueWithSource(key, value, undefined);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 787why, one step back787 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 788–789why, one step back788789 /**Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 790why, one step back790 * Store option value and where the value came from.Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 791–793why, one step back791 *792 * @param {string} key793 * @param {Object} valueAdd implied to option value sources (#1794)John Geebefore adoption72be61c
line 794why, one step back794 * @param {string} source - expected values are default/config/env/cli/impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 795–798why, one step back795 * @return {Command} `this` command for chaining796 */797798 setOptionValueWithSource(key, value, source) {setOptionValue should clear option source (#1795)John Geebefore adoption84d9201
lines 799–803why, one step back799 if (this._storeOptionsAsProperties) {800 this[key] = value;801 } else {802 this._optionValues[key] = value;803 }Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 804why, one step back804 this._optionValueSources[key] = source;Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 805why, one step back805 return this;Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 806–808why, one step back806 }807808 /**Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 809why, one step back809 * Get source of option value.Add implied to option value sources (#1794)John Geebefore adoption72be61c
line 810why, one step back810 * Expected values are default | config | env | cli | impliedAdd setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 811–817why, one step back811 *812 * @param {string} key813 * @return {string}814 */815816 getOptionValueSource(key) {817 return this._optionValueSources[key];Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 818why, one step back818 }Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 819–820why, one step back819820 /**Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 821–830why, one step back821 * Get source of option value. See also .optsWithGlobals().822 * Expected values are default | config | env | cli | implied823 *824 * @param {string} key825 * @return {string}826 */827828 getOptionValueSourceWithGlobals(key) {829 // global overwrites local, like optsWithGlobals830 let source;Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 831why, one step back831 this._getCommandAndAncestors().forEach((cmd) => {Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 832–839why, one step back832 if (cmd.getOptionValueSource(key) !== undefined) {833 source = cmd.getOptionValueSource(key);834 }835 });836 return source;837 }838839 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 840–841why, one step back840 * Get user arguments from implied or explicit arguments.841 * 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 842–885why, one step back842 *843 * @api private844 */845846 _prepareUserArgs(argv, parseOptions) {847 if (argv !== undefined && !Array.isArray(argv)) {848 throw new Error('first parameter to parse must be array or undefined');849 }850 parseOptions = parseOptions || {};851852 // Default to using process.argv853 if (argv === undefined) {854 argv = process.argv;855 // @ts-ignore: unknown property856 if (process.versions && process.versions.electron) {857 parseOptions.from = 'electron';858 }859 }860 this.rawArgs = argv.slice();861862 // make it a little easier for callers by supporting various argv conventions863 let userArgs;864 switch (parseOptions.from) {865 case undefined:866 case 'node':867 this._scriptPath = argv[1];868 userArgs = argv.slice(2);869 break;870 case 'electron':871 // @ts-ignore: unknown property872 if (process.defaultApp) {873 this._scriptPath = argv[1];874 userArgs = argv.slice(2);875 } else {876 userArgs = argv.slice(1);877 }878 break;879 case 'user':880 userArgs = argv.slice(0);881 break;882 default:883 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);884 }885Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 886–888why, one step back886 // Find default name for program from arguments.887 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);888 this._name = this._name || 'program';Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 889–898why, one step back889890 return userArgs;891 }892893 /**894 * Parse `argv`, setting options and invoking commands when defined.895 *896 * The default expectation is that the arguments are from node and have the application as argv[0]897 * and the script being run in argv[1], with user parameters after that.898 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 899–902why, one step back899 * @example900 * program.parse(process.argv);901 * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions902 * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 903–914why, one step back903 *904 * @param {string[]} [argv] - optional, defaults to process.argv905 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron906 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'907 * @return {Command} `this` command for chaining908 */909910 parse(argv, parseOptions) {911 const userArgs = this._prepareUserArgs(argv, parseOptions);912 this._parseCommand([], userArgs);913914 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 915why, one step back915 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 916–924why, one step back916917 /**918 * Parse `argv`, setting options and invoking commands when defined.919 *920 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.921 *922 * The default expectation is that the arguments are from node and have the application as argv[0]923 * and the script being run in argv[1], with user parameters after that.924 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 925–928why, one step back925 * @example926 * await program.parseAsync(process.argv);927 * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions928 * 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 929–940why, one step back929 *930 * @param {string[]} [argv]931 * @param {Object} [parseOptions]932 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'933 * @return {Promise}934 */935936 async parseAsync(argv, parseOptions) {937 const userArgs = this._prepareUserArgs(argv, parseOptions);938 await this._parseCommand([], userArgs);939940 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 941why, one step back941 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 942–953why, one step back942943 /**944 * Execute a sub-command executable.945 *946 * @api private947 */948949 _executeSubCommand(subcommand, args) {950 args = args.slice();951 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.952 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];953Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 954–957why, one step back954 function findFile(baseDir, baseName) {955 // Look for specified file956 const localBin = path.resolve(baseDir, baseName);957 if (fs.existsSync(localBin)) return localBin;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 958why, one step back958Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 959–960why, one step back959 // Stop looking if candidate already has an expected extension.960 if (sourceExt.includes(path.extname(baseName))) return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 961why, one step back961Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 962–966why, one step back962 // Try all the extensions.963 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));964 if (foundExt) return `${localBin}${foundExt}`;965966 return undefined;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 967–968why, one step back967 }968Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 969–970why, one step back969 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.970 this._checkForMissingMandatoryOptions();Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 971why, one step back971 this._checkForConflictingOptions();Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 972–983why, one step back972973 // executableFile and executableDir might be full path, or just a name974 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;975 let executableDir = this._executableDir || '';976 if (this._scriptPath) {977 let resolvedScriptPath; // resolve possible symlink for installed npm binary978 try {979 resolvedScriptPath = fs.realpathSync(this._scriptPath);980 } catch (err) {981 resolvedScriptPath = this._scriptPath;982 }983 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 984–985why, one step back984 }985Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 986–994why, one step back986 // Look for a local file in preference to a command in PATH.987 if (executableDir) {988 let localFile = findFile(executableDir, executableFile);989990 // Legacy search using prefix of script name instead of command name991 if (!localFile && !subcommand._executableFile && this._scriptPath) {992 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));993 if (legacyName !== this._name) {994 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);Refactor classes into files (#1522)John Geebefore adoption08245cc
line 995why, one step back995 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 996–997why, one step back996 }997 executableFile = localFile || executableFile;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 998–999why, one step back998 }999Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1000–1001why, one step back1000 launchWithNode = sourceExt.includes(path.extname(executableFile));1001Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1002–1004why, one step back1002 let proc;1003 if (process.platform !== 'win32') {1004 if (launchWithNode) {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1005why, one step back1005 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1006–1010why, one step back1006 // add executable arguments to spawn1007 args = incrementNodeInspectorPort(process.execArgv).concat(args);10081009 proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });1010 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1011why, one step back1011 proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1012–1013why, one step back1012 }1013 } else {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1014why, one step back1014 args.unshift(executableFile);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1015–1019why, one step back1015 // add executable arguments to spawn1016 args = incrementNodeInspectorPort(process.execArgv).concat(args);1017 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1018 }1019Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1020–1028why, one step back1020 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1021 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1022 signals.forEach((signal) => {1023 // @ts-ignore1024 process.on(signal, () => {1025 if (proc.killed === false && proc.exitCode === null) {1026 proc.kill(signal);1027 }1028 });Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1029why, one step back1029 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1030why, one step back1030 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1031–1044why, one step back10311032 // By default terminate process when spawned process terminates.1033 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!1034 const exitCallback = this._exitCallback;1035 if (!exitCallback) {1036 proc.on('close', process.exit.bind(process));1037 } else {1038 proc.on('close', () => {1039 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));1040 });1041 }1042 proc.on('error', (err) => {1043 // @ts-ignore1044 if (err.code === 'ENOENT') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1045–1048why, one step back1045 const executableDirMessage = executableDir1046 ? `searched for local subcommand relative to directory '${executableDir}'`1047 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';1048 const executableMissing = `'${executableFile}' does not existRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1049why, one step back1049 - 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 1050–1051why, one step back1050 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1051 - ${executableDirMessage}`;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1052–1054why, one step back1052 throw new Error(executableMissing);1053 // @ts-ignore1054 } else if (err.code === 'EACCES') {Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1055why, one step back1055 throw new Error(`'${executableFile}' not executable`);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1056–1067why, one step back1056 }1057 if (!exitCallback) {1058 process.exit(1);1059 } else {1060 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1061 wrappedError.nestedError = err;1062 exitCallback(wrappedError);1063 }1064 });10651066 // Store the reference to the child process1067 this.runningCommand = proc;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1068why, one step back1068 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1069–1077why, one step back10691070 /**1071 * @api private1072 */10731074 _dispatchSubcommand(commandName, operands, unknown) {1075 const subCommand = this._findCommand(commandName);1076 if (!subCommand) this.help({ error: true });1077Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1078–1080why, one step back1078 let promiseChain;1079 promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');1080 promiseChain = this._chainOrCall(promiseChain, () => {feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1081–1086why, one step back1081 if (subCommand._executableHandler) {1082 this._executeSubCommand(subCommand, operands.concat(unknown));1083 } else {1084 return subCommand._parseCommand(operands, unknown);1085 }1086 });Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1087why, one step back1087 return promiseChain;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1088why, one step back1088 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1089–1090why, one step back10891090 /**Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1091–1106why, one step back1091 * Invoke help directly if possible, or dispatch if necessary.1092 * e.g. help foo1093 *1094 * @api private1095 */10961097 _dispatchHelpCommand(subcommandName) {1098 if (!subcommandName) {1099 this.help();1100 }1101 const subCommand = this._findCommand(subcommandName);1102 if (subCommand && !subCommand._executableHandler) {1103 subCommand.help();1104 }11051106 // 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 1107–1109why, one step back1107 return this._dispatchSubcommand(subcommandName, [], [1108 this._helpLongFlag || this._helpShortFlag1109 ]);Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
lines 1110–1112why, one step back1110 }11111112 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1113why, one step back1113 * Check this.args against expected this.registeredArguments.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1114–1117why, one step back1114 *1115 * @api private1116 */1117Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1118–1119why, one step back1118 _checkNumberOfArguments() {1119 // too fewAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1120why, one step back1120 this.registeredArguments.forEach((arg, i) => {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1121–1125why, one step back1121 if (arg.required && this.args[i] == null) {1122 this.missingArgument(arg.name());1123 }1124 });1125 // too manyAdd public Arguments property (#2010)John Geebefore adoption7d23437
line 1126why, one step back1126 if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1127–1128why, one step back1127 return;1128 }Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1129why, one step back1129 if (this.args.length > this.registeredArguments.length) {Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1130–1131why, one step back1130 this._excessArguments(this.args);1131 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1132why, one step back1132 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1133–1134why, one step back11331134 /**Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1135why, one step back1135 * Process this.args using this.registeredArguments and save as this.processedArgs!Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1136–1140why, one step back1136 *1137 * @api private1138 */11391140 _processArguments() {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1141–1144why, one step back1141 const myParseArg = (argument, value, previous) => {1142 // Extra processing for nice error message on parsing failure.1143 let parsedValue = value;1144 if (value !== null && argument.parseArg) {Refactor to wrap invalid argument (#1977)John Geebefore adoption4c095d1
lines 1145–1146why, one step back1145 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1146 parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1147–1150why, one step back1147 }1148 return parsedValue;1149 };1150Support argument processing without action handler (#1529)John Geebefore adoption4663597
lines 1151–1153why, one step back1151 this._checkNumberOfArguments();11521153 const processedArgs = [];Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1154why, one step back1154 this.registeredArguments.forEach((declaredArg, index) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1155–1173why, one step back1155 let value = declaredArg.defaultValue;1156 if (declaredArg.variadic) {1157 // Collect together remaining arguments for passing together as an array.1158 if (index < this.args.length) {1159 value = this.args.slice(index);1160 if (declaredArg.parseArg) {1161 value = value.reduce((processed, v) => {1162 return myParseArg(declaredArg, v, processed);1163 }, declaredArg.defaultValue);1164 }1165 } else if (value === undefined) {1166 value = [];1167 }1168 } else if (index < this.args.length) {1169 value = this.args[index];1170 if (declaredArg.parseArg) {1171 value = myParseArg(declaredArg, value, declaredArg.defaultValue);1172 }1173 }Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1174why, one step back1174 processedArgs[index] = value;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1175why, one step back1175 });Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1176why, one step back1176 this.processedArgs = processedArgs;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1177–1184why, one step back1177 }11781179 /**1180 * Once we have a promise we chain, but call synchronously until then.1181 *1182 * @param {Promise|undefined} promise1183 * @param {Function} fn1184 * @return {Promise|undefined}Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
line 1185why, one step back1185 * @api privateRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1186–1208why, one step back1186 */11871188 _chainOrCall(promise, fn) {1189 // thenable1190 if (promise && promise.then && typeof promise.then === 'function') {1191 // already have a promise, chain callback1192 return promise.then(() => fn());1193 }1194 // callback might return a promise1195 return fn();1196 }11971198 /**1199 *1200 * @param {Promise|undefined} promise1201 * @param {string} event1202 * @return {Promise|undefined}1203 * @api private1204 */12051206 _chainOrCallHooks(promise, event) {1207 let result = promise;1208 const hooks = [];Introduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1209why, one step back1209 this._getCommandAndAncestors()Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1210–1225why, one step back1210 .reverse()1211 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1212 .forEach(hookedCommand => {1213 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1214 hooks.push({ hookedCommand, callback });1215 });1216 });1217 if (event === 'postAction') {1218 hooks.reverse();1219 }12201221 hooks.forEach((hookDetail) => {1222 result = this._chainOrCall(result, () => {1223 return hookDetail.callback(hookDetail.hookedCommand, this);1224 });1225 });feat: add preSubcommand hook (#1763)鸿则before adoption2c7f687
lines 1226–1246why, one step back1226 return result;1227 }12281229 /**1230 *1231 * @param {Promise|undefined} promise1232 * @param {Command} subCommand1233 * @param {string} event1234 * @return {Promise|undefined}1235 * @api private1236 */12371238 _chainOrCallSubCommandHook(promise, subCommand, event) {1239 let result = promise;1240 if (this._lifeCycleHooks[event] !== undefined) {1241 this._lifeCycleHooks[event].forEach((hook) => {1242 result = this._chainOrCall(result, () => {1243 return hook(this, subCommand);1244 });1245 });1246 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1247–1258why, one step back1247 return result;1248 }12491250 /**1251 * Process arguments in context of this command.1252 * Returns action result, in case it is a promise.1253 *1254 * @api private1255 */12561257 _parseCommand(operands, unknown) {1258 const parsed = this.parseOptions(unknown);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
line 1259why, one step back1259 this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and envAdd Option.implies() (#1724)John Geebefore adoptiond660967
line 1260why, one step back1260 this._parseOptionsImplied();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1261–1268why, one step back1261 operands = operands.concat(parsed.operands);1262 unknown = parsed.unknown;1263 this.args = operands.concat(unknown);12641265 if (operands && this._findCommand(operands[0])) {1266 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1267 }1268 if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {Have help command call help directly for subcommands, when possible (#1864)John Geebefore adoption63abdac
line 1269why, one step back1269 return this._dispatchHelpCommand(operands[1]);Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1270–1281why, one step back1270 }1271 if (this._defaultCommandName) {1272 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command1273 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1274 }1275 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1276 // probably missing subcommand and no handler, user needs help (and exit)1277 this.help({ error: true });1278 }12791280 outputHelpIfRequested(this, parsed.unknown);1281 this._checkForMissingMandatoryOptions();feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
line 1282why, one step back1282 this._checkForConflictingOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1283–1293why, one step back12831284 // We do not always call this check to avoid masking a "better" error, like unknown command.1285 const checkForUnknownOptions = () => {1286 if (parsed.unknown.length > 0) {1287 this.unknownOption(parsed.unknown[0]);1288 }1289 };12901291 const commandEvent = `command:${this.name()}`;1292 if (this._actionHandler) {1293 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1294why, one step back1294 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1295why, one step back1295Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1296–1298why, one step back1296 let promiseChain;1297 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1298 promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
line 1299why, one step back1299 if (this.parent) {Improve chain variable name (#1958)John Geebefore adoption5740e59
line 1300why, one step back1300 promiseChain = this._chainOrCall(promiseChain, () => {Wrap emit to preserve callback order when async (#1638)John Geebefore adoption35a028b
lines 1301–1303why, one step back1301 this.parent.emit(commandEvent, operands, unknown); // legacy1302 });1303 }Improve chain variable name (#1958)John Geebefore adoption5740e59
lines 1304–1305why, one step back1304 promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');1305 return promiseChain;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1306–1308why, one step back1306 }1307 if (this.parent && this.parent.listenerCount(commandEvent)) {1308 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1309why, one step back1309 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1310–1321why, one step back1310 this.parent.emit(commandEvent, operands, unknown); // legacy1311 } else if (operands.length) {1312 if (this._findCommand('*')) { // legacy default command1313 return this._dispatchSubcommand('*', operands, unknown);1314 }1315 if (this.listenerCount('command:*')) {1316 // skip option check, emit event for possible misspelling suggestion1317 this.emit('command:*', operands, unknown);1318 } else if (this.commands.length) {1319 this.unknownCommand();1320 } else {1321 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1322why, one step back1322 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1323–1324why, one step back1323 }1324 } else if (this.commands.length) {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
line 1325why, one step back1325 checkForUnknownOptions();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1326–1329why, one step back1326 // This command has subcommands and nothing hooked up at this level, so display help (and exit).1327 this.help({ error: true });1328 } else {1329 checkForUnknownOptions();Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1330why, one step back1330 this._processArguments();Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1331–1332why, one step back1331 // fall through for caller to handle after calling .parse()1332 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1333why, one step back1333 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1334–1342why, one step back13341335 /**1336 * Find matching command.1337 *1338 * @api private1339 */1340 _findCommand(name) {1341 if (!name) return undefined;1342 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1343why, one step back1343 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1344–1354why, one step back13441345 /**1346 * Return an option matching `arg` if any.1347 *1348 * @param {string} arg1349 * @return {Option}1350 * @api private1351 */13521353 _findOption(arg) {1354 return this.options.find(option => option.is(arg));Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1355why, one step back1355 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1356–1358why, one step back13561357 /**1358 * Display an error message if a mandatory option does not have a value.Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1359why, one step back1359 * Called after checking for help flags in leaf subcommand.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1360–1365why, one step back1360 *1361 * @api private1362 */13631364 _checkForMissingMandatoryOptions() {1365 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1366why, one step back1366 this._getCommandAndAncestors().forEach((cmd) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1367–1371why, one step back1367 cmd.options.forEach((anOption) => {1368 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1369 cmd.missingMandatoryOptionValue(anOption);1370 }1371 });Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1372why, one step back1372 });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1373why, one step back1373 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1374–1375why, one step back13741375 /**Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1376why, one step back1376 * 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 1377–1379why, one step back1377 *1378 * @api private1379 */Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1380why, one step back1380 _checkForConflictingLocalOptions() {feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1381–1402why, one step back1381 const definedNonDefaultOptions = this.options.filter(1382 (option) => {1383 const optionKey = option.attributeName();1384 if (this.getOptionValue(optionKey) === undefined) {1385 return false;1386 }1387 return this.getOptionValueSource(optionKey) !== 'default';1388 }1389 );13901391 const optionsWithConflicting = definedNonDefaultOptions.filter(1392 (option) => option.conflictsWith.length > 01393 );13941395 optionsWithConflicting.forEach((option) => {1396 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1397 option.conflictsWith.includes(defined.attributeName())1398 );1399 if (conflictingAndDefined) {1400 this._conflictingOption(option, conflictingAndDefined);1401 }1402 });Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
lines 1403–1412why, one step back1403 }14041405 /**1406 * Display an error message if conflicting options are used together.1407 * Called after checking for help flags in leaf subcommand.1408 *1409 * @api private1410 */1411 _checkForConflictingOptions() {1412 // Walk up hierarchy so can call in subcommand after checking for displaying help.Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1413why, one step back1413 this._getCommandAndAncestors().forEach((cmd) => {Check for conflicts in parent commands (#1711)John Geebefore adoptionbf205d1
line 1414why, one step back1414 cmd._checkForConflictingLocalOptions();Use _getCommandAndAncestors() consistentlyWee Bitbefore adoption25ebead
line 1415why, one step back1415 });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1416–1418why, one step back1416 }14171418 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1419–1423why, one step back1419 * Parse options from `argv` removing known options,1420 * and return argv split into operands and unknown arguments.1421 *1422 * Examples:1423 *Follow jsdoc and tsdoc more closely, especially @example (#1562)John Geebefore adoption56c4108
lines 1424–1428why, one step back1424 * argv => operands, unknown1425 * --known kkk op => [op], []1426 * op --known kkk => [op], []1427 * sub --unknown uuu op => [sub], [--unknown uuu op]1428 * sub -- --unknown uuu op => [sub --unknown uuu op], []Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1429–1547why, one step back1429 *1430 * @param {String[]} argv1431 * @return {{operands: String[], unknown: String[]}}1432 */14331434 parseOptions(argv) {1435 const operands = []; // operands, not options or values1436 const unknown = []; // first unknown option and remaining unknown args1437 let dest = operands;1438 const args = argv.slice();14391440 function maybeOption(arg) {1441 return arg.length > 1 && arg[0] === '-';1442 }14431444 // parse options1445 let activeVariadicOption = null;1446 while (args.length) {1447 const arg = args.shift();14481449 // literal1450 if (arg === '--') {1451 if (dest === unknown) dest.push(arg);1452 dest.push(...args);1453 break;1454 }14551456 if (activeVariadicOption && !maybeOption(arg)) {1457 this.emit(`option:${activeVariadicOption.name()}`, arg);1458 continue;1459 }1460 activeVariadicOption = null;14611462 if (maybeOption(arg)) {1463 const option = this._findOption(arg);1464 // recognised option, call listener to assign value with possible custom processing1465 if (option) {1466 if (option.required) {1467 const value = args.shift();1468 if (value === undefined) this.optionMissingArgument(option);1469 this.emit(`option:${option.name()}`, value);1470 } else if (option.optional) {1471 let value = null;1472 // historical behaviour is optional value is following arg unless an option1473 if (args.length > 0 && !maybeOption(args[0])) {1474 value = args.shift();1475 }1476 this.emit(`option:${option.name()}`, value);1477 } else { // boolean flag1478 this.emit(`option:${option.name()}`);1479 }1480 activeVariadicOption = option.variadic ? option : null;1481 continue;1482 }1483 }14841485 // Look for combo options following single dash, eat first one if known.1486 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1487 const option = this._findOption(`-${arg[1]}`);1488 if (option) {1489 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1490 // option with value following in same argument1491 this.emit(`option:${option.name()}`, arg.slice(2));1492 } else {1493 // boolean option, emit and put back remainder of arg for further processing1494 this.emit(`option:${option.name()}`);1495 args.unshift(`-${arg.slice(2)}`);1496 }1497 continue;1498 }1499 }15001501 // Look for known long flag with value, like --foo=bar1502 if (/^--[^=]+=/.test(arg)) {1503 const index = arg.indexOf('=');1504 const option = this._findOption(arg.slice(0, index));1505 if (option && (option.required || option.optional)) {1506 this.emit(`option:${option.name()}`, arg.slice(index + 1));1507 continue;1508 }1509 }15101511 // Not a recognised option by this command.1512 // Might be a command-argument, or subcommand option, or unknown option, or help command or option.15131514 // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.1515 if (maybeOption(arg)) {1516 dest = unknown;1517 }15181519 // If using positionalOptions, stop processing our options at subcommand.1520 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1521 if (this._findCommand(arg)) {1522 operands.push(arg);1523 if (args.length > 0) unknown.push(...args);1524 break;1525 } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {1526 operands.push(arg);1527 if (args.length > 0) operands.push(...args);1528 break;1529 } else if (this._defaultCommandName) {1530 unknown.push(arg);1531 if (args.length > 0) unknown.push(...args);1532 break;1533 }1534 }15351536 // If using passThroughOptions, stop processing options at first command-argument.1537 if (this._passThroughOptions) {1538 dest.push(arg);1539 if (args.length > 0) dest.push(...args);1540 break;1541 }15421543 // add arg1544 dest.push(arg);1545 }15461547 return { operands, unknown };Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1548why, one step back1548 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1549–1550why, one step back15491550 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1551why, one step back1551 * Return an object containing local option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1552–1568why, one step back1552 *1553 * @return {Object}1554 */1555 opts() {1556 if (this._storeOptionsAsProperties) {1557 // Preserve original behaviour so backwards compatible when still using properties1558 const result = {};1559 const len = this.options.length;15601561 for (let i = 0; i < len; i++) {1562 const key = this.options[i].attributeName();1563 result[key] = key === this._versionOptionName ? this._version : this[key];1564 }1565 return result;1566 }15671568 return this._optionValues;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1569why, one step back1569 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1570–1571why, one step back15701571 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1572why, one step back1572 * Return an object containing merged local and global option values as key-value pairs.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1573why, one step back1573 *Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1574why, one step back1574 * @return {Object}Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1575why, one step back1575 */Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1576–1577why, one step back1576 optsWithGlobals() {1577 // globals overwrite localsIntroduce _getCommandAndAncestors()Wee Bitbefore adoption1f90b11
line 1578why, one step back1578 return this._getCommandAndAncestors().reduce(Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1579–1593why, one step back1579 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1580 {}1581 );1582 }15831584 /**1585 * Display error message and exit (or call exitOverride).1586 *1587 * @param {string} message1588 * @param {Object} [errorOptions]1589 * @param {string} [errorOptions.code] - an id string representing the error1590 * @param {number} [errorOptions.exitCode] - used with process.exit1591 */1592 error(message, errorOptions) {1593 // output handlingRefactor classes into files (#1522)John Geebefore adoption08245cc
line 1594why, one step back1594 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);Add showHelpAfterError (#1534)John Geebefore adoption082717f
lines 1595–1600why, one step back1595 if (typeof this._showHelpAfterError === 'string') {1596 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1597 } else if (this._showHelpAfterError) {1598 this._outputConfiguration.writeErr('\n');1599 this.outputHelp({ error: true });1600 }Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1601–1605why, one step back16011602 // exit handling1603 const config = errorOptions || {};1604 const exitCode = config.exitCode || 1;1605 const code = config.code || 'commander.error';Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1606why, one step back1606 this._exit(exitCode, code, message);Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75
lines 1607–1618why, one step back1607 }16081609 /**1610 * Apply any option related environment variables, if option does1611 * not have a value from cli or client code.1612 *1613 * @api private1614 */1615 _parseOptionsEnv() {1616 this.options.forEach((option) => {1617 if (option.envVar && option.envVar in process.env) {1618 const optionKey = option.attributeName();Add setOptionValueWithSource and getOptionValueSource (#1613)John Geebefore adoption6e00f44
lines 1619–1620why, one step back1619 // Priority check. Do not overwrite cli or options from unknown source (client-code).1620 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 1621–1630why, one step back1621 if (option.required || option.optional) { // option can take a value1622 // keep very simple, optional always takes value1623 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1624 } else { // boolean1625 // keep very simple, only care that envVar defined and not the value1626 this.emit(`optionEnv:${option.name()}`);1627 }1628 }1629 }1630 });Add Option.implies() (#1724)John Geebefore adoptiond660967
lines 1631–1653why, one step back1631 }16321633 /**1634 * Apply any implied option values, if option is undefined or default value.1635 *1636 * @api private1637 */1638 _parseOptionsImplied() {1639 const dualHelper = new DualOptions(this.options);1640 const hasCustomOptionValue = (optionKey) => {1641 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1642 };1643 this.options1644 .filter(option => (option.implied !== undefined) &&1645 hasCustomOptionValue(option.attributeName()) &&1646 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1647 .forEach((option) => {1648 Object.keys(option.implied)1649 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1650 .forEach(impliedKey => {1651 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1652 });1653 });Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1654–1664why, one step back1654 }16551656 /**1657 * Argument `name` is missing.1658 *1659 * @param {string} name1660 * @api private1661 */16621663 missingArgument(name) {1664 const message = `error: missing required argument '${name}'`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1665–1666why, one step back1665 this.error(message, { code: 'commander.missingArgument' });1666 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1667–1676why, one step back16671668 /**1669 * `Option` is missing an argument.1670 *1671 * @param {Option} option1672 * @api private1673 */16741675 optionMissingArgument(option) {1676 const message = `error: option '${option.flags}' argument missing`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1677–1678why, one step back1677 this.error(message, { code: 'commander.optionMissingArgument' });1678 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1679–1688why, one step back16791680 /**1681 * `Option` does not have a value, and is a mandatory option.1682 *1683 * @param {Option} option1684 * @api private1685 */16861687 missingMandatoryOptionValue(option) {1688 const message = `error: required option '${option.flags}' not specified`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1689why, one step back1689 this.error(message, { code: 'commander.missingMandatoryOptionValue' });feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41
lines 1690–1727why, one step back1690 }16911692 /**1693 * `Option` conflicts with another option.1694 *1695 * @param {Option} option1696 * @param {Option} conflictingOption1697 * @api private1698 */1699 _conflictingOption(option, conflictingOption) {1700 // The calling code does not know whether a negated option is the source of the1701 // value, so do some work to take an educated guess.1702 const findBestOptionFromValue = (option) => {1703 const optionKey = option.attributeName();1704 const optionValue = this.getOptionValue(optionKey);1705 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1706 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1707 if (negativeOption && (1708 (negativeOption.presetArg === undefined && optionValue === false) ||1709 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1710 )) {1711 return negativeOption;1712 }1713 return positiveOption || option;1714 };17151716 const getErrorMessage = (option) => {1717 const bestOption = findBestOptionFromValue(option);1718 const optionKey = bestOption.attributeName();1719 const source = this.getOptionValueSource(optionKey);1720 if (source === 'env') {1721 return `environment variable '${bestOption.envVar}'`;1722 }1723 return `option '${bestOption.flags}'`;1724 };17251726 const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;1727 this.error(message, { code: 'commander.conflictingOption' });Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1728why, one step back1728 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1729–1738why, one step back17291730 /**1731 * Unknown option `flag`.1732 *1733 * @param {string} flag1734 * @api private1735 */17361737 unknownOption(flag) {1738 if (this._allowUnknownOption) return;Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1739–1743why, one step back1739 let suggestion = '';17401741 if (flag.startsWith('--') && this._showSuggestionAfterError) {1742 // Looping to pick up the global options too1743 let candidateFlags = [];Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734
lines 1744–1745why, one step back1744 let command = this;1745 do {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1746–1749why, one step back1746 const moreFlags = command.createHelp().visibleOptions(command)1747 .filter(option => option.long)1748 .map(option => option.long);1749 candidateFlags = candidateFlags.concat(moreFlags);Use _getCommandAndAncestors() less aggressivelyWee Bitbefore adoptionf76a734
lines 1750–1751why, one step back1750 command = command.parent;1751 } while (command && !command._enablePositionalOptions);Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1752–1755why, one step back1752 suggestion = suggestSimilar(flag, candidateFlags);1753 }17541755 const message = `error: unknown option '${flag}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1756–1757why, one step back1756 this.error(message, { code: 'commander.unknownOption' });1757 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1758–1768why, one step back17581759 /**1760 * Excess arguments, more than expected.1761 *1762 * @param {string[]} receivedArgs1763 * @api private1764 */17651766 _excessArguments(receivedArgs) {1767 if (this._allowExcessArguments) return;1768Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1769why, one step back1769 const expected = this.registeredArguments.length;Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1770–1772why, one step back1770 const s = (expected === 1) ? '' : 's';1771 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1772 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 1773–1774why, one step back1773 this.error(message, { code: 'commander.excessArguments' });1774 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1775–1782why, one step back17751776 /**1777 * Unknown command.1778 *1779 * @api private1780 */17811782 unknownCommand() {Suggestion for unknown command and unknown option (#1590)John Geebefore adoption91ccfd5
lines 1783–1796why, one step back1783 const unknownName = this.args[0];1784 let suggestion = '';17851786 if (this._showSuggestionAfterError) {1787 const candidateNames = [];1788 this.createHelp().visibleCommands(this).forEach((command) => {1789 candidateNames.push(command.name());1790 // just visible alias1791 if (command.alias()) candidateNames.push(command.alias());1792 });1793 suggestion = suggestSimilar(unknownName, candidateNames);1794 }17951796 const message = `error: unknown command '${unknownName}'${suggestion}`;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1797–1798why, one step back1797 this.error(message, { code: 'commander.unknownCommand' });1798 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1799–1800why, one step back17991800 /**Types for version getter (#1982)John Geebefore adoptionf5413db
line 1801why, one step back1801 * Get or set the program version.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 * This method auto-registers the "-V, --version" option which will print the version number.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 * You can optionally supply the flags and description to override the defaults.Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1806why, one step back1806 *Types for version getter (#1982)John Geebefore adoptionf5413db
line 1807why, one step back1807 * @param {string} [str]Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1808–1809why, one step back1808 * @param {string} [flags]1809 * @param {string} [description]Types for version getter (#1982)John Geebefore adoptionf5413db
line 1810why, one step back1810 * @return {this | string | undefined} `this` command for chaining, or version string if no argumentsRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1811–1818why, one step back1811 */18121813 version(str, flags, description) {1814 if (str === undefined) return this._version;1815 this._version = str;1816 flags = flags || '-V, --version';1817 description = description || 'output the version number';1818 const versionOption = this.createOption(flags, description);Types for version getter (#1982)John Geebefore adoptionf5413db
line 1819why, one step back1819 this._versionOptionName = versionOption.attributeName(); // [sic] not defined in constructor, partly legacy, partly only needed at rootRefactor classes into files (#1522)John Geebefore adoption08245cc
lines 1820–1825why, one step back1820 this.options.push(versionOption);1821 this.on('option:' + versionOption.name(), () => {1822 this._outputConfiguration.writeOut(`${str}\n`);1823 this._exit(0, 'commander.version', str);1824 });1825 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1826why, one step back1826 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1827–1828why, one step back18271828 /**Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
line 1829why, one step back1829 * Set the description.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1830–1840why, one step back1830 *1831 * @param {string} [str]1832 * @param {Object} [argsDescription]1833 * @return {string|Command}1834 */1835 description(str, argsDescription) {1836 if (str === undefined && argsDescription === undefined) return this._description;1837 this._description = str;1838 if (argsDescription) {1839 this._argsDescription = argsDescription;1840 }Add optional summary for short form of subcommand description. (#1726)John Geebefore adoptioncc2db5b
lines 1841–1852why, one step back1841 return this;1842 }18431844 /**1845 * Set the summary. Used when listed as subcommand of parent.1846 *1847 * @param {string} [str]1848 * @return {string|Command}1849 */1850 summary(str) {1851 if (str === undefined) return this._summary;1852 this._summary = str;Refactor classes into files (#1522)John Geebefore adoption08245cc
line 1853why, one step back1853 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1854why, one step back1854 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1855–1867why, one step back18551856 /**1857 * Set an alias for the command.1858 *1859 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1860 *1861 * @param {string} [alias]1862 * @return {string|Command}1863 */18641865 alias(alias) {1866 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility1867Support argument processing without action handler (#1529)John Geebefore adoption4663597
line 1868why, one step back1868 /** @type {Command} */Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1869–1878why, one step back1869 let command = this;1870 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {1871 // assume adding alias for last added executable subcommand, rather than this1872 command = this.commands[this.commands.length - 1];1873 }18741875 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');18761877 command._aliases.push(alias);1878 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1879why, one step back1879 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1880–1895why, one step back18801881 /**1882 * Set aliases for the command.1883 *1884 * Only the first alias is shown in the auto-generated help.1885 *1886 * @param {string[]} [aliases]1887 * @return {string[]|Command}1888 */18891890 aliases(aliases) {1891 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().1892 if (aliases === undefined) return this._aliases;18931894 aliases.forEach((alias) => this.alias(alias));1895 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1896why, one step back1896 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1897–1908why, one step back18971898 /**1899 * Set / get the command usage `str`.1900 *1901 * @param {string} [str]1902 * @return {String|Command}1903 */19041905 usage(str) {1906 if (str === undefined) {1907 if (this._usage) return this._usage;1908Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1909why, one step back1909 const args = this.registeredArguments.map((arg) => {Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1910–1914why, one step back1910 return humanReadableArgName(arg);1911 });1912 return [].concat(1913 (this.options.length || this._hasHelpOption ? '[options]' : []),1914 (this.commands.length ? '[command]' : []),Add public Arguments property (#2010)John Geebefore adoption7d23437
line 1915why, one step back1915 (this.registeredArguments.length ? args : [])Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1916–1920why, one step back1916 ).join(' ');1917 }19181919 this._usage = str;1920 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1921why, one step back1921 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1922–1923why, one step back19221923 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1924why, one step back1924 * Get or set the name of the command.Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1925–1933why, one step back1925 *1926 * @param {string} [str]1927 * @return {string|Command}1928 */19291930 name(str) {1931 if (str === undefined) return this._name;1932 this._name = str;1933 return this;Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1934why, one step back1934 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1935–1936why, one step back19351936 /**Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1937–1963why, one step back1937 * Set the name of the command from script filename, such as process.argv[1],1938 * or require.main.filename, or __filename.1939 *1940 * (Used internally and public although not documented in README.)1941 *1942 * @example1943 * program.nameFromFilename(require.main.filename);1944 *1945 * @param {string} filename1946 * @return {Command}1947 */19481949 nameFromFilename(filename) {1950 this._name = path.basename(filename, path.extname(filename));19511952 return this;1953 }19541955 /**1956 * Get or set the directory for searching for executable subcommands of this command.1957 *1958 * @example1959 * program.executableDir(__dirname);1960 * // or1961 * program.executableDir('subcommands');1962 *1963 * @param {string} [path]Fix executableDir() return typeWee Bitbefore adoption68a4276
line 1964why, one step back1964 * @return {string|null|Command}Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
lines 1965–1973why, one step back1965 */19661967 executableDir(path) {1968 if (path === undefined) return this._executableDir;1969 this._executableDir = path;1970 return this;1971 }19721973 /**Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1974–1985why, one step back1974 * Return program help documentation.1975 *1976 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout1977 * @return {string}1978 */19791980 helpInformation(contextOptions) {1981 const helper = this.createHelp();1982 if (helper.helpWidth === undefined) {1983 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();1984 }1985 return helper.formatHelp(this, helper);Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c
line 1986why, one step back1986 }Refactor classes into files (#1522)John Geebefore adoption08245cc
lines 1987–2021why, one step back19871988 /**1989 * @api private1990 */19911992 _getHelpContext(contextOptions) {1993 contextOptions = contextOptions || {};1994 const context = { error: !!contextOptions.error };1995 let write;1996 if (context.error) {1997 write = (arg) => this._outputConfiguration.writeErr(arg);1998 } else {1999 write = (arg) => this._outputConfiguration.writeOut(arg);2000 }The first 2,000 of 2,181 lines.