commander 7.2.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/command.js ADDED
@@ -0,0 +1,1840 @@
1
+ const EventEmitter = require('events').EventEmitter;
2
+ const childProcess = require('child_process');
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+
6
+ const { Argument, humanReadableArgName } = require('./argument.js');
7
+ const { CommanderError } = require('./error.js');
8
+ const { Help } = require('./help.js');
9
+ const { Option, splitOptionFlags } = require('./option.js');
10
+
11
+ // @ts-check
12
+
13
+ class Command extends EventEmitter {
14
+ /**
15
+ * Initialize a new `Command`.
16
+ *
17
+ * @param {string} [name]
18
+ */
19
+
20
+ constructor(name) {
21
+ super();
22
+ /** @type {Command[]} */
23
+ this.commands = [];
24
+ /** @type {Option[]} */
25
+ this.options = [];
26
+ this.parent = null;
27
+ this._allowUnknownOption = false;
28
+ this._allowExcessArguments = true;
29
+ /** @type {Argument[]} */
30
+ this._args = [];
31
+ /** @type {string[]} */
32
+ this.args = []; // cli args with options removed
33
+ this.rawArgs = [];
34
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
35
+ this._scriptPath = null;
36
+ this._name = name || '';
37
+ this._optionValues = {};
38
+ this._storeOptionsAsProperties = false;
39
+ this._actionHandler = null;
40
+ this._executableHandler = false;
41
+ this._executableFile = null; // custom name for executable
42
+ this._defaultCommandName = null;
43
+ this._exitCallback = null;
44
+ this._aliases = [];
45
+ this._combineFlagAndOptionalValue = true;
46
+ this._description = '';
47
+ this._argsDescription = undefined; // legacy
48
+ this._enablePositionalOptions = false;
49
+ this._passThroughOptions = false;
50
+ this._lifeCycleHooks = {}; // a hash of arrays
51
+ /** @type {boolean | string} */
52
+ this._showHelpAfterError = false;
53
+
54
+ // see .configureOutput() for docs
55
+ this._outputConfiguration = {
56
+ writeOut: (str) => process.stdout.write(str),
57
+ writeErr: (str) => process.stderr.write(str),
58
+ getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,
59
+ getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,
60
+ outputError: (str, write) => write(str)
61
+ };
62
+
63
+ this._hidden = false;
64
+ this._hasHelpOption = true;
65
+ this._helpFlags = '-h, --help';
66
+ this._helpDescription = 'display help for command';
67
+ this._helpShortFlag = '-h';
68
+ this._helpLongFlag = '--help';
69
+ this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false
70
+ this._helpCommandName = 'help';
71
+ this._helpCommandnameAndArgs = 'help [command]';
72
+ this._helpCommandDescription = 'display help for command';
73
+ this._helpConfiguration = {};
74
+ }
75
+
76
+ /**
77
+ * Define a command.
78
+ *
79
+ * There are two styles of command: pay attention to where to put the description.
80
+ *
81
+ * Examples:
82
+ *
83
+ * // Command implemented using action handler (description is supplied separately to `.command`)
84
+ * program
85
+ * .command('clone <source> [destination]')
86
+ * .description('clone a repository into a newly created directory')
87
+ * .action((source, destination) => {
88
+ * console.log('clone command called');
89
+ * });
90
+ *
91
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
92
+ * program
93
+ * .command('start <service>', 'start named service')
94
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
95
+ *
96
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
97
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
98
+ * @param {Object} [execOpts] - configuration options (for executable)
99
+ * @return {Command} returns new command for action handler, or `this` for executable command
100
+ */
101
+
102
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
103
+ let desc = actionOptsOrExecDesc;
104
+ let opts = execOpts;
105
+ if (typeof desc === 'object' && desc !== null) {
106
+ opts = desc;
107
+ desc = null;
108
+ }
109
+ opts = opts || {};
110
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
111
+ const cmd = this.createCommand(name);
112
+
113
+ if (desc) {
114
+ cmd.description(desc);
115
+ cmd._executableHandler = true;
116
+ }
117
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
118
+
119
+ cmd._outputConfiguration = this._outputConfiguration;
120
+
121
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
122
+ cmd._hasHelpOption = this._hasHelpOption;
123
+ cmd._helpFlags = this._helpFlags;
124
+ cmd._helpDescription = this._helpDescription;
125
+ cmd._helpShortFlag = this._helpShortFlag;
126
+ cmd._helpLongFlag = this._helpLongFlag;
127
+ cmd._helpCommandName = this._helpCommandName;
128
+ cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;
129
+ cmd._helpCommandDescription = this._helpCommandDescription;
130
+ cmd._helpConfiguration = this._helpConfiguration;
131
+ cmd._exitCallback = this._exitCallback;
132
+ cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
133
+ cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;
134
+ cmd._allowExcessArguments = this._allowExcessArguments;
135
+ cmd._enablePositionalOptions = this._enablePositionalOptions;
136
+ cmd._showHelpAfterError = this._showHelpAfterError;
137
+
138
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
139
+ if (args) cmd.arguments(args);
140
+ this.commands.push(cmd);
141
+ cmd.parent = this;
142
+
143
+ if (desc) return this;
144
+ return cmd;
145
+ };
146
+
147
+ /**
148
+ * Factory routine to create a new unattached command.
149
+ *
150
+ * See .command() for creating an attached subcommand, which uses this routine to
151
+ * create the command. You can override createCommand to customise subcommands.
152
+ *
153
+ * @param {string} [name]
154
+ * @return {Command} new command
155
+ */
156
+
157
+ createCommand(name) {
158
+ return new Command(name);
159
+ };
160
+
161
+ /**
162
+ * You can customise the help with a subclass of Help by overriding createHelp,
163
+ * or by overriding Help properties using configureHelp().
164
+ *
165
+ * @return {Help}
166
+ */
167
+
168
+ createHelp() {
169
+ return Object.assign(new Help(), this.configureHelp());
170
+ };
171
+
172
+ /**
173
+ * You can customise the help by overriding Help properties using configureHelp(),
174
+ * or with a subclass of Help by overriding createHelp().
175
+ *
176
+ * @param {Object} [configuration] - configuration options
177
+ * @return {Command|Object} `this` command for chaining, or stored configuration
178
+ */
179
+
180
+ configureHelp(configuration) {
181
+ if (configuration === undefined) return this._helpConfiguration;
182
+
183
+ this._helpConfiguration = configuration;
184
+ return this;
185
+ }
186
+
187
+ /**
188
+ * The default output goes to stdout and stderr. You can customise this for special
189
+ * applications. You can also customise the display of errors by overriding outputError.
190
+ *
191
+ * The configuration properties are all functions:
192
+ *
193
+ * // functions to change where being written, stdout and stderr
194
+ * writeOut(str)
195
+ * writeErr(str)
196
+ * // matching functions to specify width for wrapping help
197
+ * getOutHelpWidth()
198
+ * getErrHelpWidth()
199
+ * // functions based on what is being written out
200
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
201
+ *
202
+ * @param {Object} [configuration] - configuration options
203
+ * @return {Command|Object} `this` command for chaining, or stored configuration
204
+ */
205
+
206
+ configureOutput(configuration) {
207
+ if (configuration === undefined) return this._outputConfiguration;
208
+
209
+ Object.assign(this._outputConfiguration, configuration);
210
+ return this;
211
+ }
212
+
213
+ /**
214
+ * Display the help or a custom message after an error occurs.
215
+ *
216
+ * @param {boolean|string} [displayHelp]
217
+ * @return {Command} `this` command for chaining
218
+ */
219
+ showHelpAfterError(displayHelp = true) {
220
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
221
+ this._showHelpAfterError = displayHelp;
222
+ return this;
223
+ }
224
+
225
+ /**
226
+ * Add a prepared subcommand.
227
+ *
228
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
229
+ *
230
+ * @param {Command} cmd - new subcommand
231
+ * @param {Object} [opts] - configuration options
232
+ * @return {Command} `this` command for chaining
233
+ */
234
+
235
+ addCommand(cmd, opts) {
236
+ if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
237
+
238
+ // To keep things simple, block automatic name generation for deeply nested executables.
239
+ // Fail fast and detect when adding rather than later when parsing.
240
+ function checkExplicitNames(commandArray) {
241
+ commandArray.forEach((cmd) => {
242
+ if (cmd._executableHandler && !cmd._executableFile) {
243
+ throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);
244
+ }
245
+ checkExplicitNames(cmd.commands);
246
+ });
247
+ }
248
+ checkExplicitNames(cmd.commands);
249
+
250
+ opts = opts || {};
251
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
252
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
253
+
254
+ this.commands.push(cmd);
255
+ cmd.parent = this;
256
+ return this;
257
+ };
258
+
259
+ /**
260
+ * Factory routine to create a new unattached argument.
261
+ *
262
+ * See .argument() for creating an attached argument, which uses this routine to
263
+ * create the argument. You can override createArgument to return a custom argument.
264
+ *
265
+ * @param {string} name
266
+ * @param {string} [description]
267
+ * @return {Argument} new argument
268
+ */
269
+
270
+ createArgument(name, description) {
271
+ return new Argument(name, description);
272
+ };
273
+
274
+ /**
275
+ * Define argument syntax for command.
276
+ *
277
+ * The default is that the argument is required, and you can explicitly
278
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
279
+ *
280
+ * @example
281
+ *
282
+ * program.argument('<input-file>');
283
+ * program.argument('[output-file]');
284
+ *
285
+ * @param {string} name
286
+ * @param {string} [description]
287
+ * @param {Function|*} [fn] - custom argument processing function
288
+ * @param {*} [defaultValue]
289
+ * @return {Command} `this` command for chaining
290
+ */
291
+ argument(name, description, fn, defaultValue) {
292
+ const argument = this.createArgument(name, description);
293
+ if (typeof fn === 'function') {
294
+ argument.default(defaultValue).argParser(fn);
295
+ } else {
296
+ argument.default(fn);
297
+ }
298
+ this.addArgument(argument);
299
+ return this;
300
+ }
301
+
302
+ /**
303
+ * Define argument syntax for command, adding multiple at once (without descriptions).
304
+ *
305
+ * See also .argument().
306
+ *
307
+ * @example
308
+ *
309
+ * program.arguments('<cmd> [env]');
310
+ *
311
+ * @param {string} names
312
+ * @return {Command} `this` command for chaining
313
+ */
314
+
315
+ arguments(names) {
316
+ names.split(/ +/).forEach((detail) => {
317
+ this.argument(detail);
318
+ });
319
+ return this;
320
+ };
321
+
322
+ /**
323
+ * Define argument syntax for command, adding a prepared argument.
324
+ *
325
+ * @param {Argument} argument
326
+ * @return {Command} `this` command for chaining
327
+ */
328
+ addArgument(argument) {
329
+ const previousArgument = this._args.slice(-1)[0];
330
+ if (previousArgument && previousArgument.variadic) {
331
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
332
+ }
333
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
334
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
335
+ }
336
+ this._args.push(argument);
337
+ return this;
338
+ }
339
+
340
+ /**
341
+ * Override default decision whether to add implicit help command.
342
+ *
343
+ * addHelpCommand() // force on
344
+ * addHelpCommand(false); // force off
345
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
346
+ *
347
+ * @return {Command} `this` command for chaining
348
+ */
349
+
350
+ addHelpCommand(enableOrNameAndArgs, description) {
351
+ if (enableOrNameAndArgs === false) {
352
+ this._addImplicitHelpCommand = false;
353
+ } else {
354
+ this._addImplicitHelpCommand = true;
355
+ if (typeof enableOrNameAndArgs === 'string') {
356
+ this._helpCommandName = enableOrNameAndArgs.split(' ')[0];
357
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
358
+ }
359
+ this._helpCommandDescription = description || this._helpCommandDescription;
360
+ }
361
+ return this;
362
+ };
363
+
364
+ /**
365
+ * @return {boolean}
366
+ * @api private
367
+ */
368
+
369
+ _hasImplicitHelpCommand() {
370
+ if (this._addImplicitHelpCommand === undefined) {
371
+ return this.commands.length && !this._actionHandler && !this._findCommand('help');
372
+ }
373
+ return this._addImplicitHelpCommand;
374
+ };
375
+
376
+ /**
377
+ * Add hook for life cycle event.
378
+ *
379
+ * @param {string} event
380
+ * @param {Function} listener
381
+ * @return {Command} `this` command for chaining
382
+ */
383
+
384
+ hook(event, listener) {
385
+ const allowedValues = ['preAction', 'postAction'];
386
+ if (!allowedValues.includes(event)) {
387
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
388
+ Expecting one of '${allowedValues.join("', '")}'`);
389
+ }
390
+ if (this._lifeCycleHooks[event]) {
391
+ this._lifeCycleHooks[event].push(listener);
392
+ } else {
393
+ this._lifeCycleHooks[event] = [listener];
394
+ }
395
+ return this;
396
+ }
397
+
398
+ /**
399
+ * Register callback to use as replacement for calling process.exit.
400
+ *
401
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
402
+ * @return {Command} `this` command for chaining
403
+ */
404
+
405
+ exitOverride(fn) {
406
+ if (fn) {
407
+ this._exitCallback = fn;
408
+ } else {
409
+ this._exitCallback = (err) => {
410
+ if (err.code !== 'commander.executeSubCommandAsync') {
411
+ throw err;
412
+ } else {
413
+ // Async callback from spawn events, not useful to throw.
414
+ }
415
+ };
416
+ }
417
+ return this;
418
+ };
419
+
420
+ /**
421
+ * Call process.exit, and _exitCallback if defined.
422
+ *
423
+ * @param {number} exitCode exit code for using with process.exit
424
+ * @param {string} code an id string representing the error
425
+ * @param {string} message human-readable description of the error
426
+ * @return never
427
+ * @api private
428
+ */
429
+
430
+ _exit(exitCode, code, message) {
431
+ if (this._exitCallback) {
432
+ this._exitCallback(new CommanderError(exitCode, code, message));
433
+ // Expecting this line is not reached.
434
+ }
435
+ process.exit(exitCode);
436
+ };
437
+
438
+ /**
439
+ * Register callback `fn` for the command.
440
+ *
441
+ * Examples:
442
+ *
443
+ * program
444
+ * .command('help')
445
+ * .description('display verbose help')
446
+ * .action(function() {
447
+ * // output help here
448
+ * });
449
+ *
450
+ * @param {Function} fn
451
+ * @return {Command} `this` command for chaining
452
+ */
453
+
454
+ action(fn) {
455
+ const listener = (args) => {
456
+ // The .action callback takes an extra parameter which is the command or options.
457
+ const expectedArgsCount = this._args.length;
458
+ const actionArgs = args.slice(0, expectedArgsCount);
459
+ if (this._storeOptionsAsProperties) {
460
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
461
+ } else {
462
+ actionArgs[expectedArgsCount] = this.opts();
463
+ }
464
+ actionArgs.push(this);
465
+
466
+ return fn.apply(this, actionArgs);
467
+ };
468
+ this._actionHandler = listener;
469
+ return this;
470
+ };
471
+
472
+ /**
473
+ * Factory routine to create a new unattached option.
474
+ *
475
+ * See .option() for creating an attached option, which uses this routine to
476
+ * create the option. You can override createOption to return a custom option.
477
+ *
478
+ * @param {string} flags
479
+ * @param {string} [description]
480
+ * @return {Option} new option
481
+ */
482
+
483
+ createOption(flags, description) {
484
+ return new Option(flags, description);
485
+ };
486
+
487
+ /**
488
+ * Add an option.
489
+ *
490
+ * @param {Option} option
491
+ * @return {Command} `this` command for chaining
492
+ */
493
+ addOption(option) {
494
+ const oname = option.name();
495
+ const name = option.attributeName();
496
+
497
+ let defaultValue = option.defaultValue;
498
+
499
+ // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value
500
+ if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
501
+ // when --no-foo we make sure default is true, unless a --foo option is already defined
502
+ if (option.negate) {
503
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
504
+ defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true;
505
+ }
506
+ // preassign only if we have a default
507
+ if (defaultValue !== undefined) {
508
+ this.setOptionValue(name, defaultValue);
509
+ }
510
+ }
511
+
512
+ // register the option
513
+ this.options.push(option);
514
+
515
+ // when it's passed assign the value
516
+ // and conditionally invoke the callback
517
+ this.on('option:' + oname, (val) => {
518
+ const oldValue = this.getOptionValue(name);
519
+
520
+ // custom processing
521
+ if (val !== null && option.parseArg) {
522
+ try {
523
+ val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);
524
+ } catch (err) {
525
+ if (err.code === 'commander.invalidArgument') {
526
+ const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;
527
+ this._displayError(err.exitCode, err.code, message);
528
+ }
529
+ throw err;
530
+ }
531
+ } else if (val !== null && option.variadic) {
532
+ val = option._concatValue(val, oldValue);
533
+ }
534
+
535
+ // unassigned or boolean value
536
+ if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {
537
+ // if no value, negate false, and we have a default, then use it!
538
+ if (val == null) {
539
+ this.setOptionValue(name, option.negate
540
+ ? false
541
+ : defaultValue || true);
542
+ } else {
543
+ this.setOptionValue(name, val);
544
+ }
545
+ } else if (val !== null) {
546
+ // reassign
547
+ this.setOptionValue(name, option.negate ? false : val);
548
+ }
549
+ });
550
+
551
+ return this;
552
+ }
553
+
554
+ /**
555
+ * Internal implementation shared by .option() and .requiredOption()
556
+ *
557
+ * @api private
558
+ */
559
+ _optionEx(config, flags, description, fn, defaultValue) {
560
+ const option = this.createOption(flags, description);
561
+ option.makeOptionMandatory(!!config.mandatory);
562
+ if (typeof fn === 'function') {
563
+ option.default(defaultValue).argParser(fn);
564
+ } else if (fn instanceof RegExp) {
565
+ // deprecated
566
+ const regex = fn;
567
+ fn = (val, def) => {
568
+ const m = regex.exec(val);
569
+ return m ? m[0] : def;
570
+ };
571
+ option.default(defaultValue).argParser(fn);
572
+ } else {
573
+ option.default(fn);
574
+ }
575
+
576
+ return this.addOption(option);
577
+ }
578
+
579
+ /**
580
+ * Define option with `flags`, `description` and optional
581
+ * coercion `fn`.
582
+ *
583
+ * The `flags` string contains the short and/or long flags,
584
+ * separated by comma, a pipe or space. The following are all valid
585
+ * all will output this way when `--help` is used.
586
+ *
587
+ * "-p, --pepper"
588
+ * "-p|--pepper"
589
+ * "-p --pepper"
590
+ *
591
+ * Examples:
592
+ *
593
+ * // simple boolean defaulting to undefined
594
+ * program.option('-p, --pepper', 'add pepper');
595
+ *
596
+ * program.pepper
597
+ * // => undefined
598
+ *
599
+ * --pepper
600
+ * program.pepper
601
+ * // => true
602
+ *
603
+ * // simple boolean defaulting to true (unless non-negated option is also defined)
604
+ * program.option('-C, --no-cheese', 'remove cheese');
605
+ *
606
+ * program.cheese
607
+ * // => true
608
+ *
609
+ * --no-cheese
610
+ * program.cheese
611
+ * // => false
612
+ *
613
+ * // required argument
614
+ * program.option('-C, --chdir <path>', 'change the working directory');
615
+ *
616
+ * --chdir /tmp
617
+ * program.chdir
618
+ * // => "/tmp"
619
+ *
620
+ * // optional argument
621
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
622
+ *
623
+ * @param {string} flags
624
+ * @param {string} [description]
625
+ * @param {Function|*} [fn] - custom option processing function or default value
626
+ * @param {*} [defaultValue]
627
+ * @return {Command} `this` command for chaining
628
+ */
629
+
630
+ option(flags, description, fn, defaultValue) {
631
+ return this._optionEx({}, flags, description, fn, defaultValue);
632
+ };
633
+
634
+ /**
635
+ * Add a required option which must have a value after parsing. This usually means
636
+ * the option must be specified on the command line. (Otherwise the same as .option().)
637
+ *
638
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
639
+ *
640
+ * @param {string} flags
641
+ * @param {string} [description]
642
+ * @param {Function|*} [fn] - custom option processing function or default value
643
+ * @param {*} [defaultValue]
644
+ * @return {Command} `this` command for chaining
645
+ */
646
+
647
+ requiredOption(flags, description, fn, defaultValue) {
648
+ return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
649
+ };
650
+
651
+ /**
652
+ * Alter parsing of short flags with optional values.
653
+ *
654
+ * Examples:
655
+ *
656
+ * // for `.option('-f,--flag [value]'):
657
+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
658
+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
659
+ *
660
+ * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
661
+ */
662
+ combineFlagAndOptionalValue(combine = true) {
663
+ this._combineFlagAndOptionalValue = !!combine;
664
+ return this;
665
+ };
666
+
667
+ /**
668
+ * Allow unknown options on the command line.
669
+ *
670
+ * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
671
+ * for unknown options.
672
+ */
673
+ allowUnknownOption(allowUnknown = true) {
674
+ this._allowUnknownOption = !!allowUnknown;
675
+ return this;
676
+ };
677
+
678
+ /**
679
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
680
+ *
681
+ * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
682
+ * for excess arguments.
683
+ */
684
+ allowExcessArguments(allowExcess = true) {
685
+ this._allowExcessArguments = !!allowExcess;
686
+ return this;
687
+ };
688
+
689
+ /**
690
+ * Enable positional options. Positional means global options are specified before subcommands which lets
691
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
692
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
693
+ *
694
+ * @param {Boolean} [positional=true]
695
+ */
696
+ enablePositionalOptions(positional = true) {
697
+ this._enablePositionalOptions = !!positional;
698
+ return this;
699
+ };
700
+
701
+ /**
702
+ * Pass through options that come after command-arguments rather than treat them as command-options,
703
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
704
+ * positional options to have been enabled on the program (parent commands).
705
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
706
+ *
707
+ * @param {Boolean} [passThrough=true]
708
+ * for unknown options.
709
+ */
710
+ passThroughOptions(passThrough = true) {
711
+ this._passThroughOptions = !!passThrough;
712
+ if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
713
+ throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');
714
+ }
715
+ return this;
716
+ };
717
+
718
+ /**
719
+ * Whether to store option values as properties on command object,
720
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
721
+ *
722
+ * @param {boolean} [storeAsProperties=true]
723
+ * @return {Command} `this` command for chaining
724
+ */
725
+
726
+ storeOptionsAsProperties(storeAsProperties = true) {
727
+ this._storeOptionsAsProperties = !!storeAsProperties;
728
+ if (this.options.length) {
729
+ throw new Error('call .storeOptionsAsProperties() before adding options');
730
+ }
731
+ return this;
732
+ };
733
+
734
+ /**
735
+ * Retrieve option value.
736
+ *
737
+ * @param {string} key
738
+ * @return {Object} value
739
+ */
740
+
741
+ getOptionValue(key) {
742
+ if (this._storeOptionsAsProperties) {
743
+ return this[key];
744
+ }
745
+ return this._optionValues[key];
746
+ };
747
+
748
+ /**
749
+ * Store option value.
750
+ *
751
+ * @param {string} key
752
+ * @param {Object} value
753
+ * @return {Command} `this` command for chaining
754
+ */
755
+
756
+ setOptionValue(key, value) {
757
+ if (this._storeOptionsAsProperties) {
758
+ this[key] = value;
759
+ } else {
760
+ this._optionValues[key] = value;
761
+ }
762
+ return this;
763
+ };
764
+
765
+ /**
766
+ * Get user arguments implied or explicit arguments.
767
+ * Side-effects: set _scriptPath if args included application, and use that to set implicit command name.
768
+ *
769
+ * @api private
770
+ */
771
+
772
+ _prepareUserArgs(argv, parseOptions) {
773
+ if (argv !== undefined && !Array.isArray(argv)) {
774
+ throw new Error('first parameter to parse must be array or undefined');
775
+ }
776
+ parseOptions = parseOptions || {};
777
+
778
+ // Default to using process.argv
779
+ if (argv === undefined) {
780
+ argv = process.argv;
781
+ // @ts-ignore: unknown property
782
+ if (process.versions && process.versions.electron) {
783
+ parseOptions.from = 'electron';
784
+ }
785
+ }
786
+ this.rawArgs = argv.slice();
787
+
788
+ // make it a little easier for callers by supporting various argv conventions
789
+ let userArgs;
790
+ switch (parseOptions.from) {
791
+ case undefined:
792
+ case 'node':
793
+ this._scriptPath = argv[1];
794
+ userArgs = argv.slice(2);
795
+ break;
796
+ case 'electron':
797
+ // @ts-ignore: unknown property
798
+ if (process.defaultApp) {
799
+ this._scriptPath = argv[1];
800
+ userArgs = argv.slice(2);
801
+ } else {
802
+ userArgs = argv.slice(1);
803
+ }
804
+ break;
805
+ case 'user':
806
+ userArgs = argv.slice(0);
807
+ break;
808
+ default:
809
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
810
+ }
811
+ if (!this._scriptPath && require.main) {
812
+ this._scriptPath = require.main.filename;
813
+ }
814
+
815
+ // Guess name, used in usage in help.
816
+ this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));
817
+
818
+ return userArgs;
819
+ }
820
+
821
+ /**
822
+ * Parse `argv`, setting options and invoking commands when defined.
823
+ *
824
+ * The default expectation is that the arguments are from node and have the application as argv[0]
825
+ * and the script being run in argv[1], with user parameters after that.
826
+ *
827
+ * Examples:
828
+ *
829
+ * program.parse(process.argv);
830
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
831
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
832
+ *
833
+ * @param {string[]} [argv] - optional, defaults to process.argv
834
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
835
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
836
+ * @return {Command} `this` command for chaining
837
+ */
838
+
839
+ parse(argv, parseOptions) {
840
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
841
+ this._parseCommand([], userArgs);
842
+
843
+ return this;
844
+ };
845
+
846
+ /**
847
+ * Parse `argv`, setting options and invoking commands when defined.
848
+ *
849
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
850
+ *
851
+ * The default expectation is that the arguments are from node and have the application as argv[0]
852
+ * and the script being run in argv[1], with user parameters after that.
853
+ *
854
+ * Examples:
855
+ *
856
+ * await program.parseAsync(process.argv);
857
+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
858
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
859
+ *
860
+ * @param {string[]} [argv]
861
+ * @param {Object} [parseOptions]
862
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
863
+ * @return {Promise}
864
+ */
865
+
866
+ async parseAsync(argv, parseOptions) {
867
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
868
+ await this._parseCommand([], userArgs);
869
+
870
+ return this;
871
+ };
872
+
873
+ /**
874
+ * Execute a sub-command executable.
875
+ *
876
+ * @api private
877
+ */
878
+
879
+ _executeSubCommand(subcommand, args) {
880
+ args = args.slice();
881
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
882
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
883
+
884
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
885
+ this._checkForMissingMandatoryOptions();
886
+
887
+ // Want the entry script as the reference for command name and directory for searching for other files.
888
+ let scriptPath = this._scriptPath;
889
+ // Fallback in case not set, due to how Command created or called.
890
+ if (!scriptPath && require.main) {
891
+ scriptPath = require.main.filename;
892
+ }
893
+
894
+ let baseDir;
895
+ try {
896
+ const resolvedLink = fs.realpathSync(scriptPath);
897
+ baseDir = path.dirname(resolvedLink);
898
+ } catch (e) {
899
+ baseDir = '.'; // dummy, probably not going to find executable!
900
+ }
901
+
902
+ // name of the subcommand, like `pm-install`
903
+ let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;
904
+ if (subcommand._executableFile) {
905
+ bin = subcommand._executableFile;
906
+ }
907
+
908
+ const localBin = path.join(baseDir, bin);
909
+ if (fs.existsSync(localBin)) {
910
+ // prefer local `./<bin>` to bin in the $PATH
911
+ bin = localBin;
912
+ } else {
913
+ // Look for source files.
914
+ sourceExt.forEach((ext) => {
915
+ if (fs.existsSync(`${localBin}${ext}`)) {
916
+ bin = `${localBin}${ext}`;
917
+ }
918
+ });
919
+ }
920
+ launchWithNode = sourceExt.includes(path.extname(bin));
921
+
922
+ let proc;
923
+ if (process.platform !== 'win32') {
924
+ if (launchWithNode) {
925
+ args.unshift(bin);
926
+ // add executable arguments to spawn
927
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
928
+
929
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
930
+ } else {
931
+ proc = childProcess.spawn(bin, args, { stdio: 'inherit' });
932
+ }
933
+ } else {
934
+ args.unshift(bin);
935
+ // add executable arguments to spawn
936
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
937
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
938
+ }
939
+
940
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
941
+ signals.forEach((signal) => {
942
+ // @ts-ignore
943
+ process.on(signal, () => {
944
+ if (proc.killed === false && proc.exitCode === null) {
945
+ proc.kill(signal);
946
+ }
947
+ });
948
+ });
949
+
950
+ // By default terminate process when spawned process terminates.
951
+ // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
952
+ const exitCallback = this._exitCallback;
953
+ if (!exitCallback) {
954
+ proc.on('close', process.exit.bind(process));
955
+ } else {
956
+ proc.on('close', () => {
957
+ exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
958
+ });
959
+ }
960
+ proc.on('error', (err) => {
961
+ // @ts-ignore
962
+ if (err.code === 'ENOENT') {
963
+ const executableMissing = `'${bin}' does not exist
964
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
965
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name`;
966
+ throw new Error(executableMissing);
967
+ // @ts-ignore
968
+ } else if (err.code === 'EACCES') {
969
+ throw new Error(`'${bin}' not executable`);
970
+ }
971
+ if (!exitCallback) {
972
+ process.exit(1);
973
+ } else {
974
+ const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
975
+ wrappedError.nestedError = err;
976
+ exitCallback(wrappedError);
977
+ }
978
+ });
979
+
980
+ // Store the reference to the child process
981
+ this.runningCommand = proc;
982
+ };
983
+
984
+ /**
985
+ * @api private
986
+ */
987
+
988
+ _dispatchSubcommand(commandName, operands, unknown) {
989
+ const subCommand = this._findCommand(commandName);
990
+ if (!subCommand) this.help({ error: true });
991
+
992
+ if (subCommand._executableHandler) {
993
+ this._executeSubCommand(subCommand, operands.concat(unknown));
994
+ } else {
995
+ return subCommand._parseCommand(operands, unknown);
996
+ }
997
+ };
998
+
999
+ /**
1000
+ * Check this.args against expected this._args.
1001
+ *
1002
+ * @api private
1003
+ */
1004
+
1005
+ _checkNumberOfArguments() {
1006
+ // too few
1007
+ this._args.forEach((arg, i) => {
1008
+ if (arg.required && this.args[i] == null) {
1009
+ this.missingArgument(arg.name());
1010
+ }
1011
+ });
1012
+ // too many
1013
+ if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {
1014
+ return;
1015
+ }
1016
+ if (this.args.length > this._args.length) {
1017
+ this._excessArguments(this.args);
1018
+ }
1019
+ };
1020
+
1021
+ /**
1022
+ * Process this.args using this._args and save as this.processedArgs!
1023
+ *
1024
+ * @api private
1025
+ */
1026
+
1027
+ _processArguments() {
1028
+ const myParseArg = (argument, value, previous) => {
1029
+ // Extra processing for nice error message on parsing failure.
1030
+ let parsedValue = value;
1031
+ if (value !== null && argument.parseArg) {
1032
+ try {
1033
+ parsedValue = argument.parseArg(value, previous);
1034
+ } catch (err) {
1035
+ if (err.code === 'commander.invalidArgument') {
1036
+ const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;
1037
+ this._displayError(err.exitCode, err.code, message);
1038
+ }
1039
+ throw err;
1040
+ }
1041
+ }
1042
+ return parsedValue;
1043
+ };
1044
+
1045
+ this._checkNumberOfArguments();
1046
+
1047
+ const processedArgs = [];
1048
+ this._args.forEach((declaredArg, index) => {
1049
+ let value = declaredArg.defaultValue;
1050
+ if (declaredArg.variadic) {
1051
+ // Collect together remaining arguments for passing together as an array.
1052
+ if (index < this.args.length) {
1053
+ value = this.args.slice(index);
1054
+ if (declaredArg.parseArg) {
1055
+ value = value.reduce((processed, v) => {
1056
+ return myParseArg(declaredArg, v, processed);
1057
+ }, declaredArg.defaultValue);
1058
+ }
1059
+ } else if (value === undefined) {
1060
+ value = [];
1061
+ }
1062
+ } else if (index < this.args.length) {
1063
+ value = this.args[index];
1064
+ if (declaredArg.parseArg) {
1065
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1066
+ }
1067
+ }
1068
+ processedArgs[index] = value;
1069
+ });
1070
+ this.processedArgs = processedArgs;
1071
+ }
1072
+
1073
+ /**
1074
+ * Once we have a promise we chain, but call synchronously until then.
1075
+ *
1076
+ * @param {Promise|undefined} promise
1077
+ * @param {Function} fn
1078
+ * @return {Promise|undefined}
1079
+ */
1080
+
1081
+ _chainOrCall(promise, fn) {
1082
+ // thenable
1083
+ if (promise && promise.then && typeof promise.then === 'function') {
1084
+ // already have a promise, chain callback
1085
+ return promise.then(() => fn());
1086
+ }
1087
+ // callback might return a promise
1088
+ return fn();
1089
+ }
1090
+
1091
+ /**
1092
+ *
1093
+ * @param {Promise|undefined} promise
1094
+ * @param {string} event
1095
+ * @return {Promise|undefined}
1096
+ * @api private
1097
+ */
1098
+
1099
+ _chainOrCallHooks(promise, event) {
1100
+ let result = promise;
1101
+ const hooks = [];
1102
+ getCommandAndParents(this)
1103
+ .reverse()
1104
+ .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)
1105
+ .forEach(hookedCommand => {
1106
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1107
+ hooks.push({ hookedCommand, callback });
1108
+ });
1109
+ });
1110
+ if (event === 'postAction') {
1111
+ hooks.reverse();
1112
+ }
1113
+
1114
+ hooks.forEach((hookDetail) => {
1115
+ result = this._chainOrCall(result, () => {
1116
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1117
+ });
1118
+ });
1119
+ return result;
1120
+ }
1121
+
1122
+ /**
1123
+ * Process arguments in context of this command.
1124
+ * Returns action result, in case it is a promise.
1125
+ *
1126
+ * @api private
1127
+ */
1128
+
1129
+ _parseCommand(operands, unknown) {
1130
+ const parsed = this.parseOptions(unknown);
1131
+ operands = operands.concat(parsed.operands);
1132
+ unknown = parsed.unknown;
1133
+ this.args = operands.concat(unknown);
1134
+
1135
+ if (operands && this._findCommand(operands[0])) {
1136
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1137
+ }
1138
+ if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
1139
+ if (operands.length === 1) {
1140
+ this.help();
1141
+ }
1142
+ return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
1143
+ }
1144
+ if (this._defaultCommandName) {
1145
+ outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
1146
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1147
+ }
1148
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1149
+ // probably missing subcommand and no handler, user needs help (and exit)
1150
+ this.help({ error: true });
1151
+ }
1152
+
1153
+ outputHelpIfRequested(this, parsed.unknown);
1154
+ this._checkForMissingMandatoryOptions();
1155
+
1156
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
1157
+ const checkForUnknownOptions = () => {
1158
+ if (parsed.unknown.length > 0) {
1159
+ this.unknownOption(parsed.unknown[0]);
1160
+ }
1161
+ };
1162
+
1163
+ const commandEvent = `command:${this.name()}`;
1164
+ if (this._actionHandler) {
1165
+ checkForUnknownOptions();
1166
+ this._processArguments();
1167
+
1168
+ let actionResult;
1169
+ actionResult = this._chainOrCallHooks(actionResult, 'preAction');
1170
+ actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));
1171
+ if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy
1172
+ actionResult = this._chainOrCallHooks(actionResult, 'postAction');
1173
+ return actionResult;
1174
+ }
1175
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1176
+ checkForUnknownOptions();
1177
+ this._processArguments();
1178
+ this.parent.emit(commandEvent, operands, unknown); // legacy
1179
+ } else if (operands.length) {
1180
+ if (this._findCommand('*')) { // legacy default command
1181
+ return this._dispatchSubcommand('*', operands, unknown);
1182
+ }
1183
+ if (this.listenerCount('command:*')) {
1184
+ // skip option check, emit event for possible misspelling suggestion
1185
+ this.emit('command:*', operands, unknown);
1186
+ } else if (this.commands.length) {
1187
+ this.unknownCommand();
1188
+ } else {
1189
+ checkForUnknownOptions();
1190
+ this._processArguments();
1191
+ }
1192
+ } else if (this.commands.length) {
1193
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
1194
+ this.help({ error: true });
1195
+ } else {
1196
+ checkForUnknownOptions();
1197
+ this._processArguments();
1198
+ // fall through for caller to handle after calling .parse()
1199
+ }
1200
+ };
1201
+
1202
+ /**
1203
+ * Find matching command.
1204
+ *
1205
+ * @api private
1206
+ */
1207
+ _findCommand(name) {
1208
+ if (!name) return undefined;
1209
+ return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
1210
+ };
1211
+
1212
+ /**
1213
+ * Return an option matching `arg` if any.
1214
+ *
1215
+ * @param {string} arg
1216
+ * @return {Option}
1217
+ * @api private
1218
+ */
1219
+
1220
+ _findOption(arg) {
1221
+ return this.options.find(option => option.is(arg));
1222
+ };
1223
+
1224
+ /**
1225
+ * Display an error message if a mandatory option does not have a value.
1226
+ * Lazy calling after checking for help flags from leaf subcommand.
1227
+ *
1228
+ * @api private
1229
+ */
1230
+
1231
+ _checkForMissingMandatoryOptions() {
1232
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
1233
+ for (let cmd = this; cmd; cmd = cmd.parent) {
1234
+ cmd.options.forEach((anOption) => {
1235
+ if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {
1236
+ cmd.missingMandatoryOptionValue(anOption);
1237
+ }
1238
+ });
1239
+ }
1240
+ };
1241
+
1242
+ /**
1243
+ * Parse options from `argv` removing known options,
1244
+ * and return argv split into operands and unknown arguments.
1245
+ *
1246
+ * Examples:
1247
+ *
1248
+ * argv => operands, unknown
1249
+ * --known kkk op => [op], []
1250
+ * op --known kkk => [op], []
1251
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
1252
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
1253
+ *
1254
+ * @param {String[]} argv
1255
+ * @return {{operands: String[], unknown: String[]}}
1256
+ */
1257
+
1258
+ parseOptions(argv) {
1259
+ const operands = []; // operands, not options or values
1260
+ const unknown = []; // first unknown option and remaining unknown args
1261
+ let dest = operands;
1262
+ const args = argv.slice();
1263
+
1264
+ function maybeOption(arg) {
1265
+ return arg.length > 1 && arg[0] === '-';
1266
+ }
1267
+
1268
+ // parse options
1269
+ let activeVariadicOption = null;
1270
+ while (args.length) {
1271
+ const arg = args.shift();
1272
+
1273
+ // literal
1274
+ if (arg === '--') {
1275
+ if (dest === unknown) dest.push(arg);
1276
+ dest.push(...args);
1277
+ break;
1278
+ }
1279
+
1280
+ if (activeVariadicOption && !maybeOption(arg)) {
1281
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1282
+ continue;
1283
+ }
1284
+ activeVariadicOption = null;
1285
+
1286
+ if (maybeOption(arg)) {
1287
+ const option = this._findOption(arg);
1288
+ // recognised option, call listener to assign value with possible custom processing
1289
+ if (option) {
1290
+ if (option.required) {
1291
+ const value = args.shift();
1292
+ if (value === undefined) this.optionMissingArgument(option);
1293
+ this.emit(`option:${option.name()}`, value);
1294
+ } else if (option.optional) {
1295
+ let value = null;
1296
+ // historical behaviour is optional value is following arg unless an option
1297
+ if (args.length > 0 && !maybeOption(args[0])) {
1298
+ value = args.shift();
1299
+ }
1300
+ this.emit(`option:${option.name()}`, value);
1301
+ } else { // boolean flag
1302
+ this.emit(`option:${option.name()}`);
1303
+ }
1304
+ activeVariadicOption = option.variadic ? option : null;
1305
+ continue;
1306
+ }
1307
+ }
1308
+
1309
+ // Look for combo options following single dash, eat first one if known.
1310
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
1311
+ const option = this._findOption(`-${arg[1]}`);
1312
+ if (option) {
1313
+ if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
1314
+ // option with value following in same argument
1315
+ this.emit(`option:${option.name()}`, arg.slice(2));
1316
+ } else {
1317
+ // boolean option, emit and put back remainder of arg for further processing
1318
+ this.emit(`option:${option.name()}`);
1319
+ args.unshift(`-${arg.slice(2)}`);
1320
+ }
1321
+ continue;
1322
+ }
1323
+ }
1324
+
1325
+ // Look for known long flag with value, like --foo=bar
1326
+ if (/^--[^=]+=/.test(arg)) {
1327
+ const index = arg.indexOf('=');
1328
+ const option = this._findOption(arg.slice(0, index));
1329
+ if (option && (option.required || option.optional)) {
1330
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1331
+ continue;
1332
+ }
1333
+ }
1334
+
1335
+ // Not a recognised option by this command.
1336
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
1337
+
1338
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
1339
+ if (maybeOption(arg)) {
1340
+ dest = unknown;
1341
+ }
1342
+
1343
+ // If using positionalOptions, stop processing our options at subcommand.
1344
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1345
+ if (this._findCommand(arg)) {
1346
+ operands.push(arg);
1347
+ if (args.length > 0) unknown.push(...args);
1348
+ break;
1349
+ } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
1350
+ operands.push(arg);
1351
+ if (args.length > 0) operands.push(...args);
1352
+ break;
1353
+ } else if (this._defaultCommandName) {
1354
+ unknown.push(arg);
1355
+ if (args.length > 0) unknown.push(...args);
1356
+ break;
1357
+ }
1358
+ }
1359
+
1360
+ // If using passThroughOptions, stop processing options at first command-argument.
1361
+ if (this._passThroughOptions) {
1362
+ dest.push(arg);
1363
+ if (args.length > 0) dest.push(...args);
1364
+ break;
1365
+ }
1366
+
1367
+ // add arg
1368
+ dest.push(arg);
1369
+ }
1370
+
1371
+ return { operands, unknown };
1372
+ };
1373
+
1374
+ /**
1375
+ * Return an object containing options as key-value pairs
1376
+ *
1377
+ * @return {Object}
1378
+ */
1379
+ opts() {
1380
+ if (this._storeOptionsAsProperties) {
1381
+ // Preserve original behaviour so backwards compatible when still using properties
1382
+ const result = {};
1383
+ const len = this.options.length;
1384
+
1385
+ for (let i = 0; i < len; i++) {
1386
+ const key = this.options[i].attributeName();
1387
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1388
+ }
1389
+ return result;
1390
+ }
1391
+
1392
+ return this._optionValues;
1393
+ };
1394
+
1395
+ /**
1396
+ * Internal bottleneck for handling of parsing errors.
1397
+ *
1398
+ * @api private
1399
+ */
1400
+ _displayError(exitCode, code, message) {
1401
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
1402
+ if (typeof this._showHelpAfterError === 'string') {
1403
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
1404
+ } else if (this._showHelpAfterError) {
1405
+ this._outputConfiguration.writeErr('\n');
1406
+ this.outputHelp({ error: true });
1407
+ }
1408
+ this._exit(exitCode, code, message);
1409
+ }
1410
+
1411
+ /**
1412
+ * Argument `name` is missing.
1413
+ *
1414
+ * @param {string} name
1415
+ * @api private
1416
+ */
1417
+
1418
+ missingArgument(name) {
1419
+ const message = `error: missing required argument '${name}'`;
1420
+ this._displayError(1, 'commander.missingArgument', message);
1421
+ };
1422
+
1423
+ /**
1424
+ * `Option` is missing an argument.
1425
+ *
1426
+ * @param {Option} option
1427
+ * @api private
1428
+ */
1429
+
1430
+ optionMissingArgument(option) {
1431
+ const message = `error: option '${option.flags}' argument missing`;
1432
+ this._displayError(1, 'commander.optionMissingArgument', message);
1433
+ };
1434
+
1435
+ /**
1436
+ * `Option` does not have a value, and is a mandatory option.
1437
+ *
1438
+ * @param {Option} option
1439
+ * @api private
1440
+ */
1441
+
1442
+ missingMandatoryOptionValue(option) {
1443
+ const message = `error: required option '${option.flags}' not specified`;
1444
+ this._displayError(1, 'commander.missingMandatoryOptionValue', message);
1445
+ };
1446
+
1447
+ /**
1448
+ * Unknown option `flag`.
1449
+ *
1450
+ * @param {string} flag
1451
+ * @api private
1452
+ */
1453
+
1454
+ unknownOption(flag) {
1455
+ if (this._allowUnknownOption) return;
1456
+ const message = `error: unknown option '${flag}'`;
1457
+ this._displayError(1, 'commander.unknownOption', message);
1458
+ };
1459
+
1460
+ /**
1461
+ * Excess arguments, more than expected.
1462
+ *
1463
+ * @param {string[]} receivedArgs
1464
+ * @api private
1465
+ */
1466
+
1467
+ _excessArguments(receivedArgs) {
1468
+ if (this._allowExcessArguments) return;
1469
+
1470
+ const expected = this._args.length;
1471
+ const s = (expected === 1) ? '' : 's';
1472
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
1473
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1474
+ this._displayError(1, 'commander.excessArguments', message);
1475
+ };
1476
+
1477
+ /**
1478
+ * Unknown command.
1479
+ *
1480
+ * @api private
1481
+ */
1482
+
1483
+ unknownCommand() {
1484
+ const message = `error: unknown command '${this.args[0]}'`;
1485
+ this._displayError(1, 'commander.unknownCommand', message);
1486
+ };
1487
+
1488
+ /**
1489
+ * Set the program version to `str`.
1490
+ *
1491
+ * This method auto-registers the "-V, --version" flag
1492
+ * which will print the version number when passed.
1493
+ *
1494
+ * You can optionally supply the flags and description to override the defaults.
1495
+ *
1496
+ * @param {string} str
1497
+ * @param {string} [flags]
1498
+ * @param {string} [description]
1499
+ * @return {this | string} `this` command for chaining, or version string if no arguments
1500
+ */
1501
+
1502
+ version(str, flags, description) {
1503
+ if (str === undefined) return this._version;
1504
+ this._version = str;
1505
+ flags = flags || '-V, --version';
1506
+ description = description || 'output the version number';
1507
+ const versionOption = this.createOption(flags, description);
1508
+ this._versionOptionName = versionOption.attributeName();
1509
+ this.options.push(versionOption);
1510
+ this.on('option:' + versionOption.name(), () => {
1511
+ this._outputConfiguration.writeOut(`${str}\n`);
1512
+ this._exit(0, 'commander.version', str);
1513
+ });
1514
+ return this;
1515
+ };
1516
+
1517
+ /**
1518
+ * Set the description to `str`.
1519
+ *
1520
+ * @param {string} [str]
1521
+ * @param {Object} [argsDescription]
1522
+ * @return {string|Command}
1523
+ */
1524
+ description(str, argsDescription) {
1525
+ if (str === undefined && argsDescription === undefined) return this._description;
1526
+ this._description = str;
1527
+ if (argsDescription) {
1528
+ this._argsDescription = argsDescription;
1529
+ }
1530
+ return this;
1531
+ };
1532
+
1533
+ /**
1534
+ * Set an alias for the command.
1535
+ *
1536
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
1537
+ *
1538
+ * @param {string} [alias]
1539
+ * @return {string|Command}
1540
+ */
1541
+
1542
+ alias(alias) {
1543
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
1544
+
1545
+ /** @type {Command} */
1546
+ let command = this;
1547
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1548
+ // assume adding alias for last added executable subcommand, rather than this
1549
+ command = this.commands[this.commands.length - 1];
1550
+ }
1551
+
1552
+ if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
1553
+
1554
+ command._aliases.push(alias);
1555
+ return this;
1556
+ };
1557
+
1558
+ /**
1559
+ * Set aliases for the command.
1560
+ *
1561
+ * Only the first alias is shown in the auto-generated help.
1562
+ *
1563
+ * @param {string[]} [aliases]
1564
+ * @return {string[]|Command}
1565
+ */
1566
+
1567
+ aliases(aliases) {
1568
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
1569
+ if (aliases === undefined) return this._aliases;
1570
+
1571
+ aliases.forEach((alias) => this.alias(alias));
1572
+ return this;
1573
+ };
1574
+
1575
+ /**
1576
+ * Set / get the command usage `str`.
1577
+ *
1578
+ * @param {string} [str]
1579
+ * @return {String|Command}
1580
+ */
1581
+
1582
+ usage(str) {
1583
+ if (str === undefined) {
1584
+ if (this._usage) return this._usage;
1585
+
1586
+ const args = this._args.map((arg) => {
1587
+ return humanReadableArgName(arg);
1588
+ });
1589
+ return [].concat(
1590
+ (this.options.length || this._hasHelpOption ? '[options]' : []),
1591
+ (this.commands.length ? '[command]' : []),
1592
+ (this._args.length ? args : [])
1593
+ ).join(' ');
1594
+ }
1595
+
1596
+ this._usage = str;
1597
+ return this;
1598
+ };
1599
+
1600
+ /**
1601
+ * Get or set the name of the command
1602
+ *
1603
+ * @param {string} [str]
1604
+ * @return {string|Command}
1605
+ */
1606
+
1607
+ name(str) {
1608
+ if (str === undefined) return this._name;
1609
+ this._name = str;
1610
+ return this;
1611
+ };
1612
+
1613
+ /**
1614
+ * Return program help documentation.
1615
+ *
1616
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
1617
+ * @return {string}
1618
+ */
1619
+
1620
+ helpInformation(contextOptions) {
1621
+ const helper = this.createHelp();
1622
+ if (helper.helpWidth === undefined) {
1623
+ helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
1624
+ }
1625
+ return helper.formatHelp(this, helper);
1626
+ };
1627
+
1628
+ /**
1629
+ * @api private
1630
+ */
1631
+
1632
+ _getHelpContext(contextOptions) {
1633
+ contextOptions = contextOptions || {};
1634
+ const context = { error: !!contextOptions.error };
1635
+ let write;
1636
+ if (context.error) {
1637
+ write = (arg) => this._outputConfiguration.writeErr(arg);
1638
+ } else {
1639
+ write = (arg) => this._outputConfiguration.writeOut(arg);
1640
+ }
1641
+ context.write = contextOptions.write || write;
1642
+ context.command = this;
1643
+ return context;
1644
+ }
1645
+
1646
+ /**
1647
+ * Output help information for this command.
1648
+ *
1649
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
1650
+ *
1651
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
1652
+ */
1653
+
1654
+ outputHelp(contextOptions) {
1655
+ let deprecatedCallback;
1656
+ if (typeof contextOptions === 'function') {
1657
+ deprecatedCallback = contextOptions;
1658
+ contextOptions = undefined;
1659
+ }
1660
+ const context = this._getHelpContext(contextOptions);
1661
+
1662
+ const groupListeners = [];
1663
+ let command = this;
1664
+ while (command) {
1665
+ groupListeners.push(command); // ordered from current command to root
1666
+ command = command.parent;
1667
+ }
1668
+
1669
+ groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));
1670
+ this.emit('beforeHelp', context);
1671
+
1672
+ let helpInformation = this.helpInformation(context);
1673
+ if (deprecatedCallback) {
1674
+ helpInformation = deprecatedCallback(helpInformation);
1675
+ if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
1676
+ throw new Error('outputHelp callback must return a string or a Buffer');
1677
+ }
1678
+ }
1679
+ context.write(helpInformation);
1680
+
1681
+ this.emit(this._helpLongFlag); // deprecated
1682
+ this.emit('afterHelp', context);
1683
+ groupListeners.forEach(command => command.emit('afterAllHelp', context));
1684
+ };
1685
+
1686
+ /**
1687
+ * You can pass in flags and a description to override the help
1688
+ * flags and help description for your command. Pass in false to
1689
+ * disable the built-in help option.
1690
+ *
1691
+ * @param {string | boolean} [flags]
1692
+ * @param {string} [description]
1693
+ * @return {Command} `this` command for chaining
1694
+ */
1695
+
1696
+ helpOption(flags, description) {
1697
+ if (typeof flags === 'boolean') {
1698
+ this._hasHelpOption = flags;
1699
+ return this;
1700
+ }
1701
+ this._helpFlags = flags || this._helpFlags;
1702
+ this._helpDescription = description || this._helpDescription;
1703
+
1704
+ const helpFlags = splitOptionFlags(this._helpFlags);
1705
+ this._helpShortFlag = helpFlags.shortFlag;
1706
+ this._helpLongFlag = helpFlags.longFlag;
1707
+
1708
+ return this;
1709
+ };
1710
+
1711
+ /**
1712
+ * Output help information and exit.
1713
+ *
1714
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
1715
+ *
1716
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
1717
+ */
1718
+
1719
+ help(contextOptions) {
1720
+ this.outputHelp(contextOptions);
1721
+ let exitCode = process.exitCode || 0;
1722
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
1723
+ exitCode = 1;
1724
+ }
1725
+ // message: do not have all displayed text available so only passing placeholder.
1726
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
1727
+ };
1728
+
1729
+ /**
1730
+ * Add additional text to be displayed with the built-in help.
1731
+ *
1732
+ * Position is 'before' or 'after' to affect just this command,
1733
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
1734
+ *
1735
+ * @param {string} position - before or after built-in help
1736
+ * @param {string | Function} text - string to add, or a function returning a string
1737
+ * @return {Command} `this` command for chaining
1738
+ */
1739
+ addHelpText(position, text) {
1740
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
1741
+ if (!allowedValues.includes(position)) {
1742
+ throw new Error(`Unexpected value for position to addHelpText.
1743
+ Expecting one of '${allowedValues.join("', '")}'`);
1744
+ }
1745
+ const helpEvent = `${position}Help`;
1746
+ this.on(helpEvent, (context) => {
1747
+ let helpStr;
1748
+ if (typeof text === 'function') {
1749
+ helpStr = text({ error: context.error, command: context.command });
1750
+ } else {
1751
+ helpStr = text;
1752
+ }
1753
+ // Ignore falsy value when nothing to output.
1754
+ if (helpStr) {
1755
+ context.write(`${helpStr}\n`);
1756
+ }
1757
+ });
1758
+ return this;
1759
+ }
1760
+ };
1761
+
1762
+ /**
1763
+ * Output help information if help flags specified
1764
+ *
1765
+ * @param {Command} cmd - command to output help for
1766
+ * @param {Array} args - array of options to search for help flags
1767
+ * @api private
1768
+ */
1769
+
1770
+ function outputHelpIfRequested(cmd, args) {
1771
+ const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
1772
+ if (helpOption) {
1773
+ cmd.outputHelp();
1774
+ // (Do not have all displayed text available so only passing placeholder.)
1775
+ cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
1776
+ }
1777
+ }
1778
+
1779
+ /**
1780
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
1781
+ *
1782
+ * @param {string[]} args - array of arguments from node.execArgv
1783
+ * @returns {string[]}
1784
+ * @api private
1785
+ */
1786
+
1787
+ function incrementNodeInspectorPort(args) {
1788
+ // Testing for these options:
1789
+ // --inspect[=[host:]port]
1790
+ // --inspect-brk[=[host:]port]
1791
+ // --inspect-port=[host:]port
1792
+ return args.map((arg) => {
1793
+ if (!arg.startsWith('--inspect')) {
1794
+ return arg;
1795
+ }
1796
+ let debugOption;
1797
+ let debugHost = '127.0.0.1';
1798
+ let debugPort = '9229';
1799
+ let match;
1800
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
1801
+ // e.g. --inspect
1802
+ debugOption = match[1];
1803
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
1804
+ debugOption = match[1];
1805
+ if (/^\d+$/.test(match[3])) {
1806
+ // e.g. --inspect=1234
1807
+ debugPort = match[3];
1808
+ } else {
1809
+ // e.g. --inspect=localhost
1810
+ debugHost = match[3];
1811
+ }
1812
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
1813
+ // e.g. --inspect=localhost:1234
1814
+ debugOption = match[1];
1815
+ debugHost = match[3];
1816
+ debugPort = match[4];
1817
+ }
1818
+
1819
+ if (debugOption && debugPort !== '0') {
1820
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
1821
+ }
1822
+ return arg;
1823
+ });
1824
+ }
1825
+
1826
+ /**
1827
+ * @param {Command} startCommand
1828
+ * @returns {Command[]}
1829
+ * @api private
1830
+ */
1831
+
1832
+ function getCommandAndParents(startCommand) {
1833
+ const result = [];
1834
+ for (let command = startCommand; command; command = command.parent) {
1835
+ result.push(command);
1836
+ }
1837
+ return result;
1838
+ }
1839
+
1840
+ exports.Command = Command;