@backstage/codemods 0.1.35 → 0.1.37

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