Skip to content
Myr

Convert Command from prototype to class (#1159)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by John Gee · committed by GitHub · parent 1345f98 · Browse files · 1 file+1188 added−1197 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+1188 added−1197 removed

  • other:+1188 added−1197 removed

1 file+1188 added−1197 removed

modified:index.js+1188 added-1197 removed
5 unmodified lines
6var spawn = require('child_process').spawn;7var path = require('path');8var fs = require('fs');910/**11 * Inherit `Command` from `EventEmitter.prototype`.12 */1314require('util').inherits(Command, EventEmitter);1516/**17 * Expose the root command.18 */1920exports = module.exports = new Command();2122/**23 * Expose `Command`.24 */2526exports.Command = Command;2710class Option {11 /**12 * Initialize a new `Option` with the given `flags` and `description`.13 *
50 unmodified lines
64 };65}6667/**86 * Expose `Option`.87 */8889exports.Option = Option;9091/**68 * CommanderError class69 * @class70 */71class CommanderError extends Error {
13 unmodified lines
85 this.exitCode = exitCode;86 }87}88113exports.CommanderError = CommanderError;89class Command extends EventEmitter {90 /**91 * Initialize a new `Command`.92 *93 * @param {String} [name]94 * @api public95 */96115/**116 * Initialize a new `Command`.117 *118 * @param {String} [name]119 * @api public120 */97 constructor(name) {98 super();99 this.commands = [];100 this.options = [];101 this._allowUnknownOption = false;102 this._args = [];103 this._name = name || '';104 this._optionValues = {};105 this._storeOptionsAsProperties = true; // backwards compatible by default106 this._passCommandToAction = true; // backwards compatible by default107 this._actionResults = [];108 this._actionHandler = null;109 this._executableHandler = false;110 this._executableFile = null; // custom name for executable111 this._defaultCommandName = null;112 this._exitCallback = null;113122function Command(name) {123 this.commands = [];124 this.options = [];125 this._allowUnknownOption = false;126 this._args = [];127 this._name = name || '';128 this._optionValues = {};129 this._storeOptionsAsProperties = true; // backwards compatible by default130 this._passCommandToAction = true; // backwards compatible by default131 this._actionResults = [];132 this._actionHandler = null;133 this._executableHandler = false;134 this._executableFile = null; // custom name for executable135 this._defaultCommandName = null;136 this._exitCallback = null;137138 this._noHelp = false;139 this._helpFlags = '-h, --help';140 this._helpDescription = 'display help for command';141 this._helpShortFlag = '-h';142 this._helpLongFlag = '--help';143 this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false144 this._helpCommandName = 'help';145 this._helpCommandnameAndArgs = 'help [command]';146 this._helpCommandDescription = 'display help for command';114 this._noHelp = false;115 this._helpFlags = '-h, --help';116 this._helpDescription = 'display help for command';117 this._helpShortFlag = '-h';118 this._helpLongFlag = '--help';119 this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false120 this._helpCommandName = 'help';121 this._helpCommandnameAndArgs = 'help [command]';122 this._helpCommandDescription = 'display help for command';147}148149/**150 * Define a command.151 *152 * There are two styles of command: pay attention to where to put the description.153 *154 * Examples:155 *156 * // Command implemented using action handler (description is supplied separately to `.command`)157 * program158 * .command('clone <source> [destination]')159 * .description('clone a repository into a newly created directory')160 * .action((source, destination) => {161 * console.log('clone command called');162 * });163 *164 * // Command implemented using separate executable file (description is second parameter to `.command`)165 * program166 * .command('start <service>', 'start named service')167 * .command('stop [service]', 'stop named service, or all if no name supplied');168 *169 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`170 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)171 * @param {Object} [execOpts] - configuration options (for executable)172 * @return {Command} returns new command for action handler, or top-level command for executable command173 * @api public174 */175176Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) {177 var desc = actionOptsOrExecDesc;178 var opts = execOpts;179 if (typeof desc === 'object' && desc !== null) {180 opts = desc;181 desc = null;123 }183 opts = opts || {};184 var args = nameAndArgs.split(/ +/);185 var cmd = new Command(args.shift());124187 if (desc) {188 cmd.description(desc);189 cmd._executableHandler = true;190 }191 if (opts.isDefault) this._defaultCommandName = cmd._name;125 /**126 * Define a command.127 *128 * There are two styles of command: pay attention to where to put the description.129 *130 * Examples:131 *132 * // 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 * });139 *140 * // 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');144 *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 top-level command for executable command149 * @api public150 */151193 cmd._noHelp = !!opts.noHelp;194 cmd._helpFlags = this._helpFlags;195 cmd._helpDescription = this._helpDescription;196 cmd._helpShortFlag = this._helpShortFlag;197 cmd._helpLongFlag = this._helpLongFlag;198 cmd._helpCommandName = this._helpCommandName;199 cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;200 cmd._helpCommandDescription = this._helpCommandDescription;201 cmd._exitCallback = this._exitCallback;202 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;203 cmd._passCommandToAction = this._passCommandToAction;152 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {153 var desc = actionOptsOrExecDesc;154 var opts = execOpts;155 if (typeof desc === 'object' && desc !== null) {156 opts = desc;157 desc = null;158 }159 opts = opts || {};160 var args = nameAndArgs.split(/ +/);161 var cmd = new Command(args.shift());162205 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor206 this.commands.push(cmd);207 cmd._parseExpectedArgs(args);208 cmd.parent = this;163 if (desc) {164 cmd.description(desc);165 cmd._executableHandler = true;166 }167 if (opts.isDefault) this._defaultCommandName = cmd._name;168210 if (desc) return this;211 return cmd;212};169 cmd._noHelp = !!opts.noHelp;170 cmd._helpFlags = this._helpFlags;171 cmd._helpDescription = this._helpDescription;172 cmd._helpShortFlag = this._helpShortFlag;173 cmd._helpLongFlag = this._helpLongFlag;174 cmd._helpCommandName = this._helpCommandName;175 cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;176 cmd._helpCommandDescription = this._helpCommandDescription;177 cmd._exitCallback = this._exitCallback;178 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;179 cmd._passCommandToAction = this._passCommandToAction;180214/**215 * Add a prepared subcommand.216 *217 * @param {Command} cmd - new subcommand218 * @return {Command} parent command for chaining219 * @api public220 */181 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor182 this.commands.push(cmd);183 cmd._parseExpectedArgs(args);184 cmd.parent = this;185222Command.prototype.addCommand = function(cmd) {223 if (!cmd._name) throw new Error('Command passed to .AddCommand must have a name');186 if (desc) return this;187 return cmd;188 };189225 // To keep things simple, block automatic name generation for deeply nested executables.226 // Fail fast and detect when adding rather than later when parsing.227 function checkExplicitNames(commandArray) {228 commandArray.forEach((cmd) => {229 if (cmd._executableHandler && !cmd._executableFile) {230 throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);231 }232 checkExplicitNames(cmd.commands);233 });234 }235 checkExplicitNames(cmd.commands);190 /**191 * Add a prepared subcommand.192 *193 * @param {Command} cmd - new subcommand194 * @return {Command} parent command for chaining195 * @api public196 */197237 this.commands.push(cmd);238 cmd.parent = this;239 return this;240};198 addCommand(cmd) {199 if (!cmd._name) throw new Error('Command passed to .AddCommand must have a name');200242/**243 * Define argument syntax for the top-level command.244 *245 * @api public246 */247248Command.prototype.arguments = function(desc) {249 return this._parseExpectedArgs(desc.split(/ +/));250};251252/**253 * Override default decision whether to add implicit help command.254 *255 * addHelpCommand() // force on256 * addHelpCommand(false); // force off257 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom detais258 *259 * @return {Command} for chaining260 * @api public261 */262263Command.prototype.addHelpCommand = function(enableOrNameAndArgs, description) {264 if (enableOrNameAndArgs === false) {265 this._hasImplicitHelpCommand = false;266 } else {267 this._hasImplicitHelpCommand = true;268 if (typeof enableOrNameAndArgs === 'string') {269 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];270 this._helpCommandnameAndArgs = enableOrNameAndArgs;201 // To keep things simple, block automatic name generation for deeply nested executables.202 // Fail fast and detect when adding rather than later when parsing.203 function checkExplicitNames(commandArray) {204 commandArray.forEach((cmd) => {205 if (cmd._executableHandler && !cmd._executableFile) {206 throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);207 }208 checkExplicitNames(cmd.commands);209 });210 }272 this._helpCommandDescription = description || this._helpCommandDescription;273 }274 return this;275};211 checkExplicitNames(cmd.commands);212277/**278 * @return {boolean}279 * @api private280 */213 this.commands.push(cmd);214 cmd.parent = this;215 return this;216 };217282Command.prototype._lazyHasImplicitHelpCommand = function() {283 if (this._hasImplicitHelpCommand === undefined) {284 this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help');285 }286 return this._hasImplicitHelpCommand;287};218 /**219 * Define argument syntax for the top-level command.220 *221 * @api public222 */223289/**290 * Parse expected `args`.291 *292 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.293 *294 * @param {Array} args295 * @return {Command} for chaining296 * @api private297 */224 arguments(desc) {225 return this._parseExpectedArgs(desc.split(/ +/));226 };227299Command.prototype._parseExpectedArgs = function(args) {300 if (!args.length) return;301 var self = this;302 args.forEach(function(arg) {303 var argDetails = {304 required: false,305 name: '',306 variadic: false307 };228 /**229 * Override default decision whether to add implicit help command.230 *231 * addHelpCommand() // force on232 * addHelpCommand(false); // force off233 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom detais234 *235 * @return {Command} for chaining236 * @api public237 */238309 switch (arg[0]) {310 case '<':311 argDetails.required = true;312 argDetails.name = arg.slice(1, -1);313 break;314 case '[':315 argDetails.name = arg.slice(1, -1);316 break;239 addHelpCommand(enableOrNameAndArgs, description) {240 if (enableOrNameAndArgs === false) {241 this._hasImplicitHelpCommand = false;242 } else {243 this._hasImplicitHelpCommand = true;244 if (typeof enableOrNameAndArgs === 'string') {245 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];246 this._helpCommandnameAndArgs = enableOrNameAndArgs;247 }248 this._helpCommandDescription = description || this._helpCommandDescription;249 }250 return this;251 };252319 if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {320 argDetails.variadic = true;321 argDetails.name = argDetails.name.slice(0, -3);253 /**254 * @return {boolean}255 * @api private256 */257258 _lazyHasImplicitHelpCommand() {259 if (this._hasImplicitHelpCommand === undefined) {260 this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help');261 }323 if (argDetails.name) {324 self._args.push(argDetails);325 }326 });327 return this;328};262 return this._hasImplicitHelpCommand;263 };264330/**331 * Register callback to use as replacement for calling process.exit.332 *333 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing334 * @return {Command} for chaining335 * @api public336 */265 /**266 * Parse expected `args`.267 *268 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.269 *270 * @param {Array} args271 * @return {Command} for chaining272 * @api private273 */274338Command.prototype.exitOverride = function(fn) {339 if (fn) {340 this._exitCallback = fn;341 } else {342 this._exitCallback = function(err) {343 if (err.code !== 'commander.executeSubCommandAsync') {344 throw err;345 } else {346 // Async callback from spawn events, not useful to throw.275 _parseExpectedArgs(args) {276 if (!args.length) return;277 var self = this;278 args.forEach(function(arg) {279 var argDetails = {280 required: false,281 name: '',282 variadic: false283 };284285 switch (arg[0]) {286 case '<':287 argDetails.required = true;288 argDetails.name = arg.slice(1, -1);289 break;290 case '[':291 argDetails.name = arg.slice(1, -1);292 break;293 }348 };349 }350 return this;351};294353/**354 * Call process.exit, and _exitCallback if defined.355 *356 * @param {Number} exitCode exit code for using with process.exit357 * @param {String} code an id string representing the error358 * @param {String} message human-readable description of the error359 * @return never360 * @api private361 */295 if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {296 argDetails.variadic = true;297 argDetails.name = argDetails.name.slice(0, -3);298 }299 if (argDetails.name) {300 self._args.push(argDetails);301 }302 });303 return this;304 };305363Command.prototype._exit = function(exitCode, code, message) {364 if (this._exitCallback) {365 this._exitCallback(new CommanderError(exitCode, code, message));366 // Expecting this line is not reached.367 }368 process.exit(exitCode);369};306 /**307 * Register callback to use as replacement for calling process.exit.308 *309 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing310 * @return {Command} for chaining311 * @api public312 */313371/**372 * Register callback `fn` for the command.373 *374 * Examples:375 *376 * program377 * .command('help')378 * .description('display verbose help')379 * .action(function() {380 * // output help here381 * });382 *383 * @param {Function} fn384 * @return {Command} for chaining385 * @api public386 */387388Command.prototype.action = function(fn) {389 var self = this;390 var listener = function(args) {391 // The .action callback takes an extra parameter which is the command or options.392 var expectedArgsCount = self._args.length;393 var actionArgs = args.slice(0, expectedArgsCount);394 if (self._passCommandToAction) {395 actionArgs[expectedArgsCount] = self;314 exitOverride(fn) {315 if (fn) {316 this._exitCallback = fn;317 } else {397 actionArgs[expectedArgsCount] = self.opts();318 this._exitCallback = function(err) {319 if (err.code !== 'commander.executeSubCommandAsync') {320 throw err;321 } else {322 // Async callback from spawn events, not useful to throw.323 }324 };325 }399 // Add the extra arguments so available too.400 if (args.length > expectedArgsCount) {401 actionArgs.push(args.slice(expectedArgsCount));402 }326 return this;327 };328404 const actionResult = fn.apply(self, actionArgs);405 // Remember result in case it is async. Assume parseAsync getting called on root.406 let rootCommand = self;407 while (rootCommand.parent) {408 rootCommand = rootCommand.parent;329 /**330 * Call process.exit, and _exitCallback if defined.331 *332 * @param {Number} exitCode exit code for using with process.exit333 * @param {String} code an id string representing the error334 * @param {String} message human-readable description of the error335 * @return never336 * @api private337 */338339 _exit(exitCode, code, message) {340 if (this._exitCallback) {341 this._exitCallback(new CommanderError(exitCode, code, message));342 // Expecting this line is not reached.343 }410 rootCommand._actionResults.push(actionResult);344 process.exit(exitCode);345 };412 this._actionHandler = listener;413 return this;414};346416/**417 * Internal implementation shared by .option() and .requiredOption()418 *419 * @param {Object} config420 * @param {String} flags421 * @param {String} description422 * @param {Function|*} [fn] - custom option processing function or default vaue423 * @param {*} [defaultValue]424 * @return {Command} for chaining425 * @api private426 */347 /**348 * Register callback `fn` for the command.349 *350 * Examples:351 *352 * program353 * .command('help')354 * .description('display verbose help')355 * .action(function() {356 * // output help here357 * });358 *359 * @param {Function} fn360 * @return {Command} for chaining361 * @api public362 */363428Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) {429 var self = this,430 option = new Option(flags, description),431 oname = option.name(),432 name = option.attributeName();433 option.mandatory = !!config.mandatory;364 action(fn) {365 var self = this;366 var listener = function(args) {367 // The .action callback takes an extra parameter which is the command or options.368 var expectedArgsCount = self._args.length;369 var actionArgs = args.slice(0, expectedArgsCount);370 if (self._passCommandToAction) {371 actionArgs[expectedArgsCount] = self;372 } else {373 actionArgs[expectedArgsCount] = self.opts();374 }375 // Add the extra arguments so available too.376 if (args.length > expectedArgsCount) {377 actionArgs.push(args.slice(expectedArgsCount));378 }379435 // default as 3rd arg436 if (typeof fn !== 'function') {437 if (fn instanceof RegExp) {438 // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.439 // No longer documented in README, but still present for backwards compatibility.440 var regex = fn;441 fn = function(val, def) {442 var m = regex.exec(val);443 return m ? m[0] : def;444 };445 } else {446 defaultValue = fn;447 fn = null;448 }449 }380 const actionResult = fn.apply(self, actionArgs);381 // Remember result in case it is async. Assume parseAsync getting called on root.382 let rootCommand = self;383 while (rootCommand.parent) {384 rootCommand = rootCommand.parent;385 }386 rootCommand._actionResults.push(actionResult);387 };388 this._actionHandler = listener;389 return this;390 };391451 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value452 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {453 // when --no-foo we make sure default is true, unless a --foo option is already defined454 if (option.negate) {455 const positiveLongFlag = option.long.replace(/^--no-/, '--');456 defaultValue = self._findOption(positiveLongFlag) ? self._getOptionValue(name) : true;457 }458 // preassign only if we have a default459 if (defaultValue !== undefined) {460 self._setOptionValue(name, defaultValue);461 option.defaultValue = defaultValue;462 }463 }392 /**393 * Internal implementation shared by .option() and .requiredOption()394 *395 * @param {Object} config396 * @param {String} flags397 * @param {String} description398 * @param {Function|*} [fn] - custom option processing function or default vaue399 * @param {*} [defaultValue]400 * @return {Command} for chaining401 * @api private402 */403465 // register the option466 this.options.push(option);404 _optionEx(config, flags, description, fn, defaultValue) {405 var self = this,406 option = new Option(flags, description),407 oname = option.name(),408 name = option.attributeName();409 option.mandatory = !!config.mandatory;410468 // when it's passed assign the value469 // and conditionally invoke the callback470 this.on('option:' + oname, function(val) {471 // coercion472 if (val !== null && fn) {473 val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name));411 // default as 3rd arg412 if (typeof fn !== 'function') {413 if (fn instanceof RegExp) {414 // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.415 // No longer documented in README, but still present for backwards compatibility.416 var regex = fn;417 fn = function(val, def) {418 var m = regex.exec(val);419 return m ? m[0] : def;420 };421 } else {422 defaultValue = fn;423 fn = null;424 }425 }426476 // unassigned or boolean value477 if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') {478 // if no value, negate false, and we have a default, then use it!479 if (val == null) {480 self._setOptionValue(name, option.negate481 ? false482 : defaultValue || true);483 } else {484 self._setOptionValue(name, val);427 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value428 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {429 // when --no-foo we make sure default is true, unless a --foo option is already defined430 if (option.negate) {431 const positiveLongFlag = option.long.replace(/^--no-/, '--');432 defaultValue = self._findOption(positiveLongFlag) ? self._getOptionValue(name) : true;433 }486 } else if (val !== null) {487 // reassign488 self._setOptionValue(name, option.negate ? false : val);434 // preassign only if we have a default435 if (defaultValue !== undefined) {436 self._setOptionValue(name, defaultValue);437 option.defaultValue = defaultValue;438 }439 }490 });440492 return this;493};441 // register the option442 this.options.push(option);443495/**496 * Define option with `flags`, `description` and optional497 * coercion `fn`.498 *499 * The `flags` string should contain both the short and long flags,500 * separated by comma, a pipe or space. The following are all valid501 * all will output this way when `--help` is used.502 *503 * "-p, --pepper"504 * "-p|--pepper"505 * "-p --pepper"506 *507 * Examples:508 *509 * // simple boolean defaulting to undefined510 * program.option('-p, --pepper', 'add pepper');511 *512 * program.pepper513 * // => undefined514 *515 * --pepper516 * program.pepper517 * // => true518 *519 * // simple boolean defaulting to true (unless non-negated option is also defined)520 * program.option('-C, --no-cheese', 'remove cheese');521 *522 * program.cheese523 * // => true524 *525 * --no-cheese526 * program.cheese527 * // => false528 *529 * // required argument530 * program.option('-C, --chdir <path>', 'change the working directory');531 *532 * --chdir /tmp533 * program.chdir534 * // => "/tmp"535 *536 * // optional argument537 * program.option('-c, --cheese [type]', 'add cheese [marble]');538 *539 * @param {String} flags540 * @param {String} description541 * @param {Function|*} [fn] - custom option processing function or default vaue542 * @param {*} [defaultValue]543 * @return {Command} for chaining544 * @api public545 */444 // when it's passed assign the value445 // and conditionally invoke the callback446 this.on('option:' + oname, function(val) {447 // coercion448 if (val !== null && fn) {449 val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name));450 }451547Command.prototype.option = function(flags, description, fn, defaultValue) {548 return this._optionEx({}, flags, description, fn, defaultValue);549};452 // unassigned or boolean value453 if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') {454 // if no value, negate false, and we have a default, then use it!455 if (val == null) {456 self._setOptionValue(name, option.negate457 ? false458 : defaultValue || true);459 } else {460 self._setOptionValue(name, val);461 }462 } else if (val !== null) {463 // reassign464 self._setOptionValue(name, option.negate ? false : val);465 }466 });467551/*552 * Add a required option which must have a value after parsing. This usually means553 * the option must be specified on the command line. (Otherwise the same as .option().)554 *555 * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.556 *557 * @param {String} flags558 * @param {String} description559 * @param {Function|*} [fn] - custom option processing function or default vaue560 * @param {*} [defaultValue]561 * @return {Command} for chaining562 * @api public563 */468 return this;469 };470565Command.prototype.requiredOption = function(flags, description, fn, defaultValue) {566 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);567};471 /**472 * Define option with `flags`, `description` and optional473 * coercion `fn`.474 *475 * The `flags` string should contain both the short and long flags,476 * separated by comma, a pipe or space. The following are all valid477 * all will output this way when `--help` is used.478 *479 * "-p, --pepper"480 * "-p|--pepper"481 * "-p --pepper"482 *483 * Examples:484 *485 * // simple boolean defaulting to undefined486 * program.option('-p, --pepper', 'add pepper');487 *488 * program.pepper489 * // => undefined490 *491 * --pepper492 * program.pepper493 * // => true494 *495 * // simple boolean defaulting to true (unless non-negated option is also defined)496 * program.option('-C, --no-cheese', 'remove cheese');497 *498 * program.cheese499 * // => true500 *501 * --no-cheese502 * program.cheese503 * // => false504 *505 * // required argument506 * program.option('-C, --chdir <path>', 'change the working directory');507 *508 * --chdir /tmp509 * program.chdir510 * // => "/tmp"511 *512 * // optional argument513 * program.option('-c, --cheese [type]', 'add cheese [marble]');514 *515 * @param {String} flags516 * @param {String} description517 * @param {Function|*} [fn] - custom option processing function or default vaue518 * @param {*} [defaultValue]519 * @return {Command} for chaining520 * @api public521 */522569/**570 * Allow unknown options on the command line.571 *572 * @param {Boolean} arg if `true` or omitted, no error will be thrown573 * for unknown options.574 * @api public575 */576Command.prototype.allowUnknownOption = function(arg) {577 this._allowUnknownOption = arguments.length === 0 || arg;578 return this;579};523 option(flags, description, fn, defaultValue) {524 return this._optionEx({}, flags, description, fn, defaultValue);525 };526581/**582 * Whether to store option values as properties on command object,583 * or store separately (specify false). In both cases the option values can be accessed using .opts().527 /*528 * Add a required option which must have a value after parsing. This usually means529 * the option must be specified on the command line. (Otherwise the same as .option().)530 *531 * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.532 *533 * @param {String} flags534 * @param {String} description535 * @param {Function|*} [fn] - custom option processing function or default vaue585 * @param {boolean} value586 * @return {Command} Command for chaining536 * @param {*} [defaultValue]537 * @return {Command} for chaining538 * @api public539 */540590Command.prototype.storeOptionsAsProperties = function(value) {591 this._storeOptionsAsProperties = (value === undefined) || value;592 if (this.options.length) {593 // This is for programmer, not end user.594 console.error('Commander usage error: call storeOptionsAsProperties before adding options');595 }596 return this;597};541 requiredOption(flags, description, fn, defaultValue) {542 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);543 };544599/**600 * Whether to pass command to action handler,601 * or just the options (specify false).602 *603 * @param {boolean} value604 * @return {Command} Command for chaining605 * @api public606 */545 /**546 * Allow unknown options on the command line.547 *548 * @param {Boolean} arg if `true` or omitted, no error will be thrown549 * for unknown options.550 * @api public551 */552 allowUnknownOption(arg) {553 this._allowUnknownOption = arguments.length === 0 || arg;554 return this;555 };556608Command.prototype.passCommandToAction = function(value) {609 this._passCommandToAction = (value === undefined) || value;610 return this;611};557 /**558 * Whether to store option values as properties on command object,559 * or store separately (specify false). In both cases the option values can be accessed using .opts().560 *561 * @param {boolean} value562 * @return {Command} Command for chaining563 * @api public564 */565613/**614 * Store option value615 *616 * @param {String} key617 * @param {Object} value618 * @api private619 */566 storeOptionsAsProperties(value) {567 this._storeOptionsAsProperties = (value === undefined) || value;568 if (this.options.length) {569 // This is for programmer, not end user.570 console.error('Commander usage error: call storeOptionsAsProperties before adding options');571 }572 return this;573 };574621Command.prototype._setOptionValue = function(key, value) {622 if (this._storeOptionsAsProperties) {623 this[key] = value;624 } else {625 this._optionValues[key] = value;626 }627};575 /**576 * Whether to pass command to action handler,577 * or just the options (specify false).578 *579 * @param {boolean} value580 * @return {Command} Command for chaining581 * @api public582 */583629/**630 * Retrieve option value631 *632 * @param {String} key633 * @return {Object} value634 * @api private635 */584 passCommandToAction(value) {585 this._passCommandToAction = (value === undefined) || value;586 return this;587 };588637Command.prototype._getOptionValue = function(key) {638 if (this._storeOptionsAsProperties) {639 return this[key];640 }641 return this._optionValues[key];642};589 /**590 * Store option value591 *592 * @param {String} key593 * @param {Object} value594 * @api private595 */596644/**645 * Parse `argv`, setting options and invoking commands when defined.646 *647 * @param {Array} argv648 * @return {Command} for chaining649 * @api public650 */597 _setOptionValue(key, value) {598 if (this._storeOptionsAsProperties) {599 this[key] = value;600 } else {601 this._optionValues[key] = value;602 }603 };604652Command.prototype.parse = function(argv) {653 // store raw args654 this.rawArgs = argv;605 /**606 * Retrieve option value607 *608 * @param {String} key609 * @return {Object} value610 * @api private611 */612656 // Guess name, used in usage in help.657 this._name = this._name || path.basename(argv[1], path.extname(argv[1]));613 _getOptionValue(key) {614 if (this._storeOptionsAsProperties) {615 return this[key];616 }617 return this._optionValues[key];618 };619659 this._parseCommand([], argv.slice(2));620 /**621 * Parse `argv`, setting options and invoking commands when defined.622 *623 * @param {Array} argv624 * @return {Command} for chaining625 * @api public626 */627661 return this;662};628 parse(argv) {629 // store raw args630 this.rawArgs = argv;631664/**665 * Parse `argv`, setting options and invoking commands when defined.666 *667 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.668 *669 * @param {Array} argv670 * @return {Promise}671 * @api public672 */632 // Guess name, used in usage in help.633 this._name = this._name || path.basename(argv[1], path.extname(argv[1]));634674Command.prototype.parseAsync = function(argv) {675 this.parse(argv);676 return Promise.all(this._actionResults);677};635 this._parseCommand([], argv.slice(2));636679/**680 * Execute a sub-command executable.681 *682 * @api private683 */637 return this;638 };639685Command.prototype._executeSubCommand = function(subcommand, args) {686 args = args.slice();687 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.688 const sourceExt = ['.js', '.ts', '.mjs'];640 /**641 * Parse `argv`, setting options and invoking commands when defined.642 *643 * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.644 *645 * @param {Array} argv646 * @return {Promise}647 * @api public648 */649690 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.691 this._checkForMissingMandatoryOptions();650 parseAsync(argv) {651 this.parse(argv);652 return Promise.all(this._actionResults);653 };654693 // Want the entry script as the reference for command name and directory for searching for other files.694 const scriptPath = this.rawArgs[1];655 /**656 * Execute a sub-command executable.657 *658 * @api private659 */660696 let baseDir;697 try {698 const resolvedLink = fs.realpathSync(scriptPath);699 baseDir = path.dirname(resolvedLink);700 } catch (e) {701 baseDir = '.'; // dummy, probably not going to find executable!702 }661 _executeSubCommand(subcommand, args) {662 args = args.slice();663 let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.664 const sourceExt = ['.js', '.ts', '.mjs'];665704 // name of the subcommand, like `pm-install`705 let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;706 if (subcommand._executableFile) {707 bin = subcommand._executableFile;708 }666 // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.667 this._checkForMissingMandatoryOptions();668710 const localBin = path.join(baseDir, bin);711 if (fs.existsSync(localBin)) {712 // prefer local `./<bin>` to bin in the $PATH713 bin = localBin;714 } else {715 // Look for source files.716 sourceExt.forEach((ext) => {717 if (fs.existsSync(`${localBin}${ext}`)) {718 bin = `${localBin}${ext}`;719 }720 });721 }722 launchWithNode = sourceExt.includes(path.extname(bin));669 // Want the entry script as the reference for command name and directory for searching for other files.670 const scriptPath = this.rawArgs[1];671724 let proc;725 if (process.platform !== 'win32') {726 if (launchWithNode) {727 args.unshift(bin);728 // add executable arguments to spawn729 args = incrementNodeInspectorPort(process.execArgv).concat(args);672 let baseDir;673 try {674 const resolvedLink = fs.realpathSync(scriptPath);675 baseDir = path.dirname(resolvedLink);676 } catch (e) {677 baseDir = '.'; // dummy, probably not going to find executable!678 }679731 proc = spawn(process.argv[0], args, { stdio: 'inherit' });680 // name of the subcommand, like `pm-install`681 let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;682 if (subcommand._executableFile) {683 bin = subcommand._executableFile;684 }685686 const localBin = path.join(baseDir, bin);687 if (fs.existsSync(localBin)) {688 // prefer local `./<bin>` to bin in the $PATH689 bin = localBin;690 } else {733 proc = spawn(bin, args, { stdio: 'inherit' });691 // Look for source files.692 sourceExt.forEach((ext) => {693 if (fs.existsSync(`${localBin}${ext}`)) {694 bin = `${localBin}${ext}`;695 }696 });697 }735 } else {736 args.unshift(bin);737 // add executable arguments to spawn738 args = incrementNodeInspectorPort(process.execArgv).concat(args);739 proc = spawn(process.execPath, args, { stdio: 'inherit' });740 }698 launchWithNode = sourceExt.includes(path.extname(bin));699742 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];743 signals.forEach(function(signal) {744 process.on(signal, function() {745 if (proc.killed === false && proc.exitCode === null) {746 proc.kill(signal);700 let proc;701 if (process.platform !== 'win32') {702 if (launchWithNode) {703 args.unshift(bin);704 // add executable arguments to spawn705 args = incrementNodeInspectorPort(process.execArgv).concat(args);706707 proc = spawn(process.argv[0], args, { stdio: 'inherit' });708 } else {709 proc = spawn(bin, args, { stdio: 'inherit' });710 }748 });749 });711 } else {712 args.unshift(bin);713 // add executable arguments to spawn714 args = incrementNodeInspectorPort(process.execArgv).concat(args);715 proc = spawn(process.execPath, args, { stdio: 'inherit' });716 }717751 // By default terminate process when spawned process terminates.752 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!753 const exitCallback = this._exitCallback;754 if (!exitCallback) {755 proc.on('close', process.exit.bind(process));756 } else {757 proc.on('close', () => {758 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));718 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];719 signals.forEach(function(signal) {720 process.on(signal, function() {721 if (proc.killed === false && proc.exitCode === null) {722 proc.kill(signal);723 }724 });725 });760 }761 proc.on('error', function(err) {762 if (err.code === 'ENOENT') {763 console.error('error: %s(1) does not exist', bin);764 } else if (err.code === 'EACCES') {765 console.error('error: %s(1) not executable', bin);766 }726727 // By default terminate process when spawned process terminates.728 // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!729 const exitCallback = this._exitCallback;730 if (!exitCallback) {768 process.exit(1);731 proc.on('close', process.exit.bind(process));732 } else {770 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');771 wrappedError.nestedError = err;772 exitCallback(wrappedError);733 proc.on('close', () => {734 exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));735 });736 }737 proc.on('error', function(err) {738 if (err.code === 'ENOENT') {739 console.error('error: %s(1) does not exist', bin);740 } else if (err.code === 'EACCES') {741 console.error('error: %s(1) not executable', bin);742 }743 if (!exitCallback) {744 process.exit(1);745 } else {746 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');747 wrappedError.nestedError = err;748 exitCallback(wrappedError);749 }774 });750 });751776 // Store the reference to the child process777 this.runningCommand = proc;778};752 // Store the reference to the child process753 this.runningCommand = proc;754 };755780/**781 * @api private782 */783Command.prototype._dispatchSubcommand = function(commandName, operands, unknown) {784 const subCommand = this._findCommand(commandName);785 if (!subCommand) this._helpAndError();756 /**757 * @api private758 */759 _dispatchSubcommand(commandName, operands, unknown) {760 const subCommand = this._findCommand(commandName);761 if (!subCommand) this._helpAndError();762787 if (subCommand._executableHandler) {788 this._executeSubCommand(subCommand, operands.concat(unknown));789 } else {790 subCommand._parseCommand(operands, unknown);791 }792};763 if (subCommand._executableHandler) {764 this._executeSubCommand(subCommand, operands.concat(unknown));765 } else {766 subCommand._parseCommand(operands, unknown);767 }768 };769794/**795 * Process arguments in context of this command.796 *797 * @api private798 */770 /**771 * Process arguments in context of this command.772 *773 * @api private774 */775800Command.prototype._parseCommand = function(operands, unknown) {801 const parsed = this.parseOptions(unknown);802 operands = operands.concat(parsed.operands);803 unknown = parsed.unknown;804 this.args = operands.concat(unknown);776 _parseCommand(operands, unknown) {777 const parsed = this.parseOptions(unknown);778 operands = operands.concat(parsed.operands);779 unknown = parsed.unknown;780 this.args = operands.concat(unknown);781806 if (operands && this._findCommand(operands[0])) {807 this._dispatchSubcommand(operands[0], operands.slice(1), unknown);808 } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) {809 if (operands.length === 1) {810 this.help();782 if (operands && this._findCommand(operands[0])) {783 this._dispatchSubcommand(operands[0], operands.slice(1), unknown);784 } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) {785 if (operands.length === 1) {786 this.help();787 } else {788 this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);789 }790 } else if (this._defaultCommandName) {791 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command792 this._dispatchSubcommand(this._defaultCommandName, operands, unknown);793 } else {812 this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);813 }814 } else if (this._defaultCommandName) {815 outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command816 this._dispatchSubcommand(this._defaultCommandName, operands, unknown);817 } else {818 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {819 // probaby missing subcommand and no handler, user needs help820 this._helpAndError();821 }794 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {795 // probaby missing subcommand and no handler, user needs help796 this._helpAndError();797 }798823 outputHelpIfRequested(this, parsed.unknown);824 this._checkForMissingMandatoryOptions();825 if (parsed.unknown.length > 0) {826 this.unknownOption(parsed.unknown[0]);827 }799 outputHelpIfRequested(this, parsed.unknown);800 this._checkForMissingMandatoryOptions();801 if (parsed.unknown.length > 0) {802 this.unknownOption(parsed.unknown[0]);803 }804829 if (this._actionHandler) {830 const self = this;831 const args = this.args.slice();832 this._args.forEach(function(arg, i) {833 if (arg.required && args[i] == null) {834 self.missingArgument(arg.name);835 } else if (arg.variadic) {836 if (i !== self._args.length - 1) {837 self.variadicArgNotLast(arg.name);805 if (this._actionHandler) {806 const self = this;807 const args = this.args.slice();808 this._args.forEach(function(arg, i) {809 if (arg.required && args[i] == null) {810 self.missingArgument(arg.name);811 } else if (arg.variadic) {812 if (i !== self._args.length - 1) {813 self.variadicArgNotLast(arg.name);814 }815816 args[i] = args.splice(i);817 }818 });819840 args[i] = args.splice(i);820 this._actionHandler(args);821 this.emit('command:' + this.name(), operands, unknown);822 } else if (operands.length) {823 if (this._findCommand('*')) {824 this._dispatchSubcommand('*', operands, unknown);825 } else if (this.listenerCount('command:*')) {826 this.emit('command:*', operands, unknown);827 } else if (this.commands.length) {828 this.unknownCommand();829 }842 });843844 this._actionHandler(args);845 this.emit('command:' + this.name(), operands, unknown);846 } else if (operands.length) {847 if (this._findCommand('*')) {848 this._dispatchSubcommand('*', operands, unknown);849 } else if (this.listenerCount('command:*')) {850 this.emit('command:*', operands, unknown);830 } else if (this.commands.length) {852 this.unknownCommand();831 // This command has subcommands and nothing hooked up at this level, so display help.832 this._helpAndError();833 } else {834 // fall through for caller to handle after calling .parse()835 }854 } else if (this.commands.length) {855 // This command has subcommands and nothing hooked up at this level, so display help.856 this._helpAndError();857 } else {858 // fall through for caller to handle after calling .parse()836 }860 }861};837 };838863/**864 * Find matching command.865 *866 * @api private867 */868Command.prototype._findCommand = function(name) {869 if (!name) return undefined;870 return this.commands.find(cmd => cmd._name === name || cmd._alias === name);871};839 /**840 * Find matching command.841 *842 * @api private843 */844 _findCommand(name) {845 if (!name) return undefined;846 return this.commands.find(cmd => cmd._name === name || cmd._alias === name);847 };848873/**874 * Return an option matching `arg` if any.875 *876 * @param {String} arg877 * @return {Option}878 * @api private879 */849 /**850 * Return an option matching `arg` if any.851 *852 * @param {String} arg853 * @return {Option}854 * @api private855 */856881Command.prototype._findOption = function(arg) {882 return this.options.find(option => option.is(arg));883};857 _findOption(arg) {858 return this.options.find(option => option.is(arg));859 };860885/**886 * Display an error message if a mandatory option does not have a value.887 * Lazy calling after checking for help flags from leaf subcommand.888 *889 * @api private890 */861 /**862 * Display an error message if a mandatory option does not have a value.863 * Lazy calling after checking for help flags from leaf subcommand.864 *865 * @api private866 */867892Command.prototype._checkForMissingMandatoryOptions = function() {893 // Walk up hierarchy so can call in subcommand after checking for displaying help.894 for (var cmd = this; cmd; cmd = cmd.parent) {895 cmd.options.forEach((anOption) => {896 if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {897 cmd.missingMandatoryOptionValue(anOption);898 }899 });900 }901};868 _checkForMissingMandatoryOptions() {869 // Walk up hierarchy so can call in subcommand after checking for displaying help.870 for (var cmd = this; cmd; cmd = cmd.parent) {871 cmd.options.forEach((anOption) => {872 if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {873 cmd.missingMandatoryOptionValue(anOption);874 }875 });876 }877 };878903/**904 * Parse options from `argv` removing known options,905 * and return argv split into operands and unknown arguments.906 *907 * Examples:908 *909 * argv => operands, unknown910 * --known kkk op => [op], []911 * op --known kkk => [op], []912 * sub --unknown uuu op => [sub], [--unknown uuu op]913 * sub -- --unknown uuu op => [sub --unknown uuu op], []914 *915 * @param {String[]} argv916 * @return {{operands: String[], unknown: String[]}}917 * @api public918 */879 /**880 * Parse options from `argv` removing known options,881 * and return argv split into operands and unknown arguments.882 *883 * Examples:884 *885 * argv => operands, unknown886 * --known kkk op => [op], []887 * op --known kkk => [op], []888 * sub --unknown uuu op => [sub], [--unknown uuu op]889 * sub -- --unknown uuu op => [sub --unknown uuu op], []890 *891 * @param {String[]} argv892 * @return {{operands: String[], unknown: String[]}}893 * @api public894 */895920Command.prototype.parseOptions = function(argv) {921 const operands = []; // operands, not options or values922 const unknown = []; // first unknown option and remaining unknown args923 let dest = operands;924 const args = argv.slice();896 parseOptions(argv) {897 const operands = []; // operands, not options or values898 const unknown = []; // first unknown option and remaining unknown args899 let dest = operands;900 const args = argv.slice();901926 function maybeOption(arg) {927 return arg.length > 1 && arg[0] === '-';928 }902 function maybeOption(arg) {903 return arg.length > 1 && arg[0] === '-';904 }905930 // parse options931 while (args.length) {932 const arg = args.shift();906 // parse options907 while (args.length) {908 const arg = args.shift();909934 // literal935 if (arg === '--') {936 if (dest === unknown) dest.push(arg);937 dest.push(...args);938 break;939 }910 // literal911 if (arg === '--') {912 if (dest === unknown) dest.push(arg);913 dest.push(...args);914 break;915 }916941 if (maybeOption(arg)) {942 const option = this._findOption(arg);943 // recognised option, call listener to assign value with possible custom processing944 if (option) {945 if (option.required) {946 const value = args.shift();947 if (value === undefined) this.optionMissingArgument(option);948 this.emit(`option:${option.name()}`, value);949 } else if (option.optional) {950 let value = null;951 // historical behaviour is optional value is following arg unless an option952 if (args.length > 0 && !maybeOption(args[0])) {953 value = args.shift();917 if (maybeOption(arg)) {918 const option = this._findOption(arg);919 // recognised option, call listener to assign value with possible custom processing920 if (option) {921 if (option.required) {922 const value = args.shift();923 if (value === undefined) this.optionMissingArgument(option);924 this.emit(`option:${option.name()}`, value);925 } else if (option.optional) {926 let value = null;927 // historical behaviour is optional value is following arg unless an option928 if (args.length > 0 && !maybeOption(args[0])) {929 value = args.shift();930 }931 this.emit(`option:${option.name()}`, value);932 } else { // boolean flag933 this.emit(`option:${option.name()}`);934 }955 this.emit(`option:${option.name()}`, value);956 } else { // boolean flag957 this.emit(`option:${option.name()}`);935 continue;936 }959 continue;937 }961 }938963 // Look for combo options following single dash, eat first one if known.964 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {965 const option = this._findOption(`-${arg[1]}`);966 if (option) {967 if (option.required || option.optional) {968 // option with value following in same argument969 this.emit(`option:${option.name()}`, arg.slice(2));970 } else {971 // boolean option, emit and put back remainder of arg for further processing972 this.emit(`option:${option.name()}`);973 args.unshift(`-${arg.slice(2)}`);939 // Look for combo options following single dash, eat first one if known.940 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {941 const option = this._findOption(`-${arg[1]}`);942 if (option) {943 if (option.required || option.optional) {944 // option with value following in same argument945 this.emit(`option:${option.name()}`, arg.slice(2));946 } else {947 // boolean option, emit and put back remainder of arg for further processing948 this.emit(`option:${option.name()}`);949 args.unshift(`-${arg.slice(2)}`);950 }951 continue;952 }975 continue;953 }977 }954979 // Look for known long flag with value, like --foo=bar980 if (/^--[^=]+=/.test(arg)) {981 const index = arg.indexOf('=');982 const option = this._findOption(arg.slice(0, index));983 if (option && (option.required || option.optional)) {984 this.emit(`option:${option.name()}`, arg.slice(index + 1));985 continue;955 // Look for known long flag with value, like --foo=bar956 if (/^--[^=]+=/.test(arg)) {957 const index = arg.indexOf('=');958 const option = this._findOption(arg.slice(0, index));959 if (option && (option.required || option.optional)) {960 this.emit(`option:${option.name()}`, arg.slice(index + 1));961 continue;962 }963 }987 }964989 // looks like an option but unknown, unknowns from here990 if (arg.length > 1 && arg[0] === '-') {991 dest = unknown;965 // looks like an option but unknown, unknowns from here966 if (arg.length > 1 && arg[0] === '-') {967 dest = unknown;968 }969970 // add arg971 dest.push(arg);972 }973994 // add arg995 dest.push(arg);996 }974 return { operands, unknown };975 };976998 return { operands, unknown };999};977 /**978 * Return an object containing options as key-value pairs979 *980 * @return {Object}981 * @api public982 */983 opts() {984 if (this._storeOptionsAsProperties) {985 // Preserve original behaviour so backwards compatible when still using properties986 var result = {},987 len = this.options.length;9881001/**1002 * Return an object containing options as key-value pairs1003 *1004 * @return {Object}1005 * @api public1006 */1007Command.prototype.opts = function() {1008 if (this._storeOptionsAsProperties) {1009 // Preserve original behaviour so backwards compatible when still using properties1010 var result = {},1011 len = this.options.length;10121013 for (var i = 0; i < len; i++) {1014 var key = this.options[i].attributeName();1015 result[key] = key === this._versionOptionName ? this._version : this[key];989 for (var i = 0; i < len; i++) {990 var key = this.options[i].attributeName();991 result[key] = key === this._versionOptionName ? this._version : this[key];992 }993 return result;994 }1017 return result;1018 }9951020 return this._optionValues;1021};996 return this._optionValues;997 };9981023/**1024 * Argument `name` is missing.1025 *1026 * @param {String} name1027 * @api private1028 */999 /**1000 * Argument `name` is missing.1001 *1002 * @param {String} name1003 * @api private1004 */10051030Command.prototype.missingArgument = function(name) {1031 const message = `error: missing required argument '${name}'`;1032 console.error(message);1033 this._exit(1, 'commander.missingArgument', message);1034};1006 missingArgument(name) {1007 const message = `error: missing required argument '${name}'`;1008 console.error(message);1009 this._exit(1, 'commander.missingArgument', message);1010 };10111036/**1037 * `Option` is missing an argument, but received `flag` or nothing.1038 *1039 * @param {Option} option1040 * @param {String} [flag]1041 * @api private1042 */1012 /**1013 * `Option` is missing an argument, but received `flag` or nothing.1014 *1015 * @param {Option} option1016 * @param {String} [flag]1017 * @api private1018 */10191044Command.prototype.optionMissingArgument = function(option, flag) {1045 let message;1046 if (flag) {1047 message = `error: option '${option.flags}' argument missing, got '${flag}'`;1048 } else {1049 message = `error: option '${option.flags}' argument missing`;1050 }1051 console.error(message);1052 this._exit(1, 'commander.optionMissingArgument', message);1053};1020 optionMissingArgument(option, flag) {1021 let message;1022 if (flag) {1023 message = `error: option '${option.flags}' argument missing, got '${flag}'`;1024 } else {1025 message = `error: option '${option.flags}' argument missing`;1026 }1027 console.error(message);1028 this._exit(1, 'commander.optionMissingArgument', message);1029 };10301055/**1056 * `Option` does not have a value, and is a mandatory option.1057 *1058 * @param {Option} option1059 * @api private1060 */1031 /**1032 * `Option` does not have a value, and is a mandatory option.1033 *1034 * @param {Option} option1035 * @api private1036 */10371062Command.prototype.missingMandatoryOptionValue = function(option) {1063 const message = `error: required option '${option.flags}' not specified`;1064 console.error(message);1065 this._exit(1, 'commander.missingMandatoryOptionValue', message);1066};1038 missingMandatoryOptionValue(option) {1039 const message = `error: required option '${option.flags}' not specified`;1040 console.error(message);1041 this._exit(1, 'commander.missingMandatoryOptionValue', message);1042 };10431068/**1069 * Unknown option `flag`.1070 *1071 * @param {String} flag1072 * @api private1073 */1044 /**1045 * Unknown option `flag`.1046 *1047 * @param {String} flag1048 * @api private1049 */10501075Command.prototype.unknownOption = function(flag) {1076 if (this._allowUnknownOption) return;1077 const message = `error: unknown option '${flag}'`;1078 console.error(message);1079 this._exit(1, 'commander.unknownOption', message);1080};1051 unknownOption(flag) {1052 if (this._allowUnknownOption) return;1053 const message = `error: unknown option '${flag}'`;1054 console.error(message);1055 this._exit(1, 'commander.unknownOption', message);1056 };10571082/**1083 * Unknown command.1084 *1085 * @param {String} flag1086 * @api private1087 */1058 /**1059 * Unknown command.1060 *1061 * @param {String} flag1062 * @api private1063 */10641089Command.prototype.unknownCommand = function() {1090 const message = `error: unknown command '${this.args[0]}'`;1091 console.error(message);1092 this._exit(1, 'commander.unknownCommand', message);1093};1065 unknownCommand() {1066 const message = `error: unknown command '${this.args[0]}'`;1067 console.error(message);1068 this._exit(1, 'commander.unknownCommand', message);1069 };10701095/**1096 * Variadic argument with `name` is not the last argument as required.1097 *1098 * @param {String} name1099 * @api private1100 */1071 /**1072 * Variadic argument with `name` is not the last argument as required.1073 *1074 * @param {String} name1075 * @api private1076 */10771102Command.prototype.variadicArgNotLast = function(name) {1103 const message = `error: variadic arguments must be last '${name}'`;1104 console.error(message);1105 this._exit(1, 'commander.variadicArgNotLast', message);1106};1078 variadicArgNotLast(name) {1079 const message = `error: variadic arguments must be last '${name}'`;1080 console.error(message);1081 this._exit(1, 'commander.variadicArgNotLast', message);1082 };10831108/**1109 * Set the program version to `str`.1110 *1111 * This method auto-registers the "-V, --version" flag1112 * which will print the version number when passed.1113 *1114 * You can optionally supply the flags and description to override the defaults.1115 *1116 * @param {String} str1117 * @param {String} [flags]1118 * @param {String} [description]1119 * @return {Command} for chaining1120 * @api public1121 */1084 /**1085 * Set the program version to `str`.1086 *1087 * This method auto-registers the "-V, --version" flag1088 * which will print the version number when passed.1089 *1090 * You can optionally supply the flags and description to override the defaults.1091 *1092 * @param {String} str1093 * @param {String} [flags]1094 * @param {String} [description]1095 * @return {Command} for chaining1096 * @api public1097 */10981123Command.prototype.version = function(str, flags, description) {1124 if (arguments.length === 0) return this._version;1125 this._version = str;1126 flags = flags || '-V, --version';1127 description = description || 'output the version number';1128 var versionOption = new Option(flags, description);1129 this._versionOptionName = versionOption.long.substr(2) || 'version';1130 this.options.push(versionOption);1131 var self = this;1132 this.on('option:' + this._versionOptionName, function() {1133 process.stdout.write(str + '\n');1134 self._exit(0, 'commander.version', str);1135 });1136 return this;1137};1099 version(str, flags, description) {1100 if (arguments.length === 0) return this._version;1101 this._version = str;1102 flags = flags || '-V, --version';1103 description = description || 'output the version number';1104 var versionOption = new Option(flags, description);1105 this._versionOptionName = versionOption.long.substr(2) || 'version';1106 this.options.push(versionOption);1107 var self = this;1108 this.on('option:' + this._versionOptionName, function() {1109 process.stdout.write(str + '\n');1110 self._exit(0, 'commander.version', str);1111 });1112 return this;1113 };11141139/**1140 * Set the description to `str`.1141 *1142 * @param {String} str1143 * @param {Object} [argsDescription]1144 * @return {String|Command}1145 * @api public1146 */1115 /**1116 * Set the description to `str`.1117 *1118 * @param {String} str1119 * @param {Object} [argsDescription]1120 * @return {String|Command}1121 * @api public1122 */11231148Command.prototype.description = function(str, argsDescription) {1149 if (arguments.length === 0) return this._description;1150 this._description = str;1151 this._argsDescription = argsDescription;1152 return this;1153};1124 description(str, argsDescription) {1125 if (arguments.length === 0) return this._description;1126 this._description = str;1127 this._argsDescription = argsDescription;1128 return this;1129 };11301155/**1156 * Set an alias for the command1157 *1158 * @param {String} alias1159 * @return {String|Command}1160 * @api public1161 */1131 /**1132 * Set an alias for the command1133 *1134 * @param {String} alias1135 * @return {String|Command}1136 * @api public1137 */11381163Command.prototype.alias = function(alias) {1164 var command = this;1165 if (this.commands.length !== 0) {1166 command = this.commands[this.commands.length - 1];1167 }1139 alias(alias) {1140 var command = this;1141 if (this.commands.length !== 0) {1142 command = this.commands[this.commands.length - 1];1143 }11441169 if (arguments.length === 0) return command._alias;1145 if (arguments.length === 0) return command._alias;11461171 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');1147 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');11481173 command._alias = alias;1174 return this;1175};1149 command._alias = alias;1150 return this;1151 };11521177/**1178 * Set / get the command usage `str`.1179 *1180 * @param {String} [str]1181 * @return {String|Command}1182 * @api public1183 */1153 /**1154 * Set / get the command usage `str`.1155 *1156 * @param {String} [str]1157 * @return {String|Command}1158 * @api public1159 */11601185Command.prototype.usage = function(str) {1186 var args = this._args.map(function(arg) {1187 return humanReadableArgName(arg);1188 });1161 usage(str) {1162 var args = this._args.map(function(arg) {1163 return humanReadableArgName(arg);1164 });11651190 var usage = '[options]' +1191 (this.commands.length ? ' [command]' : '') +1192 (this._args.length ? ' ' + args.join(' ') : '');1166 var usage = '[options]' +1167 (this.commands.length ? ' [command]' : '') +1168 (this._args.length ? ' ' + args.join(' ') : '');11691194 if (arguments.length === 0) return this._usage || usage;1195 this._usage = str;1170 if (arguments.length === 0) return this._usage || usage;1171 this._usage = str;11721197 return this;1198};1173 return this;1174 };11751200/**1201 * Get or set the name of the command1202 *1203 * @param {String} [str]1204 * @return {String|Command}1205 * @api public1206 */1176 /**1177 * Get or set the name of the command1178 *1179 * @param {String} [str]1180 * @return {String|Command}1181 * @api public1182 */11831208Command.prototype.name = function(str) {1209 if (arguments.length === 0) return this._name;1210 this._name = str;1211 return this;1212};1184 name(str) {1185 if (arguments.length === 0) return this._name;1186 this._name = str;1187 return this;1188 };11891214/**1215 * Return prepared commands.1216 *1217 * @return {Array}1218 * @api private1219 */1190 /**1191 * Return prepared commands.1192 *1193 * @return {Array}1194 * @api private1195 */11961221Command.prototype.prepareCommands = function() {1222 const commandDetails = this.commands.filter(function(cmd) {1223 return !cmd._noHelp;1224 }).map(function(cmd) {1225 var args = cmd._args.map(function(arg) {1226 return humanReadableArgName(arg);1227 }).join(' ');1197 prepareCommands() {1198 const commandDetails = this.commands.filter(function(cmd) {1199 return !cmd._noHelp;1200 }).map(function(cmd) {1201 var args = cmd._args.map(function(arg) {1202 return humanReadableArgName(arg);1203 }).join(' ');12041229 return [1230 cmd._name +1231 (cmd._alias ? '|' + cmd._alias : '') +1232 (cmd.options.length ? ' [options]' : '') +1233 (args ? ' ' + args : ''),1234 cmd._description1235 ];1236 });1205 return [1206 cmd._name +1207 (cmd._alias ? '|' + cmd._alias : '') +1208 (cmd.options.length ? ' [options]' : '') +1209 (args ? ' ' + args : ''),1210 cmd._description1211 ];1212 });12131238 if (this._lazyHasImplicitHelpCommand()) {1239 commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);1240 }1241 return commandDetails;1242};1214 if (this._lazyHasImplicitHelpCommand()) {1215 commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);1216 }1217 return commandDetails;1218 };12191244/**1245 * Return the largest command length.1246 *1247 * @return {Number}1248 * @api private1249 */1220 /**1221 * Return the largest command length.1222 *1223 * @return {Number}1224 * @api private1225 */12261251Command.prototype.largestCommandLength = function() {1252 var commands = this.prepareCommands();1253 return commands.reduce(function(max, command) {1254 return Math.max(max, command[0].length);1255 }, 0);1256};1227 largestCommandLength() {1228 var commands = this.prepareCommands();1229 return commands.reduce(function(max, command) {1230 return Math.max(max, command[0].length);1231 }, 0);1232 };12331258/**1259 * Return the largest option length.1260 *1261 * @return {Number}1262 * @api private1263 */1234 /**1235 * Return the largest option length.1236 *1237 * @return {Number}1238 * @api private1239 */12401265Command.prototype.largestOptionLength = function() {1266 var options = [].slice.call(this.options);1267 options.push({1268 flags: this._helpFlags1269 });1241 largestOptionLength() {1242 var options = [].slice.call(this.options);1243 options.push({1244 flags: this._helpFlags1245 });12461271 return options.reduce(function(max, option) {1272 return Math.max(max, option.flags.length);1273 }, 0);1274};1247 return options.reduce(function(max, option) {1248 return Math.max(max, option.flags.length);1249 }, 0);1250 };12511276/**1277 * Return the largest arg length.1278 *1279 * @return {Number}1280 * @api private1281 */1252 /**1253 * Return the largest arg length.1254 *1255 * @return {Number}1256 * @api private1257 */12581283Command.prototype.largestArgLength = function() {1284 return this._args.reduce(function(max, arg) {1285 return Math.max(max, arg.name.length);1286 }, 0);1287};1259 largestArgLength() {1260 return this._args.reduce(function(max, arg) {1261 return Math.max(max, arg.name.length);1262 }, 0);1263 };12641289/**1290 * Return the pad width.1291 *1292 * @return {Number}1293 * @api private1294 */1265 /**1266 * Return the pad width.1267 *1268 * @return {Number}1269 * @api private1270 */12711296Command.prototype.padWidth = function() {1297 var width = this.largestOptionLength();1298 if (this._argsDescription && this._args.length) {1299 if (this.largestArgLength() > width) {1300 width = this.largestArgLength();1272 padWidth() {1273 var width = this.largestOptionLength();1274 if (this._argsDescription && this._args.length) {1275 if (this.largestArgLength() > width) {1276 width = this.largestArgLength();1277 }1278 }1302 }12791304 if (this.commands && this.commands.length) {1305 if (this.largestCommandLength() > width) {1306 width = this.largestCommandLength();1280 if (this.commands && this.commands.length) {1281 if (this.largestCommandLength() > width) {1282 width = this.largestCommandLength();1283 }1284 }1308 }12851310 return width;1311};1286 return width;1287 };12881313/**1314 * Return help for options.1315 *1316 * @return {String}1317 * @api private1318 */1289 /**1290 * Return help for options.1291 *1292 * @return {String}1293 * @api private1294 */12951320Command.prototype.optionHelp = function() {1321 var width = this.padWidth();1296 optionHelp() {1297 var width = this.padWidth();12981323 var columns = process.stdout.columns || 80;1324 var descriptionWidth = columns - width - 4;1299 var columns = process.stdout.columns || 80;1300 var descriptionWidth = columns - width - 4;13011326 // Append the help information1327 return this.options.map(function(option) {1328 const fullDesc = option.description +1329 ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');1330 return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2);1331 }).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)])1332 .join('\n');1333};1302 // Append the help information1303 return this.options.map(function(option) {1304 const fullDesc = option.description +1305 ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');1306 return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2);1307 }).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)])1308 .join('\n');1309 };13101335/**1336 * Return command help documentation.1337 *1338 * @return {String}1339 * @api private1340 */1311 /**1312 * Return command help documentation.1313 *1314 * @return {String}1315 * @api private1316 */13171342Command.prototype.commandHelp = function() {1343 if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';1318 commandHelp() {1319 if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';13201345 var commands = this.prepareCommands();1346 var width = this.padWidth();1321 var commands = this.prepareCommands();1322 var width = this.padWidth();13231348 var columns = process.stdout.columns || 80;1349 var descriptionWidth = columns - width - 4;1324 var columns = process.stdout.columns || 80;1325 var descriptionWidth = columns - width - 4;13261351 return [1352 'Commands:',1353 commands.map(function(cmd) {1354 var desc = cmd[1] ? ' ' + cmd[1] : '';1355 return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);1356 }).join('\n').replace(/^/gm, ' '),1357 ''1358 ].join('\n');1359};1327 return [1328 'Commands:',1329 commands.map(function(cmd) {1330 var desc = cmd[1] ? ' ' + cmd[1] : '';1331 return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);1332 }).join('\n').replace(/^/gm, ' '),1333 ''1334 ].join('\n');1335 };13361361/**1362 * Return program help documentation.1363 *1364 * @return {String}1365 * @api private1366 */1337 /**1338 * Return program help documentation.1339 *1340 * @return {String}1341 * @api private1342 */13431368Command.prototype.helpInformation = function() {1369 var desc = [];1370 if (this._description) {1371 desc = [1372 this._description,1344 helpInformation() {1345 var desc = [];1346 if (this._description) {1347 desc = [1348 this._description,1349 ''1350 ];13511352 var argsDescription = this._argsDescription;1353 if (argsDescription && this._args.length) {1354 var width = this.padWidth();1355 var columns = process.stdout.columns || 80;1356 var descriptionWidth = columns - width - 5;1357 desc.push('Arguments:');1358 desc.push('');1359 this._args.forEach(function(arg) {1360 desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4));1361 });1362 desc.push('');1363 }1364 }13651366 var cmdName = this._name;1367 if (this._alias) {1368 cmdName = cmdName + '|' + this._alias;1369 }1370 var parentCmdNames = '';1371 for (var parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {1372 parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;1373 }1374 var usage = [1375 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),1376 ''1377 ];13781376 var argsDescription = this._argsDescription;1377 if (argsDescription && this._args.length) {1378 var width = this.padWidth();1379 var columns = process.stdout.columns || 80;1380 var descriptionWidth = columns - width - 5;1381 desc.push('Arguments:');1382 desc.push('');1383 this._args.forEach(function(arg) {1384 desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4));1385 });1386 desc.push('');1387 }1388 }1379 var cmds = [];1380 var commandHelp = this.commandHelp();1381 if (commandHelp) cmds = [commandHelp];13821390 var cmdName = this._name;1391 if (this._alias) {1392 cmdName = cmdName + '|' + this._alias;1393 }1394 var parentCmdNames = '';1395 for (var parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {1396 parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;1397 }1398 var usage = [1399 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),1400 ''1401 ];1383 var options = [1384 'Options:',1385 '' + this.optionHelp().replace(/^/gm, ' '),1386 ''1387 ];13881403 var cmds = [];1404 var commandHelp = this.commandHelp();1405 if (commandHelp) cmds = [commandHelp];1389 return usage1390 .concat(desc)1391 .concat(options)1392 .concat(cmds)1393 .join('\n');1394 };13951407 var options = [1408 'Options:',1409 '' + this.optionHelp().replace(/^/gm, ' '),1410 ''1411 ];1396 /**1397 * Output help information for this command.1398 *1399 * When listener(s) are available for the helpLongFlag1400 * those callbacks are invoked.1401 *1402 * @api public1403 */14041413 return usage1414 .concat(desc)1415 .concat(options)1416 .concat(cmds)1417 .join('\n');1418};1405 outputHelp(cb) {1406 if (!cb) {1407 cb = function(passthru) {1408 return passthru;1409 };1410 }1411 const cbOutput = cb(this.helpInformation());1412 if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {1413 throw new Error('outputHelp callback must return a string or a Buffer');1414 }1415 process.stdout.write(cbOutput);1416 this.emit(this._helpLongFlag);1417 };14181420/**1421 * Output help information for this command.1422 *1423 * When listener(s) are available for the helpLongFlag1424 * those callbacks are invoked.1425 *1426 * @api public1427 */1419 /**1420 * You can pass in flags and a description to override the help1421 * flags and help description for your command.1422 *1423 * @param {String} [flags]1424 * @param {String} [description]1425 * @return {Command}1426 * @api public1427 */14281429Command.prototype.outputHelp = function(cb) {1430 if (!cb) {1431 cb = function(passthru) {1432 return passthru;1433 };1434 }1435 const cbOutput = cb(this.helpInformation());1436 if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {1437 throw new Error('outputHelp callback must return a string or a Buffer');1438 }1439 process.stdout.write(cbOutput);1440 this.emit(this._helpLongFlag);1441};1429 helpOption(flags, description) {1430 this._helpFlags = flags || this._helpFlags;1431 this._helpDescription = description || this._helpDescription;14321443/**1444 * You can pass in flags and a description to override the help1445 * flags and help description for your command.1446 *1447 * @param {String} [flags]1448 * @param {String} [description]1449 * @return {Command}1450 * @api public1451 */1433 var splitFlags = this._helpFlags.split(/[ ,|]+/);14341453Command.prototype.helpOption = function(flags, description) {1454 this._helpFlags = flags || this._helpFlags;1455 this._helpDescription = description || this._helpDescription;1435 if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift();14361457 var splitFlags = this._helpFlags.split(/[ ,|]+/);1437 this._helpLongFlag = splitFlags.shift();14381459 if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift();1439 return this;1440 };14411461 this._helpLongFlag = splitFlags.shift();1442 /**1443 * Output help information and exit.1444 *1445 * @param {Function} [cb]1446 * @api public1447 */14481463 return this;1449 help(cb) {1450 this.outputHelp(cb);1451 // exitCode: preserving original behaviour which was calling process.exit()1452 // message: do not have all displayed text available so only passing placeholder.1453 this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');1454 };14551456 /**1457 * Output help information and exit. Display for error situations.1458 *1459 * @api private1460 */14611462 _helpAndError() {1463 this.outputHelp();1464 // message: do not have all displayed text available so only passing placeholder.1465 this._exit(1, 'commander.help', '(outputHelp)');1466 };1467};14681469/**1467 * Output help information and exit.1468 *1469 * @param {Function} [cb]1470 * @api public1470 * Expose the root command.1471 */14721473Command.prototype.help = function(cb) {1474 this.outputHelp(cb);1475 // exitCode: preserving original behaviour which was calling process.exit()1476 // message: do not have all displayed text available so only passing placeholder.1477 this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');1478};1473exports = module.exports = new Command();14741475/**1481 * Output help information and exit. Display for error situations.1482 *1483 * @api private1476 * Expose classes1477 */14781486Command.prototype._helpAndError = function() {1487 this.outputHelp();1488 // message: do not have all displayed text available so only passing placeholder.1489 this._exit(1, 'commander.help', '(outputHelp)');1490};1479exports.Command = Command;1480exports.Option = Option;1481exports.CommanderError = CommanderError;14821483/**1484 * Camel-case the given `flag`1485 *
147 unmodified lines