bililive-cli 1.8.0 → 1.9.1

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/index.cjs DELETED
@@ -1,3830 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- var EventEmitter$1 = require('node:events');
5
- var require$$1 = require('node:child_process');
6
- var path$1 = require('node:path');
7
- var fs$1 = require('node:fs');
8
- var process$2 = require('node:process');
9
- var os = require('node:os');
10
-
11
- var commander = {};
12
-
13
- var argument = {};
14
-
15
- var error = {};
16
-
17
- /**
18
- * CommanderError class
19
- */
20
-
21
- let CommanderError$3 = class CommanderError extends Error {
22
- /**
23
- * Constructs the CommanderError class
24
- * @param {number} exitCode suggested exit code which could be used with process.exit
25
- * @param {string} code an id string representing the error
26
- * @param {string} message human-readable description of the error
27
- */
28
- constructor(exitCode, code, message) {
29
- super(message);
30
- // properly capture stack trace in Node.js
31
- Error.captureStackTrace(this, this.constructor);
32
- this.name = this.constructor.name;
33
- this.code = code;
34
- this.exitCode = exitCode;
35
- this.nestedError = undefined;
36
- }
37
- };
38
-
39
- /**
40
- * InvalidArgumentError class
41
- */
42
- let InvalidArgumentError$4 = class InvalidArgumentError extends CommanderError$3 {
43
- /**
44
- * Constructs the InvalidArgumentError class
45
- * @param {string} [message] explanation of why argument is invalid
46
- */
47
- constructor(message) {
48
- super(1, 'commander.invalidArgument', message);
49
- // properly capture stack trace in Node.js
50
- Error.captureStackTrace(this, this.constructor);
51
- this.name = this.constructor.name;
52
- }
53
- };
54
-
55
- error.CommanderError = CommanderError$3;
56
- error.InvalidArgumentError = InvalidArgumentError$4;
57
-
58
- const { InvalidArgumentError: InvalidArgumentError$3 } = error;
59
-
60
- let Argument$3 = class Argument {
61
- /**
62
- * Initialize a new command argument with the given name and description.
63
- * The default is that the argument is required, and you can explicitly
64
- * indicate this with <> around the name. Put [] around the name for an optional argument.
65
- *
66
- * @param {string} name
67
- * @param {string} [description]
68
- */
69
-
70
- constructor(name, description) {
71
- this.description = description || '';
72
- this.variadic = false;
73
- this.parseArg = undefined;
74
- this.defaultValue = undefined;
75
- this.defaultValueDescription = undefined;
76
- this.argChoices = undefined;
77
-
78
- switch (name[0]) {
79
- case '<': // e.g. <required>
80
- this.required = true;
81
- this._name = name.slice(1, -1);
82
- break;
83
- case '[': // e.g. [optional]
84
- this.required = false;
85
- this._name = name.slice(1, -1);
86
- break;
87
- default:
88
- this.required = true;
89
- this._name = name;
90
- break;
91
- }
92
-
93
- if (this._name.length > 3 && this._name.slice(-3) === '...') {
94
- this.variadic = true;
95
- this._name = this._name.slice(0, -3);
96
- }
97
- }
98
-
99
- /**
100
- * Return argument name.
101
- *
102
- * @return {string}
103
- */
104
-
105
- name() {
106
- return this._name;
107
- }
108
-
109
- /**
110
- * @package
111
- */
112
-
113
- _concatValue(value, previous) {
114
- if (previous === this.defaultValue || !Array.isArray(previous)) {
115
- return [value];
116
- }
117
-
118
- return previous.concat(value);
119
- }
120
-
121
- /**
122
- * Set the default value, and optionally supply the description to be displayed in the help.
123
- *
124
- * @param {*} value
125
- * @param {string} [description]
126
- * @return {Argument}
127
- */
128
-
129
- default(value, description) {
130
- this.defaultValue = value;
131
- this.defaultValueDescription = description;
132
- return this;
133
- }
134
-
135
- /**
136
- * Set the custom handler for processing CLI command arguments into argument values.
137
- *
138
- * @param {Function} [fn]
139
- * @return {Argument}
140
- */
141
-
142
- argParser(fn) {
143
- this.parseArg = fn;
144
- return this;
145
- }
146
-
147
- /**
148
- * Only allow argument value to be one of choices.
149
- *
150
- * @param {string[]} values
151
- * @return {Argument}
152
- */
153
-
154
- choices(values) {
155
- this.argChoices = values.slice();
156
- this.parseArg = (arg, previous) => {
157
- if (!this.argChoices.includes(arg)) {
158
- throw new InvalidArgumentError$3(
159
- `Allowed choices are ${this.argChoices.join(', ')}.`,
160
- );
161
- }
162
- if (this.variadic) {
163
- return this._concatValue(arg, previous);
164
- }
165
- return arg;
166
- };
167
- return this;
168
- }
169
-
170
- /**
171
- * Make argument required.
172
- *
173
- * @returns {Argument}
174
- */
175
- argRequired() {
176
- this.required = true;
177
- return this;
178
- }
179
-
180
- /**
181
- * Make argument optional.
182
- *
183
- * @returns {Argument}
184
- */
185
- argOptional() {
186
- this.required = false;
187
- return this;
188
- }
189
- };
190
-
191
- /**
192
- * Takes an argument and returns its human readable equivalent for help usage.
193
- *
194
- * @param {Argument} arg
195
- * @return {string}
196
- * @private
197
- */
198
-
199
- function humanReadableArgName$2(arg) {
200
- const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
201
-
202
- return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
203
- }
204
-
205
- argument.Argument = Argument$3;
206
- argument.humanReadableArgName = humanReadableArgName$2;
207
-
208
- var command = {};
209
-
210
- var help = {};
211
-
212
- const { humanReadableArgName: humanReadableArgName$1 } = argument;
213
-
214
- /**
215
- * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
216
- * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
217
- * @typedef { import("./argument.js").Argument } Argument
218
- * @typedef { import("./command.js").Command } Command
219
- * @typedef { import("./option.js").Option } Option
220
- */
221
-
222
- // Although this is a class, methods are static in style to allow override using subclass or just functions.
223
- let Help$3 = class Help {
224
- constructor() {
225
- this.helpWidth = undefined;
226
- this.sortSubcommands = false;
227
- this.sortOptions = false;
228
- this.showGlobalOptions = false;
229
- }
230
-
231
- /**
232
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
233
- *
234
- * @param {Command} cmd
235
- * @returns {Command[]}
236
- */
237
-
238
- visibleCommands(cmd) {
239
- const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
240
- const helpCommand = cmd._getHelpCommand();
241
- if (helpCommand && !helpCommand._hidden) {
242
- visibleCommands.push(helpCommand);
243
- }
244
- if (this.sortSubcommands) {
245
- visibleCommands.sort((a, b) => {
246
- // @ts-ignore: because overloaded return type
247
- return a.name().localeCompare(b.name());
248
- });
249
- }
250
- return visibleCommands;
251
- }
252
-
253
- /**
254
- * Compare options for sort.
255
- *
256
- * @param {Option} a
257
- * @param {Option} b
258
- * @returns {number}
259
- */
260
- compareOptions(a, b) {
261
- const getSortKey = (option) => {
262
- // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
263
- return option.short
264
- ? option.short.replace(/^-/, '')
265
- : option.long.replace(/^--/, '');
266
- };
267
- return getSortKey(a).localeCompare(getSortKey(b));
268
- }
269
-
270
- /**
271
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
272
- *
273
- * @param {Command} cmd
274
- * @returns {Option[]}
275
- */
276
-
277
- visibleOptions(cmd) {
278
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
279
- // Built-in help option.
280
- const helpOption = cmd._getHelpOption();
281
- if (helpOption && !helpOption.hidden) {
282
- // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
283
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
284
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
285
- if (!removeShort && !removeLong) {
286
- visibleOptions.push(helpOption); // no changes needed
287
- } else if (helpOption.long && !removeLong) {
288
- visibleOptions.push(
289
- cmd.createOption(helpOption.long, helpOption.description),
290
- );
291
- } else if (helpOption.short && !removeShort) {
292
- visibleOptions.push(
293
- cmd.createOption(helpOption.short, helpOption.description),
294
- );
295
- }
296
- }
297
- if (this.sortOptions) {
298
- visibleOptions.sort(this.compareOptions);
299
- }
300
- return visibleOptions;
301
- }
302
-
303
- /**
304
- * Get an array of the visible global options. (Not including help.)
305
- *
306
- * @param {Command} cmd
307
- * @returns {Option[]}
308
- */
309
-
310
- visibleGlobalOptions(cmd) {
311
- if (!this.showGlobalOptions) return [];
312
-
313
- const globalOptions = [];
314
- for (
315
- let ancestorCmd = cmd.parent;
316
- ancestorCmd;
317
- ancestorCmd = ancestorCmd.parent
318
- ) {
319
- const visibleOptions = ancestorCmd.options.filter(
320
- (option) => !option.hidden,
321
- );
322
- globalOptions.push(...visibleOptions);
323
- }
324
- if (this.sortOptions) {
325
- globalOptions.sort(this.compareOptions);
326
- }
327
- return globalOptions;
328
- }
329
-
330
- /**
331
- * Get an array of the arguments if any have a description.
332
- *
333
- * @param {Command} cmd
334
- * @returns {Argument[]}
335
- */
336
-
337
- visibleArguments(cmd) {
338
- // Side effect! Apply the legacy descriptions before the arguments are displayed.
339
- if (cmd._argsDescription) {
340
- cmd.registeredArguments.forEach((argument) => {
341
- argument.description =
342
- argument.description || cmd._argsDescription[argument.name()] || '';
343
- });
344
- }
345
-
346
- // If there are any arguments with a description then return all the arguments.
347
- if (cmd.registeredArguments.find((argument) => argument.description)) {
348
- return cmd.registeredArguments;
349
- }
350
- return [];
351
- }
352
-
353
- /**
354
- * Get the command term to show in the list of subcommands.
355
- *
356
- * @param {Command} cmd
357
- * @returns {string}
358
- */
359
-
360
- subcommandTerm(cmd) {
361
- // Legacy. Ignores custom usage string, and nested commands.
362
- const args = cmd.registeredArguments
363
- .map((arg) => humanReadableArgName$1(arg))
364
- .join(' ');
365
- return (
366
- cmd._name +
367
- (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
368
- (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
369
- (args ? ' ' + args : '')
370
- );
371
- }
372
-
373
- /**
374
- * Get the option term to show in the list of options.
375
- *
376
- * @param {Option} option
377
- * @returns {string}
378
- */
379
-
380
- optionTerm(option) {
381
- return option.flags;
382
- }
383
-
384
- /**
385
- * Get the argument term to show in the list of arguments.
386
- *
387
- * @param {Argument} argument
388
- * @returns {string}
389
- */
390
-
391
- argumentTerm(argument) {
392
- return argument.name();
393
- }
394
-
395
- /**
396
- * Get the longest command term length.
397
- *
398
- * @param {Command} cmd
399
- * @param {Help} helper
400
- * @returns {number}
401
- */
402
-
403
- longestSubcommandTermLength(cmd, helper) {
404
- return helper.visibleCommands(cmd).reduce((max, command) => {
405
- return Math.max(max, helper.subcommandTerm(command).length);
406
- }, 0);
407
- }
408
-
409
- /**
410
- * Get the longest option term length.
411
- *
412
- * @param {Command} cmd
413
- * @param {Help} helper
414
- * @returns {number}
415
- */
416
-
417
- longestOptionTermLength(cmd, helper) {
418
- return helper.visibleOptions(cmd).reduce((max, option) => {
419
- return Math.max(max, helper.optionTerm(option).length);
420
- }, 0);
421
- }
422
-
423
- /**
424
- * Get the longest global option term length.
425
- *
426
- * @param {Command} cmd
427
- * @param {Help} helper
428
- * @returns {number}
429
- */
430
-
431
- longestGlobalOptionTermLength(cmd, helper) {
432
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
433
- return Math.max(max, helper.optionTerm(option).length);
434
- }, 0);
435
- }
436
-
437
- /**
438
- * Get the longest argument term length.
439
- *
440
- * @param {Command} cmd
441
- * @param {Help} helper
442
- * @returns {number}
443
- */
444
-
445
- longestArgumentTermLength(cmd, helper) {
446
- return helper.visibleArguments(cmd).reduce((max, argument) => {
447
- return Math.max(max, helper.argumentTerm(argument).length);
448
- }, 0);
449
- }
450
-
451
- /**
452
- * Get the command usage to be displayed at the top of the built-in help.
453
- *
454
- * @param {Command} cmd
455
- * @returns {string}
456
- */
457
-
458
- commandUsage(cmd) {
459
- // Usage
460
- let cmdName = cmd._name;
461
- if (cmd._aliases[0]) {
462
- cmdName = cmdName + '|' + cmd._aliases[0];
463
- }
464
- let ancestorCmdNames = '';
465
- for (
466
- let ancestorCmd = cmd.parent;
467
- ancestorCmd;
468
- ancestorCmd = ancestorCmd.parent
469
- ) {
470
- ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
471
- }
472
- return ancestorCmdNames + cmdName + ' ' + cmd.usage();
473
- }
474
-
475
- /**
476
- * Get the description for the command.
477
- *
478
- * @param {Command} cmd
479
- * @returns {string}
480
- */
481
-
482
- commandDescription(cmd) {
483
- // @ts-ignore: because overloaded return type
484
- return cmd.description();
485
- }
486
-
487
- /**
488
- * Get the subcommand summary to show in the list of subcommands.
489
- * (Fallback to description for backwards compatibility.)
490
- *
491
- * @param {Command} cmd
492
- * @returns {string}
493
- */
494
-
495
- subcommandDescription(cmd) {
496
- // @ts-ignore: because overloaded return type
497
- return cmd.summary() || cmd.description();
498
- }
499
-
500
- /**
501
- * Get the option description to show in the list of options.
502
- *
503
- * @param {Option} option
504
- * @return {string}
505
- */
506
-
507
- optionDescription(option) {
508
- const extraInfo = [];
509
-
510
- if (option.argChoices) {
511
- extraInfo.push(
512
- // use stringify to match the display of the default value
513
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
514
- );
515
- }
516
- if (option.defaultValue !== undefined) {
517
- // default for boolean and negated more for programmer than end user,
518
- // but show true/false for boolean option as may be for hand-rolled env or config processing.
519
- const showDefault =
520
- option.required ||
521
- option.optional ||
522
- (option.isBoolean() && typeof option.defaultValue === 'boolean');
523
- if (showDefault) {
524
- extraInfo.push(
525
- `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
526
- );
527
- }
528
- }
529
- // preset for boolean and negated are more for programmer than end user
530
- if (option.presetArg !== undefined && option.optional) {
531
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
532
- }
533
- if (option.envVar !== undefined) {
534
- extraInfo.push(`env: ${option.envVar}`);
535
- }
536
- if (extraInfo.length > 0) {
537
- return `${option.description} (${extraInfo.join(', ')})`;
538
- }
539
-
540
- return option.description;
541
- }
542
-
543
- /**
544
- * Get the argument description to show in the list of arguments.
545
- *
546
- * @param {Argument} argument
547
- * @return {string}
548
- */
549
-
550
- argumentDescription(argument) {
551
- const extraInfo = [];
552
- if (argument.argChoices) {
553
- extraInfo.push(
554
- // use stringify to match the display of the default value
555
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
556
- );
557
- }
558
- if (argument.defaultValue !== undefined) {
559
- extraInfo.push(
560
- `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
561
- );
562
- }
563
- if (extraInfo.length > 0) {
564
- const extraDescripton = `(${extraInfo.join(', ')})`;
565
- if (argument.description) {
566
- return `${argument.description} ${extraDescripton}`;
567
- }
568
- return extraDescripton;
569
- }
570
- return argument.description;
571
- }
572
-
573
- /**
574
- * Generate the built-in help text.
575
- *
576
- * @param {Command} cmd
577
- * @param {Help} helper
578
- * @returns {string}
579
- */
580
-
581
- formatHelp(cmd, helper) {
582
- const termWidth = helper.padWidth(cmd, helper);
583
- const helpWidth = helper.helpWidth || 80;
584
- const itemIndentWidth = 2;
585
- const itemSeparatorWidth = 2; // between term and description
586
- function formatItem(term, description) {
587
- if (description) {
588
- const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
589
- return helper.wrap(
590
- fullText,
591
- helpWidth - itemIndentWidth,
592
- termWidth + itemSeparatorWidth,
593
- );
594
- }
595
- return term;
596
- }
597
- function formatList(textArray) {
598
- return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
599
- }
600
-
601
- // Usage
602
- let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
603
-
604
- // Description
605
- const commandDescription = helper.commandDescription(cmd);
606
- if (commandDescription.length > 0) {
607
- output = output.concat([
608
- helper.wrap(commandDescription, helpWidth, 0),
609
- '',
610
- ]);
611
- }
612
-
613
- // Arguments
614
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
615
- return formatItem(
616
- helper.argumentTerm(argument),
617
- helper.argumentDescription(argument),
618
- );
619
- });
620
- if (argumentList.length > 0) {
621
- output = output.concat(['Arguments:', formatList(argumentList), '']);
622
- }
623
-
624
- // Options
625
- const optionList = helper.visibleOptions(cmd).map((option) => {
626
- return formatItem(
627
- helper.optionTerm(option),
628
- helper.optionDescription(option),
629
- );
630
- });
631
- if (optionList.length > 0) {
632
- output = output.concat(['Options:', formatList(optionList), '']);
633
- }
634
-
635
- if (this.showGlobalOptions) {
636
- const globalOptionList = helper
637
- .visibleGlobalOptions(cmd)
638
- .map((option) => {
639
- return formatItem(
640
- helper.optionTerm(option),
641
- helper.optionDescription(option),
642
- );
643
- });
644
- if (globalOptionList.length > 0) {
645
- output = output.concat([
646
- 'Global Options:',
647
- formatList(globalOptionList),
648
- '',
649
- ]);
650
- }
651
- }
652
-
653
- // Commands
654
- const commandList = helper.visibleCommands(cmd).map((cmd) => {
655
- return formatItem(
656
- helper.subcommandTerm(cmd),
657
- helper.subcommandDescription(cmd),
658
- );
659
- });
660
- if (commandList.length > 0) {
661
- output = output.concat(['Commands:', formatList(commandList), '']);
662
- }
663
-
664
- return output.join('\n');
665
- }
666
-
667
- /**
668
- * Calculate the pad width from the maximum term length.
669
- *
670
- * @param {Command} cmd
671
- * @param {Help} helper
672
- * @returns {number}
673
- */
674
-
675
- padWidth(cmd, helper) {
676
- return Math.max(
677
- helper.longestOptionTermLength(cmd, helper),
678
- helper.longestGlobalOptionTermLength(cmd, helper),
679
- helper.longestSubcommandTermLength(cmd, helper),
680
- helper.longestArgumentTermLength(cmd, helper),
681
- );
682
- }
683
-
684
- /**
685
- * Wrap the given string to width characters per line, with lines after the first indented.
686
- * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
687
- *
688
- * @param {string} str
689
- * @param {number} width
690
- * @param {number} indent
691
- * @param {number} [minColumnWidth=40]
692
- * @return {string}
693
- *
694
- */
695
-
696
- wrap(str, width, indent, minColumnWidth = 40) {
697
- // Full \s characters, minus the linefeeds.
698
- const indents =
699
- ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';
700
- // Detect manually wrapped and indented strings by searching for line break followed by spaces.
701
- const manualIndent = new RegExp(`[\\n][${indents}]+`);
702
- if (str.match(manualIndent)) return str;
703
- // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
704
- const columnWidth = width - indent;
705
- if (columnWidth < minColumnWidth) return str;
706
-
707
- const leadingStr = str.slice(0, indent);
708
- const columnText = str.slice(indent).replace('\r\n', '\n');
709
- const indentString = ' '.repeat(indent);
710
- const zeroWidthSpace = '\u200B';
711
- const breaks = `\\s${zeroWidthSpace}`;
712
- // Match line end (so empty lines don't collapse),
713
- // or as much text as will fit in column, or excess text up to first break.
714
- const regex = new RegExp(
715
- `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
716
- 'g',
717
- );
718
- const lines = columnText.match(regex) || [];
719
- return (
720
- leadingStr +
721
- lines
722
- .map((line, i) => {
723
- if (line === '\n') return ''; // preserve empty lines
724
- return (i > 0 ? indentString : '') + line.trimEnd();
725
- })
726
- .join('\n')
727
- );
728
- }
729
- };
730
-
731
- help.Help = Help$3;
732
-
733
- var option = {};
734
-
735
- const { InvalidArgumentError: InvalidArgumentError$2 } = error;
736
-
737
- let Option$3 = class Option {
738
- /**
739
- * Initialize a new `Option` with the given `flags` and `description`.
740
- *
741
- * @param {string} flags
742
- * @param {string} [description]
743
- */
744
-
745
- constructor(flags, description) {
746
- this.flags = flags;
747
- this.description = description || '';
748
-
749
- this.required = flags.includes('<'); // A value must be supplied when the option is specified.
750
- this.optional = flags.includes('['); // A value is optional when the option is specified.
751
- // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
752
- this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
753
- this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
754
- const optionFlags = splitOptionFlags(flags);
755
- this.short = optionFlags.shortFlag;
756
- this.long = optionFlags.longFlag;
757
- this.negate = false;
758
- if (this.long) {
759
- this.negate = this.long.startsWith('--no-');
760
- }
761
- this.defaultValue = undefined;
762
- this.defaultValueDescription = undefined;
763
- this.presetArg = undefined;
764
- this.envVar = undefined;
765
- this.parseArg = undefined;
766
- this.hidden = false;
767
- this.argChoices = undefined;
768
- this.conflictsWith = [];
769
- this.implied = undefined;
770
- }
771
-
772
- /**
773
- * Set the default value, and optionally supply the description to be displayed in the help.
774
- *
775
- * @param {*} value
776
- * @param {string} [description]
777
- * @return {Option}
778
- */
779
-
780
- default(value, description) {
781
- this.defaultValue = value;
782
- this.defaultValueDescription = description;
783
- return this;
784
- }
785
-
786
- /**
787
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
788
- * The custom processing (parseArg) is called.
789
- *
790
- * @example
791
- * new Option('--color').default('GREYSCALE').preset('RGB');
792
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
793
- *
794
- * @param {*} arg
795
- * @return {Option}
796
- */
797
-
798
- preset(arg) {
799
- this.presetArg = arg;
800
- return this;
801
- }
802
-
803
- /**
804
- * Add option name(s) that conflict with this option.
805
- * An error will be displayed if conflicting options are found during parsing.
806
- *
807
- * @example
808
- * new Option('--rgb').conflicts('cmyk');
809
- * new Option('--js').conflicts(['ts', 'jsx']);
810
- *
811
- * @param {(string | string[])} names
812
- * @return {Option}
813
- */
814
-
815
- conflicts(names) {
816
- this.conflictsWith = this.conflictsWith.concat(names);
817
- return this;
818
- }
819
-
820
- /**
821
- * Specify implied option values for when this option is set and the implied options are not.
822
- *
823
- * The custom processing (parseArg) is not called on the implied values.
824
- *
825
- * @example
826
- * program
827
- * .addOption(new Option('--log', 'write logging information to file'))
828
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
829
- *
830
- * @param {object} impliedOptionValues
831
- * @return {Option}
832
- */
833
- implies(impliedOptionValues) {
834
- let newImplied = impliedOptionValues;
835
- if (typeof impliedOptionValues === 'string') {
836
- // string is not documented, but easy mistake and we can do what user probably intended.
837
- newImplied = { [impliedOptionValues]: true };
838
- }
839
- this.implied = Object.assign(this.implied || {}, newImplied);
840
- return this;
841
- }
842
-
843
- /**
844
- * Set environment variable to check for option value.
845
- *
846
- * An environment variable is only used if when processed the current option value is
847
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
848
- *
849
- * @param {string} name
850
- * @return {Option}
851
- */
852
-
853
- env(name) {
854
- this.envVar = name;
855
- return this;
856
- }
857
-
858
- /**
859
- * Set the custom handler for processing CLI option arguments into option values.
860
- *
861
- * @param {Function} [fn]
862
- * @return {Option}
863
- */
864
-
865
- argParser(fn) {
866
- this.parseArg = fn;
867
- return this;
868
- }
869
-
870
- /**
871
- * Whether the option is mandatory and must have a value after parsing.
872
- *
873
- * @param {boolean} [mandatory=true]
874
- * @return {Option}
875
- */
876
-
877
- makeOptionMandatory(mandatory = true) {
878
- this.mandatory = !!mandatory;
879
- return this;
880
- }
881
-
882
- /**
883
- * Hide option in help.
884
- *
885
- * @param {boolean} [hide=true]
886
- * @return {Option}
887
- */
888
-
889
- hideHelp(hide = true) {
890
- this.hidden = !!hide;
891
- return this;
892
- }
893
-
894
- /**
895
- * @package
896
- */
897
-
898
- _concatValue(value, previous) {
899
- if (previous === this.defaultValue || !Array.isArray(previous)) {
900
- return [value];
901
- }
902
-
903
- return previous.concat(value);
904
- }
905
-
906
- /**
907
- * Only allow option value to be one of choices.
908
- *
909
- * @param {string[]} values
910
- * @return {Option}
911
- */
912
-
913
- choices(values) {
914
- this.argChoices = values.slice();
915
- this.parseArg = (arg, previous) => {
916
- if (!this.argChoices.includes(arg)) {
917
- throw new InvalidArgumentError$2(
918
- `Allowed choices are ${this.argChoices.join(', ')}.`,
919
- );
920
- }
921
- if (this.variadic) {
922
- return this._concatValue(arg, previous);
923
- }
924
- return arg;
925
- };
926
- return this;
927
- }
928
-
929
- /**
930
- * Return option name.
931
- *
932
- * @return {string}
933
- */
934
-
935
- name() {
936
- if (this.long) {
937
- return this.long.replace(/^--/, '');
938
- }
939
- return this.short.replace(/^-/, '');
940
- }
941
-
942
- /**
943
- * Return option name, in a camelcase format that can be used
944
- * as a object attribute key.
945
- *
946
- * @return {string}
947
- */
948
-
949
- attributeName() {
950
- return camelcase(this.name().replace(/^no-/, ''));
951
- }
952
-
953
- /**
954
- * Check if `arg` matches the short or long flag.
955
- *
956
- * @param {string} arg
957
- * @return {boolean}
958
- * @package
959
- */
960
-
961
- is(arg) {
962
- return this.short === arg || this.long === arg;
963
- }
964
-
965
- /**
966
- * Return whether a boolean option.
967
- *
968
- * Options are one of boolean, negated, required argument, or optional argument.
969
- *
970
- * @return {boolean}
971
- * @package
972
- */
973
-
974
- isBoolean() {
975
- return !this.required && !this.optional && !this.negate;
976
- }
977
- };
978
-
979
- /**
980
- * This class is to make it easier to work with dual options, without changing the existing
981
- * implementation. We support separate dual options for separate positive and negative options,
982
- * like `--build` and `--no-build`, which share a single option value. This works nicely for some
983
- * use cases, but is tricky for others where we want separate behaviours despite
984
- * the single shared option value.
985
- */
986
- let DualOptions$1 = class DualOptions {
987
- /**
988
- * @param {Option[]} options
989
- */
990
- constructor(options) {
991
- this.positiveOptions = new Map();
992
- this.negativeOptions = new Map();
993
- this.dualOptions = new Set();
994
- options.forEach((option) => {
995
- if (option.negate) {
996
- this.negativeOptions.set(option.attributeName(), option);
997
- } else {
998
- this.positiveOptions.set(option.attributeName(), option);
999
- }
1000
- });
1001
- this.negativeOptions.forEach((value, key) => {
1002
- if (this.positiveOptions.has(key)) {
1003
- this.dualOptions.add(key);
1004
- }
1005
- });
1006
- }
1007
-
1008
- /**
1009
- * Did the value come from the option, and not from possible matching dual option?
1010
- *
1011
- * @param {*} value
1012
- * @param {Option} option
1013
- * @returns {boolean}
1014
- */
1015
- valueFromOption(value, option) {
1016
- const optionKey = option.attributeName();
1017
- if (!this.dualOptions.has(optionKey)) return true;
1018
-
1019
- // Use the value to deduce if (probably) came from the option.
1020
- const preset = this.negativeOptions.get(optionKey).presetArg;
1021
- const negativeValue = preset !== undefined ? preset : false;
1022
- return option.negate === (negativeValue === value);
1023
- }
1024
- };
1025
-
1026
- /**
1027
- * Convert string from kebab-case to camelCase.
1028
- *
1029
- * @param {string} str
1030
- * @return {string}
1031
- * @private
1032
- */
1033
-
1034
- function camelcase(str) {
1035
- return str.split('-').reduce((str, word) => {
1036
- return str + word[0].toUpperCase() + word.slice(1);
1037
- });
1038
- }
1039
-
1040
- /**
1041
- * Split the short and long flag out of something like '-m,--mixed <value>'
1042
- *
1043
- * @private
1044
- */
1045
-
1046
- function splitOptionFlags(flags) {
1047
- let shortFlag;
1048
- let longFlag;
1049
- // Use original very loose parsing to maintain backwards compatibility for now,
1050
- // which allowed for example unintended `-sw, --short-word` [sic].
1051
- const flagParts = flags.split(/[ |,]+/);
1052
- if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
1053
- shortFlag = flagParts.shift();
1054
- longFlag = flagParts.shift();
1055
- // Add support for lone short flag without significantly changing parsing!
1056
- if (!shortFlag && /^-[^-]$/.test(longFlag)) {
1057
- shortFlag = longFlag;
1058
- longFlag = undefined;
1059
- }
1060
- return { shortFlag, longFlag };
1061
- }
1062
-
1063
- option.Option = Option$3;
1064
- option.DualOptions = DualOptions$1;
1065
-
1066
- var suggestSimilar$2 = {};
1067
-
1068
- const maxDistance = 3;
1069
-
1070
- function editDistance(a, b) {
1071
- // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
1072
- // Calculating optimal string alignment distance, no substring is edited more than once.
1073
- // (Simple implementation.)
1074
-
1075
- // Quick early exit, return worst case.
1076
- if (Math.abs(a.length - b.length) > maxDistance)
1077
- return Math.max(a.length, b.length);
1078
-
1079
- // distance between prefix substrings of a and b
1080
- const d = [];
1081
-
1082
- // pure deletions turn a into empty string
1083
- for (let i = 0; i <= a.length; i++) {
1084
- d[i] = [i];
1085
- }
1086
- // pure insertions turn empty string into b
1087
- for (let j = 0; j <= b.length; j++) {
1088
- d[0][j] = j;
1089
- }
1090
-
1091
- // fill matrix
1092
- for (let j = 1; j <= b.length; j++) {
1093
- for (let i = 1; i <= a.length; i++) {
1094
- let cost = 1;
1095
- if (a[i - 1] === b[j - 1]) {
1096
- cost = 0;
1097
- } else {
1098
- cost = 1;
1099
- }
1100
- d[i][j] = Math.min(
1101
- d[i - 1][j] + 1, // deletion
1102
- d[i][j - 1] + 1, // insertion
1103
- d[i - 1][j - 1] + cost, // substitution
1104
- );
1105
- // transposition
1106
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1107
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1108
- }
1109
- }
1110
- }
1111
-
1112
- return d[a.length][b.length];
1113
- }
1114
-
1115
- /**
1116
- * Find close matches, restricted to same number of edits.
1117
- *
1118
- * @param {string} word
1119
- * @param {string[]} candidates
1120
- * @returns {string}
1121
- */
1122
-
1123
- function suggestSimilar$1(word, candidates) {
1124
- if (!candidates || candidates.length === 0) return '';
1125
- // remove possible duplicates
1126
- candidates = Array.from(new Set(candidates));
1127
-
1128
- const searchingOptions = word.startsWith('--');
1129
- if (searchingOptions) {
1130
- word = word.slice(2);
1131
- candidates = candidates.map((candidate) => candidate.slice(2));
1132
- }
1133
-
1134
- let similar = [];
1135
- let bestDistance = maxDistance;
1136
- const minSimilarity = 0.4;
1137
- candidates.forEach((candidate) => {
1138
- if (candidate.length <= 1) return; // no one character guesses
1139
-
1140
- const distance = editDistance(word, candidate);
1141
- const length = Math.max(word.length, candidate.length);
1142
- const similarity = (length - distance) / length;
1143
- if (similarity > minSimilarity) {
1144
- if (distance < bestDistance) {
1145
- // better edit distance, throw away previous worse matches
1146
- bestDistance = distance;
1147
- similar = [candidate];
1148
- } else if (distance === bestDistance) {
1149
- similar.push(candidate);
1150
- }
1151
- }
1152
- });
1153
-
1154
- similar.sort((a, b) => a.localeCompare(b));
1155
- if (searchingOptions) {
1156
- similar = similar.map((candidate) => `--${candidate}`);
1157
- }
1158
-
1159
- if (similar.length > 1) {
1160
- return `\n(Did you mean one of ${similar.join(', ')}?)`;
1161
- }
1162
- if (similar.length === 1) {
1163
- return `\n(Did you mean ${similar[0]}?)`;
1164
- }
1165
- return '';
1166
- }
1167
-
1168
- suggestSimilar$2.suggestSimilar = suggestSimilar$1;
1169
-
1170
- const EventEmitter = EventEmitter$1.EventEmitter;
1171
- const childProcess = require$$1;
1172
- const path = path$1;
1173
- const fs = fs$1;
1174
- const process$1 = process$2;
1175
-
1176
- const { Argument: Argument$2, humanReadableArgName } = argument;
1177
- const { CommanderError: CommanderError$2 } = error;
1178
- const { Help: Help$2 } = help;
1179
- const { Option: Option$2, DualOptions } = option;
1180
- const { suggestSimilar } = suggestSimilar$2;
1181
-
1182
- let Command$2 = class Command extends EventEmitter {
1183
- /**
1184
- * Initialize a new `Command`.
1185
- *
1186
- * @param {string} [name]
1187
- */
1188
-
1189
- constructor(name) {
1190
- super();
1191
- /** @type {Command[]} */
1192
- this.commands = [];
1193
- /** @type {Option[]} */
1194
- this.options = [];
1195
- this.parent = null;
1196
- this._allowUnknownOption = false;
1197
- this._allowExcessArguments = true;
1198
- /** @type {Argument[]} */
1199
- this.registeredArguments = [];
1200
- this._args = this.registeredArguments; // deprecated old name
1201
- /** @type {string[]} */
1202
- this.args = []; // cli args with options removed
1203
- this.rawArgs = [];
1204
- this.processedArgs = []; // like .args but after custom processing and collecting variadic
1205
- this._scriptPath = null;
1206
- this._name = name || '';
1207
- this._optionValues = {};
1208
- this._optionValueSources = {}; // default, env, cli etc
1209
- this._storeOptionsAsProperties = false;
1210
- this._actionHandler = null;
1211
- this._executableHandler = false;
1212
- this._executableFile = null; // custom name for executable
1213
- this._executableDir = null; // custom search directory for subcommands
1214
- this._defaultCommandName = null;
1215
- this._exitCallback = null;
1216
- this._aliases = [];
1217
- this._combineFlagAndOptionalValue = true;
1218
- this._description = '';
1219
- this._summary = '';
1220
- this._argsDescription = undefined; // legacy
1221
- this._enablePositionalOptions = false;
1222
- this._passThroughOptions = false;
1223
- this._lifeCycleHooks = {}; // a hash of arrays
1224
- /** @type {(boolean | string)} */
1225
- this._showHelpAfterError = false;
1226
- this._showSuggestionAfterError = true;
1227
-
1228
- // see .configureOutput() for docs
1229
- this._outputConfiguration = {
1230
- writeOut: (str) => process$1.stdout.write(str),
1231
- writeErr: (str) => process$1.stderr.write(str),
1232
- getOutHelpWidth: () =>
1233
- process$1.stdout.isTTY ? process$1.stdout.columns : undefined,
1234
- getErrHelpWidth: () =>
1235
- process$1.stderr.isTTY ? process$1.stderr.columns : undefined,
1236
- outputError: (str, write) => write(str),
1237
- };
1238
-
1239
- this._hidden = false;
1240
- /** @type {(Option | null | undefined)} */
1241
- this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
1242
- this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
1243
- /** @type {Command} */
1244
- this._helpCommand = undefined; // lazy initialised, inherited
1245
- this._helpConfiguration = {};
1246
- }
1247
-
1248
- /**
1249
- * Copy settings that are useful to have in common across root command and subcommands.
1250
- *
1251
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1252
- *
1253
- * @param {Command} sourceCommand
1254
- * @return {Command} `this` command for chaining
1255
- */
1256
- copyInheritedSettings(sourceCommand) {
1257
- this._outputConfiguration = sourceCommand._outputConfiguration;
1258
- this._helpOption = sourceCommand._helpOption;
1259
- this._helpCommand = sourceCommand._helpCommand;
1260
- this._helpConfiguration = sourceCommand._helpConfiguration;
1261
- this._exitCallback = sourceCommand._exitCallback;
1262
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1263
- this._combineFlagAndOptionalValue =
1264
- sourceCommand._combineFlagAndOptionalValue;
1265
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1266
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1267
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1268
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1269
-
1270
- return this;
1271
- }
1272
-
1273
- /**
1274
- * @returns {Command[]}
1275
- * @private
1276
- */
1277
-
1278
- _getCommandAndAncestors() {
1279
- const result = [];
1280
- // eslint-disable-next-line @typescript-eslint/no-this-alias
1281
- for (let command = this; command; command = command.parent) {
1282
- result.push(command);
1283
- }
1284
- return result;
1285
- }
1286
-
1287
- /**
1288
- * Define a command.
1289
- *
1290
- * There are two styles of command: pay attention to where to put the description.
1291
- *
1292
- * @example
1293
- * // Command implemented using action handler (description is supplied separately to `.command`)
1294
- * program
1295
- * .command('clone <source> [destination]')
1296
- * .description('clone a repository into a newly created directory')
1297
- * .action((source, destination) => {
1298
- * console.log('clone command called');
1299
- * });
1300
- *
1301
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1302
- * program
1303
- * .command('start <service>', 'start named service')
1304
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1305
- *
1306
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1307
- * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1308
- * @param {object} [execOpts] - configuration options (for executable)
1309
- * @return {Command} returns new command for action handler, or `this` for executable command
1310
- */
1311
-
1312
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1313
- let desc = actionOptsOrExecDesc;
1314
- let opts = execOpts;
1315
- if (typeof desc === 'object' && desc !== null) {
1316
- opts = desc;
1317
- desc = null;
1318
- }
1319
- opts = opts || {};
1320
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1321
-
1322
- const cmd = this.createCommand(name);
1323
- if (desc) {
1324
- cmd.description(desc);
1325
- cmd._executableHandler = true;
1326
- }
1327
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1328
- cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
1329
- cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
1330
- if (args) cmd.arguments(args);
1331
- this._registerCommand(cmd);
1332
- cmd.parent = this;
1333
- cmd.copyInheritedSettings(this);
1334
-
1335
- if (desc) return this;
1336
- return cmd;
1337
- }
1338
-
1339
- /**
1340
- * Factory routine to create a new unattached command.
1341
- *
1342
- * See .command() for creating an attached subcommand, which uses this routine to
1343
- * create the command. You can override createCommand to customise subcommands.
1344
- *
1345
- * @param {string} [name]
1346
- * @return {Command} new command
1347
- */
1348
-
1349
- createCommand(name) {
1350
- return new Command(name);
1351
- }
1352
-
1353
- /**
1354
- * You can customise the help with a subclass of Help by overriding createHelp,
1355
- * or by overriding Help properties using configureHelp().
1356
- *
1357
- * @return {Help}
1358
- */
1359
-
1360
- createHelp() {
1361
- return Object.assign(new Help$2(), this.configureHelp());
1362
- }
1363
-
1364
- /**
1365
- * You can customise the help by overriding Help properties using configureHelp(),
1366
- * or with a subclass of Help by overriding createHelp().
1367
- *
1368
- * @param {object} [configuration] - configuration options
1369
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1370
- */
1371
-
1372
- configureHelp(configuration) {
1373
- if (configuration === undefined) return this._helpConfiguration;
1374
-
1375
- this._helpConfiguration = configuration;
1376
- return this;
1377
- }
1378
-
1379
- /**
1380
- * The default output goes to stdout and stderr. You can customise this for special
1381
- * applications. You can also customise the display of errors by overriding outputError.
1382
- *
1383
- * The configuration properties are all functions:
1384
- *
1385
- * // functions to change where being written, stdout and stderr
1386
- * writeOut(str)
1387
- * writeErr(str)
1388
- * // matching functions to specify width for wrapping help
1389
- * getOutHelpWidth()
1390
- * getErrHelpWidth()
1391
- * // functions based on what is being written out
1392
- * outputError(str, write) // used for displaying errors, and not used for displaying help
1393
- *
1394
- * @param {object} [configuration] - configuration options
1395
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1396
- */
1397
-
1398
- configureOutput(configuration) {
1399
- if (configuration === undefined) return this._outputConfiguration;
1400
-
1401
- Object.assign(this._outputConfiguration, configuration);
1402
- return this;
1403
- }
1404
-
1405
- /**
1406
- * Display the help or a custom message after an error occurs.
1407
- *
1408
- * @param {(boolean|string)} [displayHelp]
1409
- * @return {Command} `this` command for chaining
1410
- */
1411
- showHelpAfterError(displayHelp = true) {
1412
- if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
1413
- this._showHelpAfterError = displayHelp;
1414
- return this;
1415
- }
1416
-
1417
- /**
1418
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1419
- *
1420
- * @param {boolean} [displaySuggestion]
1421
- * @return {Command} `this` command for chaining
1422
- */
1423
- showSuggestionAfterError(displaySuggestion = true) {
1424
- this._showSuggestionAfterError = !!displaySuggestion;
1425
- return this;
1426
- }
1427
-
1428
- /**
1429
- * Add a prepared subcommand.
1430
- *
1431
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1432
- *
1433
- * @param {Command} cmd - new subcommand
1434
- * @param {object} [opts] - configuration options
1435
- * @return {Command} `this` command for chaining
1436
- */
1437
-
1438
- addCommand(cmd, opts) {
1439
- if (!cmd._name) {
1440
- throw new Error(`Command passed to .addCommand() must have a name
1441
- - specify the name in Command constructor or using .name()`);
1442
- }
1443
-
1444
- opts = opts || {};
1445
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1446
- if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
1447
-
1448
- this._registerCommand(cmd);
1449
- cmd.parent = this;
1450
- cmd._checkForBrokenPassThrough();
1451
-
1452
- return this;
1453
- }
1454
-
1455
- /**
1456
- * Factory routine to create a new unattached argument.
1457
- *
1458
- * See .argument() for creating an attached argument, which uses this routine to
1459
- * create the argument. You can override createArgument to return a custom argument.
1460
- *
1461
- * @param {string} name
1462
- * @param {string} [description]
1463
- * @return {Argument} new argument
1464
- */
1465
-
1466
- createArgument(name, description) {
1467
- return new Argument$2(name, description);
1468
- }
1469
-
1470
- /**
1471
- * Define argument syntax for command.
1472
- *
1473
- * The default is that the argument is required, and you can explicitly
1474
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1475
- *
1476
- * @example
1477
- * program.argument('<input-file>');
1478
- * program.argument('[output-file]');
1479
- *
1480
- * @param {string} name
1481
- * @param {string} [description]
1482
- * @param {(Function|*)} [fn] - custom argument processing function
1483
- * @param {*} [defaultValue]
1484
- * @return {Command} `this` command for chaining
1485
- */
1486
- argument(name, description, fn, defaultValue) {
1487
- const argument = this.createArgument(name, description);
1488
- if (typeof fn === 'function') {
1489
- argument.default(defaultValue).argParser(fn);
1490
- } else {
1491
- argument.default(fn);
1492
- }
1493
- this.addArgument(argument);
1494
- return this;
1495
- }
1496
-
1497
- /**
1498
- * Define argument syntax for command, adding multiple at once (without descriptions).
1499
- *
1500
- * See also .argument().
1501
- *
1502
- * @example
1503
- * program.arguments('<cmd> [env]');
1504
- *
1505
- * @param {string} names
1506
- * @return {Command} `this` command for chaining
1507
- */
1508
-
1509
- arguments(names) {
1510
- names
1511
- .trim()
1512
- .split(/ +/)
1513
- .forEach((detail) => {
1514
- this.argument(detail);
1515
- });
1516
- return this;
1517
- }
1518
-
1519
- /**
1520
- * Define argument syntax for command, adding a prepared argument.
1521
- *
1522
- * @param {Argument} argument
1523
- * @return {Command} `this` command for chaining
1524
- */
1525
- addArgument(argument) {
1526
- const previousArgument = this.registeredArguments.slice(-1)[0];
1527
- if (previousArgument && previousArgument.variadic) {
1528
- throw new Error(
1529
- `only the last argument can be variadic '${previousArgument.name()}'`,
1530
- );
1531
- }
1532
- if (
1533
- argument.required &&
1534
- argument.defaultValue !== undefined &&
1535
- argument.parseArg === undefined
1536
- ) {
1537
- throw new Error(
1538
- `a default value for a required argument is never used: '${argument.name()}'`,
1539
- );
1540
- }
1541
- this.registeredArguments.push(argument);
1542
- return this;
1543
- }
1544
-
1545
- /**
1546
- * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1547
- *
1548
- * @example
1549
- * program.helpCommand('help [cmd]');
1550
- * program.helpCommand('help [cmd]', 'show help');
1551
- * program.helpCommand(false); // suppress default help command
1552
- * program.helpCommand(true); // add help command even if no subcommands
1553
- *
1554
- * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1555
- * @param {string} [description] - custom description
1556
- * @return {Command} `this` command for chaining
1557
- */
1558
-
1559
- helpCommand(enableOrNameAndArgs, description) {
1560
- if (typeof enableOrNameAndArgs === 'boolean') {
1561
- this._addImplicitHelpCommand = enableOrNameAndArgs;
1562
- return this;
1563
- }
1564
-
1565
- enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
1566
- const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1567
- const helpDescription = description ?? 'display help for command';
1568
-
1569
- const helpCommand = this.createCommand(helpName);
1570
- helpCommand.helpOption(false);
1571
- if (helpArgs) helpCommand.arguments(helpArgs);
1572
- if (helpDescription) helpCommand.description(helpDescription);
1573
-
1574
- this._addImplicitHelpCommand = true;
1575
- this._helpCommand = helpCommand;
1576
-
1577
- return this;
1578
- }
1579
-
1580
- /**
1581
- * Add prepared custom help command.
1582
- *
1583
- * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1584
- * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1585
- * @return {Command} `this` command for chaining
1586
- */
1587
- addHelpCommand(helpCommand, deprecatedDescription) {
1588
- // If not passed an object, call through to helpCommand for backwards compatibility,
1589
- // as addHelpCommand was originally used like helpCommand is now.
1590
- if (typeof helpCommand !== 'object') {
1591
- this.helpCommand(helpCommand, deprecatedDescription);
1592
- return this;
1593
- }
1594
-
1595
- this._addImplicitHelpCommand = true;
1596
- this._helpCommand = helpCommand;
1597
- return this;
1598
- }
1599
-
1600
- /**
1601
- * Lazy create help command.
1602
- *
1603
- * @return {(Command|null)}
1604
- * @package
1605
- */
1606
- _getHelpCommand() {
1607
- const hasImplicitHelpCommand =
1608
- this._addImplicitHelpCommand ??
1609
- (this.commands.length &&
1610
- !this._actionHandler &&
1611
- !this._findCommand('help'));
1612
-
1613
- if (hasImplicitHelpCommand) {
1614
- if (this._helpCommand === undefined) {
1615
- this.helpCommand(undefined, undefined); // use default name and description
1616
- }
1617
- return this._helpCommand;
1618
- }
1619
- return null;
1620
- }
1621
-
1622
- /**
1623
- * Add hook for life cycle event.
1624
- *
1625
- * @param {string} event
1626
- * @param {Function} listener
1627
- * @return {Command} `this` command for chaining
1628
- */
1629
-
1630
- hook(event, listener) {
1631
- const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
1632
- if (!allowedValues.includes(event)) {
1633
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1634
- Expecting one of '${allowedValues.join("', '")}'`);
1635
- }
1636
- if (this._lifeCycleHooks[event]) {
1637
- this._lifeCycleHooks[event].push(listener);
1638
- } else {
1639
- this._lifeCycleHooks[event] = [listener];
1640
- }
1641
- return this;
1642
- }
1643
-
1644
- /**
1645
- * Register callback to use as replacement for calling process.exit.
1646
- *
1647
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1648
- * @return {Command} `this` command for chaining
1649
- */
1650
-
1651
- exitOverride(fn) {
1652
- if (fn) {
1653
- this._exitCallback = fn;
1654
- } else {
1655
- this._exitCallback = (err) => {
1656
- if (err.code !== 'commander.executeSubCommandAsync') {
1657
- throw err;
1658
- }
1659
- };
1660
- }
1661
- return this;
1662
- }
1663
-
1664
- /**
1665
- * Call process.exit, and _exitCallback if defined.
1666
- *
1667
- * @param {number} exitCode exit code for using with process.exit
1668
- * @param {string} code an id string representing the error
1669
- * @param {string} message human-readable description of the error
1670
- * @return never
1671
- * @private
1672
- */
1673
-
1674
- _exit(exitCode, code, message) {
1675
- if (this._exitCallback) {
1676
- this._exitCallback(new CommanderError$2(exitCode, code, message));
1677
- // Expecting this line is not reached.
1678
- }
1679
- process$1.exit(exitCode);
1680
- }
1681
-
1682
- /**
1683
- * Register callback `fn` for the command.
1684
- *
1685
- * @example
1686
- * program
1687
- * .command('serve')
1688
- * .description('start service')
1689
- * .action(function() {
1690
- * // do work here
1691
- * });
1692
- *
1693
- * @param {Function} fn
1694
- * @return {Command} `this` command for chaining
1695
- */
1696
-
1697
- action(fn) {
1698
- const listener = (args) => {
1699
- // The .action callback takes an extra parameter which is the command or options.
1700
- const expectedArgsCount = this.registeredArguments.length;
1701
- const actionArgs = args.slice(0, expectedArgsCount);
1702
- if (this._storeOptionsAsProperties) {
1703
- actionArgs[expectedArgsCount] = this; // backwards compatible "options"
1704
- } else {
1705
- actionArgs[expectedArgsCount] = this.opts();
1706
- }
1707
- actionArgs.push(this);
1708
-
1709
- return fn.apply(this, actionArgs);
1710
- };
1711
- this._actionHandler = listener;
1712
- return this;
1713
- }
1714
-
1715
- /**
1716
- * Factory routine to create a new unattached option.
1717
- *
1718
- * See .option() for creating an attached option, which uses this routine to
1719
- * create the option. You can override createOption to return a custom option.
1720
- *
1721
- * @param {string} flags
1722
- * @param {string} [description]
1723
- * @return {Option} new option
1724
- */
1725
-
1726
- createOption(flags, description) {
1727
- return new Option$2(flags, description);
1728
- }
1729
-
1730
- /**
1731
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1732
- *
1733
- * @param {(Option | Argument)} target
1734
- * @param {string} value
1735
- * @param {*} previous
1736
- * @param {string} invalidArgumentMessage
1737
- * @private
1738
- */
1739
-
1740
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1741
- try {
1742
- return target.parseArg(value, previous);
1743
- } catch (err) {
1744
- if (err.code === 'commander.invalidArgument') {
1745
- const message = `${invalidArgumentMessage} ${err.message}`;
1746
- this.error(message, { exitCode: err.exitCode, code: err.code });
1747
- }
1748
- throw err;
1749
- }
1750
- }
1751
-
1752
- /**
1753
- * Check for option flag conflicts.
1754
- * Register option if no conflicts found, or throw on conflict.
1755
- *
1756
- * @param {Option} option
1757
- * @private
1758
- */
1759
-
1760
- _registerOption(option) {
1761
- const matchingOption =
1762
- (option.short && this._findOption(option.short)) ||
1763
- (option.long && this._findOption(option.long));
1764
- if (matchingOption) {
1765
- const matchingFlag =
1766
- option.long && this._findOption(option.long)
1767
- ? option.long
1768
- : option.short;
1769
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1770
- - already used by option '${matchingOption.flags}'`);
1771
- }
1772
-
1773
- this.options.push(option);
1774
- }
1775
-
1776
- /**
1777
- * Check for command name and alias conflicts with existing commands.
1778
- * Register command if no conflicts found, or throw on conflict.
1779
- *
1780
- * @param {Command} command
1781
- * @private
1782
- */
1783
-
1784
- _registerCommand(command) {
1785
- const knownBy = (cmd) => {
1786
- return [cmd.name()].concat(cmd.aliases());
1787
- };
1788
-
1789
- const alreadyUsed = knownBy(command).find((name) =>
1790
- this._findCommand(name),
1791
- );
1792
- if (alreadyUsed) {
1793
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
1794
- const newCmd = knownBy(command).join('|');
1795
- throw new Error(
1796
- `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
1797
- );
1798
- }
1799
-
1800
- this.commands.push(command);
1801
- }
1802
-
1803
- /**
1804
- * Add an option.
1805
- *
1806
- * @param {Option} option
1807
- * @return {Command} `this` command for chaining
1808
- */
1809
- addOption(option) {
1810
- this._registerOption(option);
1811
-
1812
- const oname = option.name();
1813
- const name = option.attributeName();
1814
-
1815
- // store default value
1816
- if (option.negate) {
1817
- // --no-foo is special and defaults foo to true, unless a --foo option is already defined
1818
- const positiveLongFlag = option.long.replace(/^--no-/, '--');
1819
- if (!this._findOption(positiveLongFlag)) {
1820
- this.setOptionValueWithSource(
1821
- name,
1822
- option.defaultValue === undefined ? true : option.defaultValue,
1823
- 'default',
1824
- );
1825
- }
1826
- } else if (option.defaultValue !== undefined) {
1827
- this.setOptionValueWithSource(name, option.defaultValue, 'default');
1828
- }
1829
-
1830
- // handler for cli and env supplied values
1831
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1832
- // val is null for optional option used without an optional-argument.
1833
- // val is undefined for boolean and negated option.
1834
- if (val == null && option.presetArg !== undefined) {
1835
- val = option.presetArg;
1836
- }
1837
-
1838
- // custom processing
1839
- const oldValue = this.getOptionValue(name);
1840
- if (val !== null && option.parseArg) {
1841
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1842
- } else if (val !== null && option.variadic) {
1843
- val = option._concatValue(val, oldValue);
1844
- }
1845
-
1846
- // Fill-in appropriate missing values. Long winded but easy to follow.
1847
- if (val == null) {
1848
- if (option.negate) {
1849
- val = false;
1850
- } else if (option.isBoolean() || option.optional) {
1851
- val = true;
1852
- } else {
1853
- val = ''; // not normal, parseArg might have failed or be a mock function for testing
1854
- }
1855
- }
1856
- this.setOptionValueWithSource(name, val, valueSource);
1857
- };
1858
-
1859
- this.on('option:' + oname, (val) => {
1860
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1861
- handleOptionValue(val, invalidValueMessage, 'cli');
1862
- });
1863
-
1864
- if (option.envVar) {
1865
- this.on('optionEnv:' + oname, (val) => {
1866
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1867
- handleOptionValue(val, invalidValueMessage, 'env');
1868
- });
1869
- }
1870
-
1871
- return this;
1872
- }
1873
-
1874
- /**
1875
- * Internal implementation shared by .option() and .requiredOption()
1876
- *
1877
- * @return {Command} `this` command for chaining
1878
- * @private
1879
- */
1880
- _optionEx(config, flags, description, fn, defaultValue) {
1881
- if (typeof flags === 'object' && flags instanceof Option$2) {
1882
- throw new Error(
1883
- 'To add an Option object use addOption() instead of option() or requiredOption()',
1884
- );
1885
- }
1886
- const option = this.createOption(flags, description);
1887
- option.makeOptionMandatory(!!config.mandatory);
1888
- if (typeof fn === 'function') {
1889
- option.default(defaultValue).argParser(fn);
1890
- } else if (fn instanceof RegExp) {
1891
- // deprecated
1892
- const regex = fn;
1893
- fn = (val, def) => {
1894
- const m = regex.exec(val);
1895
- return m ? m[0] : def;
1896
- };
1897
- option.default(defaultValue).argParser(fn);
1898
- } else {
1899
- option.default(fn);
1900
- }
1901
-
1902
- return this.addOption(option);
1903
- }
1904
-
1905
- /**
1906
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1907
- *
1908
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1909
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1910
- *
1911
- * See the README for more details, and see also addOption() and requiredOption().
1912
- *
1913
- * @example
1914
- * program
1915
- * .option('-p, --pepper', 'add pepper')
1916
- * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1917
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1918
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1919
- *
1920
- * @param {string} flags
1921
- * @param {string} [description]
1922
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1923
- * @param {*} [defaultValue]
1924
- * @return {Command} `this` command for chaining
1925
- */
1926
-
1927
- option(flags, description, parseArg, defaultValue) {
1928
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1929
- }
1930
-
1931
- /**
1932
- * Add a required option which must have a value after parsing. This usually means
1933
- * the option must be specified on the command line. (Otherwise the same as .option().)
1934
- *
1935
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1936
- *
1937
- * @param {string} flags
1938
- * @param {string} [description]
1939
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1940
- * @param {*} [defaultValue]
1941
- * @return {Command} `this` command for chaining
1942
- */
1943
-
1944
- requiredOption(flags, description, parseArg, defaultValue) {
1945
- return this._optionEx(
1946
- { mandatory: true },
1947
- flags,
1948
- description,
1949
- parseArg,
1950
- defaultValue,
1951
- );
1952
- }
1953
-
1954
- /**
1955
- * Alter parsing of short flags with optional values.
1956
- *
1957
- * @example
1958
- * // for `.option('-f,--flag [value]'):
1959
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1960
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1961
- *
1962
- * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1963
- * @return {Command} `this` command for chaining
1964
- */
1965
- combineFlagAndOptionalValue(combine = true) {
1966
- this._combineFlagAndOptionalValue = !!combine;
1967
- return this;
1968
- }
1969
-
1970
- /**
1971
- * Allow unknown options on the command line.
1972
- *
1973
- * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1974
- * @return {Command} `this` command for chaining
1975
- */
1976
- allowUnknownOption(allowUnknown = true) {
1977
- this._allowUnknownOption = !!allowUnknown;
1978
- return this;
1979
- }
1980
-
1981
- /**
1982
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1983
- *
1984
- * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1985
- * @return {Command} `this` command for chaining
1986
- */
1987
- allowExcessArguments(allowExcess = true) {
1988
- this._allowExcessArguments = !!allowExcess;
1989
- return this;
1990
- }
1991
-
1992
- /**
1993
- * Enable positional options. Positional means global options are specified before subcommands which lets
1994
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1995
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1996
- *
1997
- * @param {boolean} [positional]
1998
- * @return {Command} `this` command for chaining
1999
- */
2000
- enablePositionalOptions(positional = true) {
2001
- this._enablePositionalOptions = !!positional;
2002
- return this;
2003
- }
2004
-
2005
- /**
2006
- * Pass through options that come after command-arguments rather than treat them as command-options,
2007
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
2008
- * positional options to have been enabled on the program (parent commands).
2009
- * The default behaviour is non-positional and options may appear before or after command-arguments.
2010
- *
2011
- * @param {boolean} [passThrough] for unknown options.
2012
- * @return {Command} `this` command for chaining
2013
- */
2014
- passThroughOptions(passThrough = true) {
2015
- this._passThroughOptions = !!passThrough;
2016
- this._checkForBrokenPassThrough();
2017
- return this;
2018
- }
2019
-
2020
- /**
2021
- * @private
2022
- */
2023
-
2024
- _checkForBrokenPassThrough() {
2025
- if (
2026
- this.parent &&
2027
- this._passThroughOptions &&
2028
- !this.parent._enablePositionalOptions
2029
- ) {
2030
- throw new Error(
2031
- `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
2032
- );
2033
- }
2034
- }
2035
-
2036
- /**
2037
- * Whether to store option values as properties on command object,
2038
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
2039
- *
2040
- * @param {boolean} [storeAsProperties=true]
2041
- * @return {Command} `this` command for chaining
2042
- */
2043
-
2044
- storeOptionsAsProperties(storeAsProperties = true) {
2045
- if (this.options.length) {
2046
- throw new Error('call .storeOptionsAsProperties() before adding options');
2047
- }
2048
- if (Object.keys(this._optionValues).length) {
2049
- throw new Error(
2050
- 'call .storeOptionsAsProperties() before setting option values',
2051
- );
2052
- }
2053
- this._storeOptionsAsProperties = !!storeAsProperties;
2054
- return this;
2055
- }
2056
-
2057
- /**
2058
- * Retrieve option value.
2059
- *
2060
- * @param {string} key
2061
- * @return {object} value
2062
- */
2063
-
2064
- getOptionValue(key) {
2065
- if (this._storeOptionsAsProperties) {
2066
- return this[key];
2067
- }
2068
- return this._optionValues[key];
2069
- }
2070
-
2071
- /**
2072
- * Store option value.
2073
- *
2074
- * @param {string} key
2075
- * @param {object} value
2076
- * @return {Command} `this` command for chaining
2077
- */
2078
-
2079
- setOptionValue(key, value) {
2080
- return this.setOptionValueWithSource(key, value, undefined);
2081
- }
2082
-
2083
- /**
2084
- * Store option value and where the value came from.
2085
- *
2086
- * @param {string} key
2087
- * @param {object} value
2088
- * @param {string} source - expected values are default/config/env/cli/implied
2089
- * @return {Command} `this` command for chaining
2090
- */
2091
-
2092
- setOptionValueWithSource(key, value, source) {
2093
- if (this._storeOptionsAsProperties) {
2094
- this[key] = value;
2095
- } else {
2096
- this._optionValues[key] = value;
2097
- }
2098
- this._optionValueSources[key] = source;
2099
- return this;
2100
- }
2101
-
2102
- /**
2103
- * Get source of option value.
2104
- * Expected values are default | config | env | cli | implied
2105
- *
2106
- * @param {string} key
2107
- * @return {string}
2108
- */
2109
-
2110
- getOptionValueSource(key) {
2111
- return this._optionValueSources[key];
2112
- }
2113
-
2114
- /**
2115
- * Get source of option value. See also .optsWithGlobals().
2116
- * Expected values are default | config | env | cli | implied
2117
- *
2118
- * @param {string} key
2119
- * @return {string}
2120
- */
2121
-
2122
- getOptionValueSourceWithGlobals(key) {
2123
- // global overwrites local, like optsWithGlobals
2124
- let source;
2125
- this._getCommandAndAncestors().forEach((cmd) => {
2126
- if (cmd.getOptionValueSource(key) !== undefined) {
2127
- source = cmd.getOptionValueSource(key);
2128
- }
2129
- });
2130
- return source;
2131
- }
2132
-
2133
- /**
2134
- * Get user arguments from implied or explicit arguments.
2135
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2136
- *
2137
- * @private
2138
- */
2139
-
2140
- _prepareUserArgs(argv, parseOptions) {
2141
- if (argv !== undefined && !Array.isArray(argv)) {
2142
- throw new Error('first parameter to parse must be array or undefined');
2143
- }
2144
- parseOptions = parseOptions || {};
2145
-
2146
- // auto-detect argument conventions if nothing supplied
2147
- if (argv === undefined && parseOptions.from === undefined) {
2148
- if (process$1.versions?.electron) {
2149
- parseOptions.from = 'electron';
2150
- }
2151
- // check node specific options for scenarios where user CLI args follow executable without scriptname
2152
- const execArgv = process$1.execArgv ?? [];
2153
- if (
2154
- execArgv.includes('-e') ||
2155
- execArgv.includes('--eval') ||
2156
- execArgv.includes('-p') ||
2157
- execArgv.includes('--print')
2158
- ) {
2159
- parseOptions.from = 'eval'; // internal usage, not documented
2160
- }
2161
- }
2162
-
2163
- // default to using process.argv
2164
- if (argv === undefined) {
2165
- argv = process$1.argv;
2166
- }
2167
- this.rawArgs = argv.slice();
2168
-
2169
- // extract the user args and scriptPath
2170
- let userArgs;
2171
- switch (parseOptions.from) {
2172
- case undefined:
2173
- case 'node':
2174
- this._scriptPath = argv[1];
2175
- userArgs = argv.slice(2);
2176
- break;
2177
- case 'electron':
2178
- // @ts-ignore: because defaultApp is an unknown property
2179
- if (process$1.defaultApp) {
2180
- this._scriptPath = argv[1];
2181
- userArgs = argv.slice(2);
2182
- } else {
2183
- userArgs = argv.slice(1);
2184
- }
2185
- break;
2186
- case 'user':
2187
- userArgs = argv.slice(0);
2188
- break;
2189
- case 'eval':
2190
- userArgs = argv.slice(1);
2191
- break;
2192
- default:
2193
- throw new Error(
2194
- `unexpected parse option { from: '${parseOptions.from}' }`,
2195
- );
2196
- }
2197
-
2198
- // Find default name for program from arguments.
2199
- if (!this._name && this._scriptPath)
2200
- this.nameFromFilename(this._scriptPath);
2201
- this._name = this._name || 'program';
2202
-
2203
- return userArgs;
2204
- }
2205
-
2206
- /**
2207
- * Parse `argv`, setting options and invoking commands when defined.
2208
- *
2209
- * Use parseAsync instead of parse if any of your action handlers are async.
2210
- *
2211
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2212
- *
2213
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2214
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2215
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2216
- * - `'user'`: just user arguments
2217
- *
2218
- * @example
2219
- * program.parse(); // parse process.argv and auto-detect electron and special node flags
2220
- * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2221
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2222
- *
2223
- * @param {string[]} [argv] - optional, defaults to process.argv
2224
- * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2225
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2226
- * @return {Command} `this` command for chaining
2227
- */
2228
-
2229
- parse(argv, parseOptions) {
2230
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2231
- this._parseCommand([], userArgs);
2232
-
2233
- return this;
2234
- }
2235
-
2236
- /**
2237
- * Parse `argv`, setting options and invoking commands when defined.
2238
- *
2239
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2240
- *
2241
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2242
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2243
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2244
- * - `'user'`: just user arguments
2245
- *
2246
- * @example
2247
- * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2248
- * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2249
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2250
- *
2251
- * @param {string[]} [argv]
2252
- * @param {object} [parseOptions]
2253
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2254
- * @return {Promise}
2255
- */
2256
-
2257
- async parseAsync(argv, parseOptions) {
2258
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2259
- await this._parseCommand([], userArgs);
2260
-
2261
- return this;
2262
- }
2263
-
2264
- /**
2265
- * Execute a sub-command executable.
2266
- *
2267
- * @private
2268
- */
2269
-
2270
- _executeSubCommand(subcommand, args) {
2271
- args = args.slice();
2272
- let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
2273
- const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
2274
-
2275
- function findFile(baseDir, baseName) {
2276
- // Look for specified file
2277
- const localBin = path.resolve(baseDir, baseName);
2278
- if (fs.existsSync(localBin)) return localBin;
2279
-
2280
- // Stop looking if candidate already has an expected extension.
2281
- if (sourceExt.includes(path.extname(baseName))) return undefined;
2282
-
2283
- // Try all the extensions.
2284
- const foundExt = sourceExt.find((ext) =>
2285
- fs.existsSync(`${localBin}${ext}`),
2286
- );
2287
- if (foundExt) return `${localBin}${foundExt}`;
2288
-
2289
- return undefined;
2290
- }
2291
-
2292
- // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
2293
- this._checkForMissingMandatoryOptions();
2294
- this._checkForConflictingOptions();
2295
-
2296
- // executableFile and executableDir might be full path, or just a name
2297
- let executableFile =
2298
- subcommand._executableFile || `${this._name}-${subcommand._name}`;
2299
- let executableDir = this._executableDir || '';
2300
- if (this._scriptPath) {
2301
- let resolvedScriptPath; // resolve possible symlink for installed npm binary
2302
- try {
2303
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
2304
- } catch (err) {
2305
- resolvedScriptPath = this._scriptPath;
2306
- }
2307
- executableDir = path.resolve(
2308
- path.dirname(resolvedScriptPath),
2309
- executableDir,
2310
- );
2311
- }
2312
-
2313
- // Look for a local file in preference to a command in PATH.
2314
- if (executableDir) {
2315
- let localFile = findFile(executableDir, executableFile);
2316
-
2317
- // Legacy search using prefix of script name instead of command name
2318
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
2319
- const legacyName = path.basename(
2320
- this._scriptPath,
2321
- path.extname(this._scriptPath),
2322
- );
2323
- if (legacyName !== this._name) {
2324
- localFile = findFile(
2325
- executableDir,
2326
- `${legacyName}-${subcommand._name}`,
2327
- );
2328
- }
2329
- }
2330
- executableFile = localFile || executableFile;
2331
- }
2332
-
2333
- launchWithNode = sourceExt.includes(path.extname(executableFile));
2334
-
2335
- let proc;
2336
- if (process$1.platform !== 'win32') {
2337
- if (launchWithNode) {
2338
- args.unshift(executableFile);
2339
- // add executable arguments to spawn
2340
- args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2341
-
2342
- proc = childProcess.spawn(process$1.argv[0], args, { stdio: 'inherit' });
2343
- } else {
2344
- proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
2345
- }
2346
- } else {
2347
- args.unshift(executableFile);
2348
- // add executable arguments to spawn
2349
- args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2350
- proc = childProcess.spawn(process$1.execPath, args, { stdio: 'inherit' });
2351
- }
2352
-
2353
- if (!proc.killed) {
2354
- // testing mainly to avoid leak warnings during unit tests with mocked spawn
2355
- const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
2356
- signals.forEach((signal) => {
2357
- process$1.on(signal, () => {
2358
- if (proc.killed === false && proc.exitCode === null) {
2359
- // @ts-ignore because signals not typed to known strings
2360
- proc.kill(signal);
2361
- }
2362
- });
2363
- });
2364
- }
2365
-
2366
- // By default terminate process when spawned process terminates.
2367
- const exitCallback = this._exitCallback;
2368
- proc.on('close', (code) => {
2369
- code = code ?? 1; // code is null if spawned process terminated due to a signal
2370
- if (!exitCallback) {
2371
- process$1.exit(code);
2372
- } else {
2373
- exitCallback(
2374
- new CommanderError$2(
2375
- code,
2376
- 'commander.executeSubCommandAsync',
2377
- '(close)',
2378
- ),
2379
- );
2380
- }
2381
- });
2382
- proc.on('error', (err) => {
2383
- // @ts-ignore: because err.code is an unknown property
2384
- if (err.code === 'ENOENT') {
2385
- const executableDirMessage = executableDir
2386
- ? `searched for local subcommand relative to directory '${executableDir}'`
2387
- : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
2388
- const executableMissing = `'${executableFile}' does not exist
2389
- - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2390
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2391
- - ${executableDirMessage}`;
2392
- throw new Error(executableMissing);
2393
- // @ts-ignore: because err.code is an unknown property
2394
- } else if (err.code === 'EACCES') {
2395
- throw new Error(`'${executableFile}' not executable`);
2396
- }
2397
- if (!exitCallback) {
2398
- process$1.exit(1);
2399
- } else {
2400
- const wrappedError = new CommanderError$2(
2401
- 1,
2402
- 'commander.executeSubCommandAsync',
2403
- '(error)',
2404
- );
2405
- wrappedError.nestedError = err;
2406
- exitCallback(wrappedError);
2407
- }
2408
- });
2409
-
2410
- // Store the reference to the child process
2411
- this.runningCommand = proc;
2412
- }
2413
-
2414
- /**
2415
- * @private
2416
- */
2417
-
2418
- _dispatchSubcommand(commandName, operands, unknown) {
2419
- const subCommand = this._findCommand(commandName);
2420
- if (!subCommand) this.help({ error: true });
2421
-
2422
- let promiseChain;
2423
- promiseChain = this._chainOrCallSubCommandHook(
2424
- promiseChain,
2425
- subCommand,
2426
- 'preSubcommand',
2427
- );
2428
- promiseChain = this._chainOrCall(promiseChain, () => {
2429
- if (subCommand._executableHandler) {
2430
- this._executeSubCommand(subCommand, operands.concat(unknown));
2431
- } else {
2432
- return subCommand._parseCommand(operands, unknown);
2433
- }
2434
- });
2435
- return promiseChain;
2436
- }
2437
-
2438
- /**
2439
- * Invoke help directly if possible, or dispatch if necessary.
2440
- * e.g. help foo
2441
- *
2442
- * @private
2443
- */
2444
-
2445
- _dispatchHelpCommand(subcommandName) {
2446
- if (!subcommandName) {
2447
- this.help();
2448
- }
2449
- const subCommand = this._findCommand(subcommandName);
2450
- if (subCommand && !subCommand._executableHandler) {
2451
- subCommand.help();
2452
- }
2453
-
2454
- // Fallback to parsing the help flag to invoke the help.
2455
- return this._dispatchSubcommand(
2456
- subcommandName,
2457
- [],
2458
- [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
2459
- );
2460
- }
2461
-
2462
- /**
2463
- * Check this.args against expected this.registeredArguments.
2464
- *
2465
- * @private
2466
- */
2467
-
2468
- _checkNumberOfArguments() {
2469
- // too few
2470
- this.registeredArguments.forEach((arg, i) => {
2471
- if (arg.required && this.args[i] == null) {
2472
- this.missingArgument(arg.name());
2473
- }
2474
- });
2475
- // too many
2476
- if (
2477
- this.registeredArguments.length > 0 &&
2478
- this.registeredArguments[this.registeredArguments.length - 1].variadic
2479
- ) {
2480
- return;
2481
- }
2482
- if (this.args.length > this.registeredArguments.length) {
2483
- this._excessArguments(this.args);
2484
- }
2485
- }
2486
-
2487
- /**
2488
- * Process this.args using this.registeredArguments and save as this.processedArgs!
2489
- *
2490
- * @private
2491
- */
2492
-
2493
- _processArguments() {
2494
- const myParseArg = (argument, value, previous) => {
2495
- // Extra processing for nice error message on parsing failure.
2496
- let parsedValue = value;
2497
- if (value !== null && argument.parseArg) {
2498
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2499
- parsedValue = this._callParseArg(
2500
- argument,
2501
- value,
2502
- previous,
2503
- invalidValueMessage,
2504
- );
2505
- }
2506
- return parsedValue;
2507
- };
2508
-
2509
- this._checkNumberOfArguments();
2510
-
2511
- const processedArgs = [];
2512
- this.registeredArguments.forEach((declaredArg, index) => {
2513
- let value = declaredArg.defaultValue;
2514
- if (declaredArg.variadic) {
2515
- // Collect together remaining arguments for passing together as an array.
2516
- if (index < this.args.length) {
2517
- value = this.args.slice(index);
2518
- if (declaredArg.parseArg) {
2519
- value = value.reduce((processed, v) => {
2520
- return myParseArg(declaredArg, v, processed);
2521
- }, declaredArg.defaultValue);
2522
- }
2523
- } else if (value === undefined) {
2524
- value = [];
2525
- }
2526
- } else if (index < this.args.length) {
2527
- value = this.args[index];
2528
- if (declaredArg.parseArg) {
2529
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2530
- }
2531
- }
2532
- processedArgs[index] = value;
2533
- });
2534
- this.processedArgs = processedArgs;
2535
- }
2536
-
2537
- /**
2538
- * Once we have a promise we chain, but call synchronously until then.
2539
- *
2540
- * @param {(Promise|undefined)} promise
2541
- * @param {Function} fn
2542
- * @return {(Promise|undefined)}
2543
- * @private
2544
- */
2545
-
2546
- _chainOrCall(promise, fn) {
2547
- // thenable
2548
- if (promise && promise.then && typeof promise.then === 'function') {
2549
- // already have a promise, chain callback
2550
- return promise.then(() => fn());
2551
- }
2552
- // callback might return a promise
2553
- return fn();
2554
- }
2555
-
2556
- /**
2557
- *
2558
- * @param {(Promise|undefined)} promise
2559
- * @param {string} event
2560
- * @return {(Promise|undefined)}
2561
- * @private
2562
- */
2563
-
2564
- _chainOrCallHooks(promise, event) {
2565
- let result = promise;
2566
- const hooks = [];
2567
- this._getCommandAndAncestors()
2568
- .reverse()
2569
- .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
2570
- .forEach((hookedCommand) => {
2571
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2572
- hooks.push({ hookedCommand, callback });
2573
- });
2574
- });
2575
- if (event === 'postAction') {
2576
- hooks.reverse();
2577
- }
2578
-
2579
- hooks.forEach((hookDetail) => {
2580
- result = this._chainOrCall(result, () => {
2581
- return hookDetail.callback(hookDetail.hookedCommand, this);
2582
- });
2583
- });
2584
- return result;
2585
- }
2586
-
2587
- /**
2588
- *
2589
- * @param {(Promise|undefined)} promise
2590
- * @param {Command} subCommand
2591
- * @param {string} event
2592
- * @return {(Promise|undefined)}
2593
- * @private
2594
- */
2595
-
2596
- _chainOrCallSubCommandHook(promise, subCommand, event) {
2597
- let result = promise;
2598
- if (this._lifeCycleHooks[event] !== undefined) {
2599
- this._lifeCycleHooks[event].forEach((hook) => {
2600
- result = this._chainOrCall(result, () => {
2601
- return hook(this, subCommand);
2602
- });
2603
- });
2604
- }
2605
- return result;
2606
- }
2607
-
2608
- /**
2609
- * Process arguments in context of this command.
2610
- * Returns action result, in case it is a promise.
2611
- *
2612
- * @private
2613
- */
2614
-
2615
- _parseCommand(operands, unknown) {
2616
- const parsed = this.parseOptions(unknown);
2617
- this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
2618
- this._parseOptionsImplied();
2619
- operands = operands.concat(parsed.operands);
2620
- unknown = parsed.unknown;
2621
- this.args = operands.concat(unknown);
2622
-
2623
- if (operands && this._findCommand(operands[0])) {
2624
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2625
- }
2626
- if (
2627
- this._getHelpCommand() &&
2628
- operands[0] === this._getHelpCommand().name()
2629
- ) {
2630
- return this._dispatchHelpCommand(operands[1]);
2631
- }
2632
- if (this._defaultCommandName) {
2633
- this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
2634
- return this._dispatchSubcommand(
2635
- this._defaultCommandName,
2636
- operands,
2637
- unknown,
2638
- );
2639
- }
2640
- if (
2641
- this.commands.length &&
2642
- this.args.length === 0 &&
2643
- !this._actionHandler &&
2644
- !this._defaultCommandName
2645
- ) {
2646
- // probably missing subcommand and no handler, user needs help (and exit)
2647
- this.help({ error: true });
2648
- }
2649
-
2650
- this._outputHelpIfRequested(parsed.unknown);
2651
- this._checkForMissingMandatoryOptions();
2652
- this._checkForConflictingOptions();
2653
-
2654
- // We do not always call this check to avoid masking a "better" error, like unknown command.
2655
- const checkForUnknownOptions = () => {
2656
- if (parsed.unknown.length > 0) {
2657
- this.unknownOption(parsed.unknown[0]);
2658
- }
2659
- };
2660
-
2661
- const commandEvent = `command:${this.name()}`;
2662
- if (this._actionHandler) {
2663
- checkForUnknownOptions();
2664
- this._processArguments();
2665
-
2666
- let promiseChain;
2667
- promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
2668
- promiseChain = this._chainOrCall(promiseChain, () =>
2669
- this._actionHandler(this.processedArgs),
2670
- );
2671
- if (this.parent) {
2672
- promiseChain = this._chainOrCall(promiseChain, () => {
2673
- this.parent.emit(commandEvent, operands, unknown); // legacy
2674
- });
2675
- }
2676
- promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
2677
- return promiseChain;
2678
- }
2679
- if (this.parent && this.parent.listenerCount(commandEvent)) {
2680
- checkForUnknownOptions();
2681
- this._processArguments();
2682
- this.parent.emit(commandEvent, operands, unknown); // legacy
2683
- } else if (operands.length) {
2684
- if (this._findCommand('*')) {
2685
- // legacy default command
2686
- return this._dispatchSubcommand('*', operands, unknown);
2687
- }
2688
- if (this.listenerCount('command:*')) {
2689
- // skip option check, emit event for possible misspelling suggestion
2690
- this.emit('command:*', operands, unknown);
2691
- } else if (this.commands.length) {
2692
- this.unknownCommand();
2693
- } else {
2694
- checkForUnknownOptions();
2695
- this._processArguments();
2696
- }
2697
- } else if (this.commands.length) {
2698
- checkForUnknownOptions();
2699
- // This command has subcommands and nothing hooked up at this level, so display help (and exit).
2700
- this.help({ error: true });
2701
- } else {
2702
- checkForUnknownOptions();
2703
- this._processArguments();
2704
- // fall through for caller to handle after calling .parse()
2705
- }
2706
- }
2707
-
2708
- /**
2709
- * Find matching command.
2710
- *
2711
- * @private
2712
- * @return {Command | undefined}
2713
- */
2714
- _findCommand(name) {
2715
- if (!name) return undefined;
2716
- return this.commands.find(
2717
- (cmd) => cmd._name === name || cmd._aliases.includes(name),
2718
- );
2719
- }
2720
-
2721
- /**
2722
- * Return an option matching `arg` if any.
2723
- *
2724
- * @param {string} arg
2725
- * @return {Option}
2726
- * @package
2727
- */
2728
-
2729
- _findOption(arg) {
2730
- return this.options.find((option) => option.is(arg));
2731
- }
2732
-
2733
- /**
2734
- * Display an error message if a mandatory option does not have a value.
2735
- * Called after checking for help flags in leaf subcommand.
2736
- *
2737
- * @private
2738
- */
2739
-
2740
- _checkForMissingMandatoryOptions() {
2741
- // Walk up hierarchy so can call in subcommand after checking for displaying help.
2742
- this._getCommandAndAncestors().forEach((cmd) => {
2743
- cmd.options.forEach((anOption) => {
2744
- if (
2745
- anOption.mandatory &&
2746
- cmd.getOptionValue(anOption.attributeName()) === undefined
2747
- ) {
2748
- cmd.missingMandatoryOptionValue(anOption);
2749
- }
2750
- });
2751
- });
2752
- }
2753
-
2754
- /**
2755
- * Display an error message if conflicting options are used together in this.
2756
- *
2757
- * @private
2758
- */
2759
- _checkForConflictingLocalOptions() {
2760
- const definedNonDefaultOptions = this.options.filter((option) => {
2761
- const optionKey = option.attributeName();
2762
- if (this.getOptionValue(optionKey) === undefined) {
2763
- return false;
2764
- }
2765
- return this.getOptionValueSource(optionKey) !== 'default';
2766
- });
2767
-
2768
- const optionsWithConflicting = definedNonDefaultOptions.filter(
2769
- (option) => option.conflictsWith.length > 0,
2770
- );
2771
-
2772
- optionsWithConflicting.forEach((option) => {
2773
- const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
2774
- option.conflictsWith.includes(defined.attributeName()),
2775
- );
2776
- if (conflictingAndDefined) {
2777
- this._conflictingOption(option, conflictingAndDefined);
2778
- }
2779
- });
2780
- }
2781
-
2782
- /**
2783
- * Display an error message if conflicting options are used together.
2784
- * Called after checking for help flags in leaf subcommand.
2785
- *
2786
- * @private
2787
- */
2788
- _checkForConflictingOptions() {
2789
- // Walk up hierarchy so can call in subcommand after checking for displaying help.
2790
- this._getCommandAndAncestors().forEach((cmd) => {
2791
- cmd._checkForConflictingLocalOptions();
2792
- });
2793
- }
2794
-
2795
- /**
2796
- * Parse options from `argv` removing known options,
2797
- * and return argv split into operands and unknown arguments.
2798
- *
2799
- * Examples:
2800
- *
2801
- * argv => operands, unknown
2802
- * --known kkk op => [op], []
2803
- * op --known kkk => [op], []
2804
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2805
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2806
- *
2807
- * @param {string[]} argv
2808
- * @return {{operands: string[], unknown: string[]}}
2809
- */
2810
-
2811
- parseOptions(argv) {
2812
- const operands = []; // operands, not options or values
2813
- const unknown = []; // first unknown option and remaining unknown args
2814
- let dest = operands;
2815
- const args = argv.slice();
2816
-
2817
- function maybeOption(arg) {
2818
- return arg.length > 1 && arg[0] === '-';
2819
- }
2820
-
2821
- // parse options
2822
- let activeVariadicOption = null;
2823
- while (args.length) {
2824
- const arg = args.shift();
2825
-
2826
- // literal
2827
- if (arg === '--') {
2828
- if (dest === unknown) dest.push(arg);
2829
- dest.push(...args);
2830
- break;
2831
- }
2832
-
2833
- if (activeVariadicOption && !maybeOption(arg)) {
2834
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2835
- continue;
2836
- }
2837
- activeVariadicOption = null;
2838
-
2839
- if (maybeOption(arg)) {
2840
- const option = this._findOption(arg);
2841
- // recognised option, call listener to assign value with possible custom processing
2842
- if (option) {
2843
- if (option.required) {
2844
- const value = args.shift();
2845
- if (value === undefined) this.optionMissingArgument(option);
2846
- this.emit(`option:${option.name()}`, value);
2847
- } else if (option.optional) {
2848
- let value = null;
2849
- // historical behaviour is optional value is following arg unless an option
2850
- if (args.length > 0 && !maybeOption(args[0])) {
2851
- value = args.shift();
2852
- }
2853
- this.emit(`option:${option.name()}`, value);
2854
- } else {
2855
- // boolean flag
2856
- this.emit(`option:${option.name()}`);
2857
- }
2858
- activeVariadicOption = option.variadic ? option : null;
2859
- continue;
2860
- }
2861
- }
2862
-
2863
- // Look for combo options following single dash, eat first one if known.
2864
- if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
2865
- const option = this._findOption(`-${arg[1]}`);
2866
- if (option) {
2867
- if (
2868
- option.required ||
2869
- (option.optional && this._combineFlagAndOptionalValue)
2870
- ) {
2871
- // option with value following in same argument
2872
- this.emit(`option:${option.name()}`, arg.slice(2));
2873
- } else {
2874
- // boolean option, emit and put back remainder of arg for further processing
2875
- this.emit(`option:${option.name()}`);
2876
- args.unshift(`-${arg.slice(2)}`);
2877
- }
2878
- continue;
2879
- }
2880
- }
2881
-
2882
- // Look for known long flag with value, like --foo=bar
2883
- if (/^--[^=]+=/.test(arg)) {
2884
- const index = arg.indexOf('=');
2885
- const option = this._findOption(arg.slice(0, index));
2886
- if (option && (option.required || option.optional)) {
2887
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2888
- continue;
2889
- }
2890
- }
2891
-
2892
- // Not a recognised option by this command.
2893
- // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
2894
-
2895
- // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
2896
- if (maybeOption(arg)) {
2897
- dest = unknown;
2898
- }
2899
-
2900
- // If using positionalOptions, stop processing our options at subcommand.
2901
- if (
2902
- (this._enablePositionalOptions || this._passThroughOptions) &&
2903
- operands.length === 0 &&
2904
- unknown.length === 0
2905
- ) {
2906
- if (this._findCommand(arg)) {
2907
- operands.push(arg);
2908
- if (args.length > 0) unknown.push(...args);
2909
- break;
2910
- } else if (
2911
- this._getHelpCommand() &&
2912
- arg === this._getHelpCommand().name()
2913
- ) {
2914
- operands.push(arg);
2915
- if (args.length > 0) operands.push(...args);
2916
- break;
2917
- } else if (this._defaultCommandName) {
2918
- unknown.push(arg);
2919
- if (args.length > 0) unknown.push(...args);
2920
- break;
2921
- }
2922
- }
2923
-
2924
- // If using passThroughOptions, stop processing options at first command-argument.
2925
- if (this._passThroughOptions) {
2926
- dest.push(arg);
2927
- if (args.length > 0) dest.push(...args);
2928
- break;
2929
- }
2930
-
2931
- // add arg
2932
- dest.push(arg);
2933
- }
2934
-
2935
- return { operands, unknown };
2936
- }
2937
-
2938
- /**
2939
- * Return an object containing local option values as key-value pairs.
2940
- *
2941
- * @return {object}
2942
- */
2943
- opts() {
2944
- if (this._storeOptionsAsProperties) {
2945
- // Preserve original behaviour so backwards compatible when still using properties
2946
- const result = {};
2947
- const len = this.options.length;
2948
-
2949
- for (let i = 0; i < len; i++) {
2950
- const key = this.options[i].attributeName();
2951
- result[key] =
2952
- key === this._versionOptionName ? this._version : this[key];
2953
- }
2954
- return result;
2955
- }
2956
-
2957
- return this._optionValues;
2958
- }
2959
-
2960
- /**
2961
- * Return an object containing merged local and global option values as key-value pairs.
2962
- *
2963
- * @return {object}
2964
- */
2965
- optsWithGlobals() {
2966
- // globals overwrite locals
2967
- return this._getCommandAndAncestors().reduce(
2968
- (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2969
- {},
2970
- );
2971
- }
2972
-
2973
- /**
2974
- * Display error message and exit (or call exitOverride).
2975
- *
2976
- * @param {string} message
2977
- * @param {object} [errorOptions]
2978
- * @param {string} [errorOptions.code] - an id string representing the error
2979
- * @param {number} [errorOptions.exitCode] - used with process.exit
2980
- */
2981
- error(message, errorOptions) {
2982
- // output handling
2983
- this._outputConfiguration.outputError(
2984
- `${message}\n`,
2985
- this._outputConfiguration.writeErr,
2986
- );
2987
- if (typeof this._showHelpAfterError === 'string') {
2988
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2989
- } else if (this._showHelpAfterError) {
2990
- this._outputConfiguration.writeErr('\n');
2991
- this.outputHelp({ error: true });
2992
- }
2993
-
2994
- // exit handling
2995
- const config = errorOptions || {};
2996
- const exitCode = config.exitCode || 1;
2997
- const code = config.code || 'commander.error';
2998
- this._exit(exitCode, code, message);
2999
- }
3000
-
3001
- /**
3002
- * Apply any option related environment variables, if option does
3003
- * not have a value from cli or client code.
3004
- *
3005
- * @private
3006
- */
3007
- _parseOptionsEnv() {
3008
- this.options.forEach((option) => {
3009
- if (option.envVar && option.envVar in process$1.env) {
3010
- const optionKey = option.attributeName();
3011
- // Priority check. Do not overwrite cli or options from unknown source (client-code).
3012
- if (
3013
- this.getOptionValue(optionKey) === undefined ||
3014
- ['default', 'config', 'env'].includes(
3015
- this.getOptionValueSource(optionKey),
3016
- )
3017
- ) {
3018
- if (option.required || option.optional) {
3019
- // option can take a value
3020
- // keep very simple, optional always takes value
3021
- this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
3022
- } else {
3023
- // boolean
3024
- // keep very simple, only care that envVar defined and not the value
3025
- this.emit(`optionEnv:${option.name()}`);
3026
- }
3027
- }
3028
- }
3029
- });
3030
- }
3031
-
3032
- /**
3033
- * Apply any implied option values, if option is undefined or default value.
3034
- *
3035
- * @private
3036
- */
3037
- _parseOptionsImplied() {
3038
- const dualHelper = new DualOptions(this.options);
3039
- const hasCustomOptionValue = (optionKey) => {
3040
- return (
3041
- this.getOptionValue(optionKey) !== undefined &&
3042
- !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
3043
- );
3044
- };
3045
- this.options
3046
- .filter(
3047
- (option) =>
3048
- option.implied !== undefined &&
3049
- hasCustomOptionValue(option.attributeName()) &&
3050
- dualHelper.valueFromOption(
3051
- this.getOptionValue(option.attributeName()),
3052
- option,
3053
- ),
3054
- )
3055
- .forEach((option) => {
3056
- Object.keys(option.implied)
3057
- .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
3058
- .forEach((impliedKey) => {
3059
- this.setOptionValueWithSource(
3060
- impliedKey,
3061
- option.implied[impliedKey],
3062
- 'implied',
3063
- );
3064
- });
3065
- });
3066
- }
3067
-
3068
- /**
3069
- * Argument `name` is missing.
3070
- *
3071
- * @param {string} name
3072
- * @private
3073
- */
3074
-
3075
- missingArgument(name) {
3076
- const message = `error: missing required argument '${name}'`;
3077
- this.error(message, { code: 'commander.missingArgument' });
3078
- }
3079
-
3080
- /**
3081
- * `Option` is missing an argument.
3082
- *
3083
- * @param {Option} option
3084
- * @private
3085
- */
3086
-
3087
- optionMissingArgument(option) {
3088
- const message = `error: option '${option.flags}' argument missing`;
3089
- this.error(message, { code: 'commander.optionMissingArgument' });
3090
- }
3091
-
3092
- /**
3093
- * `Option` does not have a value, and is a mandatory option.
3094
- *
3095
- * @param {Option} option
3096
- * @private
3097
- */
3098
-
3099
- missingMandatoryOptionValue(option) {
3100
- const message = `error: required option '${option.flags}' not specified`;
3101
- this.error(message, { code: 'commander.missingMandatoryOptionValue' });
3102
- }
3103
-
3104
- /**
3105
- * `Option` conflicts with another option.
3106
- *
3107
- * @param {Option} option
3108
- * @param {Option} conflictingOption
3109
- * @private
3110
- */
3111
- _conflictingOption(option, conflictingOption) {
3112
- // The calling code does not know whether a negated option is the source of the
3113
- // value, so do some work to take an educated guess.
3114
- const findBestOptionFromValue = (option) => {
3115
- const optionKey = option.attributeName();
3116
- const optionValue = this.getOptionValue(optionKey);
3117
- const negativeOption = this.options.find(
3118
- (target) => target.negate && optionKey === target.attributeName(),
3119
- );
3120
- const positiveOption = this.options.find(
3121
- (target) => !target.negate && optionKey === target.attributeName(),
3122
- );
3123
- if (
3124
- negativeOption &&
3125
- ((negativeOption.presetArg === undefined && optionValue === false) ||
3126
- (negativeOption.presetArg !== undefined &&
3127
- optionValue === negativeOption.presetArg))
3128
- ) {
3129
- return negativeOption;
3130
- }
3131
- return positiveOption || option;
3132
- };
3133
-
3134
- const getErrorMessage = (option) => {
3135
- const bestOption = findBestOptionFromValue(option);
3136
- const optionKey = bestOption.attributeName();
3137
- const source = this.getOptionValueSource(optionKey);
3138
- if (source === 'env') {
3139
- return `environment variable '${bestOption.envVar}'`;
3140
- }
3141
- return `option '${bestOption.flags}'`;
3142
- };
3143
-
3144
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3145
- this.error(message, { code: 'commander.conflictingOption' });
3146
- }
3147
-
3148
- /**
3149
- * Unknown option `flag`.
3150
- *
3151
- * @param {string} flag
3152
- * @private
3153
- */
3154
-
3155
- unknownOption(flag) {
3156
- if (this._allowUnknownOption) return;
3157
- let suggestion = '';
3158
-
3159
- if (flag.startsWith('--') && this._showSuggestionAfterError) {
3160
- // Looping to pick up the global options too
3161
- let candidateFlags = [];
3162
- // eslint-disable-next-line @typescript-eslint/no-this-alias
3163
- let command = this;
3164
- do {
3165
- const moreFlags = command
3166
- .createHelp()
3167
- .visibleOptions(command)
3168
- .filter((option) => option.long)
3169
- .map((option) => option.long);
3170
- candidateFlags = candidateFlags.concat(moreFlags);
3171
- command = command.parent;
3172
- } while (command && !command._enablePositionalOptions);
3173
- suggestion = suggestSimilar(flag, candidateFlags);
3174
- }
3175
-
3176
- const message = `error: unknown option '${flag}'${suggestion}`;
3177
- this.error(message, { code: 'commander.unknownOption' });
3178
- }
3179
-
3180
- /**
3181
- * Excess arguments, more than expected.
3182
- *
3183
- * @param {string[]} receivedArgs
3184
- * @private
3185
- */
3186
-
3187
- _excessArguments(receivedArgs) {
3188
- if (this._allowExcessArguments) return;
3189
-
3190
- const expected = this.registeredArguments.length;
3191
- const s = expected === 1 ? '' : 's';
3192
- const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
3193
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
3194
- this.error(message, { code: 'commander.excessArguments' });
3195
- }
3196
-
3197
- /**
3198
- * Unknown command.
3199
- *
3200
- * @private
3201
- */
3202
-
3203
- unknownCommand() {
3204
- const unknownName = this.args[0];
3205
- let suggestion = '';
3206
-
3207
- if (this._showSuggestionAfterError) {
3208
- const candidateNames = [];
3209
- this.createHelp()
3210
- .visibleCommands(this)
3211
- .forEach((command) => {
3212
- candidateNames.push(command.name());
3213
- // just visible alias
3214
- if (command.alias()) candidateNames.push(command.alias());
3215
- });
3216
- suggestion = suggestSimilar(unknownName, candidateNames);
3217
- }
3218
-
3219
- const message = `error: unknown command '${unknownName}'${suggestion}`;
3220
- this.error(message, { code: 'commander.unknownCommand' });
3221
- }
3222
-
3223
- /**
3224
- * Get or set the program version.
3225
- *
3226
- * This method auto-registers the "-V, --version" option which will print the version number.
3227
- *
3228
- * You can optionally supply the flags and description to override the defaults.
3229
- *
3230
- * @param {string} [str]
3231
- * @param {string} [flags]
3232
- * @param {string} [description]
3233
- * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3234
- */
3235
-
3236
- version(str, flags, description) {
3237
- if (str === undefined) return this._version;
3238
- this._version = str;
3239
- flags = flags || '-V, --version';
3240
- description = description || 'output the version number';
3241
- const versionOption = this.createOption(flags, description);
3242
- this._versionOptionName = versionOption.attributeName();
3243
- this._registerOption(versionOption);
3244
-
3245
- this.on('option:' + versionOption.name(), () => {
3246
- this._outputConfiguration.writeOut(`${str}\n`);
3247
- this._exit(0, 'commander.version', str);
3248
- });
3249
- return this;
3250
- }
3251
-
3252
- /**
3253
- * Set the description.
3254
- *
3255
- * @param {string} [str]
3256
- * @param {object} [argsDescription]
3257
- * @return {(string|Command)}
3258
- */
3259
- description(str, argsDescription) {
3260
- if (str === undefined && argsDescription === undefined)
3261
- return this._description;
3262
- this._description = str;
3263
- if (argsDescription) {
3264
- this._argsDescription = argsDescription;
3265
- }
3266
- return this;
3267
- }
3268
-
3269
- /**
3270
- * Set the summary. Used when listed as subcommand of parent.
3271
- *
3272
- * @param {string} [str]
3273
- * @return {(string|Command)}
3274
- */
3275
- summary(str) {
3276
- if (str === undefined) return this._summary;
3277
- this._summary = str;
3278
- return this;
3279
- }
3280
-
3281
- /**
3282
- * Set an alias for the command.
3283
- *
3284
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3285
- *
3286
- * @param {string} [alias]
3287
- * @return {(string|Command)}
3288
- */
3289
-
3290
- alias(alias) {
3291
- if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
3292
-
3293
- /** @type {Command} */
3294
- // eslint-disable-next-line @typescript-eslint/no-this-alias
3295
- let command = this;
3296
- if (
3297
- this.commands.length !== 0 &&
3298
- this.commands[this.commands.length - 1]._executableHandler
3299
- ) {
3300
- // assume adding alias for last added executable subcommand, rather than this
3301
- command = this.commands[this.commands.length - 1];
3302
- }
3303
-
3304
- if (alias === command._name)
3305
- throw new Error("Command alias can't be the same as its name");
3306
- const matchingCommand = this.parent?._findCommand(alias);
3307
- if (matchingCommand) {
3308
- // c.f. _registerCommand
3309
- const existingCmd = [matchingCommand.name()]
3310
- .concat(matchingCommand.aliases())
3311
- .join('|');
3312
- throw new Error(
3313
- `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
3314
- );
3315
- }
3316
-
3317
- command._aliases.push(alias);
3318
- return this;
3319
- }
3320
-
3321
- /**
3322
- * Set aliases for the command.
3323
- *
3324
- * Only the first alias is shown in the auto-generated help.
3325
- *
3326
- * @param {string[]} [aliases]
3327
- * @return {(string[]|Command)}
3328
- */
3329
-
3330
- aliases(aliases) {
3331
- // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
3332
- if (aliases === undefined) return this._aliases;
3333
-
3334
- aliases.forEach((alias) => this.alias(alias));
3335
- return this;
3336
- }
3337
-
3338
- /**
3339
- * Set / get the command usage `str`.
3340
- *
3341
- * @param {string} [str]
3342
- * @return {(string|Command)}
3343
- */
3344
-
3345
- usage(str) {
3346
- if (str === undefined) {
3347
- if (this._usage) return this._usage;
3348
-
3349
- const args = this.registeredArguments.map((arg) => {
3350
- return humanReadableArgName(arg);
3351
- });
3352
- return []
3353
- .concat(
3354
- this.options.length || this._helpOption !== null ? '[options]' : [],
3355
- this.commands.length ? '[command]' : [],
3356
- this.registeredArguments.length ? args : [],
3357
- )
3358
- .join(' ');
3359
- }
3360
-
3361
- this._usage = str;
3362
- return this;
3363
- }
3364
-
3365
- /**
3366
- * Get or set the name of the command.
3367
- *
3368
- * @param {string} [str]
3369
- * @return {(string|Command)}
3370
- */
3371
-
3372
- name(str) {
3373
- if (str === undefined) return this._name;
3374
- this._name = str;
3375
- return this;
3376
- }
3377
-
3378
- /**
3379
- * Set the name of the command from script filename, such as process.argv[1],
3380
- * or require.main.filename, or __filename.
3381
- *
3382
- * (Used internally and public although not documented in README.)
3383
- *
3384
- * @example
3385
- * program.nameFromFilename(require.main.filename);
3386
- *
3387
- * @param {string} filename
3388
- * @return {Command}
3389
- */
3390
-
3391
- nameFromFilename(filename) {
3392
- this._name = path.basename(filename, path.extname(filename));
3393
-
3394
- return this;
3395
- }
3396
-
3397
- /**
3398
- * Get or set the directory for searching for executable subcommands of this command.
3399
- *
3400
- * @example
3401
- * program.executableDir(__dirname);
3402
- * // or
3403
- * program.executableDir('subcommands');
3404
- *
3405
- * @param {string} [path]
3406
- * @return {(string|null|Command)}
3407
- */
3408
-
3409
- executableDir(path) {
3410
- if (path === undefined) return this._executableDir;
3411
- this._executableDir = path;
3412
- return this;
3413
- }
3414
-
3415
- /**
3416
- * Return program help documentation.
3417
- *
3418
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3419
- * @return {string}
3420
- */
3421
-
3422
- helpInformation(contextOptions) {
3423
- const helper = this.createHelp();
3424
- if (helper.helpWidth === undefined) {
3425
- helper.helpWidth =
3426
- contextOptions && contextOptions.error
3427
- ? this._outputConfiguration.getErrHelpWidth()
3428
- : this._outputConfiguration.getOutHelpWidth();
3429
- }
3430
- return helper.formatHelp(this, helper);
3431
- }
3432
-
3433
- /**
3434
- * @private
3435
- */
3436
-
3437
- _getHelpContext(contextOptions) {
3438
- contextOptions = contextOptions || {};
3439
- const context = { error: !!contextOptions.error };
3440
- let write;
3441
- if (context.error) {
3442
- write = (arg) => this._outputConfiguration.writeErr(arg);
3443
- } else {
3444
- write = (arg) => this._outputConfiguration.writeOut(arg);
3445
- }
3446
- context.write = contextOptions.write || write;
3447
- context.command = this;
3448
- return context;
3449
- }
3450
-
3451
- /**
3452
- * Output help information for this command.
3453
- *
3454
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3455
- *
3456
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3457
- */
3458
-
3459
- outputHelp(contextOptions) {
3460
- let deprecatedCallback;
3461
- if (typeof contextOptions === 'function') {
3462
- deprecatedCallback = contextOptions;
3463
- contextOptions = undefined;
3464
- }
3465
- const context = this._getHelpContext(contextOptions);
3466
-
3467
- this._getCommandAndAncestors()
3468
- .reverse()
3469
- .forEach((command) => command.emit('beforeAllHelp', context));
3470
- this.emit('beforeHelp', context);
3471
-
3472
- let helpInformation = this.helpInformation(context);
3473
- if (deprecatedCallback) {
3474
- helpInformation = deprecatedCallback(helpInformation);
3475
- if (
3476
- typeof helpInformation !== 'string' &&
3477
- !Buffer.isBuffer(helpInformation)
3478
- ) {
3479
- throw new Error('outputHelp callback must return a string or a Buffer');
3480
- }
3481
- }
3482
- context.write(helpInformation);
3483
-
3484
- if (this._getHelpOption()?.long) {
3485
- this.emit(this._getHelpOption().long); // deprecated
3486
- }
3487
- this.emit('afterHelp', context);
3488
- this._getCommandAndAncestors().forEach((command) =>
3489
- command.emit('afterAllHelp', context),
3490
- );
3491
- }
3492
-
3493
- /**
3494
- * You can pass in flags and a description to customise the built-in help option.
3495
- * Pass in false to disable the built-in help option.
3496
- *
3497
- * @example
3498
- * program.helpOption('-?, --help' 'show help'); // customise
3499
- * program.helpOption(false); // disable
3500
- *
3501
- * @param {(string | boolean)} flags
3502
- * @param {string} [description]
3503
- * @return {Command} `this` command for chaining
3504
- */
3505
-
3506
- helpOption(flags, description) {
3507
- // Support disabling built-in help option.
3508
- if (typeof flags === 'boolean') {
3509
- if (flags) {
3510
- this._helpOption = this._helpOption ?? undefined; // preserve existing option
3511
- } else {
3512
- this._helpOption = null; // disable
3513
- }
3514
- return this;
3515
- }
3516
-
3517
- // Customise flags and description.
3518
- flags = flags ?? '-h, --help';
3519
- description = description ?? 'display help for command';
3520
- this._helpOption = this.createOption(flags, description);
3521
-
3522
- return this;
3523
- }
3524
-
3525
- /**
3526
- * Lazy create help option.
3527
- * Returns null if has been disabled with .helpOption(false).
3528
- *
3529
- * @returns {(Option | null)} the help option
3530
- * @package
3531
- */
3532
- _getHelpOption() {
3533
- // Lazy create help option on demand.
3534
- if (this._helpOption === undefined) {
3535
- this.helpOption(undefined, undefined);
3536
- }
3537
- return this._helpOption;
3538
- }
3539
-
3540
- /**
3541
- * Supply your own option to use for the built-in help option.
3542
- * This is an alternative to using helpOption() to customise the flags and description etc.
3543
- *
3544
- * @param {Option} option
3545
- * @return {Command} `this` command for chaining
3546
- */
3547
- addHelpOption(option) {
3548
- this._helpOption = option;
3549
- return this;
3550
- }
3551
-
3552
- /**
3553
- * Output help information and exit.
3554
- *
3555
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3556
- *
3557
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3558
- */
3559
-
3560
- help(contextOptions) {
3561
- this.outputHelp(contextOptions);
3562
- let exitCode = process$1.exitCode || 0;
3563
- if (
3564
- exitCode === 0 &&
3565
- contextOptions &&
3566
- typeof contextOptions !== 'function' &&
3567
- contextOptions.error
3568
- ) {
3569
- exitCode = 1;
3570
- }
3571
- // message: do not have all displayed text available so only passing placeholder.
3572
- this._exit(exitCode, 'commander.help', '(outputHelp)');
3573
- }
3574
-
3575
- /**
3576
- * Add additional text to be displayed with the built-in help.
3577
- *
3578
- * Position is 'before' or 'after' to affect just this command,
3579
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3580
- *
3581
- * @param {string} position - before or after built-in help
3582
- * @param {(string | Function)} text - string to add, or a function returning a string
3583
- * @return {Command} `this` command for chaining
3584
- */
3585
- addHelpText(position, text) {
3586
- const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
3587
- if (!allowedValues.includes(position)) {
3588
- throw new Error(`Unexpected value for position to addHelpText.
3589
- Expecting one of '${allowedValues.join("', '")}'`);
3590
- }
3591
- const helpEvent = `${position}Help`;
3592
- this.on(helpEvent, (context) => {
3593
- let helpStr;
3594
- if (typeof text === 'function') {
3595
- helpStr = text({ error: context.error, command: context.command });
3596
- } else {
3597
- helpStr = text;
3598
- }
3599
- // Ignore falsy value when nothing to output.
3600
- if (helpStr) {
3601
- context.write(`${helpStr}\n`);
3602
- }
3603
- });
3604
- return this;
3605
- }
3606
-
3607
- /**
3608
- * Output help information if help flags specified
3609
- *
3610
- * @param {Array} args - array of options to search for help flags
3611
- * @private
3612
- */
3613
-
3614
- _outputHelpIfRequested(args) {
3615
- const helpOption = this._getHelpOption();
3616
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3617
- if (helpRequested) {
3618
- this.outputHelp();
3619
- // (Do not have all displayed text available so only passing placeholder.)
3620
- this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
3621
- }
3622
- }
3623
- };
3624
-
3625
- /**
3626
- * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
3627
- *
3628
- * @param {string[]} args - array of arguments from node.execArgv
3629
- * @returns {string[]}
3630
- * @private
3631
- */
3632
-
3633
- function incrementNodeInspectorPort(args) {
3634
- // Testing for these options:
3635
- // --inspect[=[host:]port]
3636
- // --inspect-brk[=[host:]port]
3637
- // --inspect-port=[host:]port
3638
- return args.map((arg) => {
3639
- if (!arg.startsWith('--inspect')) {
3640
- return arg;
3641
- }
3642
- let debugOption;
3643
- let debugHost = '127.0.0.1';
3644
- let debugPort = '9229';
3645
- let match;
3646
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3647
- // e.g. --inspect
3648
- debugOption = match[1];
3649
- } else if (
3650
- (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
3651
- ) {
3652
- debugOption = match[1];
3653
- if (/^\d+$/.test(match[3])) {
3654
- // e.g. --inspect=1234
3655
- debugPort = match[3];
3656
- } else {
3657
- // e.g. --inspect=localhost
3658
- debugHost = match[3];
3659
- }
3660
- } else if (
3661
- (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
3662
- ) {
3663
- // e.g. --inspect=localhost:1234
3664
- debugOption = match[1];
3665
- debugHost = match[3];
3666
- debugPort = match[4];
3667
- }
3668
-
3669
- if (debugOption && debugPort !== '0') {
3670
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3671
- }
3672
- return arg;
3673
- });
3674
- }
3675
-
3676
- command.Command = Command$2;
3677
-
3678
- const { Argument: Argument$1 } = argument;
3679
- const { Command: Command$1 } = command;
3680
- const { CommanderError: CommanderError$1, InvalidArgumentError: InvalidArgumentError$1 } = error;
3681
- const { Help: Help$1 } = help;
3682
- const { Option: Option$1 } = option;
3683
-
3684
- commander.program = new Command$1();
3685
-
3686
- commander.createCommand = (name) => new Command$1(name);
3687
- commander.createOption = (flags, description) => new Option$1(flags, description);
3688
- commander.createArgument = (name, description) => new Argument$1(name, description);
3689
-
3690
- /**
3691
- * Expose classes
3692
- */
3693
-
3694
- commander.Command = Command$1;
3695
- commander.Option = Option$1;
3696
- commander.Argument = Argument$1;
3697
- commander.Help = Help$1;
3698
-
3699
- commander.CommanderError = CommanderError$1;
3700
- commander.InvalidArgumentError = InvalidArgumentError$1;
3701
- commander.InvalidOptionArgumentError = InvalidArgumentError$1; // Deprecated
3702
-
3703
- // wrapper to provide named exports for ESM.
3704
- const {
3705
- program: program$1,
3706
- createCommand,
3707
- createArgument,
3708
- createOption,
3709
- CommanderError,
3710
- InvalidArgumentError,
3711
- InvalidOptionArgumentError, // deprecated old name
3712
- Command,
3713
- Argument,
3714
- Option,
3715
- Help,
3716
- } = commander;
3717
-
3718
- var version = "1.8.0";
3719
-
3720
- process.on("uncaughtException", function (error) {
3721
- console.error(`${new Date().toISOString()} uncaughtException`, error);
3722
- });
3723
- process.on("unhandledRejection", function (error) {
3724
- console.error(`${new Date().toISOString()} unhandledRejection`, error);
3725
- });
3726
- const program = new Command();
3727
- program.name("biliLive").description("biliLive-tools命令行").version(version);
3728
- program
3729
- .command("server")
3730
- .description("开启服务")
3731
- .option("-c, --config <string>", "配置文件路径", "config.json")
3732
- .option("-h, --host <string>", "host")
3733
- .option("-p, --port <number>", "port")
3734
- .action(async (opts) => {
3735
- if (!fs$1.existsSync(opts.config)) {
3736
- console.error("请先运行 config gen 命令生成配置文件");
3737
- return;
3738
- }
3739
- const c = JSON.parse(fs$1.readFileSync(opts.config).toString());
3740
- if (c?.configFolder === undefined) {
3741
- throw new Error(`${c.configFolder}参数不存在,请先重新运行 config gen 命令`);
3742
- }
3743
- // 下面两行顺序不能换(
3744
- const { init } = await Promise.resolve().then(function () { return require('./index-CEo5tP7w.cjs'); }).then(function (n) { return n.index; });
3745
- const { serverStart } = await Promise.resolve().then(function () { return require('./index-nT_yCbCf.cjs'); });
3746
- const globalConfig = {
3747
- ffmpegPresetPath: path$1.join(c.configFolder, "ffmpeg_presets.json"),
3748
- videoPresetPath: path$1.join(c.configFolder, "presets.json"),
3749
- danmuPresetPath: path$1.join(c.configFolder, "danmu_presets.json"),
3750
- configPath: path$1.join(c.configFolder, "appConfig.json"),
3751
- logPath: c.logPath,
3752
- defaultFfmpegPath: c.ffmpegPath,
3753
- defaultFfprobePath: c.ffprobePath,
3754
- defaultDanmakuFactoryPath: c.danmakuFactoryPath,
3755
- version: version,
3756
- userDataPath: c.configFolder,
3757
- };
3758
- const container = await init(globalConfig);
3759
- const appConfig = container.resolve("appConfig");
3760
- const passKey = process.env.BILILIVE_TOOLS_PASSKEY || appConfig.get("passKey");
3761
- if (!passKey) {
3762
- console.warn("如果想使用webui,必须设置鉴权 passKey 参数,具体见文档");
3763
- }
3764
- await serverStart({
3765
- port: opts.port ? Number(opts.port) : c.port,
3766
- host: opts.host ?? c.host,
3767
- auth: true,
3768
- passKey: passKey,
3769
- }, container);
3770
- });
3771
- const configCommand = program.command("config").description("配置相关");
3772
- configCommand
3773
- .command("gen")
3774
- .description("生成配置文件")
3775
- .option("-c, --config <string>", "配置文件路径", "config.json")
3776
- .option("-f, --force", "强制覆盖已有配置文件", false)
3777
- .action(async (opts) => {
3778
- if (fs$1.existsSync(opts.config)) {
3779
- if (opts.force) {
3780
- console.log("配置文件已生成,请根据需求进行修改");
3781
- generateConfig(opts.config);
3782
- }
3783
- else {
3784
- console.error("配置文件已存在,如果想重新生成请使用 -f 参数强制覆盖");
3785
- return;
3786
- }
3787
- }
3788
- else {
3789
- console.log("配置文件已生成,请根据需求进行修改");
3790
- generateConfig(opts.config);
3791
- }
3792
- });
3793
- configCommand
3794
- .command("print")
3795
- .description("打印配置文件")
3796
- .option("-c, --config <string>", "配置文件路径", "config.json")
3797
- .action((opts) => {
3798
- if (!fs$1.existsSync(opts.config)) {
3799
- console.error("配置文件不存在,请先运行 config gen 命令生成配置文件");
3800
- return;
3801
- }
3802
- const c = JSON.parse(fs$1.readFileSync(opts.config).toString());
3803
- console.table(c);
3804
- });
3805
- function generateConfig(configPath) {
3806
- const defaultConfig = {
3807
- port: 18010,
3808
- host: "127.0.0.1",
3809
- configFolder: "",
3810
- ffmpegPath: "ffmpeg.exe",
3811
- ffprobePath: "ffprobe.exe",
3812
- danmakuFactoryPath: "DanmakuFactory.exe",
3813
- logPath: "main.log",
3814
- };
3815
- if (process.platform === "win32") {
3816
- const homedir = os.homedir();
3817
- const configFolder = path$1.join(homedir, "AppData", "Roaming", "biliLive-tools");
3818
- if (fs$1.existsSync(configFolder)) {
3819
- defaultConfig.configFolder = configFolder;
3820
- }
3821
- }
3822
- else if (process.platform === "linux") {
3823
- defaultConfig.ffmpegPath = "ffmpeg";
3824
- defaultConfig.ffprobePath = "ffprobe";
3825
- defaultConfig.danmakuFactoryPath = "DanmakuFactory";
3826
- }
3827
- fs$1.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2));
3828
- return;
3829
- }
3830
- program.parse();