1 | const EventEmitter = require('node:events').EventEmitter;
|
2 | const childProcess = require('node:child_process');
|
3 | const path = require('node:path');
|
4 | const fs = require('node:fs');
|
5 | const process = require('node:process');
|
6 |
|
7 | const { Argument, humanReadableArgName } = require('./argument.js');
|
8 | const { CommanderError } = require('./error.js');
|
9 | const { Help } = require('./help.js');
|
10 | const { Option, DualOptions } = require('./option.js');
|
11 | const { suggestSimilar } = require('./suggestSimilar');
|
12 |
|
13 | class Command extends EventEmitter {
|
14 | |
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | constructor(name) {
|
21 | super();
|
22 |
|
23 | this.commands = [];
|
24 |
|
25 | this.options = [];
|
26 | this.parent = null;
|
27 | this._allowUnknownOption = false;
|
28 | this._allowExcessArguments = true;
|
29 |
|
30 | this.registeredArguments = [];
|
31 | this._args = this.registeredArguments;
|
32 |
|
33 | this.args = [];
|
34 | this.rawArgs = [];
|
35 | this.processedArgs = [];
|
36 | this._scriptPath = null;
|
37 | this._name = name || '';
|
38 | this._optionValues = {};
|
39 | this._optionValueSources = {};
|
40 | this._storeOptionsAsProperties = false;
|
41 | this._actionHandler = null;
|
42 | this._executableHandler = false;
|
43 | this._executableFile = null;
|
44 | this._executableDir = null;
|
45 | this._defaultCommandName = null;
|
46 | this._exitCallback = null;
|
47 | this._aliases = [];
|
48 | this._combineFlagAndOptionalValue = true;
|
49 | this._description = '';
|
50 | this._summary = '';
|
51 | this._argsDescription = undefined;
|
52 | this._enablePositionalOptions = false;
|
53 | this._passThroughOptions = false;
|
54 | this._lifeCycleHooks = {};
|
55 |
|
56 | this._showHelpAfterError = false;
|
57 | this._showSuggestionAfterError = true;
|
58 |
|
59 |
|
60 | this._outputConfiguration = {
|
61 | writeOut: (str) => process.stdout.write(str),
|
62 | writeErr: (str) => process.stderr.write(str),
|
63 | getOutHelpWidth: () =>
|
64 | process.stdout.isTTY ? process.stdout.columns : undefined,
|
65 | getErrHelpWidth: () =>
|
66 | process.stderr.isTTY ? process.stderr.columns : undefined,
|
67 | outputError: (str, write) => write(str),
|
68 | };
|
69 |
|
70 | this._hidden = false;
|
71 |
|
72 | this._helpOption = undefined;
|
73 | this._addImplicitHelpCommand = undefined;
|
74 |
|
75 | this._helpCommand = undefined;
|
76 | this._helpConfiguration = {};
|
77 | }
|
78 |
|
79 | |
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | copyInheritedSettings(sourceCommand) {
|
88 | this._outputConfiguration = sourceCommand._outputConfiguration;
|
89 | this._helpOption = sourceCommand._helpOption;
|
90 | this._helpCommand = sourceCommand._helpCommand;
|
91 | this._helpConfiguration = sourceCommand._helpConfiguration;
|
92 | this._exitCallback = sourceCommand._exitCallback;
|
93 | this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
94 | this._combineFlagAndOptionalValue =
|
95 | sourceCommand._combineFlagAndOptionalValue;
|
96 | this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
97 | this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
98 | this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
99 | this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
100 |
|
101 | return this;
|
102 | }
|
103 |
|
104 | |
105 |
|
106 |
|
107 |
|
108 |
|
109 | _getCommandAndAncestors() {
|
110 | const result = [];
|
111 |
|
112 | for (let command = this; command; command = command.parent) {
|
113 | result.push(command);
|
114 | }
|
115 | return result;
|
116 | }
|
117 |
|
118 | |
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 |
|
132 |
|
133 |
|
134 |
|
135 |
|
136 |
|
137 |
|
138 |
|
139 |
|
140 |
|
141 |
|
142 |
|
143 | command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
144 | let desc = actionOptsOrExecDesc;
|
145 | let opts = execOpts;
|
146 | if (typeof desc === 'object' && desc !== null) {
|
147 | opts = desc;
|
148 | desc = null;
|
149 | }
|
150 | opts = opts || {};
|
151 | const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
152 |
|
153 | const cmd = this.createCommand(name);
|
154 | if (desc) {
|
155 | cmd.description(desc);
|
156 | cmd._executableHandler = true;
|
157 | }
|
158 | if (opts.isDefault) this._defaultCommandName = cmd._name;
|
159 | cmd._hidden = !!(opts.noHelp || opts.hidden);
|
160 | cmd._executableFile = opts.executableFile || null;
|
161 | if (args) cmd.arguments(args);
|
162 | this._registerCommand(cmd);
|
163 | cmd.parent = this;
|
164 | cmd.copyInheritedSettings(this);
|
165 |
|
166 | if (desc) return this;
|
167 | return cmd;
|
168 | }
|
169 |
|
170 | |
171 |
|
172 |
|
173 |
|
174 |
|
175 |
|
176 |
|
177 |
|
178 |
|
179 |
|
180 | createCommand(name) {
|
181 | return new Command(name);
|
182 | }
|
183 |
|
184 | |
185 |
|
186 |
|
187 |
|
188 |
|
189 |
|
190 |
|
191 | createHelp() {
|
192 | return Object.assign(new Help(), this.configureHelp());
|
193 | }
|
194 |
|
195 | |
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 |
|
203 | configureHelp(configuration) {
|
204 | if (configuration === undefined) return this._helpConfiguration;
|
205 |
|
206 | this._helpConfiguration = configuration;
|
207 | return this;
|
208 | }
|
209 |
|
210 | |
211 |
|
212 |
|
213 |
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 |
|
228 |
|
229 | configureOutput(configuration) {
|
230 | if (configuration === undefined) return this._outputConfiguration;
|
231 |
|
232 | Object.assign(this._outputConfiguration, configuration);
|
233 | return this;
|
234 | }
|
235 |
|
236 | |
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 | showHelpAfterError(displayHelp = true) {
|
243 | if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
|
244 | this._showHelpAfterError = displayHelp;
|
245 | return this;
|
246 | }
|
247 |
|
248 | |
249 |
|
250 |
|
251 |
|
252 |
|
253 |
|
254 | showSuggestionAfterError(displaySuggestion = true) {
|
255 | this._showSuggestionAfterError = !!displaySuggestion;
|
256 | return this;
|
257 | }
|
258 |
|
259 | |
260 |
|
261 |
|
262 |
|
263 |
|
264 |
|
265 |
|
266 |
|
267 |
|
268 |
|
269 | addCommand(cmd, opts) {
|
270 | if (!cmd._name) {
|
271 | throw new Error(`Command passed to .addCommand() must have a name
|
272 | - specify the name in Command constructor or using .name()`);
|
273 | }
|
274 |
|
275 | opts = opts || {};
|
276 | if (opts.isDefault) this._defaultCommandName = cmd._name;
|
277 | if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
278 |
|
279 | this._registerCommand(cmd);
|
280 | cmd.parent = this;
|
281 | cmd._checkForBrokenPassThrough();
|
282 |
|
283 | return this;
|
284 | }
|
285 |
|
286 | |
287 |
|
288 |
|
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 | createArgument(name, description) {
|
298 | return new Argument(name, description);
|
299 | }
|
300 |
|
301 | |
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 |
|
315 |
|
316 |
|
317 | argument(name, description, fn, defaultValue) {
|
318 | const argument = this.createArgument(name, description);
|
319 | if (typeof fn === 'function') {
|
320 | argument.default(defaultValue).argParser(fn);
|
321 | } else {
|
322 | argument.default(fn);
|
323 | }
|
324 | this.addArgument(argument);
|
325 | return this;
|
326 | }
|
327 |
|
328 | |
329 |
|
330 |
|
331 |
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 |
|
340 | arguments(names) {
|
341 | names
|
342 | .trim()
|
343 | .split(/ +/)
|
344 | .forEach((detail) => {
|
345 | this.argument(detail);
|
346 | });
|
347 | return this;
|
348 | }
|
349 |
|
350 | |
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 | addArgument(argument) {
|
357 | const previousArgument = this.registeredArguments.slice(-1)[0];
|
358 | if (previousArgument && previousArgument.variadic) {
|
359 | throw new Error(
|
360 | `only the last argument can be variadic '${previousArgument.name()}'`,
|
361 | );
|
362 | }
|
363 | if (
|
364 | argument.required &&
|
365 | argument.defaultValue !== undefined &&
|
366 | argument.parseArg === undefined
|
367 | ) {
|
368 | throw new Error(
|
369 | `a default value for a required argument is never used: '${argument.name()}'`,
|
370 | );
|
371 | }
|
372 | this.registeredArguments.push(argument);
|
373 | return this;
|
374 | }
|
375 |
|
376 | |
377 |
|
378 |
|
379 |
|
380 |
|
381 |
|
382 |
|
383 |
|
384 |
|
385 |
|
386 |
|
387 |
|
388 |
|
389 |
|
390 | helpCommand(enableOrNameAndArgs, description) {
|
391 | if (typeof enableOrNameAndArgs === 'boolean') {
|
392 | this._addImplicitHelpCommand = enableOrNameAndArgs;
|
393 | return this;
|
394 | }
|
395 |
|
396 | enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
|
397 | const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
|
398 | const helpDescription = description ?? 'display help for command';
|
399 |
|
400 | const helpCommand = this.createCommand(helpName);
|
401 | helpCommand.helpOption(false);
|
402 | if (helpArgs) helpCommand.arguments(helpArgs);
|
403 | if (helpDescription) helpCommand.description(helpDescription);
|
404 |
|
405 | this._addImplicitHelpCommand = true;
|
406 | this._helpCommand = helpCommand;
|
407 |
|
408 | return this;
|
409 | }
|
410 |
|
411 | |
412 |
|
413 |
|
414 |
|
415 |
|
416 |
|
417 |
|
418 | addHelpCommand(helpCommand, deprecatedDescription) {
|
419 |
|
420 |
|
421 | if (typeof helpCommand !== 'object') {
|
422 | this.helpCommand(helpCommand, deprecatedDescription);
|
423 | return this;
|
424 | }
|
425 |
|
426 | this._addImplicitHelpCommand = true;
|
427 | this._helpCommand = helpCommand;
|
428 | return this;
|
429 | }
|
430 |
|
431 | |
432 |
|
433 |
|
434 |
|
435 |
|
436 |
|
437 | _getHelpCommand() {
|
438 | const hasImplicitHelpCommand =
|
439 | this._addImplicitHelpCommand ??
|
440 | (this.commands.length &&
|
441 | !this._actionHandler &&
|
442 | !this._findCommand('help'));
|
443 |
|
444 | if (hasImplicitHelpCommand) {
|
445 | if (this._helpCommand === undefined) {
|
446 | this.helpCommand(undefined, undefined);
|
447 | }
|
448 | return this._helpCommand;
|
449 | }
|
450 | return null;
|
451 | }
|
452 |
|
453 | |
454 |
|
455 |
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 | hook(event, listener) {
|
462 | const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
|
463 | if (!allowedValues.includes(event)) {
|
464 | throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
465 | Expecting one of '${allowedValues.join("', '")}'`);
|
466 | }
|
467 | if (this._lifeCycleHooks[event]) {
|
468 | this._lifeCycleHooks[event].push(listener);
|
469 | } else {
|
470 | this._lifeCycleHooks[event] = [listener];
|
471 | }
|
472 | return this;
|
473 | }
|
474 |
|
475 | |
476 |
|
477 |
|
478 |
|
479 |
|
480 |
|
481 |
|
482 | exitOverride(fn) {
|
483 | if (fn) {
|
484 | this._exitCallback = fn;
|
485 | } else {
|
486 | this._exitCallback = (err) => {
|
487 | if (err.code !== 'commander.executeSubCommandAsync') {
|
488 | throw err;
|
489 | } else {
|
490 |
|
491 | }
|
492 | };
|
493 | }
|
494 | return this;
|
495 | }
|
496 |
|
497 | |
498 |
|
499 |
|
500 |
|
501 |
|
502 |
|
503 |
|
504 |
|
505 |
|
506 |
|
507 | _exit(exitCode, code, message) {
|
508 | if (this._exitCallback) {
|
509 | this._exitCallback(new CommanderError(exitCode, code, message));
|
510 |
|
511 | }
|
512 | process.exit(exitCode);
|
513 | }
|
514 |
|
515 | |
516 |
|
517 |
|
518 |
|
519 |
|
520 |
|
521 |
|
522 |
|
523 |
|
524 |
|
525 |
|
526 |
|
527 |
|
528 |
|
529 |
|
530 | action(fn) {
|
531 | const listener = (args) => {
|
532 |
|
533 | const expectedArgsCount = this.registeredArguments.length;
|
534 | const actionArgs = args.slice(0, expectedArgsCount);
|
535 | if (this._storeOptionsAsProperties) {
|
536 | actionArgs[expectedArgsCount] = this;
|
537 | } else {
|
538 | actionArgs[expectedArgsCount] = this.opts();
|
539 | }
|
540 | actionArgs.push(this);
|
541 |
|
542 | return fn.apply(this, actionArgs);
|
543 | };
|
544 | this._actionHandler = listener;
|
545 | return this;
|
546 | }
|
547 |
|
548 | |
549 |
|
550 |
|
551 |
|
552 |
|
553 |
|
554 |
|
555 |
|
556 |
|
557 |
|
558 |
|
559 | createOption(flags, description) {
|
560 | return new Option(flags, description);
|
561 | }
|
562 |
|
563 | |
564 |
|
565 |
|
566 |
|
567 |
|
568 |
|
569 |
|
570 |
|
571 |
|
572 |
|
573 | _callParseArg(target, value, previous, invalidArgumentMessage) {
|
574 | try {
|
575 | return target.parseArg(value, previous);
|
576 | } catch (err) {
|
577 | if (err.code === 'commander.invalidArgument') {
|
578 | const message = `${invalidArgumentMessage} ${err.message}`;
|
579 | this.error(message, { exitCode: err.exitCode, code: err.code });
|
580 | }
|
581 | throw err;
|
582 | }
|
583 | }
|
584 |
|
585 | |
586 |
|
587 |
|
588 |
|
589 |
|
590 |
|
591 |
|
592 |
|
593 | _registerOption(option) {
|
594 | const matchingOption =
|
595 | (option.short && this._findOption(option.short)) ||
|
596 | (option.long && this._findOption(option.long));
|
597 | if (matchingOption) {
|
598 | const matchingFlag =
|
599 | option.long && this._findOption(option.long)
|
600 | ? option.long
|
601 | : option.short;
|
602 | throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
603 | - already used by option '${matchingOption.flags}'`);
|
604 | }
|
605 |
|
606 | this.options.push(option);
|
607 | }
|
608 |
|
609 | |
610 |
|
611 |
|
612 |
|
613 |
|
614 |
|
615 |
|
616 |
|
617 | _registerCommand(command) {
|
618 | const knownBy = (cmd) => {
|
619 | return [cmd.name()].concat(cmd.aliases());
|
620 | };
|
621 |
|
622 | const alreadyUsed = knownBy(command).find((name) =>
|
623 | this._findCommand(name),
|
624 | );
|
625 | if (alreadyUsed) {
|
626 | const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
|
627 | const newCmd = knownBy(command).join('|');
|
628 | throw new Error(
|
629 | `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
|
630 | );
|
631 | }
|
632 |
|
633 | this.commands.push(command);
|
634 | }
|
635 |
|
636 | |
637 |
|
638 |
|
639 |
|
640 |
|
641 |
|
642 | addOption(option) {
|
643 | this._registerOption(option);
|
644 |
|
645 | const oname = option.name();
|
646 | const name = option.attributeName();
|
647 |
|
648 |
|
649 | if (option.negate) {
|
650 |
|
651 | const positiveLongFlag = option.long.replace(/^--no-/, '--');
|
652 | if (!this._findOption(positiveLongFlag)) {
|
653 | this.setOptionValueWithSource(
|
654 | name,
|
655 | option.defaultValue === undefined ? true : option.defaultValue,
|
656 | 'default',
|
657 | );
|
658 | }
|
659 | } else if (option.defaultValue !== undefined) {
|
660 | this.setOptionValueWithSource(name, option.defaultValue, 'default');
|
661 | }
|
662 |
|
663 |
|
664 | const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
665 |
|
666 |
|
667 | if (val == null && option.presetArg !== undefined) {
|
668 | val = option.presetArg;
|
669 | }
|
670 |
|
671 |
|
672 | const oldValue = this.getOptionValue(name);
|
673 | if (val !== null && option.parseArg) {
|
674 | val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
675 | } else if (val !== null && option.variadic) {
|
676 | val = option._concatValue(val, oldValue);
|
677 | }
|
678 |
|
679 |
|
680 | if (val == null) {
|
681 | if (option.negate) {
|
682 | val = false;
|
683 | } else if (option.isBoolean() || option.optional) {
|
684 | val = true;
|
685 | } else {
|
686 | val = '';
|
687 | }
|
688 | }
|
689 | this.setOptionValueWithSource(name, val, valueSource);
|
690 | };
|
691 |
|
692 | this.on('option:' + oname, (val) => {
|
693 | const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
694 | handleOptionValue(val, invalidValueMessage, 'cli');
|
695 | });
|
696 |
|
697 | if (option.envVar) {
|
698 | this.on('optionEnv:' + oname, (val) => {
|
699 | const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
700 | handleOptionValue(val, invalidValueMessage, 'env');
|
701 | });
|
702 | }
|
703 |
|
704 | return this;
|
705 | }
|
706 |
|
707 | |
708 |
|
709 |
|
710 |
|
711 |
|
712 |
|
713 | _optionEx(config, flags, description, fn, defaultValue) {
|
714 | if (typeof flags === 'object' && flags instanceof Option) {
|
715 | throw new Error(
|
716 | 'To add an Option object use addOption() instead of option() or requiredOption()',
|
717 | );
|
718 | }
|
719 | const option = this.createOption(flags, description);
|
720 | option.makeOptionMandatory(!!config.mandatory);
|
721 | if (typeof fn === 'function') {
|
722 | option.default(defaultValue).argParser(fn);
|
723 | } else if (fn instanceof RegExp) {
|
724 |
|
725 | const regex = fn;
|
726 | fn = (val, def) => {
|
727 | const m = regex.exec(val);
|
728 | return m ? m[0] : def;
|
729 | };
|
730 | option.default(defaultValue).argParser(fn);
|
731 | } else {
|
732 | option.default(fn);
|
733 | }
|
734 |
|
735 | return this.addOption(option);
|
736 | }
|
737 |
|
738 | |
739 |
|
740 |
|
741 |
|
742 |
|
743 |
|
744 |
|
745 |
|
746 |
|
747 |
|
748 |
|
749 |
|
750 |
|
751 |
|
752 |
|
753 |
|
754 |
|
755 |
|
756 |
|
757 |
|
758 |
|
759 |
|
760 | option(flags, description, parseArg, defaultValue) {
|
761 | return this._optionEx({}, flags, description, parseArg, defaultValue);
|
762 | }
|
763 |
|
764 | |
765 |
|
766 |
|
767 |
|
768 |
|
769 |
|
770 |
|
771 |
|
772 |
|
773 |
|
774 |
|
775 |
|
776 |
|
777 | requiredOption(flags, description, parseArg, defaultValue) {
|
778 | return this._optionEx(
|
779 | { mandatory: true },
|
780 | flags,
|
781 | description,
|
782 | parseArg,
|
783 | defaultValue,
|
784 | );
|
785 | }
|
786 |
|
787 | |
788 |
|
789 |
|
790 |
|
791 |
|
792 |
|
793 |
|
794 |
|
795 |
|
796 |
|
797 |
|
798 | combineFlagAndOptionalValue(combine = true) {
|
799 | this._combineFlagAndOptionalValue = !!combine;
|
800 | return this;
|
801 | }
|
802 |
|
803 | |
804 |
|
805 |
|
806 |
|
807 |
|
808 |
|
809 | allowUnknownOption(allowUnknown = true) {
|
810 | this._allowUnknownOption = !!allowUnknown;
|
811 | return this;
|
812 | }
|
813 |
|
814 | |
815 |
|
816 |
|
817 |
|
818 |
|
819 |
|
820 | allowExcessArguments(allowExcess = true) {
|
821 | this._allowExcessArguments = !!allowExcess;
|
822 | return this;
|
823 | }
|
824 |
|
825 | |
826 |
|
827 |
|
828 |
|
829 |
|
830 |
|
831 |
|
832 |
|
833 | enablePositionalOptions(positional = true) {
|
834 | this._enablePositionalOptions = !!positional;
|
835 | return this;
|
836 | }
|
837 |
|
838 | |
839 |
|
840 |
|
841 |
|
842 |
|
843 |
|
844 |
|
845 |
|
846 |
|
847 | passThroughOptions(passThrough = true) {
|
848 | this._passThroughOptions = !!passThrough;
|
849 | this._checkForBrokenPassThrough();
|
850 | return this;
|
851 | }
|
852 |
|
853 | |
854 |
|
855 |
|
856 |
|
857 | _checkForBrokenPassThrough() {
|
858 | if (
|
859 | this.parent &&
|
860 | this._passThroughOptions &&
|
861 | !this.parent._enablePositionalOptions
|
862 | ) {
|
863 | throw new Error(
|
864 | `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
|
865 | );
|
866 | }
|
867 | }
|
868 |
|
869 | |
870 |
|
871 |
|
872 |
|
873 |
|
874 |
|
875 |
|
876 |
|
877 | storeOptionsAsProperties(storeAsProperties = true) {
|
878 | if (this.options.length) {
|
879 | throw new Error('call .storeOptionsAsProperties() before adding options');
|
880 | }
|
881 | if (Object.keys(this._optionValues).length) {
|
882 | throw new Error(
|
883 | 'call .storeOptionsAsProperties() before setting option values',
|
884 | );
|
885 | }
|
886 | this._storeOptionsAsProperties = !!storeAsProperties;
|
887 | return this;
|
888 | }
|
889 |
|
890 | |
891 |
|
892 |
|
893 |
|
894 |
|
895 |
|
896 |
|
897 | getOptionValue(key) {
|
898 | if (this._storeOptionsAsProperties) {
|
899 | return this[key];
|
900 | }
|
901 | return this._optionValues[key];
|
902 | }
|
903 |
|
904 | |
905 |
|
906 |
|
907 |
|
908 |
|
909 |
|
910 |
|
911 |
|
912 | setOptionValue(key, value) {
|
913 | return this.setOptionValueWithSource(key, value, undefined);
|
914 | }
|
915 |
|
916 | |
917 |
|
918 |
|
919 |
|
920 |
|
921 |
|
922 |
|
923 |
|
924 |
|
925 | setOptionValueWithSource(key, value, source) {
|
926 | if (this._storeOptionsAsProperties) {
|
927 | this[key] = value;
|
928 | } else {
|
929 | this._optionValues[key] = value;
|
930 | }
|
931 | this._optionValueSources[key] = source;
|
932 | return this;
|
933 | }
|
934 |
|
935 | |
936 |
|
937 |
|
938 |
|
939 |
|
940 |
|
941 |
|
942 |
|
943 | getOptionValueSource(key) {
|
944 | return this._optionValueSources[key];
|
945 | }
|
946 |
|
947 | |
948 |
|
949 |
|
950 |
|
951 |
|
952 |
|
953 |
|
954 |
|
955 | getOptionValueSourceWithGlobals(key) {
|
956 |
|
957 | let source;
|
958 | this._getCommandAndAncestors().forEach((cmd) => {
|
959 | if (cmd.getOptionValueSource(key) !== undefined) {
|
960 | source = cmd.getOptionValueSource(key);
|
961 | }
|
962 | });
|
963 | return source;
|
964 | }
|
965 |
|
966 | |
967 |
|
968 |
|
969 |
|
970 |
|
971 |
|
972 |
|
973 | _prepareUserArgs(argv, parseOptions) {
|
974 | if (argv !== undefined && !Array.isArray(argv)) {
|
975 | throw new Error('first parameter to parse must be array or undefined');
|
976 | }
|
977 | parseOptions = parseOptions || {};
|
978 |
|
979 |
|
980 | if (argv === undefined && parseOptions.from === undefined) {
|
981 | if (process.versions?.electron) {
|
982 | parseOptions.from = 'electron';
|
983 | }
|
984 |
|
985 | const execArgv = process.execArgv ?? [];
|
986 | if (
|
987 | execArgv.includes('-e') ||
|
988 | execArgv.includes('--eval') ||
|
989 | execArgv.includes('-p') ||
|
990 | execArgv.includes('--print')
|
991 | ) {
|
992 | parseOptions.from = 'eval';
|
993 | }
|
994 | }
|
995 |
|
996 |
|
997 | if (argv === undefined) {
|
998 | argv = process.argv;
|
999 | }
|
1000 | this.rawArgs = argv.slice();
|
1001 |
|
1002 |
|
1003 | let userArgs;
|
1004 | switch (parseOptions.from) {
|
1005 | case undefined:
|
1006 | case 'node':
|
1007 | this._scriptPath = argv[1];
|
1008 | userArgs = argv.slice(2);
|
1009 | break;
|
1010 | case 'electron':
|
1011 |
|
1012 | if (process.defaultApp) {
|
1013 | this._scriptPath = argv[1];
|
1014 | userArgs = argv.slice(2);
|
1015 | } else {
|
1016 | userArgs = argv.slice(1);
|
1017 | }
|
1018 | break;
|
1019 | case 'user':
|
1020 | userArgs = argv.slice(0);
|
1021 | break;
|
1022 | case 'eval':
|
1023 | userArgs = argv.slice(1);
|
1024 | break;
|
1025 | default:
|
1026 | throw new Error(
|
1027 | `unexpected parse option { from: '${parseOptions.from}' }`,
|
1028 | );
|
1029 | }
|
1030 |
|
1031 |
|
1032 | if (!this._name && this._scriptPath)
|
1033 | this.nameFromFilename(this._scriptPath);
|
1034 | this._name = this._name || 'program';
|
1035 |
|
1036 | return userArgs;
|
1037 | }
|
1038 |
|
1039 | |
1040 |
|
1041 |
|
1042 |
|
1043 |
|
1044 |
|
1045 |
|
1046 |
|
1047 |
|
1048 |
|
1049 |
|
1050 |
|
1051 |
|
1052 |
|
1053 |
|
1054 |
|
1055 |
|
1056 |
|
1057 |
|
1058 |
|
1059 |
|
1060 |
|
1061 |
|
1062 | parse(argv, parseOptions) {
|
1063 | const userArgs = this._prepareUserArgs(argv, parseOptions);
|
1064 | this._parseCommand([], userArgs);
|
1065 |
|
1066 | return this;
|
1067 | }
|
1068 |
|
1069 | |
1070 |
|
1071 |
|
1072 |
|
1073 |
|
1074 |
|
1075 |
|
1076 |
|
1077 |
|
1078 |
|
1079 |
|
1080 |
|
1081 |
|
1082 |
|
1083 |
|
1084 |
|
1085 |
|
1086 |
|
1087 |
|
1088 |
|
1089 |
|
1090 | async parseAsync(argv, parseOptions) {
|
1091 | const userArgs = this._prepareUserArgs(argv, parseOptions);
|
1092 | await this._parseCommand([], userArgs);
|
1093 |
|
1094 | return this;
|
1095 | }
|
1096 |
|
1097 | |
1098 |
|
1099 |
|
1100 |
|
1101 |
|
1102 |
|
1103 | _executeSubCommand(subcommand, args) {
|
1104 | args = args.slice();
|
1105 | let launchWithNode = false;
|
1106 | const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
|
1107 |
|
1108 | function findFile(baseDir, baseName) {
|
1109 |
|
1110 | const localBin = path.resolve(baseDir, baseName);
|
1111 | if (fs.existsSync(localBin)) return localBin;
|
1112 |
|
1113 |
|
1114 | if (sourceExt.includes(path.extname(baseName))) return undefined;
|
1115 |
|
1116 |
|
1117 | const foundExt = sourceExt.find((ext) =>
|
1118 | fs.existsSync(`${localBin}${ext}`),
|
1119 | );
|
1120 | if (foundExt) return `${localBin}${foundExt}`;
|
1121 |
|
1122 | return undefined;
|
1123 | }
|
1124 |
|
1125 |
|
1126 | this._checkForMissingMandatoryOptions();
|
1127 | this._checkForConflictingOptions();
|
1128 |
|
1129 |
|
1130 | let executableFile =
|
1131 | subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
1132 | let executableDir = this._executableDir || '';
|
1133 | if (this._scriptPath) {
|
1134 | let resolvedScriptPath;
|
1135 | try {
|
1136 | resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
1137 | } catch (err) {
|
1138 | resolvedScriptPath = this._scriptPath;
|
1139 | }
|
1140 | executableDir = path.resolve(
|
1141 | path.dirname(resolvedScriptPath),
|
1142 | executableDir,
|
1143 | );
|
1144 | }
|
1145 |
|
1146 |
|
1147 | if (executableDir) {
|
1148 | let localFile = findFile(executableDir, executableFile);
|
1149 |
|
1150 |
|
1151 | if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
1152 | const legacyName = path.basename(
|
1153 | this._scriptPath,
|
1154 | path.extname(this._scriptPath),
|
1155 | );
|
1156 | if (legacyName !== this._name) {
|
1157 | localFile = findFile(
|
1158 | executableDir,
|
1159 | `${legacyName}-${subcommand._name}`,
|
1160 | );
|
1161 | }
|
1162 | }
|
1163 | executableFile = localFile || executableFile;
|
1164 | }
|
1165 |
|
1166 | launchWithNode = sourceExt.includes(path.extname(executableFile));
|
1167 |
|
1168 | let proc;
|
1169 | if (process.platform !== 'win32') {
|
1170 | if (launchWithNode) {
|
1171 | args.unshift(executableFile);
|
1172 |
|
1173 | args = incrementNodeInspectorPort(process.execArgv).concat(args);
|
1174 |
|
1175 | proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
|
1176 | } else {
|
1177 | proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
|
1178 | }
|
1179 | } else {
|
1180 | args.unshift(executableFile);
|
1181 |
|
1182 | args = incrementNodeInspectorPort(process.execArgv).concat(args);
|
1183 | proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
|
1184 | }
|
1185 |
|
1186 | if (!proc.killed) {
|
1187 |
|
1188 | const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
|
1189 | signals.forEach((signal) => {
|
1190 | process.on(signal, () => {
|
1191 | if (proc.killed === false && proc.exitCode === null) {
|
1192 |
|
1193 | proc.kill(signal);
|
1194 | }
|
1195 | });
|
1196 | });
|
1197 | }
|
1198 |
|
1199 |
|
1200 | const exitCallback = this._exitCallback;
|
1201 | proc.on('close', (code) => {
|
1202 | code = code ?? 1;
|
1203 | if (!exitCallback) {
|
1204 | process.exit(code);
|
1205 | } else {
|
1206 | exitCallback(
|
1207 | new CommanderError(
|
1208 | code,
|
1209 | 'commander.executeSubCommandAsync',
|
1210 | '(close)',
|
1211 | ),
|
1212 | );
|
1213 | }
|
1214 | });
|
1215 | proc.on('error', (err) => {
|
1216 |
|
1217 | if (err.code === 'ENOENT') {
|
1218 | const executableDirMessage = executableDir
|
1219 | ? `searched for local subcommand relative to directory '${executableDir}'`
|
1220 | : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
|
1221 | const executableMissing = `'${executableFile}' does not exist
|
1222 | - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
1223 | - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
1224 | - ${executableDirMessage}`;
|
1225 | throw new Error(executableMissing);
|
1226 |
|
1227 | } else if (err.code === 'EACCES') {
|
1228 | throw new Error(`'${executableFile}' not executable`);
|
1229 | }
|
1230 | if (!exitCallback) {
|
1231 | process.exit(1);
|
1232 | } else {
|
1233 | const wrappedError = new CommanderError(
|
1234 | 1,
|
1235 | 'commander.executeSubCommandAsync',
|
1236 | '(error)',
|
1237 | );
|
1238 | wrappedError.nestedError = err;
|
1239 | exitCallback(wrappedError);
|
1240 | }
|
1241 | });
|
1242 |
|
1243 |
|
1244 | this.runningCommand = proc;
|
1245 | }
|
1246 |
|
1247 | |
1248 |
|
1249 |
|
1250 |
|
1251 | _dispatchSubcommand(commandName, operands, unknown) {
|
1252 | const subCommand = this._findCommand(commandName);
|
1253 | if (!subCommand) this.help({ error: true });
|
1254 |
|
1255 | let promiseChain;
|
1256 | promiseChain = this._chainOrCallSubCommandHook(
|
1257 | promiseChain,
|
1258 | subCommand,
|
1259 | 'preSubcommand',
|
1260 | );
|
1261 | promiseChain = this._chainOrCall(promiseChain, () => {
|
1262 | if (subCommand._executableHandler) {
|
1263 | this._executeSubCommand(subCommand, operands.concat(unknown));
|
1264 | } else {
|
1265 | return subCommand._parseCommand(operands, unknown);
|
1266 | }
|
1267 | });
|
1268 | return promiseChain;
|
1269 | }
|
1270 |
|
1271 | |
1272 |
|
1273 |
|
1274 |
|
1275 |
|
1276 |
|
1277 |
|
1278 | _dispatchHelpCommand(subcommandName) {
|
1279 | if (!subcommandName) {
|
1280 | this.help();
|
1281 | }
|
1282 | const subCommand = this._findCommand(subcommandName);
|
1283 | if (subCommand && !subCommand._executableHandler) {
|
1284 | subCommand.help();
|
1285 | }
|
1286 |
|
1287 |
|
1288 | return this._dispatchSubcommand(
|
1289 | subcommandName,
|
1290 | [],
|
1291 | [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
|
1292 | );
|
1293 | }
|
1294 |
|
1295 | |
1296 |
|
1297 |
|
1298 |
|
1299 |
|
1300 |
|
1301 | _checkNumberOfArguments() {
|
1302 |
|
1303 | this.registeredArguments.forEach((arg, i) => {
|
1304 | if (arg.required && this.args[i] == null) {
|
1305 | this.missingArgument(arg.name());
|
1306 | }
|
1307 | });
|
1308 |
|
1309 | if (
|
1310 | this.registeredArguments.length > 0 &&
|
1311 | this.registeredArguments[this.registeredArguments.length - 1].variadic
|
1312 | ) {
|
1313 | return;
|
1314 | }
|
1315 | if (this.args.length > this.registeredArguments.length) {
|
1316 | this._excessArguments(this.args);
|
1317 | }
|
1318 | }
|
1319 |
|
1320 | |
1321 |
|
1322 |
|
1323 |
|
1324 |
|
1325 |
|
1326 | _processArguments() {
|
1327 | const myParseArg = (argument, value, previous) => {
|
1328 |
|
1329 | let parsedValue = value;
|
1330 | if (value !== null && argument.parseArg) {
|
1331 | const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
1332 | parsedValue = this._callParseArg(
|
1333 | argument,
|
1334 | value,
|
1335 | previous,
|
1336 | invalidValueMessage,
|
1337 | );
|
1338 | }
|
1339 | return parsedValue;
|
1340 | };
|
1341 |
|
1342 | this._checkNumberOfArguments();
|
1343 |
|
1344 | const processedArgs = [];
|
1345 | this.registeredArguments.forEach((declaredArg, index) => {
|
1346 | let value = declaredArg.defaultValue;
|
1347 | if (declaredArg.variadic) {
|
1348 |
|
1349 | if (index < this.args.length) {
|
1350 | value = this.args.slice(index);
|
1351 | if (declaredArg.parseArg) {
|
1352 | value = value.reduce((processed, v) => {
|
1353 | return myParseArg(declaredArg, v, processed);
|
1354 | }, declaredArg.defaultValue);
|
1355 | }
|
1356 | } else if (value === undefined) {
|
1357 | value = [];
|
1358 | }
|
1359 | } else if (index < this.args.length) {
|
1360 | value = this.args[index];
|
1361 | if (declaredArg.parseArg) {
|
1362 | value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
1363 | }
|
1364 | }
|
1365 | processedArgs[index] = value;
|
1366 | });
|
1367 | this.processedArgs = processedArgs;
|
1368 | }
|
1369 |
|
1370 | |
1371 |
|
1372 |
|
1373 |
|
1374 |
|
1375 |
|
1376 |
|
1377 |
|
1378 |
|
1379 | _chainOrCall(promise, fn) {
|
1380 |
|
1381 | if (promise && promise.then && typeof promise.then === 'function') {
|
1382 |
|
1383 | return promise.then(() => fn());
|
1384 | }
|
1385 |
|
1386 | return fn();
|
1387 | }
|
1388 |
|
1389 | |
1390 |
|
1391 |
|
1392 |
|
1393 |
|
1394 |
|
1395 |
|
1396 |
|
1397 | _chainOrCallHooks(promise, event) {
|
1398 | let result = promise;
|
1399 | const hooks = [];
|
1400 | this._getCommandAndAncestors()
|
1401 | .reverse()
|
1402 | .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
|
1403 | .forEach((hookedCommand) => {
|
1404 | hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
1405 | hooks.push({ hookedCommand, callback });
|
1406 | });
|
1407 | });
|
1408 | if (event === 'postAction') {
|
1409 | hooks.reverse();
|
1410 | }
|
1411 |
|
1412 | hooks.forEach((hookDetail) => {
|
1413 | result = this._chainOrCall(result, () => {
|
1414 | return hookDetail.callback(hookDetail.hookedCommand, this);
|
1415 | });
|
1416 | });
|
1417 | return result;
|
1418 | }
|
1419 |
|
1420 | |
1421 |
|
1422 |
|
1423 |
|
1424 |
|
1425 |
|
1426 |
|
1427 |
|
1428 |
|
1429 | _chainOrCallSubCommandHook(promise, subCommand, event) {
|
1430 | let result = promise;
|
1431 | if (this._lifeCycleHooks[event] !== undefined) {
|
1432 | this._lifeCycleHooks[event].forEach((hook) => {
|
1433 | result = this._chainOrCall(result, () => {
|
1434 | return hook(this, subCommand);
|
1435 | });
|
1436 | });
|
1437 | }
|
1438 | return result;
|
1439 | }
|
1440 |
|
1441 | |
1442 |
|
1443 |
|
1444 |
|
1445 |
|
1446 |
|
1447 |
|
1448 | _parseCommand(operands, unknown) {
|
1449 | const parsed = this.parseOptions(unknown);
|
1450 | this._parseOptionsEnv();
|
1451 | this._parseOptionsImplied();
|
1452 | operands = operands.concat(parsed.operands);
|
1453 | unknown = parsed.unknown;
|
1454 | this.args = operands.concat(unknown);
|
1455 |
|
1456 | if (operands && this._findCommand(operands[0])) {
|
1457 | return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
1458 | }
|
1459 | if (
|
1460 | this._getHelpCommand() &&
|
1461 | operands[0] === this._getHelpCommand().name()
|
1462 | ) {
|
1463 | return this._dispatchHelpCommand(operands[1]);
|
1464 | }
|
1465 | if (this._defaultCommandName) {
|
1466 | this._outputHelpIfRequested(unknown);
|
1467 | return this._dispatchSubcommand(
|
1468 | this._defaultCommandName,
|
1469 | operands,
|
1470 | unknown,
|
1471 | );
|
1472 | }
|
1473 | if (
|
1474 | this.commands.length &&
|
1475 | this.args.length === 0 &&
|
1476 | !this._actionHandler &&
|
1477 | !this._defaultCommandName
|
1478 | ) {
|
1479 |
|
1480 | this.help({ error: true });
|
1481 | }
|
1482 |
|
1483 | this._outputHelpIfRequested(parsed.unknown);
|
1484 | this._checkForMissingMandatoryOptions();
|
1485 | this._checkForConflictingOptions();
|
1486 |
|
1487 |
|
1488 | const checkForUnknownOptions = () => {
|
1489 | if (parsed.unknown.length > 0) {
|
1490 | this.unknownOption(parsed.unknown[0]);
|
1491 | }
|
1492 | };
|
1493 |
|
1494 | const commandEvent = `command:${this.name()}`;
|
1495 | if (this._actionHandler) {
|
1496 | checkForUnknownOptions();
|
1497 | this._processArguments();
|
1498 |
|
1499 | let promiseChain;
|
1500 | promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
|
1501 | promiseChain = this._chainOrCall(promiseChain, () =>
|
1502 | this._actionHandler(this.processedArgs),
|
1503 | );
|
1504 | if (this.parent) {
|
1505 | promiseChain = this._chainOrCall(promiseChain, () => {
|
1506 | this.parent.emit(commandEvent, operands, unknown);
|
1507 | });
|
1508 | }
|
1509 | promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
|
1510 | return promiseChain;
|
1511 | }
|
1512 | if (this.parent && this.parent.listenerCount(commandEvent)) {
|
1513 | checkForUnknownOptions();
|
1514 | this._processArguments();
|
1515 | this.parent.emit(commandEvent, operands, unknown);
|
1516 | } else if (operands.length) {
|
1517 | if (this._findCommand('*')) {
|
1518 |
|
1519 | return this._dispatchSubcommand('*', operands, unknown);
|
1520 | }
|
1521 | if (this.listenerCount('command:*')) {
|
1522 |
|
1523 | this.emit('command:*', operands, unknown);
|
1524 | } else if (this.commands.length) {
|
1525 | this.unknownCommand();
|
1526 | } else {
|
1527 | checkForUnknownOptions();
|
1528 | this._processArguments();
|
1529 | }
|
1530 | } else if (this.commands.length) {
|
1531 | checkForUnknownOptions();
|
1532 |
|
1533 | this.help({ error: true });
|
1534 | } else {
|
1535 | checkForUnknownOptions();
|
1536 | this._processArguments();
|
1537 |
|
1538 | }
|
1539 | }
|
1540 |
|
1541 | |
1542 |
|
1543 |
|
1544 |
|
1545 |
|
1546 |
|
1547 | _findCommand(name) {
|
1548 | if (!name) return undefined;
|
1549 | return this.commands.find(
|
1550 | (cmd) => cmd._name === name || cmd._aliases.includes(name),
|
1551 | );
|
1552 | }
|
1553 |
|
1554 | |
1555 |
|
1556 |
|
1557 |
|
1558 |
|
1559 |
|
1560 |
|
1561 |
|
1562 | _findOption(arg) {
|
1563 | return this.options.find((option) => option.is(arg));
|
1564 | }
|
1565 |
|
1566 | |
1567 |
|
1568 |
|
1569 |
|
1570 |
|
1571 |
|
1572 |
|
1573 | _checkForMissingMandatoryOptions() {
|
1574 |
|
1575 | this._getCommandAndAncestors().forEach((cmd) => {
|
1576 | cmd.options.forEach((anOption) => {
|
1577 | if (
|
1578 | anOption.mandatory &&
|
1579 | cmd.getOptionValue(anOption.attributeName()) === undefined
|
1580 | ) {
|
1581 | cmd.missingMandatoryOptionValue(anOption);
|
1582 | }
|
1583 | });
|
1584 | });
|
1585 | }
|
1586 |
|
1587 | |
1588 |
|
1589 |
|
1590 |
|
1591 |
|
1592 | _checkForConflictingLocalOptions() {
|
1593 | const definedNonDefaultOptions = this.options.filter((option) => {
|
1594 | const optionKey = option.attributeName();
|
1595 | if (this.getOptionValue(optionKey) === undefined) {
|
1596 | return false;
|
1597 | }
|
1598 | return this.getOptionValueSource(optionKey) !== 'default';
|
1599 | });
|
1600 |
|
1601 | const optionsWithConflicting = definedNonDefaultOptions.filter(
|
1602 | (option) => option.conflictsWith.length > 0,
|
1603 | );
|
1604 |
|
1605 | optionsWithConflicting.forEach((option) => {
|
1606 | const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
|
1607 | option.conflictsWith.includes(defined.attributeName()),
|
1608 | );
|
1609 | if (conflictingAndDefined) {
|
1610 | this._conflictingOption(option, conflictingAndDefined);
|
1611 | }
|
1612 | });
|
1613 | }
|
1614 |
|
1615 | |
1616 |
|
1617 |
|
1618 |
|
1619 |
|
1620 |
|
1621 | _checkForConflictingOptions() {
|
1622 |
|
1623 | this._getCommandAndAncestors().forEach((cmd) => {
|
1624 | cmd._checkForConflictingLocalOptions();
|
1625 | });
|
1626 | }
|
1627 |
|
1628 | |
1629 |
|
1630 |
|
1631 |
|
1632 |
|
1633 |
|
1634 |
|
1635 |
|
1636 |
|
1637 |
|
1638 |
|
1639 |
|
1640 |
|
1641 |
|
1642 |
|
1643 |
|
1644 | parseOptions(argv) {
|
1645 | const operands = [];
|
1646 | const unknown = [];
|
1647 | let dest = operands;
|
1648 | const args = argv.slice();
|
1649 |
|
1650 | function maybeOption(arg) {
|
1651 | return arg.length > 1 && arg[0] === '-';
|
1652 | }
|
1653 |
|
1654 |
|
1655 | let activeVariadicOption = null;
|
1656 | while (args.length) {
|
1657 | const arg = args.shift();
|
1658 |
|
1659 |
|
1660 | if (arg === '--') {
|
1661 | if (dest === unknown) dest.push(arg);
|
1662 | dest.push(...args);
|
1663 | break;
|
1664 | }
|
1665 |
|
1666 | if (activeVariadicOption && !maybeOption(arg)) {
|
1667 | this.emit(`option:${activeVariadicOption.name()}`, arg);
|
1668 | continue;
|
1669 | }
|
1670 | activeVariadicOption = null;
|
1671 |
|
1672 | if (maybeOption(arg)) {
|
1673 | const option = this._findOption(arg);
|
1674 |
|
1675 | if (option) {
|
1676 | if (option.required) {
|
1677 | const value = args.shift();
|
1678 | if (value === undefined) this.optionMissingArgument(option);
|
1679 | this.emit(`option:${option.name()}`, value);
|
1680 | } else if (option.optional) {
|
1681 | let value = null;
|
1682 |
|
1683 | if (args.length > 0 && !maybeOption(args[0])) {
|
1684 | value = args.shift();
|
1685 | }
|
1686 | this.emit(`option:${option.name()}`, value);
|
1687 | } else {
|
1688 |
|
1689 | this.emit(`option:${option.name()}`);
|
1690 | }
|
1691 | activeVariadicOption = option.variadic ? option : null;
|
1692 | continue;
|
1693 | }
|
1694 | }
|
1695 |
|
1696 |
|
1697 | if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
|
1698 | const option = this._findOption(`-${arg[1]}`);
|
1699 | if (option) {
|
1700 | if (
|
1701 | option.required ||
|
1702 | (option.optional && this._combineFlagAndOptionalValue)
|
1703 | ) {
|
1704 |
|
1705 | this.emit(`option:${option.name()}`, arg.slice(2));
|
1706 | } else {
|
1707 |
|
1708 | this.emit(`option:${option.name()}`);
|
1709 | args.unshift(`-${arg.slice(2)}`);
|
1710 | }
|
1711 | continue;
|
1712 | }
|
1713 | }
|
1714 |
|
1715 |
|
1716 | if (/^--[^=]+=/.test(arg)) {
|
1717 | const index = arg.indexOf('=');
|
1718 | const option = this._findOption(arg.slice(0, index));
|
1719 | if (option && (option.required || option.optional)) {
|
1720 | this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
1721 | continue;
|
1722 | }
|
1723 | }
|
1724 |
|
1725 |
|
1726 |
|
1727 |
|
1728 |
|
1729 | if (maybeOption(arg)) {
|
1730 | dest = unknown;
|
1731 | }
|
1732 |
|
1733 |
|
1734 | if (
|
1735 | (this._enablePositionalOptions || this._passThroughOptions) &&
|
1736 | operands.length === 0 &&
|
1737 | unknown.length === 0
|
1738 | ) {
|
1739 | if (this._findCommand(arg)) {
|
1740 | operands.push(arg);
|
1741 | if (args.length > 0) unknown.push(...args);
|
1742 | break;
|
1743 | } else if (
|
1744 | this._getHelpCommand() &&
|
1745 | arg === this._getHelpCommand().name()
|
1746 | ) {
|
1747 | operands.push(arg);
|
1748 | if (args.length > 0) operands.push(...args);
|
1749 | break;
|
1750 | } else if (this._defaultCommandName) {
|
1751 | unknown.push(arg);
|
1752 | if (args.length > 0) unknown.push(...args);
|
1753 | break;
|
1754 | }
|
1755 | }
|
1756 |
|
1757 |
|
1758 | if (this._passThroughOptions) {
|
1759 | dest.push(arg);
|
1760 | if (args.length > 0) dest.push(...args);
|
1761 | break;
|
1762 | }
|
1763 |
|
1764 |
|
1765 | dest.push(arg);
|
1766 | }
|
1767 |
|
1768 | return { operands, unknown };
|
1769 | }
|
1770 |
|
1771 | |
1772 |
|
1773 |
|
1774 |
|
1775 |
|
1776 | opts() {
|
1777 | if (this._storeOptionsAsProperties) {
|
1778 |
|
1779 | const result = {};
|
1780 | const len = this.options.length;
|
1781 |
|
1782 | for (let i = 0; i < len; i++) {
|
1783 | const key = this.options[i].attributeName();
|
1784 | result[key] =
|
1785 | key === this._versionOptionName ? this._version : this[key];
|
1786 | }
|
1787 | return result;
|
1788 | }
|
1789 |
|
1790 | return this._optionValues;
|
1791 | }
|
1792 |
|
1793 | |
1794 |
|
1795 |
|
1796 |
|
1797 |
|
1798 | optsWithGlobals() {
|
1799 |
|
1800 | return this._getCommandAndAncestors().reduce(
|
1801 | (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
1802 | {},
|
1803 | );
|
1804 | }
|
1805 |
|
1806 | |
1807 |
|
1808 |
|
1809 |
|
1810 |
|
1811 |
|
1812 |
|
1813 |
|
1814 | error(message, errorOptions) {
|
1815 |
|
1816 | this._outputConfiguration.outputError(
|
1817 | `${message}\n`,
|
1818 | this._outputConfiguration.writeErr,
|
1819 | );
|
1820 | if (typeof this._showHelpAfterError === 'string') {
|
1821 | this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
|
1822 | } else if (this._showHelpAfterError) {
|
1823 | this._outputConfiguration.writeErr('\n');
|
1824 | this.outputHelp({ error: true });
|
1825 | }
|
1826 |
|
1827 |
|
1828 | const config = errorOptions || {};
|
1829 | const exitCode = config.exitCode || 1;
|
1830 | const code = config.code || 'commander.error';
|
1831 | this._exit(exitCode, code, message);
|
1832 | }
|
1833 |
|
1834 | |
1835 |
|
1836 |
|
1837 |
|
1838 |
|
1839 |
|
1840 | _parseOptionsEnv() {
|
1841 | this.options.forEach((option) => {
|
1842 | if (option.envVar && option.envVar in process.env) {
|
1843 | const optionKey = option.attributeName();
|
1844 |
|
1845 | if (
|
1846 | this.getOptionValue(optionKey) === undefined ||
|
1847 | ['default', 'config', 'env'].includes(
|
1848 | this.getOptionValueSource(optionKey),
|
1849 | )
|
1850 | ) {
|
1851 | if (option.required || option.optional) {
|
1852 |
|
1853 |
|
1854 | this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
|
1855 | } else {
|
1856 |
|
1857 |
|
1858 | this.emit(`optionEnv:${option.name()}`);
|
1859 | }
|
1860 | }
|
1861 | }
|
1862 | });
|
1863 | }
|
1864 |
|
1865 | |
1866 |
|
1867 |
|
1868 |
|
1869 |
|
1870 | _parseOptionsImplied() {
|
1871 | const dualHelper = new DualOptions(this.options);
|
1872 | const hasCustomOptionValue = (optionKey) => {
|
1873 | return (
|
1874 | this.getOptionValue(optionKey) !== undefined &&
|
1875 | !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
|
1876 | );
|
1877 | };
|
1878 | this.options
|
1879 | .filter(
|
1880 | (option) =>
|
1881 | option.implied !== undefined &&
|
1882 | hasCustomOptionValue(option.attributeName()) &&
|
1883 | dualHelper.valueFromOption(
|
1884 | this.getOptionValue(option.attributeName()),
|
1885 | option,
|
1886 | ),
|
1887 | )
|
1888 | .forEach((option) => {
|
1889 | Object.keys(option.implied)
|
1890 | .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
|
1891 | .forEach((impliedKey) => {
|
1892 | this.setOptionValueWithSource(
|
1893 | impliedKey,
|
1894 | option.implied[impliedKey],
|
1895 | 'implied',
|
1896 | );
|
1897 | });
|
1898 | });
|
1899 | }
|
1900 |
|
1901 | |
1902 |
|
1903 |
|
1904 |
|
1905 |
|
1906 |
|
1907 |
|
1908 | missingArgument(name) {
|
1909 | const message = `error: missing required argument '${name}'`;
|
1910 | this.error(message, { code: 'commander.missingArgument' });
|
1911 | }
|
1912 |
|
1913 | |
1914 |
|
1915 |
|
1916 |
|
1917 |
|
1918 |
|
1919 |
|
1920 | optionMissingArgument(option) {
|
1921 | const message = `error: option '${option.flags}' argument missing`;
|
1922 | this.error(message, { code: 'commander.optionMissingArgument' });
|
1923 | }
|
1924 |
|
1925 | |
1926 |
|
1927 |
|
1928 |
|
1929 |
|
1930 |
|
1931 |
|
1932 | missingMandatoryOptionValue(option) {
|
1933 | const message = `error: required option '${option.flags}' not specified`;
|
1934 | this.error(message, { code: 'commander.missingMandatoryOptionValue' });
|
1935 | }
|
1936 |
|
1937 | |
1938 |
|
1939 |
|
1940 |
|
1941 |
|
1942 |
|
1943 |
|
1944 | _conflictingOption(option, conflictingOption) {
|
1945 |
|
1946 |
|
1947 | const findBestOptionFromValue = (option) => {
|
1948 | const optionKey = option.attributeName();
|
1949 | const optionValue = this.getOptionValue(optionKey);
|
1950 | const negativeOption = this.options.find(
|
1951 | (target) => target.negate && optionKey === target.attributeName(),
|
1952 | );
|
1953 | const positiveOption = this.options.find(
|
1954 | (target) => !target.negate && optionKey === target.attributeName(),
|
1955 | );
|
1956 | if (
|
1957 | negativeOption &&
|
1958 | ((negativeOption.presetArg === undefined && optionValue === false) ||
|
1959 | (negativeOption.presetArg !== undefined &&
|
1960 | optionValue === negativeOption.presetArg))
|
1961 | ) {
|
1962 | return negativeOption;
|
1963 | }
|
1964 | return positiveOption || option;
|
1965 | };
|
1966 |
|
1967 | const getErrorMessage = (option) => {
|
1968 | const bestOption = findBestOptionFromValue(option);
|
1969 | const optionKey = bestOption.attributeName();
|
1970 | const source = this.getOptionValueSource(optionKey);
|
1971 | if (source === 'env') {
|
1972 | return `environment variable '${bestOption.envVar}'`;
|
1973 | }
|
1974 | return `option '${bestOption.flags}'`;
|
1975 | };
|
1976 |
|
1977 | const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
1978 | this.error(message, { code: 'commander.conflictingOption' });
|
1979 | }
|
1980 |
|
1981 | |
1982 |
|
1983 |
|
1984 |
|
1985 |
|
1986 |
|
1987 |
|
1988 | unknownOption(flag) {
|
1989 | if (this._allowUnknownOption) return;
|
1990 | let suggestion = '';
|
1991 |
|
1992 | if (flag.startsWith('--') && this._showSuggestionAfterError) {
|
1993 |
|
1994 | let candidateFlags = [];
|
1995 |
|
1996 | let command = this;
|
1997 | do {
|
1998 | const moreFlags = command
|
1999 | .createHelp()
|
2000 | .visibleOptions(command)
|
2001 | .filter((option) => option.long)
|
2002 | .map((option) => option.long);
|
2003 | candidateFlags = candidateFlags.concat(moreFlags);
|
2004 | command = command.parent;
|
2005 | } while (command && !command._enablePositionalOptions);
|
2006 | suggestion = suggestSimilar(flag, candidateFlags);
|
2007 | }
|
2008 |
|
2009 | const message = `error: unknown option '${flag}'${suggestion}`;
|
2010 | this.error(message, { code: 'commander.unknownOption' });
|
2011 | }
|
2012 |
|
2013 | |
2014 |
|
2015 |
|
2016 |
|
2017 |
|
2018 |
|
2019 |
|
2020 | _excessArguments(receivedArgs) {
|
2021 | if (this._allowExcessArguments) return;
|
2022 |
|
2023 | const expected = this.registeredArguments.length;
|
2024 | const s = expected === 1 ? '' : 's';
|
2025 | const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
|
2026 | const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
2027 | this.error(message, { code: 'commander.excessArguments' });
|
2028 | }
|
2029 |
|
2030 | |
2031 |
|
2032 |
|
2033 |
|
2034 |
|
2035 |
|
2036 | unknownCommand() {
|
2037 | const unknownName = this.args[0];
|
2038 | let suggestion = '';
|
2039 |
|
2040 | if (this._showSuggestionAfterError) {
|
2041 | const candidateNames = [];
|
2042 | this.createHelp()
|
2043 | .visibleCommands(this)
|
2044 | .forEach((command) => {
|
2045 | candidateNames.push(command.name());
|
2046 |
|
2047 | if (command.alias()) candidateNames.push(command.alias());
|
2048 | });
|
2049 | suggestion = suggestSimilar(unknownName, candidateNames);
|
2050 | }
|
2051 |
|
2052 | const message = `error: unknown command '${unknownName}'${suggestion}`;
|
2053 | this.error(message, { code: 'commander.unknownCommand' });
|
2054 | }
|
2055 |
|
2056 | |
2057 |
|
2058 |
|
2059 |
|
2060 |
|
2061 |
|
2062 |
|
2063 |
|
2064 |
|
2065 |
|
2066 |
|
2067 |
|
2068 |
|
2069 | version(str, flags, description) {
|
2070 | if (str === undefined) return this._version;
|
2071 | this._version = str;
|
2072 | flags = flags || '-V, --version';
|
2073 | description = description || 'output the version number';
|
2074 | const versionOption = this.createOption(flags, description);
|
2075 | this._versionOptionName = versionOption.attributeName();
|
2076 | this._registerOption(versionOption);
|
2077 |
|
2078 | this.on('option:' + versionOption.name(), () => {
|
2079 | this._outputConfiguration.writeOut(`${str}\n`);
|
2080 | this._exit(0, 'commander.version', str);
|
2081 | });
|
2082 | return this;
|
2083 | }
|
2084 |
|
2085 | |
2086 |
|
2087 |
|
2088 |
|
2089 |
|
2090 |
|
2091 |
|
2092 | description(str, argsDescription) {
|
2093 | if (str === undefined && argsDescription === undefined)
|
2094 | return this._description;
|
2095 | this._description = str;
|
2096 | if (argsDescription) {
|
2097 | this._argsDescription = argsDescription;
|
2098 | }
|
2099 | return this;
|
2100 | }
|
2101 |
|
2102 | |
2103 |
|
2104 |
|
2105 |
|
2106 |
|
2107 |
|
2108 | summary(str) {
|
2109 | if (str === undefined) return this._summary;
|
2110 | this._summary = str;
|
2111 | return this;
|
2112 | }
|
2113 |
|
2114 | |
2115 |
|
2116 |
|
2117 |
|
2118 |
|
2119 |
|
2120 |
|
2121 |
|
2122 |
|
2123 | alias(alias) {
|
2124 | if (alias === undefined) return this._aliases[0];
|
2125 |
|
2126 |
|
2127 |
|
2128 | let command = this;
|
2129 | if (
|
2130 | this.commands.length !== 0 &&
|
2131 | this.commands[this.commands.length - 1]._executableHandler
|
2132 | ) {
|
2133 |
|
2134 | command = this.commands[this.commands.length - 1];
|
2135 | }
|
2136 |
|
2137 | if (alias === command._name)
|
2138 | throw new Error("Command alias can't be the same as its name");
|
2139 | const matchingCommand = this.parent?._findCommand(alias);
|
2140 | if (matchingCommand) {
|
2141 |
|
2142 | const existingCmd = [matchingCommand.name()]
|
2143 | .concat(matchingCommand.aliases())
|
2144 | .join('|');
|
2145 | throw new Error(
|
2146 | `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
|
2147 | );
|
2148 | }
|
2149 |
|
2150 | command._aliases.push(alias);
|
2151 | return this;
|
2152 | }
|
2153 |
|
2154 | |
2155 |
|
2156 |
|
2157 |
|
2158 |
|
2159 |
|
2160 |
|
2161 |
|
2162 |
|
2163 | aliases(aliases) {
|
2164 |
|
2165 | if (aliases === undefined) return this._aliases;
|
2166 |
|
2167 | aliases.forEach((alias) => this.alias(alias));
|
2168 | return this;
|
2169 | }
|
2170 |
|
2171 | |
2172 |
|
2173 |
|
2174 |
|
2175 |
|
2176 |
|
2177 |
|
2178 | usage(str) {
|
2179 | if (str === undefined) {
|
2180 | if (this._usage) return this._usage;
|
2181 |
|
2182 | const args = this.registeredArguments.map((arg) => {
|
2183 | return humanReadableArgName(arg);
|
2184 | });
|
2185 | return []
|
2186 | .concat(
|
2187 | this.options.length || this._helpOption !== null ? '[options]' : [],
|
2188 | this.commands.length ? '[command]' : [],
|
2189 | this.registeredArguments.length ? args : [],
|
2190 | )
|
2191 | .join(' ');
|
2192 | }
|
2193 |
|
2194 | this._usage = str;
|
2195 | return this;
|
2196 | }
|
2197 |
|
2198 | |
2199 |
|
2200 |
|
2201 |
|
2202 |
|
2203 |
|
2204 |
|
2205 | name(str) {
|
2206 | if (str === undefined) return this._name;
|
2207 | this._name = str;
|
2208 | return this;
|
2209 | }
|
2210 |
|
2211 | |
2212 |
|
2213 |
|
2214 |
|
2215 |
|
2216 |
|
2217 |
|
2218 |
|
2219 |
|
2220 |
|
2221 |
|
2222 |
|
2223 |
|
2224 | nameFromFilename(filename) {
|
2225 | this._name = path.basename(filename, path.extname(filename));
|
2226 |
|
2227 | return this;
|
2228 | }
|
2229 |
|
2230 | |
2231 |
|
2232 |
|
2233 |
|
2234 |
|
2235 |
|
2236 |
|
2237 |
|
2238 |
|
2239 |
|
2240 |
|
2241 |
|
2242 | executableDir(path) {
|
2243 | if (path === undefined) return this._executableDir;
|
2244 | this._executableDir = path;
|
2245 | return this;
|
2246 | }
|
2247 |
|
2248 | |
2249 |
|
2250 |
|
2251 |
|
2252 |
|
2253 |
|
2254 |
|
2255 | helpInformation(contextOptions) {
|
2256 | const helper = this.createHelp();
|
2257 | if (helper.helpWidth === undefined) {
|
2258 | helper.helpWidth =
|
2259 | contextOptions && contextOptions.error
|
2260 | ? this._outputConfiguration.getErrHelpWidth()
|
2261 | : this._outputConfiguration.getOutHelpWidth();
|
2262 | }
|
2263 | return helper.formatHelp(this, helper);
|
2264 | }
|
2265 |
|
2266 | |
2267 |
|
2268 |
|
2269 |
|
2270 | _getHelpContext(contextOptions) {
|
2271 | contextOptions = contextOptions || {};
|
2272 | const context = { error: !!contextOptions.error };
|
2273 | let write;
|
2274 | if (context.error) {
|
2275 | write = (arg) => this._outputConfiguration.writeErr(arg);
|
2276 | } else {
|
2277 | write = (arg) => this._outputConfiguration.writeOut(arg);
|
2278 | }
|
2279 | context.write = contextOptions.write || write;
|
2280 | context.command = this;
|
2281 | return context;
|
2282 | }
|
2283 |
|
2284 | |
2285 |
|
2286 |
|
2287 |
|
2288 |
|
2289 |
|
2290 |
|
2291 |
|
2292 | outputHelp(contextOptions) {
|
2293 | let deprecatedCallback;
|
2294 | if (typeof contextOptions === 'function') {
|
2295 | deprecatedCallback = contextOptions;
|
2296 | contextOptions = undefined;
|
2297 | }
|
2298 | const context = this._getHelpContext(contextOptions);
|
2299 |
|
2300 | this._getCommandAndAncestors()
|
2301 | .reverse()
|
2302 | .forEach((command) => command.emit('beforeAllHelp', context));
|
2303 | this.emit('beforeHelp', context);
|
2304 |
|
2305 | let helpInformation = this.helpInformation(context);
|
2306 | if (deprecatedCallback) {
|
2307 | helpInformation = deprecatedCallback(helpInformation);
|
2308 | if (
|
2309 | typeof helpInformation !== 'string' &&
|
2310 | !Buffer.isBuffer(helpInformation)
|
2311 | ) {
|
2312 | throw new Error('outputHelp callback must return a string or a Buffer');
|
2313 | }
|
2314 | }
|
2315 | context.write(helpInformation);
|
2316 |
|
2317 | if (this._getHelpOption()?.long) {
|
2318 | this.emit(this._getHelpOption().long);
|
2319 | }
|
2320 | this.emit('afterHelp', context);
|
2321 | this._getCommandAndAncestors().forEach((command) =>
|
2322 | command.emit('afterAllHelp', context),
|
2323 | );
|
2324 | }
|
2325 |
|
2326 | |
2327 |
|
2328 |
|
2329 |
|
2330 |
|
2331 |
|
2332 |
|
2333 |
|
2334 |
|
2335 |
|
2336 |
|
2337 |
|
2338 |
|
2339 | helpOption(flags, description) {
|
2340 |
|
2341 | if (typeof flags === 'boolean') {
|
2342 | if (flags) {
|
2343 | this._helpOption = this._helpOption ?? undefined;
|
2344 | } else {
|
2345 | this._helpOption = null;
|
2346 | }
|
2347 | return this;
|
2348 | }
|
2349 |
|
2350 |
|
2351 | flags = flags ?? '-h, --help';
|
2352 | description = description ?? 'display help for command';
|
2353 | this._helpOption = this.createOption(flags, description);
|
2354 |
|
2355 | return this;
|
2356 | }
|
2357 |
|
2358 | |
2359 |
|
2360 |
|
2361 |
|
2362 |
|
2363 |
|
2364 |
|
2365 | _getHelpOption() {
|
2366 |
|
2367 | if (this._helpOption === undefined) {
|
2368 | this.helpOption(undefined, undefined);
|
2369 | }
|
2370 | return this._helpOption;
|
2371 | }
|
2372 |
|
2373 | |
2374 |
|
2375 |
|
2376 |
|
2377 |
|
2378 |
|
2379 |
|
2380 | addHelpOption(option) {
|
2381 | this._helpOption = option;
|
2382 | return this;
|
2383 | }
|
2384 |
|
2385 | |
2386 |
|
2387 |
|
2388 |
|
2389 |
|
2390 |
|
2391 |
|
2392 |
|
2393 | help(contextOptions) {
|
2394 | this.outputHelp(contextOptions);
|
2395 | let exitCode = process.exitCode || 0;
|
2396 | if (
|
2397 | exitCode === 0 &&
|
2398 | contextOptions &&
|
2399 | typeof contextOptions !== 'function' &&
|
2400 | contextOptions.error
|
2401 | ) {
|
2402 | exitCode = 1;
|
2403 | }
|
2404 |
|
2405 | this._exit(exitCode, 'commander.help', '(outputHelp)');
|
2406 | }
|
2407 |
|
2408 | |
2409 |
|
2410 |
|
2411 |
|
2412 |
|
2413 |
|
2414 |
|
2415 |
|
2416 |
|
2417 |
|
2418 | addHelpText(position, text) {
|
2419 | const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
|
2420 | if (!allowedValues.includes(position)) {
|
2421 | throw new Error(`Unexpected value for position to addHelpText.
|
2422 | Expecting one of '${allowedValues.join("', '")}'`);
|
2423 | }
|
2424 | const helpEvent = `${position}Help`;
|
2425 | this.on(helpEvent, (context) => {
|
2426 | let helpStr;
|
2427 | if (typeof text === 'function') {
|
2428 | helpStr = text({ error: context.error, command: context.command });
|
2429 | } else {
|
2430 | helpStr = text;
|
2431 | }
|
2432 |
|
2433 | if (helpStr) {
|
2434 | context.write(`${helpStr}\n`);
|
2435 | }
|
2436 | });
|
2437 | return this;
|
2438 | }
|
2439 |
|
2440 | |
2441 |
|
2442 |
|
2443 |
|
2444 |
|
2445 |
|
2446 |
|
2447 | _outputHelpIfRequested(args) {
|
2448 | const helpOption = this._getHelpOption();
|
2449 | const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
2450 | if (helpRequested) {
|
2451 | this.outputHelp();
|
2452 |
|
2453 | this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
|
2454 | }
|
2455 | }
|
2456 | }
|
2457 |
|
2458 |
|
2459 |
|
2460 |
|
2461 |
|
2462 |
|
2463 |
|
2464 |
|
2465 |
|
2466 | function incrementNodeInspectorPort(args) {
|
2467 |
|
2468 |
|
2469 |
|
2470 |
|
2471 | return args.map((arg) => {
|
2472 | if (!arg.startsWith('--inspect')) {
|
2473 | return arg;
|
2474 | }
|
2475 | let debugOption;
|
2476 | let debugHost = '127.0.0.1';
|
2477 | let debugPort = '9229';
|
2478 | let match;
|
2479 | if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
2480 |
|
2481 | debugOption = match[1];
|
2482 | } else if (
|
2483 | (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
|
2484 | ) {
|
2485 | debugOption = match[1];
|
2486 | if (/^\d+$/.test(match[3])) {
|
2487 |
|
2488 | debugPort = match[3];
|
2489 | } else {
|
2490 |
|
2491 | debugHost = match[3];
|
2492 | }
|
2493 | } else if (
|
2494 | (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
|
2495 | ) {
|
2496 |
|
2497 | debugOption = match[1];
|
2498 | debugHost = match[3];
|
2499 | debugPort = match[4];
|
2500 | }
|
2501 |
|
2502 | if (debugOption && debugPort !== '0') {
|
2503 | return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
2504 | }
|
2505 | return arg;
|
2506 | });
|
2507 | }
|
2508 |
|
2509 | exports.Command = Command;
|