sdkvm 1.0.1 → 1.0.3
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/README.en.md +39 -30
- package/README.md +39 -30
- package/dist/index.js +3651 -173
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,3470 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
9
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
|
|
28
|
+
// node_modules/picocolors/picocolors.js
|
|
29
|
+
var require_picocolors = __commonJS({
|
|
30
|
+
"node_modules/picocolors/picocolors.js"(exports, module) {
|
|
31
|
+
"use strict";
|
|
32
|
+
var p = process || {};
|
|
33
|
+
var argv = p.argv || [];
|
|
34
|
+
var env = p.env || {};
|
|
35
|
+
var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
|
|
36
|
+
var formatter = (open, close, replace = open) => (input) => {
|
|
37
|
+
let string = "" + input, index = string.indexOf(close, open.length);
|
|
38
|
+
return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
|
|
39
|
+
};
|
|
40
|
+
var replaceClose = (string, close, replace, index) => {
|
|
41
|
+
let result = "", cursor = 0;
|
|
42
|
+
do {
|
|
43
|
+
result += string.substring(cursor, index) + replace;
|
|
44
|
+
cursor = index + close.length;
|
|
45
|
+
index = string.indexOf(close, cursor);
|
|
46
|
+
} while (~index);
|
|
47
|
+
return result + string.substring(cursor);
|
|
48
|
+
};
|
|
49
|
+
var createColors = (enabled = isColorSupported) => {
|
|
50
|
+
let f = enabled ? formatter : () => String;
|
|
51
|
+
return {
|
|
52
|
+
isColorSupported: enabled,
|
|
53
|
+
reset: f("\x1B[0m", "\x1B[0m"),
|
|
54
|
+
bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
|
|
55
|
+
dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
|
|
56
|
+
italic: f("\x1B[3m", "\x1B[23m"),
|
|
57
|
+
underline: f("\x1B[4m", "\x1B[24m"),
|
|
58
|
+
inverse: f("\x1B[7m", "\x1B[27m"),
|
|
59
|
+
hidden: f("\x1B[8m", "\x1B[28m"),
|
|
60
|
+
strikethrough: f("\x1B[9m", "\x1B[29m"),
|
|
61
|
+
black: f("\x1B[30m", "\x1B[39m"),
|
|
62
|
+
red: f("\x1B[31m", "\x1B[39m"),
|
|
63
|
+
green: f("\x1B[32m", "\x1B[39m"),
|
|
64
|
+
yellow: f("\x1B[33m", "\x1B[39m"),
|
|
65
|
+
blue: f("\x1B[34m", "\x1B[39m"),
|
|
66
|
+
magenta: f("\x1B[35m", "\x1B[39m"),
|
|
67
|
+
cyan: f("\x1B[36m", "\x1B[39m"),
|
|
68
|
+
white: f("\x1B[37m", "\x1B[39m"),
|
|
69
|
+
gray: f("\x1B[90m", "\x1B[39m"),
|
|
70
|
+
bgBlack: f("\x1B[40m", "\x1B[49m"),
|
|
71
|
+
bgRed: f("\x1B[41m", "\x1B[49m"),
|
|
72
|
+
bgGreen: f("\x1B[42m", "\x1B[49m"),
|
|
73
|
+
bgYellow: f("\x1B[43m", "\x1B[49m"),
|
|
74
|
+
bgBlue: f("\x1B[44m", "\x1B[49m"),
|
|
75
|
+
bgMagenta: f("\x1B[45m", "\x1B[49m"),
|
|
76
|
+
bgCyan: f("\x1B[46m", "\x1B[49m"),
|
|
77
|
+
bgWhite: f("\x1B[47m", "\x1B[49m"),
|
|
78
|
+
blackBright: f("\x1B[90m", "\x1B[39m"),
|
|
79
|
+
redBright: f("\x1B[91m", "\x1B[39m"),
|
|
80
|
+
greenBright: f("\x1B[92m", "\x1B[39m"),
|
|
81
|
+
yellowBright: f("\x1B[93m", "\x1B[39m"),
|
|
82
|
+
blueBright: f("\x1B[94m", "\x1B[39m"),
|
|
83
|
+
magentaBright: f("\x1B[95m", "\x1B[39m"),
|
|
84
|
+
cyanBright: f("\x1B[96m", "\x1B[39m"),
|
|
85
|
+
whiteBright: f("\x1B[97m", "\x1B[39m"),
|
|
86
|
+
bgBlackBright: f("\x1B[100m", "\x1B[49m"),
|
|
87
|
+
bgRedBright: f("\x1B[101m", "\x1B[49m"),
|
|
88
|
+
bgGreenBright: f("\x1B[102m", "\x1B[49m"),
|
|
89
|
+
bgYellowBright: f("\x1B[103m", "\x1B[49m"),
|
|
90
|
+
bgBlueBright: f("\x1B[104m", "\x1B[49m"),
|
|
91
|
+
bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
|
|
92
|
+
bgCyanBright: f("\x1B[106m", "\x1B[49m"),
|
|
93
|
+
bgWhiteBright: f("\x1B[107m", "\x1B[49m")
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
module.exports = createColors();
|
|
97
|
+
module.exports.createColors = createColors;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// node_modules/commander/lib/error.js
|
|
102
|
+
var CommanderError = class extends Error {
|
|
103
|
+
/**
|
|
104
|
+
* Constructs the CommanderError class
|
|
105
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
106
|
+
* @param {string} code an id string representing the error
|
|
107
|
+
* @param {string} message human-readable description of the error
|
|
108
|
+
*/
|
|
109
|
+
constructor(exitCode, code, message) {
|
|
110
|
+
super(message);
|
|
111
|
+
Error.captureStackTrace(this, this.constructor);
|
|
112
|
+
this.name = this.constructor.name;
|
|
113
|
+
this.code = code;
|
|
114
|
+
this.exitCode = exitCode;
|
|
115
|
+
this.nestedError = void 0;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
119
|
+
/**
|
|
120
|
+
* Constructs the InvalidArgumentError class
|
|
121
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
122
|
+
*/
|
|
123
|
+
constructor(message) {
|
|
124
|
+
super(1, "commander.invalidArgument", message);
|
|
125
|
+
Error.captureStackTrace(this, this.constructor);
|
|
126
|
+
this.name = this.constructor.name;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
// node_modules/commander/lib/argument.js
|
|
131
|
+
var Argument = class {
|
|
132
|
+
/**
|
|
133
|
+
* Initialize a new command argument with the given name and description.
|
|
134
|
+
* The default is that the argument is required, and you can explicitly
|
|
135
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
136
|
+
*
|
|
137
|
+
* @param {string} name
|
|
138
|
+
* @param {string} [description]
|
|
139
|
+
*/
|
|
140
|
+
constructor(name, description) {
|
|
141
|
+
this.description = description || "";
|
|
142
|
+
this.variadic = false;
|
|
143
|
+
this.parseArg = void 0;
|
|
144
|
+
this.defaultValue = void 0;
|
|
145
|
+
this.defaultValueDescription = void 0;
|
|
146
|
+
this.argChoices = void 0;
|
|
147
|
+
switch (name[0]) {
|
|
148
|
+
case "<":
|
|
149
|
+
this.required = true;
|
|
150
|
+
this._name = name.slice(1, -1);
|
|
151
|
+
break;
|
|
152
|
+
case "[":
|
|
153
|
+
this.required = false;
|
|
154
|
+
this._name = name.slice(1, -1);
|
|
155
|
+
break;
|
|
156
|
+
default:
|
|
157
|
+
this.required = true;
|
|
158
|
+
this._name = name;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
if (this._name.endsWith("...")) {
|
|
162
|
+
this.variadic = true;
|
|
163
|
+
this._name = this._name.slice(0, -3);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Return argument name.
|
|
168
|
+
*
|
|
169
|
+
* @return {string}
|
|
170
|
+
*/
|
|
171
|
+
name() {
|
|
172
|
+
return this._name;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* @package
|
|
176
|
+
*/
|
|
177
|
+
_collectValue(value, previous) {
|
|
178
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
179
|
+
return [value];
|
|
180
|
+
}
|
|
181
|
+
previous.push(value);
|
|
182
|
+
return previous;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
186
|
+
*
|
|
187
|
+
* @param {*} value
|
|
188
|
+
* @param {string} [description]
|
|
189
|
+
* @return {Argument}
|
|
190
|
+
*/
|
|
191
|
+
default(value, description) {
|
|
192
|
+
this.defaultValue = value;
|
|
193
|
+
this.defaultValueDescription = description;
|
|
194
|
+
return this;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
198
|
+
*
|
|
199
|
+
* @param {Function} [fn]
|
|
200
|
+
* @return {Argument}
|
|
201
|
+
*/
|
|
202
|
+
argParser(fn) {
|
|
203
|
+
this.parseArg = fn;
|
|
204
|
+
return this;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Only allow argument value to be one of choices.
|
|
208
|
+
*
|
|
209
|
+
* @param {string[]} values
|
|
210
|
+
* @return {Argument}
|
|
211
|
+
*/
|
|
212
|
+
choices(values) {
|
|
213
|
+
this.argChoices = values.slice();
|
|
214
|
+
this.parseArg = (arg, previous) => {
|
|
215
|
+
if (!this.argChoices.includes(arg)) {
|
|
216
|
+
throw new InvalidArgumentError(
|
|
217
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
if (this.variadic) {
|
|
221
|
+
return this._collectValue(arg, previous);
|
|
222
|
+
}
|
|
223
|
+
return arg;
|
|
224
|
+
};
|
|
225
|
+
return this;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Make argument required.
|
|
229
|
+
*
|
|
230
|
+
* @returns {Argument}
|
|
231
|
+
*/
|
|
232
|
+
argRequired() {
|
|
233
|
+
this.required = true;
|
|
234
|
+
return this;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Make argument optional.
|
|
238
|
+
*
|
|
239
|
+
* @returns {Argument}
|
|
240
|
+
*/
|
|
241
|
+
argOptional() {
|
|
242
|
+
this.required = false;
|
|
243
|
+
return this;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
function humanReadableArgName(arg) {
|
|
247
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
248
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// node_modules/commander/lib/command.js
|
|
252
|
+
import { EventEmitter } from "events";
|
|
253
|
+
import childProcess from "child_process";
|
|
254
|
+
import path from "path";
|
|
255
|
+
import fs from "fs";
|
|
256
|
+
import process2 from "process";
|
|
257
|
+
import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
|
|
258
|
+
|
|
259
|
+
// node_modules/commander/lib/help.js
|
|
260
|
+
import { stripVTControlCharacters } from "util";
|
|
261
|
+
var Help = class {
|
|
262
|
+
constructor() {
|
|
263
|
+
this.helpWidth = void 0;
|
|
264
|
+
this.minWidthToWrap = 40;
|
|
265
|
+
this.sortSubcommands = false;
|
|
266
|
+
this.sortOptions = false;
|
|
267
|
+
this.showGlobalOptions = false;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
271
|
+
* and just before calling `formatHelp()`.
|
|
272
|
+
*
|
|
273
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
274
|
+
*
|
|
275
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
276
|
+
*/
|
|
277
|
+
prepareContext(contextOptions) {
|
|
278
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
282
|
+
*
|
|
283
|
+
* @param {Command} cmd
|
|
284
|
+
* @returns {Command[]}
|
|
285
|
+
*/
|
|
286
|
+
visibleCommands(cmd) {
|
|
287
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
288
|
+
const helpCommand = cmd._getHelpCommand();
|
|
289
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
290
|
+
visibleCommands.push(helpCommand);
|
|
291
|
+
}
|
|
292
|
+
if (this.sortSubcommands) {
|
|
293
|
+
visibleCommands.sort((a, b) => {
|
|
294
|
+
return a.name().localeCompare(b.name());
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
return visibleCommands;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Compare options for sort.
|
|
301
|
+
*
|
|
302
|
+
* @param {Option} a
|
|
303
|
+
* @param {Option} b
|
|
304
|
+
* @returns {number}
|
|
305
|
+
*/
|
|
306
|
+
compareOptions(a, b) {
|
|
307
|
+
const getSortKey = (option) => {
|
|
308
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
309
|
+
};
|
|
310
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
314
|
+
*
|
|
315
|
+
* @param {Command} cmd
|
|
316
|
+
* @returns {Option[]}
|
|
317
|
+
*/
|
|
318
|
+
visibleOptions(cmd) {
|
|
319
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
320
|
+
const helpOption = cmd._getHelpOption();
|
|
321
|
+
if (helpOption && !helpOption.hidden) {
|
|
322
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
323
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
324
|
+
if (!removeShort && !removeLong) {
|
|
325
|
+
visibleOptions.push(helpOption);
|
|
326
|
+
} else if (helpOption.long && !removeLong) {
|
|
327
|
+
visibleOptions.push(
|
|
328
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
329
|
+
);
|
|
330
|
+
} else if (helpOption.short && !removeShort) {
|
|
331
|
+
visibleOptions.push(
|
|
332
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (this.sortOptions) {
|
|
337
|
+
visibleOptions.sort(this.compareOptions);
|
|
338
|
+
}
|
|
339
|
+
return visibleOptions;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Get an array of the visible global options. (Not including help.)
|
|
343
|
+
*
|
|
344
|
+
* @param {Command} cmd
|
|
345
|
+
* @returns {Option[]}
|
|
346
|
+
*/
|
|
347
|
+
visibleGlobalOptions(cmd) {
|
|
348
|
+
if (!this.showGlobalOptions) return [];
|
|
349
|
+
const globalOptions = [];
|
|
350
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
351
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
352
|
+
(option) => !option.hidden
|
|
353
|
+
);
|
|
354
|
+
globalOptions.push(...visibleOptions);
|
|
355
|
+
}
|
|
356
|
+
if (this.sortOptions) {
|
|
357
|
+
globalOptions.sort(this.compareOptions);
|
|
358
|
+
}
|
|
359
|
+
return globalOptions;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Get an array of the arguments if any have a description.
|
|
363
|
+
*
|
|
364
|
+
* @param {Command} cmd
|
|
365
|
+
* @returns {Argument[]}
|
|
366
|
+
*/
|
|
367
|
+
visibleArguments(cmd) {
|
|
368
|
+
if (cmd._argsDescription) {
|
|
369
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
370
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
374
|
+
return cmd.registeredArguments;
|
|
375
|
+
}
|
|
376
|
+
return [];
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Get the command term to show in the list of subcommands.
|
|
380
|
+
*
|
|
381
|
+
* @param {Command} cmd
|
|
382
|
+
* @returns {string}
|
|
383
|
+
*/
|
|
384
|
+
subcommandTerm(cmd) {
|
|
385
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
386
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
387
|
+
(args ? " " + args : "");
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Get the option term to show in the list of options.
|
|
391
|
+
*
|
|
392
|
+
* @param {Option} option
|
|
393
|
+
* @returns {string}
|
|
394
|
+
*/
|
|
395
|
+
optionTerm(option) {
|
|
396
|
+
return option.flags;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Get the argument term to show in the list of arguments.
|
|
400
|
+
*
|
|
401
|
+
* @param {Argument} argument
|
|
402
|
+
* @returns {string}
|
|
403
|
+
*/
|
|
404
|
+
argumentTerm(argument) {
|
|
405
|
+
return argument.name();
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Get the longest command term length.
|
|
409
|
+
*
|
|
410
|
+
* @param {Command} cmd
|
|
411
|
+
* @param {Help} helper
|
|
412
|
+
* @returns {number}
|
|
413
|
+
*/
|
|
414
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
415
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
416
|
+
return Math.max(
|
|
417
|
+
max,
|
|
418
|
+
this.displayWidth(
|
|
419
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
420
|
+
)
|
|
421
|
+
);
|
|
422
|
+
}, 0);
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Get the longest option term length.
|
|
426
|
+
*
|
|
427
|
+
* @param {Command} cmd
|
|
428
|
+
* @param {Help} helper
|
|
429
|
+
* @returns {number}
|
|
430
|
+
*/
|
|
431
|
+
longestOptionTermLength(cmd, helper) {
|
|
432
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
433
|
+
return Math.max(
|
|
434
|
+
max,
|
|
435
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
436
|
+
);
|
|
437
|
+
}, 0);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Get the longest global option term length.
|
|
441
|
+
*
|
|
442
|
+
* @param {Command} cmd
|
|
443
|
+
* @param {Help} helper
|
|
444
|
+
* @returns {number}
|
|
445
|
+
*/
|
|
446
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
447
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
448
|
+
return Math.max(
|
|
449
|
+
max,
|
|
450
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
451
|
+
);
|
|
452
|
+
}, 0);
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Get the longest argument term length.
|
|
456
|
+
*
|
|
457
|
+
* @param {Command} cmd
|
|
458
|
+
* @param {Help} helper
|
|
459
|
+
* @returns {number}
|
|
460
|
+
*/
|
|
461
|
+
longestArgumentTermLength(cmd, helper) {
|
|
462
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
463
|
+
return Math.max(
|
|
464
|
+
max,
|
|
465
|
+
this.displayWidth(
|
|
466
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
467
|
+
)
|
|
468
|
+
);
|
|
469
|
+
}, 0);
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
473
|
+
*
|
|
474
|
+
* @param {Command} cmd
|
|
475
|
+
* @returns {string}
|
|
476
|
+
*/
|
|
477
|
+
commandUsage(cmd) {
|
|
478
|
+
let cmdName = cmd._name;
|
|
479
|
+
if (cmd._aliases[0]) {
|
|
480
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
481
|
+
}
|
|
482
|
+
let ancestorCmdNames = "";
|
|
483
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
484
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
485
|
+
}
|
|
486
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Get the description for the command.
|
|
490
|
+
*
|
|
491
|
+
* @param {Command} cmd
|
|
492
|
+
* @returns {string}
|
|
493
|
+
*/
|
|
494
|
+
commandDescription(cmd) {
|
|
495
|
+
return cmd.description();
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
499
|
+
* (Fallback to description for backwards compatibility.)
|
|
500
|
+
*
|
|
501
|
+
* @param {Command} cmd
|
|
502
|
+
* @returns {string}
|
|
503
|
+
*/
|
|
504
|
+
subcommandDescription(cmd) {
|
|
505
|
+
return cmd.summary() || cmd.description();
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Get the option description to show in the list of options.
|
|
509
|
+
*
|
|
510
|
+
* @param {Option} option
|
|
511
|
+
* @return {string}
|
|
512
|
+
*/
|
|
513
|
+
optionDescription(option) {
|
|
514
|
+
const extraInfo = [];
|
|
515
|
+
if (option.argChoices) {
|
|
516
|
+
extraInfo.push(
|
|
517
|
+
// use stringify to match the display of the default value
|
|
518
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
if (option.defaultValue !== void 0) {
|
|
522
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
523
|
+
if (showDefault) {
|
|
524
|
+
extraInfo.push(
|
|
525
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
530
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
531
|
+
}
|
|
532
|
+
if (option.envVar !== void 0) {
|
|
533
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
534
|
+
}
|
|
535
|
+
if (extraInfo.length > 0) {
|
|
536
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
537
|
+
if (option.description) {
|
|
538
|
+
return `${option.description} ${extraDescription}`;
|
|
539
|
+
}
|
|
540
|
+
return extraDescription;
|
|
541
|
+
}
|
|
542
|
+
return option.description;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Get the argument description to show in the list of arguments.
|
|
546
|
+
*
|
|
547
|
+
* @param {Argument} argument
|
|
548
|
+
* @return {string}
|
|
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 !== void 0) {
|
|
559
|
+
extraInfo.push(
|
|
560
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
if (extraInfo.length > 0) {
|
|
564
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
565
|
+
if (argument.description) {
|
|
566
|
+
return `${argument.description} ${extraDescription}`;
|
|
567
|
+
}
|
|
568
|
+
return extraDescription;
|
|
569
|
+
}
|
|
570
|
+
return argument.description;
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
574
|
+
*
|
|
575
|
+
* @param {string} heading
|
|
576
|
+
* @param {string[]} items
|
|
577
|
+
* @param {Help} helper
|
|
578
|
+
* @returns string[]
|
|
579
|
+
*/
|
|
580
|
+
formatItemList(heading, items, helper) {
|
|
581
|
+
if (items.length === 0) return [];
|
|
582
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Group items by their help group heading.
|
|
586
|
+
*
|
|
587
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
588
|
+
* @param {Command[] | Option[]} visibleItems
|
|
589
|
+
* @param {Function} getGroup
|
|
590
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
591
|
+
*/
|
|
592
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
593
|
+
const result = /* @__PURE__ */ new Map();
|
|
594
|
+
unsortedItems.forEach((item) => {
|
|
595
|
+
const group = getGroup(item);
|
|
596
|
+
if (!result.has(group)) result.set(group, []);
|
|
597
|
+
});
|
|
598
|
+
visibleItems.forEach((item) => {
|
|
599
|
+
const group = getGroup(item);
|
|
600
|
+
if (!result.has(group)) {
|
|
601
|
+
result.set(group, []);
|
|
602
|
+
}
|
|
603
|
+
result.get(group).push(item);
|
|
604
|
+
});
|
|
605
|
+
return result;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Generate the built-in help text.
|
|
609
|
+
*
|
|
610
|
+
* @param {Command} cmd
|
|
611
|
+
* @param {Help} helper
|
|
612
|
+
* @returns {string}
|
|
613
|
+
*/
|
|
614
|
+
formatHelp(cmd, helper) {
|
|
615
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
616
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
617
|
+
function callFormatItem(term, description) {
|
|
618
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
619
|
+
}
|
|
620
|
+
let output = [
|
|
621
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
622
|
+
""
|
|
623
|
+
];
|
|
624
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
625
|
+
if (commandDescription.length > 0) {
|
|
626
|
+
output = output.concat([
|
|
627
|
+
helper.boxWrap(
|
|
628
|
+
helper.styleCommandDescription(commandDescription),
|
|
629
|
+
helpWidth
|
|
630
|
+
),
|
|
631
|
+
""
|
|
632
|
+
]);
|
|
633
|
+
}
|
|
634
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
635
|
+
return callFormatItem(
|
|
636
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
637
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
638
|
+
);
|
|
639
|
+
});
|
|
640
|
+
output = output.concat(
|
|
641
|
+
this.formatItemList("Arguments:", argumentList, helper)
|
|
642
|
+
);
|
|
643
|
+
const optionGroups = this.groupItems(
|
|
644
|
+
cmd.options,
|
|
645
|
+
helper.visibleOptions(cmd),
|
|
646
|
+
(option) => option.helpGroupHeading ?? "Options:"
|
|
647
|
+
);
|
|
648
|
+
optionGroups.forEach((options, group) => {
|
|
649
|
+
const optionList = options.map((option) => {
|
|
650
|
+
return callFormatItem(
|
|
651
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
652
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
653
|
+
);
|
|
654
|
+
});
|
|
655
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
656
|
+
});
|
|
657
|
+
if (helper.showGlobalOptions) {
|
|
658
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
659
|
+
return callFormatItem(
|
|
660
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
661
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
662
|
+
);
|
|
663
|
+
});
|
|
664
|
+
output = output.concat(
|
|
665
|
+
this.formatItemList("Global Options:", globalOptionList, helper)
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
const commandGroups = this.groupItems(
|
|
669
|
+
cmd.commands,
|
|
670
|
+
helper.visibleCommands(cmd),
|
|
671
|
+
(sub) => sub.helpGroup() || "Commands:"
|
|
672
|
+
);
|
|
673
|
+
commandGroups.forEach((commands, group) => {
|
|
674
|
+
const commandList = commands.map((sub) => {
|
|
675
|
+
return callFormatItem(
|
|
676
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
|
|
677
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(sub))
|
|
678
|
+
);
|
|
679
|
+
});
|
|
680
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
681
|
+
});
|
|
682
|
+
return output.join("\n");
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
686
|
+
*
|
|
687
|
+
* @param {string} str
|
|
688
|
+
* @returns {number}
|
|
689
|
+
*/
|
|
690
|
+
displayWidth(str) {
|
|
691
|
+
return stripVTControlCharacters(str).length;
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
695
|
+
*
|
|
696
|
+
* @param {string} str
|
|
697
|
+
* @returns {string}
|
|
698
|
+
*/
|
|
699
|
+
styleTitle(str) {
|
|
700
|
+
return str;
|
|
701
|
+
}
|
|
702
|
+
styleUsage(str) {
|
|
703
|
+
return str.split(" ").map((word) => {
|
|
704
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
705
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
706
|
+
if (word[0] === "[" || word[0] === "<")
|
|
707
|
+
return this.styleArgumentText(word);
|
|
708
|
+
return this.styleCommandText(word);
|
|
709
|
+
}).join(" ");
|
|
710
|
+
}
|
|
711
|
+
styleCommandDescription(str) {
|
|
712
|
+
return this.styleDescriptionText(str);
|
|
713
|
+
}
|
|
714
|
+
styleOptionDescription(str) {
|
|
715
|
+
return this.styleDescriptionText(str);
|
|
716
|
+
}
|
|
717
|
+
styleSubcommandDescription(str) {
|
|
718
|
+
return this.styleDescriptionText(str);
|
|
719
|
+
}
|
|
720
|
+
styleArgumentDescription(str) {
|
|
721
|
+
return this.styleDescriptionText(str);
|
|
722
|
+
}
|
|
723
|
+
styleDescriptionText(str) {
|
|
724
|
+
return str;
|
|
725
|
+
}
|
|
726
|
+
styleOptionTerm(str) {
|
|
727
|
+
return this.styleOptionText(str);
|
|
728
|
+
}
|
|
729
|
+
styleSubcommandTerm(str) {
|
|
730
|
+
return str.split(" ").map((word) => {
|
|
731
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
732
|
+
if (word[0] === "[" || word[0] === "<")
|
|
733
|
+
return this.styleArgumentText(word);
|
|
734
|
+
return this.styleSubcommandText(word);
|
|
735
|
+
}).join(" ");
|
|
736
|
+
}
|
|
737
|
+
styleArgumentTerm(str) {
|
|
738
|
+
return this.styleArgumentText(str);
|
|
739
|
+
}
|
|
740
|
+
styleOptionText(str) {
|
|
741
|
+
return str;
|
|
742
|
+
}
|
|
743
|
+
styleArgumentText(str) {
|
|
744
|
+
return str;
|
|
745
|
+
}
|
|
746
|
+
styleSubcommandText(str) {
|
|
747
|
+
return str;
|
|
748
|
+
}
|
|
749
|
+
styleCommandText(str) {
|
|
750
|
+
return str;
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Calculate the pad width from the maximum term length.
|
|
754
|
+
*
|
|
755
|
+
* @param {Command} cmd
|
|
756
|
+
* @param {Help} helper
|
|
757
|
+
* @returns {number}
|
|
758
|
+
*/
|
|
759
|
+
padWidth(cmd, helper) {
|
|
760
|
+
return Math.max(
|
|
761
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
762
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
763
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
764
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
769
|
+
*
|
|
770
|
+
* @param {string} str
|
|
771
|
+
* @returns {boolean}
|
|
772
|
+
*/
|
|
773
|
+
preformatted(str) {
|
|
774
|
+
return /\n[^\S\r\n]/.test(str);
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
778
|
+
*
|
|
779
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
780
|
+
* TTT DDD DDDD
|
|
781
|
+
* DD DDD
|
|
782
|
+
*
|
|
783
|
+
* @param {string} term
|
|
784
|
+
* @param {number} termWidth
|
|
785
|
+
* @param {string} description
|
|
786
|
+
* @param {Help} helper
|
|
787
|
+
* @returns {string}
|
|
788
|
+
*/
|
|
789
|
+
formatItem(term, termWidth, description, helper) {
|
|
790
|
+
const itemIndent = 2;
|
|
791
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
792
|
+
if (!description) return itemIndentStr + term;
|
|
793
|
+
const paddedTerm = term.padEnd(
|
|
794
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
795
|
+
);
|
|
796
|
+
const spacerWidth = 2;
|
|
797
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
798
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
799
|
+
let formattedDescription;
|
|
800
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
801
|
+
formattedDescription = description;
|
|
802
|
+
} else {
|
|
803
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
804
|
+
formattedDescription = wrappedDescription.replace(
|
|
805
|
+
/\n/g,
|
|
806
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
807
|
+
);
|
|
808
|
+
}
|
|
809
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
810
|
+
${itemIndentStr}`);
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
814
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
815
|
+
*
|
|
816
|
+
* @param {string} str
|
|
817
|
+
* @param {number} width
|
|
818
|
+
* @returns {string}
|
|
819
|
+
*/
|
|
820
|
+
boxWrap(str, width) {
|
|
821
|
+
if (width < this.minWidthToWrap) return str;
|
|
822
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
823
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
824
|
+
const wrappedLines = [];
|
|
825
|
+
rawLines.forEach((line) => {
|
|
826
|
+
const chunks = line.match(chunkPattern);
|
|
827
|
+
if (chunks === null) {
|
|
828
|
+
wrappedLines.push("");
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
let sumChunks = [chunks.shift()];
|
|
832
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
833
|
+
chunks.forEach((chunk) => {
|
|
834
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
835
|
+
if (sumWidth + visibleWidth <= width) {
|
|
836
|
+
sumChunks.push(chunk);
|
|
837
|
+
sumWidth += visibleWidth;
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
wrappedLines.push(sumChunks.join(""));
|
|
841
|
+
const nextChunk = chunk.trimStart();
|
|
842
|
+
sumChunks = [nextChunk];
|
|
843
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
844
|
+
});
|
|
845
|
+
wrappedLines.push(sumChunks.join(""));
|
|
846
|
+
});
|
|
847
|
+
return wrappedLines.join("\n");
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
|
|
851
|
+
// node_modules/commander/lib/option.js
|
|
852
|
+
var Option = class {
|
|
853
|
+
/**
|
|
854
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
855
|
+
*
|
|
856
|
+
* @param {string} flags
|
|
857
|
+
* @param {string} [description]
|
|
858
|
+
*/
|
|
859
|
+
constructor(flags, description) {
|
|
860
|
+
this.flags = flags;
|
|
861
|
+
this.description = description || "";
|
|
862
|
+
this.required = flags.includes("<");
|
|
863
|
+
this.optional = flags.includes("[");
|
|
864
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
865
|
+
this.mandatory = false;
|
|
866
|
+
const optionFlags = splitOptionFlags(flags);
|
|
867
|
+
this.short = optionFlags.shortFlag;
|
|
868
|
+
this.long = optionFlags.longFlag;
|
|
869
|
+
this.negate = false;
|
|
870
|
+
if (this.long) {
|
|
871
|
+
this.negate = this.long.startsWith("--no-");
|
|
872
|
+
}
|
|
873
|
+
this.defaultValue = void 0;
|
|
874
|
+
this.defaultValueDescription = void 0;
|
|
875
|
+
this.presetArg = void 0;
|
|
876
|
+
this.envVar = void 0;
|
|
877
|
+
this.parseArg = void 0;
|
|
878
|
+
this.hidden = false;
|
|
879
|
+
this.argChoices = void 0;
|
|
880
|
+
this.conflictsWith = [];
|
|
881
|
+
this.implied = void 0;
|
|
882
|
+
this.helpGroupHeading = void 0;
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
886
|
+
*
|
|
887
|
+
* @param {*} value
|
|
888
|
+
* @param {string} [description]
|
|
889
|
+
* @return {Option}
|
|
890
|
+
*/
|
|
891
|
+
default(value, description) {
|
|
892
|
+
this.defaultValue = value;
|
|
893
|
+
this.defaultValueDescription = description;
|
|
894
|
+
return this;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
898
|
+
* The custom processing (parseArg) is called.
|
|
899
|
+
*
|
|
900
|
+
* @example
|
|
901
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
902
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
903
|
+
*
|
|
904
|
+
* @param {*} arg
|
|
905
|
+
* @return {Option}
|
|
906
|
+
*/
|
|
907
|
+
preset(arg) {
|
|
908
|
+
this.presetArg = arg;
|
|
909
|
+
return this;
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Add option name(s) that conflict with this option.
|
|
913
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
914
|
+
*
|
|
915
|
+
* @example
|
|
916
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
917
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
918
|
+
*
|
|
919
|
+
* @param {(string | string[])} names
|
|
920
|
+
* @return {Option}
|
|
921
|
+
*/
|
|
922
|
+
conflicts(names) {
|
|
923
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
924
|
+
return this;
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
928
|
+
*
|
|
929
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
930
|
+
*
|
|
931
|
+
* @example
|
|
932
|
+
* program
|
|
933
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
934
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
935
|
+
*
|
|
936
|
+
* @param {object} impliedOptionValues
|
|
937
|
+
* @return {Option}
|
|
938
|
+
*/
|
|
939
|
+
implies(impliedOptionValues) {
|
|
940
|
+
let newImplied = impliedOptionValues;
|
|
941
|
+
if (typeof impliedOptionValues === "string") {
|
|
942
|
+
newImplied = { [impliedOptionValues]: true };
|
|
943
|
+
}
|
|
944
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
945
|
+
return this;
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* Set environment variable to check for option value.
|
|
949
|
+
*
|
|
950
|
+
* An environment variable is only used if when processed the current option value is
|
|
951
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
952
|
+
*
|
|
953
|
+
* @param {string} name
|
|
954
|
+
* @return {Option}
|
|
955
|
+
*/
|
|
956
|
+
env(name) {
|
|
957
|
+
this.envVar = name;
|
|
958
|
+
return this;
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
962
|
+
*
|
|
963
|
+
* @param {Function} [fn]
|
|
964
|
+
* @return {Option}
|
|
965
|
+
*/
|
|
966
|
+
argParser(fn) {
|
|
967
|
+
this.parseArg = fn;
|
|
968
|
+
return this;
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
972
|
+
*
|
|
973
|
+
* @param {boolean} [mandatory=true]
|
|
974
|
+
* @return {Option}
|
|
975
|
+
*/
|
|
976
|
+
makeOptionMandatory(mandatory = true) {
|
|
977
|
+
this.mandatory = !!mandatory;
|
|
978
|
+
return this;
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* Hide option in help.
|
|
982
|
+
*
|
|
983
|
+
* @param {boolean} [hide=true]
|
|
984
|
+
* @return {Option}
|
|
985
|
+
*/
|
|
986
|
+
hideHelp(hide = true) {
|
|
987
|
+
this.hidden = !!hide;
|
|
988
|
+
return this;
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* @package
|
|
992
|
+
*/
|
|
993
|
+
_collectValue(value, previous) {
|
|
994
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
995
|
+
return [value];
|
|
996
|
+
}
|
|
997
|
+
previous.push(value);
|
|
998
|
+
return previous;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Only allow option value to be one of choices.
|
|
1002
|
+
*
|
|
1003
|
+
* @param {string[]} values
|
|
1004
|
+
* @return {Option}
|
|
1005
|
+
*/
|
|
1006
|
+
choices(values) {
|
|
1007
|
+
this.argChoices = values.slice();
|
|
1008
|
+
this.parseArg = (arg, previous) => {
|
|
1009
|
+
if (!this.argChoices.includes(arg)) {
|
|
1010
|
+
throw new InvalidArgumentError(
|
|
1011
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
1012
|
+
);
|
|
1013
|
+
}
|
|
1014
|
+
if (this.variadic) {
|
|
1015
|
+
return this._collectValue(arg, previous);
|
|
1016
|
+
}
|
|
1017
|
+
return arg;
|
|
1018
|
+
};
|
|
1019
|
+
return this;
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Return option name.
|
|
1023
|
+
*
|
|
1024
|
+
* @return {string}
|
|
1025
|
+
*/
|
|
1026
|
+
name() {
|
|
1027
|
+
if (this.long) {
|
|
1028
|
+
return this.long.replace(/^--/, "");
|
|
1029
|
+
}
|
|
1030
|
+
return this.short.replace(/^-/, "");
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Return option name, in a camelcase format that can be used
|
|
1034
|
+
* as an object attribute key.
|
|
1035
|
+
*
|
|
1036
|
+
* @return {string}
|
|
1037
|
+
*/
|
|
1038
|
+
attributeName() {
|
|
1039
|
+
if (this.negate) {
|
|
1040
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
1041
|
+
}
|
|
1042
|
+
return camelcase(this.name());
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Set the help group heading.
|
|
1046
|
+
*
|
|
1047
|
+
* @param {string} heading
|
|
1048
|
+
* @return {Option}
|
|
1049
|
+
*/
|
|
1050
|
+
helpGroup(heading) {
|
|
1051
|
+
this.helpGroupHeading = heading;
|
|
1052
|
+
return this;
|
|
1053
|
+
}
|
|
1054
|
+
/**
|
|
1055
|
+
* Check if `arg` matches the short or long flag.
|
|
1056
|
+
*
|
|
1057
|
+
* @param {string} arg
|
|
1058
|
+
* @return {boolean}
|
|
1059
|
+
* @package
|
|
1060
|
+
*/
|
|
1061
|
+
is(arg) {
|
|
1062
|
+
return this.short === arg || this.long === arg;
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Return whether a boolean option.
|
|
1066
|
+
*
|
|
1067
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
1068
|
+
*
|
|
1069
|
+
* @return {boolean}
|
|
1070
|
+
* @package
|
|
1071
|
+
*/
|
|
1072
|
+
isBoolean() {
|
|
1073
|
+
return !this.required && !this.optional && !this.negate;
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
var DualOptions = class {
|
|
1077
|
+
/**
|
|
1078
|
+
* @param {Option[]} options
|
|
1079
|
+
*/
|
|
1080
|
+
constructor(options) {
|
|
1081
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
1082
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
1083
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
1084
|
+
options.forEach((option) => {
|
|
1085
|
+
if (option.negate) {
|
|
1086
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
1087
|
+
} else {
|
|
1088
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
this.negativeOptions.forEach((value, key) => {
|
|
1092
|
+
if (this.positiveOptions.has(key)) {
|
|
1093
|
+
this.dualOptions.add(key);
|
|
1094
|
+
}
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1099
|
+
*
|
|
1100
|
+
* @param {*} value
|
|
1101
|
+
* @param {Option} option
|
|
1102
|
+
* @returns {boolean}
|
|
1103
|
+
*/
|
|
1104
|
+
valueFromOption(value, option) {
|
|
1105
|
+
const optionKey = option.attributeName();
|
|
1106
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1107
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1108
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1109
|
+
return option.negate === (negativeValue === value);
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
function camelcase(str) {
|
|
1113
|
+
return str.split("-").reduce((str2, word) => {
|
|
1114
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1117
|
+
function splitOptionFlags(flags) {
|
|
1118
|
+
let shortFlag;
|
|
1119
|
+
let longFlag;
|
|
1120
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1121
|
+
const longFlagExp = /^--[^-]/;
|
|
1122
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1123
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1124
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1125
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1126
|
+
shortFlag = flagParts.shift();
|
|
1127
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1128
|
+
shortFlag = longFlag;
|
|
1129
|
+
longFlag = flagParts.shift();
|
|
1130
|
+
}
|
|
1131
|
+
if (flagParts[0].startsWith("-")) {
|
|
1132
|
+
const unsupportedFlag = flagParts[0];
|
|
1133
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1134
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1135
|
+
throw new Error(
|
|
1136
|
+
`${baseError}
|
|
1137
|
+
- a short flag is a single dash and a single character
|
|
1138
|
+
- either use a single dash and a single character (for a short flag)
|
|
1139
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1140
|
+
);
|
|
1141
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1142
|
+
throw new Error(`${baseError}
|
|
1143
|
+
- too many short flags`);
|
|
1144
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1145
|
+
throw new Error(`${baseError}
|
|
1146
|
+
- too many long flags`);
|
|
1147
|
+
throw new Error(`${baseError}
|
|
1148
|
+
- unrecognised flag format`);
|
|
1149
|
+
}
|
|
1150
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1151
|
+
throw new Error(
|
|
1152
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1153
|
+
);
|
|
1154
|
+
return { shortFlag, longFlag };
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1158
|
+
var maxDistance = 3;
|
|
1159
|
+
function editDistance(a, b) {
|
|
1160
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1161
|
+
return Math.max(a.length, b.length);
|
|
1162
|
+
const d = [];
|
|
1163
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1164
|
+
d[i] = [i];
|
|
1165
|
+
}
|
|
1166
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1167
|
+
d[0][j] = j;
|
|
1168
|
+
}
|
|
1169
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1170
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1171
|
+
let cost;
|
|
1172
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1173
|
+
cost = 0;
|
|
1174
|
+
} else {
|
|
1175
|
+
cost = 1;
|
|
1176
|
+
}
|
|
1177
|
+
d[i][j] = Math.min(
|
|
1178
|
+
d[i - 1][j] + 1,
|
|
1179
|
+
// deletion
|
|
1180
|
+
d[i][j - 1] + 1,
|
|
1181
|
+
// insertion
|
|
1182
|
+
d[i - 1][j - 1] + cost
|
|
1183
|
+
// substitution
|
|
1184
|
+
);
|
|
1185
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1186
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
return d[a.length][b.length];
|
|
1191
|
+
}
|
|
1192
|
+
function suggestSimilar(word, candidates) {
|
|
1193
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1194
|
+
candidates = Array.from(new Set(candidates));
|
|
1195
|
+
const searchingOptions = word.startsWith("--");
|
|
1196
|
+
if (searchingOptions) {
|
|
1197
|
+
word = word.slice(2);
|
|
1198
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1199
|
+
}
|
|
1200
|
+
let similar = [];
|
|
1201
|
+
let bestDistance = maxDistance;
|
|
1202
|
+
const minSimilarity = 0.4;
|
|
1203
|
+
candidates.forEach((candidate) => {
|
|
1204
|
+
if (candidate.length <= 1) return;
|
|
1205
|
+
const distance = editDistance(word, candidate);
|
|
1206
|
+
const length = Math.max(word.length, candidate.length);
|
|
1207
|
+
const similarity = (length - distance) / length;
|
|
1208
|
+
if (similarity > minSimilarity) {
|
|
1209
|
+
if (distance < bestDistance) {
|
|
1210
|
+
bestDistance = distance;
|
|
1211
|
+
similar = [candidate];
|
|
1212
|
+
} else if (distance === bestDistance) {
|
|
1213
|
+
similar.push(candidate);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1218
|
+
if (searchingOptions) {
|
|
1219
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1220
|
+
}
|
|
1221
|
+
if (similar.length > 1) {
|
|
1222
|
+
return `
|
|
1223
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1224
|
+
}
|
|
1225
|
+
if (similar.length === 1) {
|
|
1226
|
+
return `
|
|
1227
|
+
(Did you mean ${similar[0]}?)`;
|
|
1228
|
+
}
|
|
1229
|
+
return "";
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
// node_modules/commander/lib/command.js
|
|
1233
|
+
var Command = class _Command extends EventEmitter {
|
|
1234
|
+
/**
|
|
1235
|
+
* Initialize a new `Command`.
|
|
1236
|
+
*
|
|
1237
|
+
* @param {string} [name]
|
|
1238
|
+
*/
|
|
1239
|
+
constructor(name) {
|
|
1240
|
+
super();
|
|
1241
|
+
this.commands = [];
|
|
1242
|
+
this.options = [];
|
|
1243
|
+
this.parent = null;
|
|
1244
|
+
this._allowUnknownOption = false;
|
|
1245
|
+
this._allowExcessArguments = false;
|
|
1246
|
+
this.registeredArguments = [];
|
|
1247
|
+
this._args = this.registeredArguments;
|
|
1248
|
+
this.args = [];
|
|
1249
|
+
this.rawArgs = [];
|
|
1250
|
+
this.processedArgs = [];
|
|
1251
|
+
this._scriptPath = null;
|
|
1252
|
+
this._name = name || "";
|
|
1253
|
+
this._optionValues = {};
|
|
1254
|
+
this._optionValueSources = {};
|
|
1255
|
+
this._storeOptionsAsProperties = false;
|
|
1256
|
+
this._actionHandler = null;
|
|
1257
|
+
this._executableHandler = false;
|
|
1258
|
+
this._executableFile = null;
|
|
1259
|
+
this._executableDir = null;
|
|
1260
|
+
this._defaultCommandName = null;
|
|
1261
|
+
this._exitCallback = null;
|
|
1262
|
+
this._aliases = [];
|
|
1263
|
+
this._combineFlagAndOptionalValue = true;
|
|
1264
|
+
this._description = "";
|
|
1265
|
+
this._summary = "";
|
|
1266
|
+
this._argsDescription = void 0;
|
|
1267
|
+
this._enablePositionalOptions = false;
|
|
1268
|
+
this._passThroughOptions = false;
|
|
1269
|
+
this._lifeCycleHooks = {};
|
|
1270
|
+
this._showHelpAfterError = false;
|
|
1271
|
+
this._showSuggestionAfterError = true;
|
|
1272
|
+
this._savedState = null;
|
|
1273
|
+
this._outputConfiguration = {
|
|
1274
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1275
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1276
|
+
outputError: (str, write) => write(str),
|
|
1277
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1278
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1279
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1280
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1281
|
+
stripColor: (str) => stripVTControlCharacters2(str)
|
|
1282
|
+
};
|
|
1283
|
+
this._hidden = false;
|
|
1284
|
+
this._helpOption = void 0;
|
|
1285
|
+
this._addImplicitHelpCommand = void 0;
|
|
1286
|
+
this._helpCommand = void 0;
|
|
1287
|
+
this._helpConfiguration = {};
|
|
1288
|
+
this._helpGroupHeading = void 0;
|
|
1289
|
+
this._defaultCommandGroup = void 0;
|
|
1290
|
+
this._defaultOptionGroup = void 0;
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1294
|
+
*
|
|
1295
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1296
|
+
*
|
|
1297
|
+
* @param {Command} sourceCommand
|
|
1298
|
+
* @return {Command} `this` command for chaining
|
|
1299
|
+
*/
|
|
1300
|
+
copyInheritedSettings(sourceCommand) {
|
|
1301
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1302
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1303
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1304
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1305
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1306
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1307
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1308
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1309
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1310
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1311
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1312
|
+
return this;
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* @returns {Command[]}
|
|
1316
|
+
* @private
|
|
1317
|
+
*/
|
|
1318
|
+
_getCommandAndAncestors() {
|
|
1319
|
+
const result = [];
|
|
1320
|
+
for (let command = this; command; command = command.parent) {
|
|
1321
|
+
result.push(command);
|
|
1322
|
+
}
|
|
1323
|
+
return result;
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Define a command.
|
|
1327
|
+
*
|
|
1328
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1329
|
+
*
|
|
1330
|
+
* @example
|
|
1331
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1332
|
+
* program
|
|
1333
|
+
* .command('clone <source> [destination]')
|
|
1334
|
+
* .description('clone a repository into a newly created directory')
|
|
1335
|
+
* .action((source, destination) => {
|
|
1336
|
+
* console.log('clone command called');
|
|
1337
|
+
* });
|
|
1338
|
+
*
|
|
1339
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1340
|
+
* program
|
|
1341
|
+
* .command('start <service>', 'start named service')
|
|
1342
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1343
|
+
*
|
|
1344
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1345
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1346
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1347
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1348
|
+
*/
|
|
1349
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1350
|
+
let desc = actionOptsOrExecDesc;
|
|
1351
|
+
let opts = execOpts;
|
|
1352
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1353
|
+
opts = desc;
|
|
1354
|
+
desc = null;
|
|
1355
|
+
}
|
|
1356
|
+
opts = opts || {};
|
|
1357
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1358
|
+
const cmd = this.createCommand(name);
|
|
1359
|
+
if (desc) {
|
|
1360
|
+
cmd.description(desc);
|
|
1361
|
+
cmd._executableHandler = true;
|
|
1362
|
+
}
|
|
1363
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1364
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1365
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1366
|
+
if (args) cmd.arguments(args);
|
|
1367
|
+
this._registerCommand(cmd);
|
|
1368
|
+
cmd.parent = this;
|
|
1369
|
+
cmd.copyInheritedSettings(this);
|
|
1370
|
+
if (desc) return this;
|
|
1371
|
+
return cmd;
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* Factory routine to create a new unattached command.
|
|
1375
|
+
*
|
|
1376
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1377
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1378
|
+
*
|
|
1379
|
+
* @param {string} [name]
|
|
1380
|
+
* @return {Command} new command
|
|
1381
|
+
*/
|
|
1382
|
+
createCommand(name) {
|
|
1383
|
+
return new _Command(name);
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1387
|
+
* or by overriding Help properties using configureHelp().
|
|
1388
|
+
*
|
|
1389
|
+
* @return {Help}
|
|
1390
|
+
*/
|
|
1391
|
+
createHelp() {
|
|
1392
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1396
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1397
|
+
*
|
|
1398
|
+
* @param {object} [configuration] - configuration options
|
|
1399
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1400
|
+
*/
|
|
1401
|
+
configureHelp(configuration) {
|
|
1402
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1403
|
+
this._helpConfiguration = configuration;
|
|
1404
|
+
return this;
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1408
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1409
|
+
*
|
|
1410
|
+
* The configuration properties are all functions:
|
|
1411
|
+
*
|
|
1412
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1413
|
+
* writeOut(str)
|
|
1414
|
+
* writeErr(str)
|
|
1415
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1416
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1417
|
+
* // specify width for wrapping help
|
|
1418
|
+
* getOutHelpWidth()
|
|
1419
|
+
* getErrHelpWidth()
|
|
1420
|
+
* // color support, currently only used with Help
|
|
1421
|
+
* getOutHasColors()
|
|
1422
|
+
* getErrHasColors()
|
|
1423
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1424
|
+
*
|
|
1425
|
+
* @param {object} [configuration] - configuration options
|
|
1426
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1427
|
+
*/
|
|
1428
|
+
configureOutput(configuration) {
|
|
1429
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1430
|
+
this._outputConfiguration = {
|
|
1431
|
+
...this._outputConfiguration,
|
|
1432
|
+
...configuration
|
|
1433
|
+
};
|
|
1434
|
+
return this;
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* Display the help or a custom message after an error occurs.
|
|
1438
|
+
*
|
|
1439
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1440
|
+
* @return {Command} `this` command for chaining
|
|
1441
|
+
*/
|
|
1442
|
+
showHelpAfterError(displayHelp = true) {
|
|
1443
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1444
|
+
this._showHelpAfterError = displayHelp;
|
|
1445
|
+
return this;
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1449
|
+
*
|
|
1450
|
+
* @param {boolean} [displaySuggestion]
|
|
1451
|
+
* @return {Command} `this` command for chaining
|
|
1452
|
+
*/
|
|
1453
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1454
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1455
|
+
return this;
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* Add a prepared subcommand.
|
|
1459
|
+
*
|
|
1460
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1461
|
+
*
|
|
1462
|
+
* @param {Command} cmd - new subcommand
|
|
1463
|
+
* @param {object} [opts] - configuration options
|
|
1464
|
+
* @return {Command} `this` command for chaining
|
|
1465
|
+
*/
|
|
1466
|
+
addCommand(cmd, opts) {
|
|
1467
|
+
if (!cmd._name) {
|
|
1468
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1469
|
+
- specify the name in Command constructor or using .name()`);
|
|
1470
|
+
}
|
|
1471
|
+
opts = opts || {};
|
|
1472
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1473
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1474
|
+
this._registerCommand(cmd);
|
|
1475
|
+
cmd.parent = this;
|
|
1476
|
+
cmd._checkForBrokenPassThrough();
|
|
1477
|
+
return this;
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Factory routine to create a new unattached argument.
|
|
1481
|
+
*
|
|
1482
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1483
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1484
|
+
*
|
|
1485
|
+
* @param {string} name
|
|
1486
|
+
* @param {string} [description]
|
|
1487
|
+
* @return {Argument} new argument
|
|
1488
|
+
*/
|
|
1489
|
+
createArgument(name, description) {
|
|
1490
|
+
return new Argument(name, description);
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Define argument syntax for command.
|
|
1494
|
+
*
|
|
1495
|
+
* The default is that the argument is required, and you can explicitly
|
|
1496
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1497
|
+
*
|
|
1498
|
+
* @example
|
|
1499
|
+
* program.argument('<input-file>');
|
|
1500
|
+
* program.argument('[output-file]');
|
|
1501
|
+
*
|
|
1502
|
+
* @param {string} name
|
|
1503
|
+
* @param {string} [description]
|
|
1504
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1505
|
+
* @param {*} [defaultValue]
|
|
1506
|
+
* @return {Command} `this` command for chaining
|
|
1507
|
+
*/
|
|
1508
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1509
|
+
const argument = this.createArgument(name, description);
|
|
1510
|
+
if (typeof parseArg === "function") {
|
|
1511
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
1512
|
+
} else {
|
|
1513
|
+
argument.default(parseArg);
|
|
1514
|
+
}
|
|
1515
|
+
this.addArgument(argument);
|
|
1516
|
+
return this;
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1520
|
+
*
|
|
1521
|
+
* See also .argument().
|
|
1522
|
+
*
|
|
1523
|
+
* @example
|
|
1524
|
+
* program.arguments('<cmd> [env]');
|
|
1525
|
+
*
|
|
1526
|
+
* @param {string} names
|
|
1527
|
+
* @return {Command} `this` command for chaining
|
|
1528
|
+
*/
|
|
1529
|
+
arguments(names) {
|
|
1530
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1531
|
+
this.argument(detail);
|
|
1532
|
+
});
|
|
1533
|
+
return this;
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1537
|
+
*
|
|
1538
|
+
* @param {Argument} argument
|
|
1539
|
+
* @return {Command} `this` command for chaining
|
|
1540
|
+
*/
|
|
1541
|
+
addArgument(argument) {
|
|
1542
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1543
|
+
if (previousArgument?.variadic) {
|
|
1544
|
+
throw new Error(
|
|
1545
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1546
|
+
);
|
|
1547
|
+
}
|
|
1548
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1549
|
+
throw new Error(
|
|
1550
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1551
|
+
);
|
|
1552
|
+
}
|
|
1553
|
+
this.registeredArguments.push(argument);
|
|
1554
|
+
return this;
|
|
1555
|
+
}
|
|
1556
|
+
/**
|
|
1557
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1558
|
+
*
|
|
1559
|
+
* @example
|
|
1560
|
+
* program.helpCommand('help [cmd]');
|
|
1561
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1562
|
+
* program.helpCommand(false); // suppress default help command
|
|
1563
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1564
|
+
*
|
|
1565
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1566
|
+
* @param {string} [description] - custom description
|
|
1567
|
+
* @return {Command} `this` command for chaining
|
|
1568
|
+
*/
|
|
1569
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1570
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1571
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1572
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
1573
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
1574
|
+
}
|
|
1575
|
+
return this;
|
|
1576
|
+
}
|
|
1577
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1578
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1579
|
+
const helpDescription = description ?? "display help for command";
|
|
1580
|
+
const helpCommand = this.createCommand(helpName);
|
|
1581
|
+
helpCommand.helpOption(false);
|
|
1582
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1583
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1584
|
+
this._addImplicitHelpCommand = true;
|
|
1585
|
+
this._helpCommand = helpCommand;
|
|
1586
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1587
|
+
return this;
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Add prepared custom help command.
|
|
1591
|
+
*
|
|
1592
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1593
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1594
|
+
* @return {Command} `this` command for chaining
|
|
1595
|
+
*/
|
|
1596
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1597
|
+
if (typeof helpCommand !== "object") {
|
|
1598
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1599
|
+
return this;
|
|
1600
|
+
}
|
|
1601
|
+
this._addImplicitHelpCommand = true;
|
|
1602
|
+
this._helpCommand = helpCommand;
|
|
1603
|
+
this._initCommandGroup(helpCommand);
|
|
1604
|
+
return this;
|
|
1605
|
+
}
|
|
1606
|
+
/**
|
|
1607
|
+
* Lazy create help command.
|
|
1608
|
+
*
|
|
1609
|
+
* @return {(Command|null)}
|
|
1610
|
+
* @package
|
|
1611
|
+
*/
|
|
1612
|
+
_getHelpCommand() {
|
|
1613
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1614
|
+
if (hasImplicitHelpCommand) {
|
|
1615
|
+
if (this._helpCommand === void 0) {
|
|
1616
|
+
this.helpCommand(void 0, void 0);
|
|
1617
|
+
}
|
|
1618
|
+
return this._helpCommand;
|
|
1619
|
+
}
|
|
1620
|
+
return null;
|
|
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
|
+
hook(event, listener) {
|
|
1630
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1631
|
+
if (!allowedValues.includes(event)) {
|
|
1632
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1633
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1634
|
+
}
|
|
1635
|
+
if (this._lifeCycleHooks[event]) {
|
|
1636
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1637
|
+
} else {
|
|
1638
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1639
|
+
}
|
|
1640
|
+
return this;
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1644
|
+
*
|
|
1645
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1646
|
+
* @return {Command} `this` command for chaining
|
|
1647
|
+
*/
|
|
1648
|
+
exitOverride(fn) {
|
|
1649
|
+
if (fn) {
|
|
1650
|
+
this._exitCallback = fn;
|
|
1651
|
+
} else {
|
|
1652
|
+
this._exitCallback = (err) => {
|
|
1653
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1654
|
+
throw err;
|
|
1655
|
+
} else {
|
|
1656
|
+
}
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
return this;
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1663
|
+
*
|
|
1664
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1665
|
+
* @param {string} code an id string representing the error
|
|
1666
|
+
* @param {string} message human-readable description of the error
|
|
1667
|
+
* @return never
|
|
1668
|
+
* @private
|
|
1669
|
+
*/
|
|
1670
|
+
_exit(exitCode, code, message) {
|
|
1671
|
+
if (this._exitCallback) {
|
|
1672
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1673
|
+
}
|
|
1674
|
+
process2.exit(exitCode);
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Register callback `fn` for the command.
|
|
1678
|
+
*
|
|
1679
|
+
* @example
|
|
1680
|
+
* program
|
|
1681
|
+
* .command('serve')
|
|
1682
|
+
* .description('start service')
|
|
1683
|
+
* .action(function() {
|
|
1684
|
+
* // do work here
|
|
1685
|
+
* });
|
|
1686
|
+
*
|
|
1687
|
+
* @param {Function} fn
|
|
1688
|
+
* @return {Command} `this` command for chaining
|
|
1689
|
+
*/
|
|
1690
|
+
action(fn) {
|
|
1691
|
+
const listener = (args) => {
|
|
1692
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1693
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1694
|
+
if (this._storeOptionsAsProperties) {
|
|
1695
|
+
actionArgs[expectedArgsCount] = this;
|
|
1696
|
+
} else {
|
|
1697
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1698
|
+
}
|
|
1699
|
+
actionArgs.push(this);
|
|
1700
|
+
return fn.apply(this, actionArgs);
|
|
1701
|
+
};
|
|
1702
|
+
this._actionHandler = listener;
|
|
1703
|
+
return this;
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Factory routine to create a new unattached option.
|
|
1707
|
+
*
|
|
1708
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1709
|
+
* create the option. You can override createOption to return a custom option.
|
|
1710
|
+
*
|
|
1711
|
+
* @param {string} flags
|
|
1712
|
+
* @param {string} [description]
|
|
1713
|
+
* @return {Option} new option
|
|
1714
|
+
*/
|
|
1715
|
+
createOption(flags, description) {
|
|
1716
|
+
return new Option(flags, description);
|
|
1717
|
+
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1720
|
+
*
|
|
1721
|
+
* @param {(Option | Argument)} target
|
|
1722
|
+
* @param {string} value
|
|
1723
|
+
* @param {*} previous
|
|
1724
|
+
* @param {string} invalidArgumentMessage
|
|
1725
|
+
* @private
|
|
1726
|
+
*/
|
|
1727
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1728
|
+
try {
|
|
1729
|
+
return target.parseArg(value, previous);
|
|
1730
|
+
} catch (err) {
|
|
1731
|
+
if (err.code === "commander.invalidArgument") {
|
|
1732
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1733
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1734
|
+
}
|
|
1735
|
+
throw err;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
/**
|
|
1739
|
+
* Check for option flag conflicts.
|
|
1740
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1741
|
+
*
|
|
1742
|
+
* @param {Option} option
|
|
1743
|
+
* @private
|
|
1744
|
+
*/
|
|
1745
|
+
_registerOption(option) {
|
|
1746
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1747
|
+
if (matchingOption) {
|
|
1748
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1749
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1750
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1751
|
+
}
|
|
1752
|
+
this._initOptionGroup(option);
|
|
1753
|
+
this.options.push(option);
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1757
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1758
|
+
*
|
|
1759
|
+
* @param {Command} command
|
|
1760
|
+
* @private
|
|
1761
|
+
*/
|
|
1762
|
+
_registerCommand(command) {
|
|
1763
|
+
const knownBy = (cmd) => {
|
|
1764
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1765
|
+
};
|
|
1766
|
+
const alreadyUsed = knownBy(command).find(
|
|
1767
|
+
(name) => this._findCommand(name)
|
|
1768
|
+
);
|
|
1769
|
+
if (alreadyUsed) {
|
|
1770
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1771
|
+
const newCmd = knownBy(command).join("|");
|
|
1772
|
+
throw new Error(
|
|
1773
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1774
|
+
);
|
|
1775
|
+
}
|
|
1776
|
+
this._initCommandGroup(command);
|
|
1777
|
+
this.commands.push(command);
|
|
1778
|
+
}
|
|
1779
|
+
/**
|
|
1780
|
+
* Add an option.
|
|
1781
|
+
*
|
|
1782
|
+
* @param {Option} option
|
|
1783
|
+
* @return {Command} `this` command for chaining
|
|
1784
|
+
*/
|
|
1785
|
+
addOption(option) {
|
|
1786
|
+
this._registerOption(option);
|
|
1787
|
+
const oname = option.name();
|
|
1788
|
+
const name = option.attributeName();
|
|
1789
|
+
if (option.defaultValue !== void 0) {
|
|
1790
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1791
|
+
}
|
|
1792
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1793
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1794
|
+
val = option.presetArg;
|
|
1795
|
+
}
|
|
1796
|
+
const oldValue = this.getOptionValue(name);
|
|
1797
|
+
if (val !== null && option.parseArg) {
|
|
1798
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1799
|
+
} else if (val !== null && option.variadic) {
|
|
1800
|
+
val = option._collectValue(val, oldValue);
|
|
1801
|
+
}
|
|
1802
|
+
if (val == null) {
|
|
1803
|
+
if (option.negate) {
|
|
1804
|
+
val = false;
|
|
1805
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1806
|
+
val = true;
|
|
1807
|
+
} else {
|
|
1808
|
+
val = "";
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1812
|
+
};
|
|
1813
|
+
this.on("option:" + oname, (val) => {
|
|
1814
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1815
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1816
|
+
});
|
|
1817
|
+
if (option.envVar) {
|
|
1818
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1819
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1820
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
return this;
|
|
1824
|
+
}
|
|
1825
|
+
/**
|
|
1826
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1827
|
+
*
|
|
1828
|
+
* @return {Command} `this` command for chaining
|
|
1829
|
+
* @private
|
|
1830
|
+
*/
|
|
1831
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1832
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
1833
|
+
throw new Error(
|
|
1834
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
const option = this.createOption(flags, description);
|
|
1838
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1839
|
+
if (typeof fn === "function") {
|
|
1840
|
+
option.default(defaultValue).argParser(fn);
|
|
1841
|
+
} else if (fn instanceof RegExp) {
|
|
1842
|
+
const regex = fn;
|
|
1843
|
+
fn = (val, def) => {
|
|
1844
|
+
const m = regex.exec(val);
|
|
1845
|
+
return m ? m[0] : def;
|
|
1846
|
+
};
|
|
1847
|
+
option.default(defaultValue).argParser(fn);
|
|
1848
|
+
} else {
|
|
1849
|
+
option.default(fn);
|
|
1850
|
+
}
|
|
1851
|
+
return this.addOption(option);
|
|
1852
|
+
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1855
|
+
*
|
|
1856
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1857
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1858
|
+
*
|
|
1859
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1860
|
+
*
|
|
1861
|
+
* @example
|
|
1862
|
+
* program
|
|
1863
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1864
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1865
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1866
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1867
|
+
*
|
|
1868
|
+
* @param {string} flags
|
|
1869
|
+
* @param {string} [description]
|
|
1870
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1871
|
+
* @param {*} [defaultValue]
|
|
1872
|
+
* @return {Command} `this` command for chaining
|
|
1873
|
+
*/
|
|
1874
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1875
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1879
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1880
|
+
*
|
|
1881
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1882
|
+
*
|
|
1883
|
+
* @param {string} flags
|
|
1884
|
+
* @param {string} [description]
|
|
1885
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1886
|
+
* @param {*} [defaultValue]
|
|
1887
|
+
* @return {Command} `this` command for chaining
|
|
1888
|
+
*/
|
|
1889
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1890
|
+
return this._optionEx(
|
|
1891
|
+
{ mandatory: true },
|
|
1892
|
+
flags,
|
|
1893
|
+
description,
|
|
1894
|
+
parseArg,
|
|
1895
|
+
defaultValue
|
|
1896
|
+
);
|
|
1897
|
+
}
|
|
1898
|
+
/**
|
|
1899
|
+
* Alter parsing of short flags with optional values.
|
|
1900
|
+
*
|
|
1901
|
+
* @example
|
|
1902
|
+
* // for `.option('-f,--flag [value]'):
|
|
1903
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1904
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1905
|
+
*
|
|
1906
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1907
|
+
* @return {Command} `this` command for chaining
|
|
1908
|
+
*/
|
|
1909
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1910
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1911
|
+
return this;
|
|
1912
|
+
}
|
|
1913
|
+
/**
|
|
1914
|
+
* Allow unknown options on the command line.
|
|
1915
|
+
*
|
|
1916
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1917
|
+
* @return {Command} `this` command for chaining
|
|
1918
|
+
*/
|
|
1919
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1920
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1921
|
+
return this;
|
|
1922
|
+
}
|
|
1923
|
+
/**
|
|
1924
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1925
|
+
*
|
|
1926
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1927
|
+
* @return {Command} `this` command for chaining
|
|
1928
|
+
*/
|
|
1929
|
+
allowExcessArguments(allowExcess = true) {
|
|
1930
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1931
|
+
return this;
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1935
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1936
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1937
|
+
*
|
|
1938
|
+
* @param {boolean} [positional]
|
|
1939
|
+
* @return {Command} `this` command for chaining
|
|
1940
|
+
*/
|
|
1941
|
+
enablePositionalOptions(positional = true) {
|
|
1942
|
+
this._enablePositionalOptions = !!positional;
|
|
1943
|
+
return this;
|
|
1944
|
+
}
|
|
1945
|
+
/**
|
|
1946
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1947
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1948
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1949
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1950
|
+
*
|
|
1951
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1952
|
+
* @return {Command} `this` command for chaining
|
|
1953
|
+
*/
|
|
1954
|
+
passThroughOptions(passThrough = true) {
|
|
1955
|
+
this._passThroughOptions = !!passThrough;
|
|
1956
|
+
this._checkForBrokenPassThrough();
|
|
1957
|
+
return this;
|
|
1958
|
+
}
|
|
1959
|
+
/**
|
|
1960
|
+
* @private
|
|
1961
|
+
*/
|
|
1962
|
+
_checkForBrokenPassThrough() {
|
|
1963
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1964
|
+
throw new Error(
|
|
1965
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1966
|
+
);
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
/**
|
|
1970
|
+
* Whether to store option values as properties on command object,
|
|
1971
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1972
|
+
*
|
|
1973
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1974
|
+
* @return {Command} `this` command for chaining
|
|
1975
|
+
*/
|
|
1976
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1977
|
+
if (this.options.length) {
|
|
1978
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1979
|
+
}
|
|
1980
|
+
if (Object.keys(this._optionValues).length) {
|
|
1981
|
+
throw new Error(
|
|
1982
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1983
|
+
);
|
|
1984
|
+
}
|
|
1985
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1986
|
+
return this;
|
|
1987
|
+
}
|
|
1988
|
+
/**
|
|
1989
|
+
* Retrieve option value.
|
|
1990
|
+
*
|
|
1991
|
+
* @param {string} key
|
|
1992
|
+
* @return {object} value
|
|
1993
|
+
*/
|
|
1994
|
+
getOptionValue(key) {
|
|
1995
|
+
if (this._storeOptionsAsProperties) {
|
|
1996
|
+
return this[key];
|
|
1997
|
+
}
|
|
1998
|
+
return this._optionValues[key];
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* Store option value.
|
|
2002
|
+
*
|
|
2003
|
+
* @param {string} key
|
|
2004
|
+
* @param {object} value
|
|
2005
|
+
* @return {Command} `this` command for chaining
|
|
2006
|
+
*/
|
|
2007
|
+
setOptionValue(key, value) {
|
|
2008
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
2009
|
+
}
|
|
2010
|
+
/**
|
|
2011
|
+
* Store option value and where the value came from.
|
|
2012
|
+
*
|
|
2013
|
+
* @param {string} key
|
|
2014
|
+
* @param {object} value
|
|
2015
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
2016
|
+
* @return {Command} `this` command for chaining
|
|
2017
|
+
*/
|
|
2018
|
+
setOptionValueWithSource(key, value, source) {
|
|
2019
|
+
if (this._storeOptionsAsProperties) {
|
|
2020
|
+
this[key] = value;
|
|
2021
|
+
} else {
|
|
2022
|
+
this._optionValues[key] = value;
|
|
2023
|
+
}
|
|
2024
|
+
this._optionValueSources[key] = source;
|
|
2025
|
+
return this;
|
|
2026
|
+
}
|
|
2027
|
+
/**
|
|
2028
|
+
* Get source of option value.
|
|
2029
|
+
* Expected values are default | config | env | cli | implied
|
|
2030
|
+
*
|
|
2031
|
+
* @param {string} key
|
|
2032
|
+
* @return {string}
|
|
2033
|
+
*/
|
|
2034
|
+
getOptionValueSource(key) {
|
|
2035
|
+
return this._optionValueSources[key];
|
|
2036
|
+
}
|
|
2037
|
+
/**
|
|
2038
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
2039
|
+
* Expected values are default | config | env | cli | implied
|
|
2040
|
+
*
|
|
2041
|
+
* @param {string} key
|
|
2042
|
+
* @return {string}
|
|
2043
|
+
*/
|
|
2044
|
+
getOptionValueSourceWithGlobals(key) {
|
|
2045
|
+
let source;
|
|
2046
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2047
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
2048
|
+
source = cmd.getOptionValueSource(key);
|
|
2049
|
+
}
|
|
2050
|
+
});
|
|
2051
|
+
return source;
|
|
2052
|
+
}
|
|
2053
|
+
/**
|
|
2054
|
+
* Get user arguments from implied or explicit arguments.
|
|
2055
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
2056
|
+
*
|
|
2057
|
+
* @private
|
|
2058
|
+
*/
|
|
2059
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
2060
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
2061
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
2062
|
+
}
|
|
2063
|
+
parseOptions = parseOptions || {};
|
|
2064
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
2065
|
+
if (process2.versions?.electron) {
|
|
2066
|
+
parseOptions.from = "electron";
|
|
2067
|
+
}
|
|
2068
|
+
const execArgv = process2.execArgv ?? [];
|
|
2069
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
2070
|
+
parseOptions.from = "eval";
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
if (argv === void 0) {
|
|
2074
|
+
argv = process2.argv;
|
|
2075
|
+
}
|
|
2076
|
+
this.rawArgs = argv.slice();
|
|
2077
|
+
let userArgs;
|
|
2078
|
+
switch (parseOptions.from) {
|
|
2079
|
+
case void 0:
|
|
2080
|
+
case "node":
|
|
2081
|
+
this._scriptPath = argv[1];
|
|
2082
|
+
userArgs = argv.slice(2);
|
|
2083
|
+
break;
|
|
2084
|
+
case "electron":
|
|
2085
|
+
if (process2.defaultApp) {
|
|
2086
|
+
this._scriptPath = argv[1];
|
|
2087
|
+
userArgs = argv.slice(2);
|
|
2088
|
+
} else {
|
|
2089
|
+
userArgs = argv.slice(1);
|
|
2090
|
+
}
|
|
2091
|
+
break;
|
|
2092
|
+
case "user":
|
|
2093
|
+
userArgs = argv.slice(0);
|
|
2094
|
+
break;
|
|
2095
|
+
case "eval":
|
|
2096
|
+
userArgs = argv.slice(1);
|
|
2097
|
+
break;
|
|
2098
|
+
default:
|
|
2099
|
+
throw new Error(
|
|
2100
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2101
|
+
);
|
|
2102
|
+
}
|
|
2103
|
+
if (!this._name && this._scriptPath)
|
|
2104
|
+
this.nameFromFilename(this._scriptPath);
|
|
2105
|
+
this._name = this._name || "program";
|
|
2106
|
+
return userArgs;
|
|
2107
|
+
}
|
|
2108
|
+
/**
|
|
2109
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2110
|
+
*
|
|
2111
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2112
|
+
*
|
|
2113
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2114
|
+
*
|
|
2115
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2116
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2117
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2118
|
+
* - `'user'`: just user arguments
|
|
2119
|
+
*
|
|
2120
|
+
* @example
|
|
2121
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2122
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2123
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2124
|
+
*
|
|
2125
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2126
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2127
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2128
|
+
* @return {Command} `this` command for chaining
|
|
2129
|
+
*/
|
|
2130
|
+
parse(argv, parseOptions) {
|
|
2131
|
+
this._prepareForParse();
|
|
2132
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2133
|
+
this._parseCommand([], userArgs);
|
|
2134
|
+
return this;
|
|
2135
|
+
}
|
|
2136
|
+
/**
|
|
2137
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2138
|
+
*
|
|
2139
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2140
|
+
*
|
|
2141
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2142
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2143
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2144
|
+
* - `'user'`: just user arguments
|
|
2145
|
+
*
|
|
2146
|
+
* @example
|
|
2147
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2148
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2149
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2150
|
+
*
|
|
2151
|
+
* @param {string[]} [argv]
|
|
2152
|
+
* @param {object} [parseOptions]
|
|
2153
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2154
|
+
* @return {Promise}
|
|
2155
|
+
*/
|
|
2156
|
+
async parseAsync(argv, parseOptions) {
|
|
2157
|
+
this._prepareForParse();
|
|
2158
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2159
|
+
await this._parseCommand([], userArgs);
|
|
2160
|
+
return this;
|
|
2161
|
+
}
|
|
2162
|
+
_prepareForParse() {
|
|
2163
|
+
if (this._savedState === null) {
|
|
2164
|
+
this.options.filter(
|
|
2165
|
+
(option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
|
|
2166
|
+
).forEach((option) => {
|
|
2167
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
2168
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
2169
|
+
this.setOptionValueWithSource(
|
|
2170
|
+
option.attributeName(),
|
|
2171
|
+
true,
|
|
2172
|
+
"default"
|
|
2173
|
+
);
|
|
2174
|
+
}
|
|
2175
|
+
});
|
|
2176
|
+
this.saveStateBeforeParse();
|
|
2177
|
+
} else {
|
|
2178
|
+
this.restoreStateBeforeParse();
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2183
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2184
|
+
*
|
|
2185
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2186
|
+
*/
|
|
2187
|
+
saveStateBeforeParse() {
|
|
2188
|
+
this._savedState = {
|
|
2189
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2190
|
+
_name: this._name,
|
|
2191
|
+
// option values before parse have default values (including false for negated options)
|
|
2192
|
+
// shallow clones
|
|
2193
|
+
_optionValues: { ...this._optionValues },
|
|
2194
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2195
|
+
};
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Restore state before parse for calls after the first.
|
|
2199
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2200
|
+
*
|
|
2201
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2202
|
+
*/
|
|
2203
|
+
restoreStateBeforeParse() {
|
|
2204
|
+
if (this._storeOptionsAsProperties)
|
|
2205
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2206
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2207
|
+
this._name = this._savedState._name;
|
|
2208
|
+
this._scriptPath = null;
|
|
2209
|
+
this.rawArgs = [];
|
|
2210
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2211
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2212
|
+
this.args = [];
|
|
2213
|
+
this.processedArgs = [];
|
|
2214
|
+
}
|
|
2215
|
+
/**
|
|
2216
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2217
|
+
*
|
|
2218
|
+
* @param {string} executableFile
|
|
2219
|
+
* @param {string} executableDir
|
|
2220
|
+
* @param {string} subcommandName
|
|
2221
|
+
*/
|
|
2222
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2223
|
+
if (fs.existsSync(executableFile)) return;
|
|
2224
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
2225
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2226
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2227
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2228
|
+
- ${executableDirMessage}`;
|
|
2229
|
+
throw new Error(executableMissing);
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* Execute a sub-command executable.
|
|
2233
|
+
*
|
|
2234
|
+
* @private
|
|
2235
|
+
*/
|
|
2236
|
+
_executeSubCommand(subcommand, args) {
|
|
2237
|
+
args = args.slice();
|
|
2238
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2239
|
+
function findFile(baseDir, baseName) {
|
|
2240
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2241
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2242
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2243
|
+
const foundExt = sourceExt.find(
|
|
2244
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2245
|
+
);
|
|
2246
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2247
|
+
return void 0;
|
|
2248
|
+
}
|
|
2249
|
+
this._checkForMissingMandatoryOptions();
|
|
2250
|
+
this._checkForConflictingOptions();
|
|
2251
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2252
|
+
let executableDir = this._executableDir || "";
|
|
2253
|
+
if (this._scriptPath) {
|
|
2254
|
+
let resolvedScriptPath;
|
|
2255
|
+
try {
|
|
2256
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2257
|
+
} catch {
|
|
2258
|
+
resolvedScriptPath = this._scriptPath;
|
|
2259
|
+
}
|
|
2260
|
+
executableDir = path.resolve(
|
|
2261
|
+
path.dirname(resolvedScriptPath),
|
|
2262
|
+
executableDir
|
|
2263
|
+
);
|
|
2264
|
+
}
|
|
2265
|
+
if (executableDir) {
|
|
2266
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2267
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2268
|
+
const legacyName = path.basename(
|
|
2269
|
+
this._scriptPath,
|
|
2270
|
+
path.extname(this._scriptPath)
|
|
2271
|
+
);
|
|
2272
|
+
if (legacyName !== this._name) {
|
|
2273
|
+
localFile = findFile(
|
|
2274
|
+
executableDir,
|
|
2275
|
+
`${legacyName}-${subcommand._name}`
|
|
2276
|
+
);
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
executableFile = localFile || executableFile;
|
|
2280
|
+
}
|
|
2281
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2282
|
+
let proc;
|
|
2283
|
+
if (process2.platform !== "win32") {
|
|
2284
|
+
if (launchWithNode) {
|
|
2285
|
+
args.unshift(executableFile);
|
|
2286
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2287
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2288
|
+
} else {
|
|
2289
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2290
|
+
}
|
|
2291
|
+
} else {
|
|
2292
|
+
this._checkForMissingExecutable(
|
|
2293
|
+
executableFile,
|
|
2294
|
+
executableDir,
|
|
2295
|
+
subcommand._name
|
|
2296
|
+
);
|
|
2297
|
+
args.unshift(executableFile);
|
|
2298
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2299
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2300
|
+
}
|
|
2301
|
+
if (!proc.killed) {
|
|
2302
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2303
|
+
signals.forEach((signal) => {
|
|
2304
|
+
process2.on(signal, () => {
|
|
2305
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2306
|
+
proc.kill(signal);
|
|
2307
|
+
}
|
|
2308
|
+
});
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
const exitCallback = this._exitCallback;
|
|
2312
|
+
proc.on("close", (code) => {
|
|
2313
|
+
code = code ?? 1;
|
|
2314
|
+
if (!exitCallback) {
|
|
2315
|
+
process2.exit(code);
|
|
2316
|
+
} else {
|
|
2317
|
+
exitCallback(
|
|
2318
|
+
new CommanderError(
|
|
2319
|
+
code,
|
|
2320
|
+
"commander.executeSubCommandAsync",
|
|
2321
|
+
"(close)"
|
|
2322
|
+
)
|
|
2323
|
+
);
|
|
2324
|
+
}
|
|
2325
|
+
});
|
|
2326
|
+
proc.on("error", (err) => {
|
|
2327
|
+
if (err.code === "ENOENT") {
|
|
2328
|
+
this._checkForMissingExecutable(
|
|
2329
|
+
executableFile,
|
|
2330
|
+
executableDir,
|
|
2331
|
+
subcommand._name
|
|
2332
|
+
);
|
|
2333
|
+
} else if (err.code === "EACCES") {
|
|
2334
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2335
|
+
}
|
|
2336
|
+
if (!exitCallback) {
|
|
2337
|
+
process2.exit(1);
|
|
2338
|
+
} else {
|
|
2339
|
+
const wrappedError = new CommanderError(
|
|
2340
|
+
1,
|
|
2341
|
+
"commander.executeSubCommandAsync",
|
|
2342
|
+
"(error)"
|
|
2343
|
+
);
|
|
2344
|
+
wrappedError.nestedError = err;
|
|
2345
|
+
exitCallback(wrappedError);
|
|
2346
|
+
}
|
|
2347
|
+
});
|
|
2348
|
+
this.runningCommand = proc;
|
|
2349
|
+
}
|
|
2350
|
+
/**
|
|
2351
|
+
* @private
|
|
2352
|
+
*/
|
|
2353
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2354
|
+
const subCommand = this._findCommand(commandName);
|
|
2355
|
+
if (!subCommand) this.help({ error: true });
|
|
2356
|
+
subCommand._prepareForParse();
|
|
2357
|
+
let promiseChain;
|
|
2358
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2359
|
+
promiseChain,
|
|
2360
|
+
subCommand,
|
|
2361
|
+
"preSubcommand"
|
|
2362
|
+
);
|
|
2363
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2364
|
+
if (subCommand._executableHandler) {
|
|
2365
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2366
|
+
} else {
|
|
2367
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2368
|
+
}
|
|
2369
|
+
});
|
|
2370
|
+
return promiseChain;
|
|
2371
|
+
}
|
|
2372
|
+
/**
|
|
2373
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2374
|
+
* e.g. help foo
|
|
2375
|
+
*
|
|
2376
|
+
* @private
|
|
2377
|
+
*/
|
|
2378
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2379
|
+
if (!subcommandName) {
|
|
2380
|
+
this.help();
|
|
2381
|
+
}
|
|
2382
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2383
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2384
|
+
subCommand.help();
|
|
2385
|
+
}
|
|
2386
|
+
return this._dispatchSubcommand(
|
|
2387
|
+
subcommandName,
|
|
2388
|
+
[],
|
|
2389
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2390
|
+
);
|
|
2391
|
+
}
|
|
2392
|
+
/**
|
|
2393
|
+
* Check this.args against expected this.registeredArguments.
|
|
2394
|
+
*
|
|
2395
|
+
* @private
|
|
2396
|
+
*/
|
|
2397
|
+
_checkNumberOfArguments() {
|
|
2398
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2399
|
+
if (arg.required && this.args[i] == null) {
|
|
2400
|
+
this.missingArgument(arg.name());
|
|
2401
|
+
}
|
|
2402
|
+
});
|
|
2403
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2404
|
+
return;
|
|
2405
|
+
}
|
|
2406
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2407
|
+
this._excessArguments(this.args);
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
/**
|
|
2411
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2412
|
+
*
|
|
2413
|
+
* @private
|
|
2414
|
+
*/
|
|
2415
|
+
_processArguments() {
|
|
2416
|
+
const myParseArg = (argument, value, previous) => {
|
|
2417
|
+
let parsedValue = value;
|
|
2418
|
+
if (value !== null && argument.parseArg) {
|
|
2419
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2420
|
+
parsedValue = this._callParseArg(
|
|
2421
|
+
argument,
|
|
2422
|
+
value,
|
|
2423
|
+
previous,
|
|
2424
|
+
invalidValueMessage
|
|
2425
|
+
);
|
|
2426
|
+
}
|
|
2427
|
+
return parsedValue;
|
|
2428
|
+
};
|
|
2429
|
+
this._checkNumberOfArguments();
|
|
2430
|
+
const processedArgs = [];
|
|
2431
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2432
|
+
let value = declaredArg.defaultValue;
|
|
2433
|
+
if (declaredArg.variadic) {
|
|
2434
|
+
if (index < this.args.length) {
|
|
2435
|
+
value = this.args.slice(index);
|
|
2436
|
+
if (declaredArg.parseArg) {
|
|
2437
|
+
value = value.reduce((processed, v) => {
|
|
2438
|
+
return myParseArg(declaredArg, v, processed);
|
|
2439
|
+
}, declaredArg.defaultValue);
|
|
2440
|
+
}
|
|
2441
|
+
} else if (value === void 0) {
|
|
2442
|
+
value = [];
|
|
2443
|
+
}
|
|
2444
|
+
} else if (index < this.args.length) {
|
|
2445
|
+
value = this.args[index];
|
|
2446
|
+
if (declaredArg.parseArg) {
|
|
2447
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
processedArgs[index] = value;
|
|
2451
|
+
});
|
|
2452
|
+
this.processedArgs = processedArgs;
|
|
2453
|
+
}
|
|
2454
|
+
/**
|
|
2455
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2456
|
+
*
|
|
2457
|
+
* @param {(Promise|undefined)} promise
|
|
2458
|
+
* @param {Function} fn
|
|
2459
|
+
* @return {(Promise|undefined)}
|
|
2460
|
+
* @private
|
|
2461
|
+
*/
|
|
2462
|
+
_chainOrCall(promise, fn) {
|
|
2463
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
2464
|
+
return promise.then(() => fn());
|
|
2465
|
+
}
|
|
2466
|
+
return fn();
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
*
|
|
2470
|
+
* @param {(Promise|undefined)} promise
|
|
2471
|
+
* @param {string} event
|
|
2472
|
+
* @return {(Promise|undefined)}
|
|
2473
|
+
* @private
|
|
2474
|
+
*/
|
|
2475
|
+
_chainOrCallHooks(promise, event) {
|
|
2476
|
+
let result = promise;
|
|
2477
|
+
const hooks = [];
|
|
2478
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2479
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2480
|
+
hooks.push({ hookedCommand, callback });
|
|
2481
|
+
});
|
|
2482
|
+
});
|
|
2483
|
+
if (event === "postAction") {
|
|
2484
|
+
hooks.reverse();
|
|
2485
|
+
}
|
|
2486
|
+
hooks.forEach((hookDetail) => {
|
|
2487
|
+
result = this._chainOrCall(result, () => {
|
|
2488
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2489
|
+
});
|
|
2490
|
+
});
|
|
2491
|
+
return result;
|
|
2492
|
+
}
|
|
2493
|
+
/**
|
|
2494
|
+
*
|
|
2495
|
+
* @param {(Promise|undefined)} promise
|
|
2496
|
+
* @param {Command} subCommand
|
|
2497
|
+
* @param {string} event
|
|
2498
|
+
* @return {(Promise|undefined)}
|
|
2499
|
+
* @private
|
|
2500
|
+
*/
|
|
2501
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2502
|
+
let result = promise;
|
|
2503
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2504
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2505
|
+
result = this._chainOrCall(result, () => {
|
|
2506
|
+
return hook(this, subCommand);
|
|
2507
|
+
});
|
|
2508
|
+
});
|
|
2509
|
+
}
|
|
2510
|
+
return result;
|
|
2511
|
+
}
|
|
2512
|
+
/**
|
|
2513
|
+
* Process arguments in context of this command.
|
|
2514
|
+
* Returns action result, in case it is a promise.
|
|
2515
|
+
*
|
|
2516
|
+
* @private
|
|
2517
|
+
*/
|
|
2518
|
+
_parseCommand(operands, unknown) {
|
|
2519
|
+
const parsed = this.parseOptions(unknown);
|
|
2520
|
+
this._parseOptionsEnv();
|
|
2521
|
+
this._parseOptionsImplied();
|
|
2522
|
+
operands = operands.concat(parsed.operands);
|
|
2523
|
+
unknown = parsed.unknown;
|
|
2524
|
+
this.args = operands.concat(unknown);
|
|
2525
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2526
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2527
|
+
}
|
|
2528
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2529
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2530
|
+
}
|
|
2531
|
+
if (this._defaultCommandName) {
|
|
2532
|
+
this._outputHelpIfRequested(unknown);
|
|
2533
|
+
return this._dispatchSubcommand(
|
|
2534
|
+
this._defaultCommandName,
|
|
2535
|
+
operands,
|
|
2536
|
+
unknown
|
|
2537
|
+
);
|
|
2538
|
+
}
|
|
2539
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2540
|
+
this.help({ error: true });
|
|
2541
|
+
}
|
|
2542
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2543
|
+
this._checkForMissingMandatoryOptions();
|
|
2544
|
+
this._checkForConflictingOptions();
|
|
2545
|
+
const checkForUnknownOptions = () => {
|
|
2546
|
+
if (parsed.unknown.length > 0) {
|
|
2547
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2548
|
+
}
|
|
2549
|
+
};
|
|
2550
|
+
const commandEvent = `command:${this.name()}`;
|
|
2551
|
+
if (this._actionHandler) {
|
|
2552
|
+
checkForUnknownOptions();
|
|
2553
|
+
this._processArguments();
|
|
2554
|
+
let promiseChain;
|
|
2555
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2556
|
+
promiseChain = this._chainOrCall(
|
|
2557
|
+
promiseChain,
|
|
2558
|
+
() => this._actionHandler(this.processedArgs)
|
|
2559
|
+
);
|
|
2560
|
+
if (this.parent) {
|
|
2561
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2562
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2563
|
+
});
|
|
2564
|
+
}
|
|
2565
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2566
|
+
return promiseChain;
|
|
2567
|
+
}
|
|
2568
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2569
|
+
checkForUnknownOptions();
|
|
2570
|
+
this._processArguments();
|
|
2571
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2572
|
+
} else if (operands.length) {
|
|
2573
|
+
if (this._findCommand("*")) {
|
|
2574
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2575
|
+
}
|
|
2576
|
+
if (this.listenerCount("command:*")) {
|
|
2577
|
+
this.emit("command:*", operands, unknown);
|
|
2578
|
+
} else if (this.commands.length) {
|
|
2579
|
+
this.unknownCommand();
|
|
2580
|
+
} else {
|
|
2581
|
+
checkForUnknownOptions();
|
|
2582
|
+
this._processArguments();
|
|
2583
|
+
}
|
|
2584
|
+
} else if (this.commands.length) {
|
|
2585
|
+
checkForUnknownOptions();
|
|
2586
|
+
this.help({ error: true });
|
|
2587
|
+
} else {
|
|
2588
|
+
checkForUnknownOptions();
|
|
2589
|
+
this._processArguments();
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
/**
|
|
2593
|
+
* Find matching command.
|
|
2594
|
+
*
|
|
2595
|
+
* @private
|
|
2596
|
+
* @return {Command | undefined}
|
|
2597
|
+
*/
|
|
2598
|
+
_findCommand(name) {
|
|
2599
|
+
if (!name) return void 0;
|
|
2600
|
+
return this.commands.find(
|
|
2601
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2602
|
+
);
|
|
2603
|
+
}
|
|
2604
|
+
/**
|
|
2605
|
+
* Return an option matching `arg` if any.
|
|
2606
|
+
*
|
|
2607
|
+
* @param {string} arg
|
|
2608
|
+
* @return {Option}
|
|
2609
|
+
* @package
|
|
2610
|
+
*/
|
|
2611
|
+
_findOption(arg) {
|
|
2612
|
+
return this.options.find((option) => option.is(arg));
|
|
2613
|
+
}
|
|
2614
|
+
/**
|
|
2615
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2616
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2617
|
+
*
|
|
2618
|
+
* @private
|
|
2619
|
+
*/
|
|
2620
|
+
_checkForMissingMandatoryOptions() {
|
|
2621
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2622
|
+
cmd.options.forEach((anOption) => {
|
|
2623
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2624
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2625
|
+
}
|
|
2626
|
+
});
|
|
2627
|
+
});
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* Display an error message if conflicting options are used together in this.
|
|
2631
|
+
*
|
|
2632
|
+
* @private
|
|
2633
|
+
*/
|
|
2634
|
+
_checkForConflictingLocalOptions() {
|
|
2635
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2636
|
+
const optionKey = option.attributeName();
|
|
2637
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2638
|
+
return false;
|
|
2639
|
+
}
|
|
2640
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2641
|
+
});
|
|
2642
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2643
|
+
(option) => option.conflictsWith.length > 0
|
|
2644
|
+
);
|
|
2645
|
+
optionsWithConflicting.forEach((option) => {
|
|
2646
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2647
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2648
|
+
);
|
|
2649
|
+
if (conflictingAndDefined) {
|
|
2650
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2651
|
+
}
|
|
2652
|
+
});
|
|
2653
|
+
}
|
|
2654
|
+
/**
|
|
2655
|
+
* Display an error message if conflicting options are used together.
|
|
2656
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2657
|
+
*
|
|
2658
|
+
* @private
|
|
2659
|
+
*/
|
|
2660
|
+
_checkForConflictingOptions() {
|
|
2661
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2662
|
+
cmd._checkForConflictingLocalOptions();
|
|
2663
|
+
});
|
|
2664
|
+
}
|
|
2665
|
+
/**
|
|
2666
|
+
* Parse options from `argv` removing known options,
|
|
2667
|
+
* and return argv split into operands and unknown arguments.
|
|
2668
|
+
*
|
|
2669
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2670
|
+
*
|
|
2671
|
+
* Examples:
|
|
2672
|
+
*
|
|
2673
|
+
* argv => operands, unknown
|
|
2674
|
+
* --known kkk op => [op], []
|
|
2675
|
+
* op --known kkk => [op], []
|
|
2676
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2677
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2678
|
+
*
|
|
2679
|
+
* @param {string[]} args
|
|
2680
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2681
|
+
*/
|
|
2682
|
+
parseOptions(args) {
|
|
2683
|
+
const operands = [];
|
|
2684
|
+
const unknown = [];
|
|
2685
|
+
let dest = operands;
|
|
2686
|
+
function maybeOption(arg) {
|
|
2687
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2688
|
+
}
|
|
2689
|
+
const negativeNumberArg = (arg) => {
|
|
2690
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2691
|
+
return !this._getCommandAndAncestors().some(
|
|
2692
|
+
(cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
|
|
2693
|
+
);
|
|
2694
|
+
};
|
|
2695
|
+
let activeVariadicOption = null;
|
|
2696
|
+
let activeGroup = null;
|
|
2697
|
+
let i = 0;
|
|
2698
|
+
while (i < args.length || activeGroup) {
|
|
2699
|
+
const arg = activeGroup ?? args[i++];
|
|
2700
|
+
activeGroup = null;
|
|
2701
|
+
if (arg === "--") {
|
|
2702
|
+
if (dest === unknown) dest.push(arg);
|
|
2703
|
+
dest.push(...args.slice(i));
|
|
2704
|
+
break;
|
|
2705
|
+
}
|
|
2706
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2707
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2708
|
+
continue;
|
|
2709
|
+
}
|
|
2710
|
+
activeVariadicOption = null;
|
|
2711
|
+
if (maybeOption(arg)) {
|
|
2712
|
+
const option = this._findOption(arg);
|
|
2713
|
+
if (option) {
|
|
2714
|
+
if (option.required) {
|
|
2715
|
+
const value = args[i++];
|
|
2716
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2717
|
+
this.emit(`option:${option.name()}`, value);
|
|
2718
|
+
} else if (option.optional) {
|
|
2719
|
+
let value = null;
|
|
2720
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
2721
|
+
value = args[i++];
|
|
2722
|
+
}
|
|
2723
|
+
this.emit(`option:${option.name()}`, value);
|
|
2724
|
+
} else {
|
|
2725
|
+
this.emit(`option:${option.name()}`);
|
|
2726
|
+
}
|
|
2727
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2728
|
+
continue;
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2732
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2733
|
+
if (option) {
|
|
2734
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2735
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2736
|
+
} else {
|
|
2737
|
+
this.emit(`option:${option.name()}`);
|
|
2738
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2739
|
+
}
|
|
2740
|
+
continue;
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2744
|
+
const index = arg.indexOf("=");
|
|
2745
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2746
|
+
if (option && (option.required || option.optional)) {
|
|
2747
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2748
|
+
continue;
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
2752
|
+
dest = unknown;
|
|
2753
|
+
}
|
|
2754
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2755
|
+
if (this._findCommand(arg)) {
|
|
2756
|
+
operands.push(arg);
|
|
2757
|
+
unknown.push(...args.slice(i));
|
|
2758
|
+
break;
|
|
2759
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2760
|
+
operands.push(arg, ...args.slice(i));
|
|
2761
|
+
break;
|
|
2762
|
+
} else if (this._defaultCommandName) {
|
|
2763
|
+
unknown.push(arg, ...args.slice(i));
|
|
2764
|
+
break;
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
if (this._passThroughOptions) {
|
|
2768
|
+
dest.push(arg, ...args.slice(i));
|
|
2769
|
+
break;
|
|
2770
|
+
}
|
|
2771
|
+
dest.push(arg);
|
|
2772
|
+
}
|
|
2773
|
+
return { operands, unknown };
|
|
2774
|
+
}
|
|
2775
|
+
/**
|
|
2776
|
+
* Return an object containing local option values as key-value pairs.
|
|
2777
|
+
*
|
|
2778
|
+
* @return {object}
|
|
2779
|
+
*/
|
|
2780
|
+
opts() {
|
|
2781
|
+
if (this._storeOptionsAsProperties) {
|
|
2782
|
+
const result = {};
|
|
2783
|
+
const len = this.options.length;
|
|
2784
|
+
for (let i = 0; i < len; i++) {
|
|
2785
|
+
const key = this.options[i].attributeName();
|
|
2786
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2787
|
+
}
|
|
2788
|
+
return result;
|
|
2789
|
+
}
|
|
2790
|
+
return this._optionValues;
|
|
2791
|
+
}
|
|
2792
|
+
/**
|
|
2793
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2794
|
+
*
|
|
2795
|
+
* @return {object}
|
|
2796
|
+
*/
|
|
2797
|
+
optsWithGlobals() {
|
|
2798
|
+
return this._getCommandAndAncestors().reduce(
|
|
2799
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2800
|
+
{}
|
|
2801
|
+
);
|
|
2802
|
+
}
|
|
2803
|
+
/**
|
|
2804
|
+
* Display error message and exit (or call exitOverride).
|
|
2805
|
+
*
|
|
2806
|
+
* @param {string} message
|
|
2807
|
+
* @param {object} [errorOptions]
|
|
2808
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2809
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2810
|
+
*/
|
|
2811
|
+
error(message, errorOptions) {
|
|
2812
|
+
this._outputConfiguration.outputError(
|
|
2813
|
+
`${message}
|
|
2814
|
+
`,
|
|
2815
|
+
this._outputConfiguration.writeErr
|
|
2816
|
+
);
|
|
2817
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2818
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2819
|
+
`);
|
|
2820
|
+
} else if (this._showHelpAfterError) {
|
|
2821
|
+
this._outputConfiguration.writeErr("\n");
|
|
2822
|
+
this.outputHelp({ error: true });
|
|
2823
|
+
}
|
|
2824
|
+
const config = errorOptions || {};
|
|
2825
|
+
const exitCode = config.exitCode || 1;
|
|
2826
|
+
const code = config.code || "commander.error";
|
|
2827
|
+
this._exit(exitCode, code, message);
|
|
2828
|
+
}
|
|
2829
|
+
/**
|
|
2830
|
+
* Apply any option related environment variables, if option does
|
|
2831
|
+
* not have a value from cli or client code.
|
|
2832
|
+
*
|
|
2833
|
+
* @private
|
|
2834
|
+
*/
|
|
2835
|
+
_parseOptionsEnv() {
|
|
2836
|
+
this.options.forEach((option) => {
|
|
2837
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2838
|
+
const optionKey = option.attributeName();
|
|
2839
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2840
|
+
this.getOptionValueSource(optionKey)
|
|
2841
|
+
)) {
|
|
2842
|
+
if (option.required || option.optional) {
|
|
2843
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2844
|
+
} else {
|
|
2845
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
});
|
|
2850
|
+
}
|
|
2851
|
+
/**
|
|
2852
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2853
|
+
*
|
|
2854
|
+
* @private
|
|
2855
|
+
*/
|
|
2856
|
+
_parseOptionsImplied() {
|
|
2857
|
+
const dualHelper = new DualOptions(this.options);
|
|
2858
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2859
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2860
|
+
};
|
|
2861
|
+
this.options.filter(
|
|
2862
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2863
|
+
this.getOptionValue(option.attributeName()),
|
|
2864
|
+
option
|
|
2865
|
+
)
|
|
2866
|
+
).forEach((option) => {
|
|
2867
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2868
|
+
this.setOptionValueWithSource(
|
|
2869
|
+
impliedKey,
|
|
2870
|
+
option.implied[impliedKey],
|
|
2871
|
+
"implied"
|
|
2872
|
+
);
|
|
2873
|
+
});
|
|
2874
|
+
});
|
|
2875
|
+
}
|
|
2876
|
+
/**
|
|
2877
|
+
* Argument `name` is missing.
|
|
2878
|
+
*
|
|
2879
|
+
* @param {string} name
|
|
2880
|
+
* @private
|
|
2881
|
+
*/
|
|
2882
|
+
missingArgument(name) {
|
|
2883
|
+
const message = `error: missing required argument '${name}'`;
|
|
2884
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2885
|
+
}
|
|
2886
|
+
/**
|
|
2887
|
+
* `Option` is missing an argument.
|
|
2888
|
+
*
|
|
2889
|
+
* @param {Option} option
|
|
2890
|
+
* @private
|
|
2891
|
+
*/
|
|
2892
|
+
optionMissingArgument(option) {
|
|
2893
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2894
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2895
|
+
}
|
|
2896
|
+
/**
|
|
2897
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2898
|
+
*
|
|
2899
|
+
* @param {Option} option
|
|
2900
|
+
* @private
|
|
2901
|
+
*/
|
|
2902
|
+
missingMandatoryOptionValue(option) {
|
|
2903
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2904
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2905
|
+
}
|
|
2906
|
+
/**
|
|
2907
|
+
* `Option` conflicts with another option.
|
|
2908
|
+
*
|
|
2909
|
+
* @param {Option} option
|
|
2910
|
+
* @param {Option} conflictingOption
|
|
2911
|
+
* @private
|
|
2912
|
+
*/
|
|
2913
|
+
_conflictingOption(option, conflictingOption) {
|
|
2914
|
+
const findBestOptionFromValue = (option2) => {
|
|
2915
|
+
const optionKey = option2.attributeName();
|
|
2916
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2917
|
+
const negativeOption = this.options.find(
|
|
2918
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2919
|
+
);
|
|
2920
|
+
const positiveOption = this.options.find(
|
|
2921
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2922
|
+
);
|
|
2923
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2924
|
+
return negativeOption;
|
|
2925
|
+
}
|
|
2926
|
+
return positiveOption || option2;
|
|
2927
|
+
};
|
|
2928
|
+
const getErrorMessage = (option2) => {
|
|
2929
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2930
|
+
const optionKey = bestOption.attributeName();
|
|
2931
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2932
|
+
if (source === "env") {
|
|
2933
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2934
|
+
}
|
|
2935
|
+
return `option '${bestOption.flags}'`;
|
|
2936
|
+
};
|
|
2937
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2938
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2939
|
+
}
|
|
2940
|
+
/**
|
|
2941
|
+
* Unknown option `flag`.
|
|
2942
|
+
*
|
|
2943
|
+
* @param {string} flag
|
|
2944
|
+
* @private
|
|
2945
|
+
*/
|
|
2946
|
+
unknownOption(flag) {
|
|
2947
|
+
if (this._allowUnknownOption) return;
|
|
2948
|
+
let suggestion = "";
|
|
2949
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2950
|
+
let candidateFlags = [];
|
|
2951
|
+
let command = this;
|
|
2952
|
+
do {
|
|
2953
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2954
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2955
|
+
command = command.parent;
|
|
2956
|
+
} while (command && !command._enablePositionalOptions);
|
|
2957
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2958
|
+
}
|
|
2959
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2960
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2961
|
+
}
|
|
2962
|
+
/**
|
|
2963
|
+
* Excess arguments, more than expected.
|
|
2964
|
+
*
|
|
2965
|
+
* @param {string[]} receivedArgs
|
|
2966
|
+
* @private
|
|
2967
|
+
*/
|
|
2968
|
+
_excessArguments(receivedArgs) {
|
|
2969
|
+
if (this._allowExcessArguments) return;
|
|
2970
|
+
const expected = this.registeredArguments.length;
|
|
2971
|
+
const s = expected === 1 ? "" : "s";
|
|
2972
|
+
const received = receivedArgs.length;
|
|
2973
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2974
|
+
const details = receivedArgs.join(", ");
|
|
2975
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
|
|
2976
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2977
|
+
}
|
|
2978
|
+
/**
|
|
2979
|
+
* Unknown command.
|
|
2980
|
+
*
|
|
2981
|
+
* @private
|
|
2982
|
+
*/
|
|
2983
|
+
unknownCommand() {
|
|
2984
|
+
const unknownName = this.args[0];
|
|
2985
|
+
let suggestion = "";
|
|
2986
|
+
if (this._showSuggestionAfterError) {
|
|
2987
|
+
const candidateNames = [];
|
|
2988
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2989
|
+
candidateNames.push(command.name());
|
|
2990
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2991
|
+
});
|
|
2992
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2993
|
+
}
|
|
2994
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2995
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2996
|
+
}
|
|
2997
|
+
/**
|
|
2998
|
+
* Get or set the program version.
|
|
2999
|
+
*
|
|
3000
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
3001
|
+
*
|
|
3002
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
3003
|
+
*
|
|
3004
|
+
* @param {string} [str]
|
|
3005
|
+
* @param {string} [flags]
|
|
3006
|
+
* @param {string} [description]
|
|
3007
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
3008
|
+
*/
|
|
3009
|
+
version(str, flags, description) {
|
|
3010
|
+
if (str === void 0) return this._version;
|
|
3011
|
+
this._version = str;
|
|
3012
|
+
flags = flags || "-V, --version";
|
|
3013
|
+
description = description || "output the version number";
|
|
3014
|
+
const versionOption = this.createOption(flags, description);
|
|
3015
|
+
this._versionOptionName = versionOption.attributeName();
|
|
3016
|
+
this._registerOption(versionOption);
|
|
3017
|
+
this.on("option:" + versionOption.name(), () => {
|
|
3018
|
+
this._outputConfiguration.writeOut(`${str}
|
|
3019
|
+
`);
|
|
3020
|
+
this._exit(0, "commander.version", str);
|
|
3021
|
+
});
|
|
3022
|
+
return this;
|
|
3023
|
+
}
|
|
3024
|
+
/**
|
|
3025
|
+
* Set the description.
|
|
3026
|
+
*
|
|
3027
|
+
* @param {string} [str]
|
|
3028
|
+
* @param {object} [argsDescription]
|
|
3029
|
+
* @return {(string|Command)}
|
|
3030
|
+
*/
|
|
3031
|
+
description(str, argsDescription) {
|
|
3032
|
+
if (str === void 0 && argsDescription === void 0)
|
|
3033
|
+
return this._description;
|
|
3034
|
+
this._description = str;
|
|
3035
|
+
if (argsDescription) {
|
|
3036
|
+
this._argsDescription = argsDescription;
|
|
3037
|
+
}
|
|
3038
|
+
return this;
|
|
3039
|
+
}
|
|
3040
|
+
/**
|
|
3041
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
3042
|
+
*
|
|
3043
|
+
* @param {string} [str]
|
|
3044
|
+
* @return {(string|Command)}
|
|
3045
|
+
*/
|
|
3046
|
+
summary(str) {
|
|
3047
|
+
if (str === void 0) return this._summary;
|
|
3048
|
+
this._summary = str;
|
|
3049
|
+
return this;
|
|
3050
|
+
}
|
|
3051
|
+
/**
|
|
3052
|
+
* Set an alias for the command.
|
|
3053
|
+
*
|
|
3054
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
3055
|
+
*
|
|
3056
|
+
* @param {string} [alias]
|
|
3057
|
+
* @return {(string|Command)}
|
|
3058
|
+
*/
|
|
3059
|
+
alias(alias) {
|
|
3060
|
+
if (alias === void 0) return this._aliases[0];
|
|
3061
|
+
let command = this;
|
|
3062
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
3063
|
+
command = this.commands[this.commands.length - 1];
|
|
3064
|
+
}
|
|
3065
|
+
if (alias === command._name)
|
|
3066
|
+
throw new Error("Command alias can't be the same as its name");
|
|
3067
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
3068
|
+
if (matchingCommand) {
|
|
3069
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
3070
|
+
throw new Error(
|
|
3071
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
3072
|
+
);
|
|
3073
|
+
}
|
|
3074
|
+
command._aliases.push(alias);
|
|
3075
|
+
return this;
|
|
3076
|
+
}
|
|
3077
|
+
/**
|
|
3078
|
+
* Set aliases for the command.
|
|
3079
|
+
*
|
|
3080
|
+
* Only the first alias is shown in the auto-generated help.
|
|
3081
|
+
*
|
|
3082
|
+
* @param {string[]} [aliases]
|
|
3083
|
+
* @return {(string[]|Command)}
|
|
3084
|
+
*/
|
|
3085
|
+
aliases(aliases) {
|
|
3086
|
+
if (aliases === void 0) return this._aliases;
|
|
3087
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
3088
|
+
return this;
|
|
3089
|
+
}
|
|
3090
|
+
/**
|
|
3091
|
+
* Set / get the command usage `str`.
|
|
3092
|
+
*
|
|
3093
|
+
* @param {string} [str]
|
|
3094
|
+
* @return {(string|Command)}
|
|
3095
|
+
*/
|
|
3096
|
+
usage(str) {
|
|
3097
|
+
if (str === void 0) {
|
|
3098
|
+
if (this._usage) return this._usage;
|
|
3099
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3100
|
+
return humanReadableArgName(arg);
|
|
3101
|
+
});
|
|
3102
|
+
return [].concat(
|
|
3103
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3104
|
+
this.commands.length ? "[command]" : [],
|
|
3105
|
+
this.registeredArguments.length ? args : []
|
|
3106
|
+
).join(" ");
|
|
3107
|
+
}
|
|
3108
|
+
this._usage = str;
|
|
3109
|
+
return this;
|
|
3110
|
+
}
|
|
3111
|
+
/**
|
|
3112
|
+
* Get or set the name of the command.
|
|
3113
|
+
*
|
|
3114
|
+
* @param {string} [str]
|
|
3115
|
+
* @return {(string|Command)}
|
|
3116
|
+
*/
|
|
3117
|
+
name(str) {
|
|
3118
|
+
if (str === void 0) return this._name;
|
|
3119
|
+
this._name = str;
|
|
3120
|
+
return this;
|
|
3121
|
+
}
|
|
3122
|
+
/**
|
|
3123
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
3124
|
+
*
|
|
3125
|
+
* @param {string} [heading]
|
|
3126
|
+
* @return {Command | string}
|
|
3127
|
+
*/
|
|
3128
|
+
helpGroup(heading) {
|
|
3129
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
3130
|
+
this._helpGroupHeading = heading;
|
|
3131
|
+
return this;
|
|
3132
|
+
}
|
|
3133
|
+
/**
|
|
3134
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
3135
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
3136
|
+
*
|
|
3137
|
+
* @example
|
|
3138
|
+
* program.commandsGroup('Development Commands:);
|
|
3139
|
+
* program.command('watch')...
|
|
3140
|
+
* program.command('lint')...
|
|
3141
|
+
* ...
|
|
3142
|
+
*
|
|
3143
|
+
* @param {string} [heading]
|
|
3144
|
+
* @returns {Command | string}
|
|
3145
|
+
*/
|
|
3146
|
+
commandsGroup(heading) {
|
|
3147
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
3148
|
+
this._defaultCommandGroup = heading;
|
|
3149
|
+
return this;
|
|
3150
|
+
}
|
|
3151
|
+
/**
|
|
3152
|
+
* Set/get the default help group heading for options added to this command.
|
|
3153
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
3154
|
+
*
|
|
3155
|
+
* @example
|
|
3156
|
+
* program
|
|
3157
|
+
* .optionsGroup('Development Options:')
|
|
3158
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
3159
|
+
* .option('-p, --profile', 'output profiling information')
|
|
3160
|
+
*
|
|
3161
|
+
* @param {string} [heading]
|
|
3162
|
+
* @returns {Command | string}
|
|
3163
|
+
*/
|
|
3164
|
+
optionsGroup(heading) {
|
|
3165
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
3166
|
+
this._defaultOptionGroup = heading;
|
|
3167
|
+
return this;
|
|
3168
|
+
}
|
|
3169
|
+
/**
|
|
3170
|
+
* @param {Option} option
|
|
3171
|
+
* @private
|
|
3172
|
+
*/
|
|
3173
|
+
_initOptionGroup(option) {
|
|
3174
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
3175
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* @param {Command} cmd
|
|
3179
|
+
* @private
|
|
3180
|
+
*/
|
|
3181
|
+
_initCommandGroup(cmd) {
|
|
3182
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
3183
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
3184
|
+
}
|
|
3185
|
+
/**
|
|
3186
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3187
|
+
* or import.meta.filename.
|
|
3188
|
+
*
|
|
3189
|
+
* (Used internally and public although not documented in README.)
|
|
3190
|
+
*
|
|
3191
|
+
* @example
|
|
3192
|
+
* program.nameFromFilename(import.meta.filename);
|
|
3193
|
+
*
|
|
3194
|
+
* @param {string} filename
|
|
3195
|
+
* @return {Command}
|
|
3196
|
+
*/
|
|
3197
|
+
nameFromFilename(filename) {
|
|
3198
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3199
|
+
return this;
|
|
3200
|
+
}
|
|
3201
|
+
/**
|
|
3202
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3203
|
+
*
|
|
3204
|
+
* @example
|
|
3205
|
+
* program.executableDir(import.meta.dirname);
|
|
3206
|
+
* // or
|
|
3207
|
+
* program.executableDir('subcommands');
|
|
3208
|
+
*
|
|
3209
|
+
* @param {string} [path]
|
|
3210
|
+
* @return {(string|null|Command)}
|
|
3211
|
+
*/
|
|
3212
|
+
executableDir(path17) {
|
|
3213
|
+
if (path17 === void 0) return this._executableDir;
|
|
3214
|
+
this._executableDir = path17;
|
|
3215
|
+
return this;
|
|
3216
|
+
}
|
|
3217
|
+
/**
|
|
3218
|
+
* Return program help documentation.
|
|
3219
|
+
*
|
|
3220
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3221
|
+
* @return {string}
|
|
3222
|
+
*/
|
|
3223
|
+
helpInformation(contextOptions) {
|
|
3224
|
+
const helper = this.createHelp();
|
|
3225
|
+
const context = this._getOutputContext(contextOptions);
|
|
3226
|
+
helper.prepareContext({
|
|
3227
|
+
error: context.error,
|
|
3228
|
+
helpWidth: context.helpWidth,
|
|
3229
|
+
outputHasColors: context.hasColors
|
|
3230
|
+
});
|
|
3231
|
+
const text = helper.formatHelp(this, helper);
|
|
3232
|
+
if (context.hasColors) return text;
|
|
3233
|
+
return this._outputConfiguration.stripColor(text);
|
|
3234
|
+
}
|
|
3235
|
+
/**
|
|
3236
|
+
* @typedef HelpContext
|
|
3237
|
+
* @type {object}
|
|
3238
|
+
* @property {boolean} error
|
|
3239
|
+
* @property {number} helpWidth
|
|
3240
|
+
* @property {boolean} hasColors
|
|
3241
|
+
* @property {function} write - includes stripColor if needed
|
|
3242
|
+
*
|
|
3243
|
+
* @returns {HelpContext}
|
|
3244
|
+
* @private
|
|
3245
|
+
*/
|
|
3246
|
+
_getOutputContext(contextOptions) {
|
|
3247
|
+
contextOptions = contextOptions || {};
|
|
3248
|
+
const error = !!contextOptions.error;
|
|
3249
|
+
let baseWrite;
|
|
3250
|
+
let hasColors;
|
|
3251
|
+
let helpWidth;
|
|
3252
|
+
if (error) {
|
|
3253
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3254
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3255
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3256
|
+
} else {
|
|
3257
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3258
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3259
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3260
|
+
}
|
|
3261
|
+
const write = (str) => {
|
|
3262
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3263
|
+
return baseWrite(str);
|
|
3264
|
+
};
|
|
3265
|
+
return { error, write, hasColors, helpWidth };
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* Output help information for this command.
|
|
3269
|
+
*
|
|
3270
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3271
|
+
*
|
|
3272
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3273
|
+
*/
|
|
3274
|
+
outputHelp(contextOptions) {
|
|
3275
|
+
let deprecatedCallback;
|
|
3276
|
+
if (typeof contextOptions === "function") {
|
|
3277
|
+
deprecatedCallback = contextOptions;
|
|
3278
|
+
contextOptions = void 0;
|
|
3279
|
+
}
|
|
3280
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3281
|
+
const eventContext = {
|
|
3282
|
+
error: outputContext.error,
|
|
3283
|
+
write: outputContext.write,
|
|
3284
|
+
command: this
|
|
3285
|
+
};
|
|
3286
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3287
|
+
this.emit("beforeHelp", eventContext);
|
|
3288
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3289
|
+
if (deprecatedCallback) {
|
|
3290
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3291
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3292
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
outputContext.write(helpInformation);
|
|
3296
|
+
if (this._getHelpOption()?.long) {
|
|
3297
|
+
this.emit(this._getHelpOption().long);
|
|
3298
|
+
}
|
|
3299
|
+
this.emit("afterHelp", eventContext);
|
|
3300
|
+
this._getCommandAndAncestors().forEach(
|
|
3301
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3302
|
+
);
|
|
3303
|
+
}
|
|
3304
|
+
/**
|
|
3305
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3306
|
+
* Pass in false to disable the built-in help option.
|
|
3307
|
+
*
|
|
3308
|
+
* @example
|
|
3309
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3310
|
+
* program.helpOption(false); // disable
|
|
3311
|
+
*
|
|
3312
|
+
* @param {(string | boolean)} flags
|
|
3313
|
+
* @param {string} [description]
|
|
3314
|
+
* @return {Command} `this` command for chaining
|
|
3315
|
+
*/
|
|
3316
|
+
helpOption(flags, description) {
|
|
3317
|
+
if (typeof flags === "boolean") {
|
|
3318
|
+
if (flags) {
|
|
3319
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
3320
|
+
if (this._defaultOptionGroup) {
|
|
3321
|
+
this._initOptionGroup(this._getHelpOption());
|
|
3322
|
+
}
|
|
3323
|
+
} else {
|
|
3324
|
+
this._helpOption = null;
|
|
3325
|
+
}
|
|
3326
|
+
return this;
|
|
3327
|
+
}
|
|
3328
|
+
this._helpOption = this.createOption(
|
|
3329
|
+
flags ?? "-h, --help",
|
|
3330
|
+
description ?? "display help for command"
|
|
3331
|
+
);
|
|
3332
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
3333
|
+
return this;
|
|
3334
|
+
}
|
|
3335
|
+
/**
|
|
3336
|
+
* Lazy create help option.
|
|
3337
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3338
|
+
*
|
|
3339
|
+
* @returns {(Option | null)} the help option
|
|
3340
|
+
* @package
|
|
3341
|
+
*/
|
|
3342
|
+
_getHelpOption() {
|
|
3343
|
+
if (this._helpOption === void 0) {
|
|
3344
|
+
this.helpOption(void 0, void 0);
|
|
3345
|
+
}
|
|
3346
|
+
return this._helpOption;
|
|
3347
|
+
}
|
|
3348
|
+
/**
|
|
3349
|
+
* Supply your own option to use for the built-in help option.
|
|
3350
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3351
|
+
*
|
|
3352
|
+
* @param {Option} option
|
|
3353
|
+
* @return {Command} `this` command for chaining
|
|
3354
|
+
*/
|
|
3355
|
+
addHelpOption(option) {
|
|
3356
|
+
this._helpOption = option;
|
|
3357
|
+
this._initOptionGroup(option);
|
|
3358
|
+
return this;
|
|
3359
|
+
}
|
|
3360
|
+
/**
|
|
3361
|
+
* Output help information and exit.
|
|
3362
|
+
*
|
|
3363
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3364
|
+
*
|
|
3365
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3366
|
+
*/
|
|
3367
|
+
help(contextOptions) {
|
|
3368
|
+
this.outputHelp(contextOptions);
|
|
3369
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3370
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3371
|
+
exitCode = 1;
|
|
3372
|
+
}
|
|
3373
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3374
|
+
}
|
|
3375
|
+
/**
|
|
3376
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3377
|
+
* @typedef HelpTextEventContext
|
|
3378
|
+
* @type {object}
|
|
3379
|
+
* @property {boolean} error
|
|
3380
|
+
* @property {Command} command
|
|
3381
|
+
* @property {function} write
|
|
3382
|
+
*/
|
|
3383
|
+
/**
|
|
3384
|
+
* Add additional text to be displayed with the built-in help.
|
|
3385
|
+
*
|
|
3386
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3387
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3388
|
+
*
|
|
3389
|
+
* @param {string} position - before or after built-in help
|
|
3390
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3391
|
+
* @return {Command} `this` command for chaining
|
|
3392
|
+
*/
|
|
3393
|
+
addHelpText(position, text) {
|
|
3394
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3395
|
+
if (!allowedValues.includes(position)) {
|
|
3396
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3397
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3398
|
+
}
|
|
3399
|
+
const helpEvent = `${position}Help`;
|
|
3400
|
+
this.on(helpEvent, (context) => {
|
|
3401
|
+
let helpStr;
|
|
3402
|
+
if (typeof text === "function") {
|
|
3403
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3404
|
+
} else {
|
|
3405
|
+
helpStr = text;
|
|
3406
|
+
}
|
|
3407
|
+
if (helpStr) {
|
|
3408
|
+
context.write(`${helpStr}
|
|
3409
|
+
`);
|
|
3410
|
+
}
|
|
3411
|
+
});
|
|
3412
|
+
return this;
|
|
3413
|
+
}
|
|
3414
|
+
/**
|
|
3415
|
+
* Output help information if help flags specified
|
|
3416
|
+
*
|
|
3417
|
+
* @param {Array} args - array of options to search for help flags
|
|
3418
|
+
* @private
|
|
3419
|
+
*/
|
|
3420
|
+
_outputHelpIfRequested(args) {
|
|
3421
|
+
const helpOption = this._getHelpOption();
|
|
3422
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3423
|
+
if (helpRequested) {
|
|
3424
|
+
this.outputHelp();
|
|
3425
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
};
|
|
3429
|
+
function incrementNodeInspectorPort(args) {
|
|
3430
|
+
return args.map((arg) => {
|
|
3431
|
+
if (!arg.startsWith("--inspect")) {
|
|
3432
|
+
return arg;
|
|
3433
|
+
}
|
|
3434
|
+
let debugOption;
|
|
3435
|
+
let debugHost = "127.0.0.1";
|
|
3436
|
+
let debugPort = "9229";
|
|
3437
|
+
let match;
|
|
3438
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3439
|
+
debugOption = match[1];
|
|
3440
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3441
|
+
debugOption = match[1];
|
|
3442
|
+
if (/^\d+$/.test(match[3])) {
|
|
3443
|
+
debugPort = match[3];
|
|
3444
|
+
} else {
|
|
3445
|
+
debugHost = match[3];
|
|
3446
|
+
}
|
|
3447
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3448
|
+
debugOption = match[1];
|
|
3449
|
+
debugHost = match[3];
|
|
3450
|
+
debugPort = match[4];
|
|
3451
|
+
}
|
|
3452
|
+
if (debugOption && debugPort !== "0") {
|
|
3453
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3454
|
+
}
|
|
3455
|
+
return arg;
|
|
3456
|
+
});
|
|
3457
|
+
}
|
|
3458
|
+
function useColor() {
|
|
3459
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3460
|
+
return false;
|
|
3461
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3462
|
+
return true;
|
|
3463
|
+
return void 0;
|
|
3464
|
+
}
|
|
2
3465
|
|
|
3
|
-
//
|
|
4
|
-
|
|
3466
|
+
// node_modules/commander/index.js
|
|
3467
|
+
var program = new Command();
|
|
5
3468
|
|
|
6
3469
|
// src/util/errors.ts
|
|
7
3470
|
var SdkvmError = class extends Error {
|
|
@@ -21,7 +3484,7 @@ function toSdkvmError(err) {
|
|
|
21
3484
|
}
|
|
22
3485
|
|
|
23
3486
|
// src/ui/log.ts
|
|
24
|
-
|
|
3487
|
+
var import_picocolors = __toESM(require_picocolors(), 1);
|
|
25
3488
|
|
|
26
3489
|
// src/core/env.ts
|
|
27
3490
|
function envGet(name) {
|
|
@@ -33,10 +3496,10 @@ function envGet(name) {
|
|
|
33
3496
|
// src/ui/log.ts
|
|
34
3497
|
var isQuiet = () => Boolean(envGet("SDKVM_QUIET"));
|
|
35
3498
|
var label = {
|
|
36
|
-
info:
|
|
37
|
-
ok:
|
|
38
|
-
warn:
|
|
39
|
-
error:
|
|
3499
|
+
info: import_picocolors.default.cyan("sdkvm"),
|
|
3500
|
+
ok: import_picocolors.default.green("sdkvm"),
|
|
3501
|
+
warn: import_picocolors.default.yellow("sdkvm"),
|
|
3502
|
+
error: import_picocolors.default.red("sdkvm")
|
|
40
3503
|
};
|
|
41
3504
|
var log = {
|
|
42
3505
|
info(msg) {
|
|
@@ -46,10 +3509,10 @@ var log = {
|
|
|
46
3509
|
if (!isQuiet()) console.log(`${label.ok} ${msg}`);
|
|
47
3510
|
},
|
|
48
3511
|
warn(msg) {
|
|
49
|
-
if (!isQuiet()) console.error(`${label.warn} ${
|
|
3512
|
+
if (!isQuiet()) console.error(`${label.warn} ${import_picocolors.default.yellow(msg)}`);
|
|
50
3513
|
},
|
|
51
3514
|
error(msg) {
|
|
52
|
-
console.error(`${label.error} ${
|
|
3515
|
+
console.error(`${label.error} ${import_picocolors.default.red(msg)}`);
|
|
53
3516
|
},
|
|
54
3517
|
/** 无前缀输出(列表、表格数据) */
|
|
55
3518
|
raw(msg) {
|
|
@@ -58,8 +3521,8 @@ var log = {
|
|
|
58
3521
|
};
|
|
59
3522
|
|
|
60
3523
|
// src/cli/install.ts
|
|
61
|
-
import
|
|
62
|
-
import
|
|
3524
|
+
import fs10 from "fs";
|
|
3525
|
+
import path9 from "path";
|
|
63
3526
|
|
|
64
3527
|
// src/core/platform.ts
|
|
65
3528
|
function detectPlatform(override) {
|
|
@@ -91,8 +3554,8 @@ function detectPlatform(override) {
|
|
|
91
3554
|
}
|
|
92
3555
|
|
|
93
3556
|
// src/core/config.ts
|
|
94
|
-
import
|
|
95
|
-
import
|
|
3557
|
+
import fs6 from "fs";
|
|
3558
|
+
import path5 from "path";
|
|
96
3559
|
|
|
97
3560
|
// src/core/version.ts
|
|
98
3561
|
var LTS_MAJORS = /* @__PURE__ */ new Set([8, 11, 17, 21, 25]);
|
|
@@ -348,26 +3811,26 @@ function parseNodeUserSpec(input) {
|
|
|
348
3811
|
}
|
|
349
3812
|
|
|
350
3813
|
// src/core/lock.ts
|
|
351
|
-
import
|
|
3814
|
+
import fs5 from "fs";
|
|
352
3815
|
|
|
353
3816
|
// src/core/paths.ts
|
|
354
|
-
import
|
|
3817
|
+
import fs4 from "fs";
|
|
355
3818
|
import os from "os";
|
|
356
|
-
import
|
|
3819
|
+
import path4 from "path";
|
|
357
3820
|
|
|
358
3821
|
// src/sdk/java.ts
|
|
359
|
-
import
|
|
360
|
-
import
|
|
3822
|
+
import fs3 from "fs";
|
|
3823
|
+
import path3 from "path";
|
|
361
3824
|
|
|
362
3825
|
// src/cli/misc.ts
|
|
363
|
-
import
|
|
3826
|
+
import fs2 from "fs";
|
|
364
3827
|
import { fileURLToPath } from "url";
|
|
365
|
-
import
|
|
3828
|
+
import path2 from "path";
|
|
366
3829
|
function getVersion() {
|
|
367
3830
|
const fallback = "0.1.0";
|
|
368
3831
|
try {
|
|
369
|
-
const pkgPath =
|
|
370
|
-
const pkg = JSON.parse(
|
|
3832
|
+
const pkgPath = path2.resolve(path2.dirname(fileURLToPath(import.meta.url)), "../package.json");
|
|
3833
|
+
const pkg = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
|
|
371
3834
|
return pkg.version ?? fallback;
|
|
372
3835
|
} catch {
|
|
373
3836
|
return fallback;
|
|
@@ -993,8 +4456,8 @@ var javaSdk = {
|
|
|
993
4456
|
return platform.os === "windows" ? "\\bin" : "/bin";
|
|
994
4457
|
},
|
|
995
4458
|
locateHome(root) {
|
|
996
|
-
const contentsHome =
|
|
997
|
-
return
|
|
4459
|
+
const contentsHome = path3.join(root, "Contents", "Home");
|
|
4460
|
+
return fs3.existsSync(path3.join(contentsHome, "bin")) ? contentsHome : root;
|
|
998
4461
|
},
|
|
999
4462
|
versionCheck: { args: ["-version"], stream: "stderr" }
|
|
1000
4463
|
};
|
|
@@ -1089,23 +4552,23 @@ function getSdkType(id) {
|
|
|
1089
4552
|
|
|
1090
4553
|
// src/core/paths.ts
|
|
1091
4554
|
function sdkvmHome() {
|
|
1092
|
-
return envGet("SDKVM_HOME") ??
|
|
4555
|
+
return envGet("SDKVM_HOME") ?? path4.join(os.homedir(), ".sdkvm");
|
|
1093
4556
|
}
|
|
1094
4557
|
var paths = {
|
|
1095
4558
|
root: sdkvmHome,
|
|
1096
4559
|
/** 各 SDK 类型的安装根(~/.sdkvm/jdks 等) */
|
|
1097
|
-
sdks: (type) =>
|
|
4560
|
+
sdks: (type) => path4.join(sdkvmHome(), getSdkType(type).installDirName),
|
|
1098
4561
|
/** 各 SDK 类型的 current 链接(~/.sdkvm/current-java 等) */
|
|
1099
|
-
current: (type) =>
|
|
1100
|
-
cache: () =>
|
|
1101
|
-
tmp: () =>
|
|
1102
|
-
config: () =>
|
|
1103
|
-
lock: () =>
|
|
4562
|
+
current: (type) => path4.join(sdkvmHome(), getSdkType(type).currentLinkName),
|
|
4563
|
+
cache: () => path4.join(sdkvmHome(), "cache"),
|
|
4564
|
+
tmp: () => path4.join(sdkvmHome(), "tmp"),
|
|
4565
|
+
config: () => path4.join(sdkvmHome(), "config.json"),
|
|
4566
|
+
lock: () => path4.join(sdkvmHome(), ".lock")
|
|
1104
4567
|
};
|
|
1105
4568
|
function ensureLayout() {
|
|
1106
4569
|
const dirs = [sdkvmHome(), ...SDK_TYPES.map((t) => paths.sdks(t)), paths.cache(), paths.tmp()];
|
|
1107
4570
|
for (const dir of dirs) {
|
|
1108
|
-
|
|
4571
|
+
fs4.mkdirSync(dir, { recursive: true });
|
|
1109
4572
|
}
|
|
1110
4573
|
}
|
|
1111
4574
|
|
|
@@ -1117,7 +4580,7 @@ function lockInfoPath() {
|
|
|
1117
4580
|
}
|
|
1118
4581
|
function readLockPid() {
|
|
1119
4582
|
try {
|
|
1120
|
-
const raw =
|
|
4583
|
+
const raw = fs5.readFileSync(lockInfoPath(), "utf8");
|
|
1121
4584
|
const parsed = JSON.parse(raw);
|
|
1122
4585
|
return typeof parsed.pid === "number" ? parsed.pid : null;
|
|
1123
4586
|
} catch {
|
|
@@ -1134,24 +4597,24 @@ function isProcessAlive(pid) {
|
|
|
1134
4597
|
}
|
|
1135
4598
|
}
|
|
1136
4599
|
function writeLockInfo(startedAt) {
|
|
1137
|
-
|
|
4600
|
+
fs5.writeFileSync(
|
|
1138
4601
|
lockInfoPath(),
|
|
1139
4602
|
JSON.stringify({ pid: process.pid, startedAt, heartbeatAt: Date.now() })
|
|
1140
4603
|
);
|
|
1141
4604
|
}
|
|
1142
4605
|
function touchLock() {
|
|
1143
4606
|
const lockDir = paths.lock();
|
|
1144
|
-
if (!
|
|
4607
|
+
if (!fs5.existsSync(lockDir)) return;
|
|
1145
4608
|
const now = /* @__PURE__ */ new Date();
|
|
1146
4609
|
try {
|
|
1147
|
-
|
|
4610
|
+
fs5.utimesSync(lockDir, now, now);
|
|
1148
4611
|
} catch {
|
|
1149
4612
|
}
|
|
1150
4613
|
try {
|
|
1151
4614
|
const pid = readLockPid() ?? process.pid;
|
|
1152
4615
|
let startedAt = Date.now();
|
|
1153
4616
|
try {
|
|
1154
|
-
const raw = JSON.parse(
|
|
4617
|
+
const raw = JSON.parse(fs5.readFileSync(lockInfoPath(), "utf8"));
|
|
1155
4618
|
if (typeof raw.startedAt === "number") startedAt = raw.startedAt;
|
|
1156
4619
|
} catch {
|
|
1157
4620
|
}
|
|
@@ -1161,21 +4624,21 @@ function touchLock() {
|
|
|
1161
4624
|
}
|
|
1162
4625
|
function acquireLock() {
|
|
1163
4626
|
const lockDir = paths.lock();
|
|
1164
|
-
|
|
4627
|
+
fs5.mkdirSync(paths.root(), { recursive: true });
|
|
1165
4628
|
try {
|
|
1166
|
-
|
|
4629
|
+
fs5.mkdirSync(lockDir);
|
|
1167
4630
|
writeLockInfo(Date.now());
|
|
1168
4631
|
} catch (err) {
|
|
1169
4632
|
const e = err;
|
|
1170
4633
|
if (e.code === "EEXIST") {
|
|
1171
4634
|
const holder = readLockPid();
|
|
1172
4635
|
if (holder != null && !isProcessAlive(holder)) {
|
|
1173
|
-
|
|
4636
|
+
fs5.rmSync(lockDir, { recursive: true, force: true });
|
|
1174
4637
|
return acquireLock();
|
|
1175
4638
|
}
|
|
1176
|
-
const stat =
|
|
4639
|
+
const stat = fs5.statSync(lockDir);
|
|
1177
4640
|
if (Date.now() - stat.mtimeMs > STALE_MS) {
|
|
1178
|
-
|
|
4641
|
+
fs5.rmSync(lockDir, { recursive: true, force: true });
|
|
1179
4642
|
return acquireLock();
|
|
1180
4643
|
}
|
|
1181
4644
|
throw new SdkvmError("Another sdkvm operation is in progress", {
|
|
@@ -1186,7 +4649,7 @@ function acquireLock() {
|
|
|
1186
4649
|
}
|
|
1187
4650
|
}
|
|
1188
4651
|
function releaseLock() {
|
|
1189
|
-
|
|
4652
|
+
fs5.rmSync(paths.lock(), { recursive: true, force: true });
|
|
1190
4653
|
}
|
|
1191
4654
|
async function withLock(fn) {
|
|
1192
4655
|
acquireLock();
|
|
@@ -1209,9 +4672,9 @@ var DEFAULT_CONFIG = {
|
|
|
1209
4672
|
};
|
|
1210
4673
|
function loadConfig() {
|
|
1211
4674
|
const file = paths.config();
|
|
1212
|
-
if (!
|
|
4675
|
+
if (!fs6.existsSync(file)) return { ...DEFAULT_CONFIG, mirror: {}, npmRegistries: {} };
|
|
1213
4676
|
try {
|
|
1214
|
-
const parsed = JSON.parse(
|
|
4677
|
+
const parsed = JSON.parse(fs6.readFileSync(file, "utf8"));
|
|
1215
4678
|
const config = {
|
|
1216
4679
|
version: 1,
|
|
1217
4680
|
defaultVendor: parsed.defaultVendor && JAVA_VENDOR_IDS.includes(parsed.defaultVendor) ? parsed.defaultVendor : "temurin",
|
|
@@ -1232,7 +4695,7 @@ function loadConfig() {
|
|
|
1232
4695
|
} catch (err) {
|
|
1233
4696
|
const bak = `${file}.bak`;
|
|
1234
4697
|
try {
|
|
1235
|
-
|
|
4698
|
+
fs6.renameSync(file, bak);
|
|
1236
4699
|
log.warn(`config.json was corrupted; backed up to ${bak}, using defaults`);
|
|
1237
4700
|
} catch {
|
|
1238
4701
|
}
|
|
@@ -1243,10 +4706,10 @@ function loadConfig() {
|
|
|
1243
4706
|
function saveConfig(config) {
|
|
1244
4707
|
ensureLayout();
|
|
1245
4708
|
const file = paths.config();
|
|
1246
|
-
const tmp =
|
|
1247
|
-
|
|
4709
|
+
const tmp = path5.join(path5.dirname(file), `.config.json.tmp-${process.pid}`);
|
|
4710
|
+
fs6.writeFileSync(tmp, `${JSON.stringify(config, null, 2)}
|
|
1248
4711
|
`);
|
|
1249
|
-
|
|
4712
|
+
fs6.renameSync(tmp, file);
|
|
1250
4713
|
}
|
|
1251
4714
|
function updateConfig(mutator) {
|
|
1252
4715
|
acquireLock();
|
|
@@ -1295,13 +4758,13 @@ function applyMirrorDetail(artifact, platform, mirrorRoot) {
|
|
|
1295
4758
|
// src/net/download.ts
|
|
1296
4759
|
import crypto from "crypto";
|
|
1297
4760
|
import { once } from "events";
|
|
1298
|
-
import
|
|
1299
|
-
import
|
|
4761
|
+
import fs7 from "fs";
|
|
4762
|
+
import path6 from "path";
|
|
1300
4763
|
var IDLE_TIMEOUT_MS = 6e4;
|
|
1301
4764
|
async function downloadFile(url, destFile, onProgress) {
|
|
1302
4765
|
const partFile = `${destFile}.part`;
|
|
1303
4766
|
const hash = crypto.createHash("sha256");
|
|
1304
|
-
const out =
|
|
4767
|
+
const out = fs7.createWriteStream(partFile);
|
|
1305
4768
|
let bytes = 0;
|
|
1306
4769
|
let total = null;
|
|
1307
4770
|
let encoded2 = false;
|
|
@@ -1335,7 +4798,7 @@ async function downloadFile(url, destFile, onProgress) {
|
|
|
1335
4798
|
out.once("close", resolve);
|
|
1336
4799
|
out.destroy();
|
|
1337
4800
|
});
|
|
1338
|
-
|
|
4801
|
+
fs7.rmSync(partFile, { force: true });
|
|
1339
4802
|
if (stalled) {
|
|
1340
4803
|
throw new SdkvmError(`Download stalled: no data for ${IDLE_TIMEOUT_MS / 1e3}s (${bytes} bytes so far)`, {
|
|
1341
4804
|
hint: url
|
|
@@ -1346,29 +4809,44 @@ async function downloadFile(url, destFile, onProgress) {
|
|
|
1346
4809
|
clearTimeout(timer);
|
|
1347
4810
|
}
|
|
1348
4811
|
if (bytes === 0) {
|
|
1349
|
-
|
|
4812
|
+
fs7.rmSync(partFile, { force: true });
|
|
1350
4813
|
throw new SdkvmError(`Download incomplete: 0 bytes`, { hint: url });
|
|
1351
4814
|
}
|
|
1352
4815
|
if (total !== null && !encoded2 && bytes !== total) {
|
|
1353
|
-
|
|
4816
|
+
fs7.rmSync(partFile, { force: true });
|
|
1354
4817
|
throw new SdkvmError(`Download incomplete: ${bytes}/${total} bytes`, { hint: url });
|
|
1355
4818
|
}
|
|
1356
|
-
|
|
4819
|
+
fs7.renameSync(partFile, destFile);
|
|
1357
4820
|
return { file: destFile, sha256: hash.digest("hex"), bytes };
|
|
1358
4821
|
}
|
|
1359
4822
|
function cacheFileName(url) {
|
|
1360
|
-
const safe =
|
|
4823
|
+
const safe = path6.basename(new URL(url).pathname).replace(/[^\w.+-]/g, "_");
|
|
1361
4824
|
return safe || `download-${Date.now()}`;
|
|
1362
4825
|
}
|
|
1363
4826
|
|
|
1364
4827
|
// src/net/checksum.ts
|
|
1365
4828
|
var HEX64 = /^[0-9a-f]{64}$/i;
|
|
4829
|
+
function hex64(value) {
|
|
4830
|
+
return typeof value === "string" && HEX64.test(value) ? value.toLowerCase() : null;
|
|
4831
|
+
}
|
|
1366
4832
|
function extractExpectedChecksum(text) {
|
|
1367
4833
|
const trimmed = text.trim();
|
|
1368
4834
|
if (trimmed.startsWith("{")) {
|
|
1369
4835
|
try {
|
|
1370
4836
|
const obj = JSON.parse(trimmed);
|
|
1371
|
-
|
|
4837
|
+
const direct = hex64(obj.checksum) ?? hex64(obj.sha256);
|
|
4838
|
+
if (direct) return direct;
|
|
4839
|
+
if (Array.isArray(obj.hashes)) {
|
|
4840
|
+
for (const item of obj.hashes) {
|
|
4841
|
+
if (!item || typeof item !== "object") continue;
|
|
4842
|
+
const hash = item;
|
|
4843
|
+
const alg = typeof hash.alg === "string" ? hash.alg.toLowerCase().replace(/-/g, "") : "";
|
|
4844
|
+
if (alg === "sha256") {
|
|
4845
|
+
const content = hex64(hash.content);
|
|
4846
|
+
if (content) return content;
|
|
4847
|
+
}
|
|
4848
|
+
}
|
|
4849
|
+
}
|
|
1372
4850
|
} catch {
|
|
1373
4851
|
}
|
|
1374
4852
|
return null;
|
|
@@ -1420,8 +4898,8 @@ async function verifyChecksum(artifact, actual, opts = {}) {
|
|
|
1420
4898
|
}
|
|
1421
4899
|
|
|
1422
4900
|
// src/fs/extract.ts
|
|
1423
|
-
import
|
|
1424
|
-
import
|
|
4901
|
+
import fs8 from "fs";
|
|
4902
|
+
import path7 from "path";
|
|
1425
4903
|
|
|
1426
4904
|
// src/util/spawn.ts
|
|
1427
4905
|
import { execFile } from "child_process";
|
|
@@ -1446,9 +4924,9 @@ async function run(cmd, args, opts = {}) {
|
|
|
1446
4924
|
// src/fs/extract.ts
|
|
1447
4925
|
var WIN_TAR = "C:\\Windows\\System32\\tar.exe";
|
|
1448
4926
|
async function extractArchive(archiveFile, archiveType, destDir, platform) {
|
|
1449
|
-
|
|
4927
|
+
fs8.mkdirSync(destDir, { recursive: true });
|
|
1450
4928
|
if (platform.os === "windows") {
|
|
1451
|
-
if (
|
|
4929
|
+
if (fs8.existsSync(WIN_TAR)) {
|
|
1452
4930
|
await run(WIN_TAR, ["-xf", archiveFile, "-C", destDir]);
|
|
1453
4931
|
} else {
|
|
1454
4932
|
await run("powershell.exe", [
|
|
@@ -1467,25 +4945,25 @@ async function extractArchive(archiveFile, archiveType, destDir, platform) {
|
|
|
1467
4945
|
await run("tar", ["-xf", archiveFile, "-C", destDir]);
|
|
1468
4946
|
}
|
|
1469
4947
|
function tmpExtractDir(base) {
|
|
1470
|
-
return
|
|
4948
|
+
return path7.join(base, `extract-${Date.now()}-${process.pid}`);
|
|
1471
4949
|
}
|
|
1472
4950
|
|
|
1473
4951
|
// src/fs/layout.ts
|
|
1474
|
-
import
|
|
1475
|
-
import
|
|
4952
|
+
import fs9 from "fs";
|
|
4953
|
+
import path8 from "path";
|
|
1476
4954
|
function normalizeExtracted(tmpDir, platform, type) {
|
|
1477
4955
|
const spec = getSdkType(type);
|
|
1478
|
-
const entries =
|
|
4956
|
+
const entries = fs9.readdirSync(tmpDir).filter((e) => e !== "._" && !e.startsWith("._"));
|
|
1479
4957
|
const real = entries.filter((e) => e !== ".DS_Store");
|
|
1480
4958
|
let root;
|
|
1481
|
-
if (real.length === 1 &&
|
|
1482
|
-
root =
|
|
4959
|
+
if (real.length === 1 && fs9.statSync(path8.join(tmpDir, real[0])).isDirectory()) {
|
|
4960
|
+
root = path8.join(tmpDir, real[0]);
|
|
1483
4961
|
} else {
|
|
1484
4962
|
root = tmpDir;
|
|
1485
4963
|
}
|
|
1486
4964
|
const home = spec.locateHome(root);
|
|
1487
|
-
const bin =
|
|
1488
|
-
if (!
|
|
4965
|
+
const bin = path8.join(home, spec.binRelPath(platform));
|
|
4966
|
+
if (!fs9.existsSync(bin)) {
|
|
1489
4967
|
throw new SdkvmError(`Archive does not look like a valid ${spec.label} (bin not found)`, {
|
|
1490
4968
|
hint: `expected ${bin}`
|
|
1491
4969
|
});
|
|
@@ -1537,7 +5015,7 @@ function createProgress(label2) {
|
|
|
1537
5015
|
async function renameWithRetry(from, to, attempts = 3) {
|
|
1538
5016
|
for (let i = 1; ; i++) {
|
|
1539
5017
|
try {
|
|
1540
|
-
|
|
5018
|
+
fs10.renameSync(from, to);
|
|
1541
5019
|
return;
|
|
1542
5020
|
} catch (err) {
|
|
1543
5021
|
if (i >= attempts) throw err;
|
|
@@ -1567,11 +5045,11 @@ async function installCommand(type, specInput, opts) {
|
|
|
1567
5045
|
);
|
|
1568
5046
|
}
|
|
1569
5047
|
}
|
|
1570
|
-
const finalDir =
|
|
5048
|
+
const finalDir = path9.join(paths.sdks(type), artifact.dirName);
|
|
1571
5049
|
const hintVersion = type === "java" || type === "node" ? String(artifact.version.major) : `${artifact.version.major}.${artifact.version.minor}`;
|
|
1572
5050
|
await withLock(async () => {
|
|
1573
5051
|
ensureLayout();
|
|
1574
|
-
if (
|
|
5052
|
+
if (fs10.existsSync(finalDir)) {
|
|
1575
5053
|
if (!opts.force) {
|
|
1576
5054
|
log.warn(`${artifact.displayName} is already installed`);
|
|
1577
5055
|
log.info(`run: ${cmdPath(type)} use ${hintVersion}`);
|
|
@@ -1579,10 +5057,10 @@ async function installCommand(type, specInput, opts) {
|
|
|
1579
5057
|
}
|
|
1580
5058
|
log.warn(`--force: removing existing ${artifact.dirName}`);
|
|
1581
5059
|
}
|
|
1582
|
-
for (const f of
|
|
1583
|
-
if (f.endsWith(".part"))
|
|
5060
|
+
for (const f of fs10.readdirSync(paths.cache())) {
|
|
5061
|
+
if (f.endsWith(".part")) fs10.rmSync(path9.join(paths.cache(), f), { force: true });
|
|
1584
5062
|
}
|
|
1585
|
-
const dest =
|
|
5063
|
+
const dest = path9.join(paths.cache(), cacheFileName(artifact.downloadUrl));
|
|
1586
5064
|
const progress = createProgress(`\u2193 ${artifact.displayName}`);
|
|
1587
5065
|
log.info(`downloading ${artifact.downloadUrl}`);
|
|
1588
5066
|
const dl = await downloadFile(artifact.downloadUrl, dest, (b, t) => progress.update(b, t));
|
|
@@ -1596,28 +5074,28 @@ async function installCommand(type, specInput, opts) {
|
|
|
1596
5074
|
await extractArchive(dest, artifact.archive, tmp, platform);
|
|
1597
5075
|
const normalized = normalizeExtracted(tmp, platform, type);
|
|
1598
5076
|
finalTmp = normalized.root;
|
|
1599
|
-
|
|
1600
|
-
if (
|
|
5077
|
+
fs10.rmSync(bak, { recursive: true, force: true });
|
|
5078
|
+
if (fs10.existsSync(finalDir)) fs10.renameSync(finalDir, bak);
|
|
1601
5079
|
try {
|
|
1602
5080
|
await renameWithRetry(normalized.root, finalDir);
|
|
1603
5081
|
} catch (err) {
|
|
1604
|
-
if (
|
|
5082
|
+
if (fs10.existsSync(bak) && !fs10.existsSync(finalDir)) {
|
|
1605
5083
|
try {
|
|
1606
|
-
|
|
5084
|
+
fs10.renameSync(bak, finalDir);
|
|
1607
5085
|
} catch {
|
|
1608
5086
|
}
|
|
1609
5087
|
}
|
|
1610
5088
|
throw err;
|
|
1611
5089
|
}
|
|
1612
|
-
|
|
5090
|
+
fs10.rmSync(bak, { recursive: true, force: true });
|
|
1613
5091
|
} catch (err) {
|
|
1614
|
-
|
|
1615
|
-
|
|
5092
|
+
fs10.rmSync(finalTmp, { recursive: true, force: true });
|
|
5093
|
+
fs10.rmSync(tmp, { recursive: true, force: true });
|
|
1616
5094
|
throw err;
|
|
1617
5095
|
} finally {
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
5096
|
+
fs10.rmSync(dest, { force: true });
|
|
5097
|
+
fs10.rmSync(paths.tmp(), { recursive: true, force: true });
|
|
5098
|
+
fs10.mkdirSync(paths.tmp(), { recursive: true });
|
|
1621
5099
|
}
|
|
1622
5100
|
log.ok(`installed ${artifact.displayName} \u2192 ${finalDir}`);
|
|
1623
5101
|
log.info(`switch to it: ${cmdPath(type)} use ${hintVersion}`);
|
|
@@ -1627,38 +5105,38 @@ async function installCommand(type, specInput, opts) {
|
|
|
1627
5105
|
// src/cli/use.ts
|
|
1628
5106
|
import { execFile as execFile2 } from "child_process";
|
|
1629
5107
|
import { promisify as promisify2 } from "util";
|
|
1630
|
-
import
|
|
5108
|
+
import path15 from "path";
|
|
1631
5109
|
|
|
1632
5110
|
// src/core/registry.ts
|
|
1633
|
-
import
|
|
1634
|
-
import
|
|
5111
|
+
import fs12 from "fs";
|
|
5112
|
+
import path11 from "path";
|
|
1635
5113
|
|
|
1636
5114
|
// src/fs/link.ts
|
|
1637
|
-
import
|
|
1638
|
-
import
|
|
5115
|
+
import fs11 from "fs";
|
|
5116
|
+
import path10 from "path";
|
|
1639
5117
|
function setCurrent(type, target, platform) {
|
|
1640
5118
|
const link = paths.current(type);
|
|
1641
5119
|
if (platform.os === "windows") {
|
|
1642
5120
|
try {
|
|
1643
|
-
|
|
5121
|
+
fs11.rmSync(link, { force: true });
|
|
1644
5122
|
} catch {
|
|
1645
|
-
|
|
5123
|
+
fs11.rmSync(link, { recursive: true, force: true });
|
|
1646
5124
|
}
|
|
1647
|
-
|
|
5125
|
+
fs11.symlinkSync(target, link, "junction");
|
|
1648
5126
|
return;
|
|
1649
5127
|
}
|
|
1650
5128
|
const tmp = `${link}.tmp-${process.pid}`;
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
5129
|
+
fs11.rmSync(tmp, { force: true });
|
|
5130
|
+
fs11.symlinkSync(target, tmp);
|
|
5131
|
+
fs11.renameSync(tmp, link);
|
|
1654
5132
|
}
|
|
1655
5133
|
function readCurrent(type) {
|
|
1656
5134
|
const link = paths.current(type);
|
|
1657
5135
|
try {
|
|
1658
|
-
const st =
|
|
5136
|
+
const st = fs11.lstatSync(link);
|
|
1659
5137
|
if (!st.isSymbolicLink()) return null;
|
|
1660
|
-
const raw =
|
|
1661
|
-
return
|
|
5138
|
+
const raw = fs11.readlinkSync(link);
|
|
5139
|
+
return path10.resolve(path10.dirname(link), raw);
|
|
1662
5140
|
} catch {
|
|
1663
5141
|
return null;
|
|
1664
5142
|
}
|
|
@@ -1666,9 +5144,9 @@ function readCurrent(type) {
|
|
|
1666
5144
|
function clearCurrent(type) {
|
|
1667
5145
|
const link = paths.current(type);
|
|
1668
5146
|
try {
|
|
1669
|
-
|
|
5147
|
+
fs11.rmSync(link, { force: true });
|
|
1670
5148
|
} catch {
|
|
1671
|
-
|
|
5149
|
+
fs11.rmSync(link, { recursive: true, force: true });
|
|
1672
5150
|
}
|
|
1673
5151
|
}
|
|
1674
5152
|
|
|
@@ -1676,13 +5154,13 @@ function clearCurrent(type) {
|
|
|
1676
5154
|
function listInstalled(type) {
|
|
1677
5155
|
const spec = getSdkType(type);
|
|
1678
5156
|
const root = paths.sdks(type);
|
|
1679
|
-
if (!
|
|
5157
|
+
if (!fs12.existsSync(root)) return [];
|
|
1680
5158
|
const result = [];
|
|
1681
|
-
for (const name of
|
|
5159
|
+
for (const name of fs12.readdirSync(root)) {
|
|
1682
5160
|
const version = spec.parseDirName(name);
|
|
1683
5161
|
if (!version) continue;
|
|
1684
|
-
const dirPath =
|
|
1685
|
-
if (!
|
|
5162
|
+
const dirPath = path11.join(root, name);
|
|
5163
|
+
if (!fs12.statSync(dirPath).isDirectory()) continue;
|
|
1686
5164
|
result.push({ type, version, dirPath, home: spec.locateHome(dirPath) });
|
|
1687
5165
|
}
|
|
1688
5166
|
result.sort((a, b) => spec.compareVersions(a.version, b.version));
|
|
@@ -1692,7 +5170,7 @@ function currentSdk(type) {
|
|
|
1692
5170
|
const current = readCurrent(type);
|
|
1693
5171
|
if (!current) return null;
|
|
1694
5172
|
return listInstalled(type).find(
|
|
1695
|
-
(j) => j.home === current || j.dirPath === current || current.startsWith(j.dirPath +
|
|
5173
|
+
(j) => j.home === current || j.dirPath === current || current.startsWith(j.dirPath + path11.sep)
|
|
1696
5174
|
) ?? null;
|
|
1697
5175
|
}
|
|
1698
5176
|
function findInstalled(type, specInput, vendorArg) {
|
|
@@ -1739,24 +5217,24 @@ ${installedList}
|
|
|
1739
5217
|
|
|
1740
5218
|
// src/shell/detect.ts
|
|
1741
5219
|
import os2 from "os";
|
|
1742
|
-
import
|
|
5220
|
+
import path12 from "path";
|
|
1743
5221
|
function detectRcFile(platform) {
|
|
1744
5222
|
if (platform === "windows") return null;
|
|
1745
5223
|
const shell = process.env.SHELL ?? "";
|
|
1746
|
-
const base =
|
|
5224
|
+
const base = path12.basename(shell);
|
|
1747
5225
|
const home = os2.homedir();
|
|
1748
|
-
if (base === "zsh" || base === "-zsh") return
|
|
5226
|
+
if (base === "zsh" || base === "-zsh") return path12.join(home, ".zshrc");
|
|
1749
5227
|
if (base === "bash" || base === "-bash") {
|
|
1750
|
-
return platform === "mac" ?
|
|
5228
|
+
return platform === "mac" ? path12.join(home, ".bash_profile") : path12.join(home, ".bashrc");
|
|
1751
5229
|
}
|
|
1752
5230
|
if (base === "fish") return null;
|
|
1753
5231
|
return null;
|
|
1754
5232
|
}
|
|
1755
5233
|
|
|
1756
5234
|
// src/shell/rc.ts
|
|
1757
|
-
import
|
|
5235
|
+
import fs13 from "fs";
|
|
1758
5236
|
import os3 from "os";
|
|
1759
|
-
import
|
|
5237
|
+
import path13 from "path";
|
|
1760
5238
|
function rcBegin(type) {
|
|
1761
5239
|
return `# >>> ${CLI_BIN} ${type} init >>>`;
|
|
1762
5240
|
}
|
|
@@ -1767,9 +5245,9 @@ function rcBlock(type) {
|
|
|
1767
5245
|
const spec = getSdkType(type);
|
|
1768
5246
|
const binSuffix = spec.envBinSuffix(detectPlatform()).replace(/\\/g, "/");
|
|
1769
5247
|
const abs = paths.current(type);
|
|
1770
|
-
const rel =
|
|
1771
|
-
const toPosix = (p) => p.split(
|
|
1772
|
-
const link = rel.startsWith("..") ||
|
|
5248
|
+
const rel = path13.relative(os3.homedir(), abs);
|
|
5249
|
+
const toPosix = (p) => p.split(path13.sep).join("/");
|
|
5250
|
+
const link = rel.startsWith("..") || path13.isAbsolute(rel) ? toPosix(abs) : `$HOME/${toPosix(rel)}`;
|
|
1773
5251
|
return [
|
|
1774
5252
|
rcBegin(type),
|
|
1775
5253
|
`export ${spec.envVar}="${link}"`,
|
|
@@ -1792,8 +5270,8 @@ ${rcBlock(type)}
|
|
|
1792
5270
|
`;
|
|
1793
5271
|
}
|
|
1794
5272
|
function upsertRcFile(file, type) {
|
|
1795
|
-
const content =
|
|
1796
|
-
|
|
5273
|
+
const content = fs13.existsSync(file) ? fs13.readFileSync(file, "utf8") : "";
|
|
5274
|
+
fs13.writeFileSync(file, upsertRcContent(content, type));
|
|
1797
5275
|
}
|
|
1798
5276
|
function escapeRegex(s) {
|
|
1799
5277
|
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -1801,17 +5279,17 @@ function escapeRegex(s) {
|
|
|
1801
5279
|
|
|
1802
5280
|
// src/shell/winenv.ts
|
|
1803
5281
|
import os4 from "os";
|
|
1804
|
-
import
|
|
5282
|
+
import path14 from "path";
|
|
1805
5283
|
function encoded(ps) {
|
|
1806
5284
|
return ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(ps, "utf16le").toString("base64")];
|
|
1807
5285
|
}
|
|
1808
5286
|
function currentLinkWin(type) {
|
|
1809
5287
|
const abs = paths.current(type);
|
|
1810
|
-
const rel =
|
|
1811
|
-
if (rel.startsWith("..") ||
|
|
5288
|
+
const rel = path14.relative(os4.homedir(), abs);
|
|
5289
|
+
if (rel.startsWith("..") || path14.isAbsolute(rel)) {
|
|
1812
5290
|
return abs;
|
|
1813
5291
|
}
|
|
1814
|
-
return `%USERPROFILE%\\${rel.split(
|
|
5292
|
+
return `%USERPROFILE%\\${rel.split(path14.sep).join("\\")}`;
|
|
1815
5293
|
}
|
|
1816
5294
|
function broadcastPs() {
|
|
1817
5295
|
return [
|
|
@@ -1896,7 +5374,7 @@ async function useCommand(type, specInput, opts) {
|
|
|
1896
5374
|
console.log(rcBlock(type));
|
|
1897
5375
|
}
|
|
1898
5376
|
}
|
|
1899
|
-
await showSdkVersion(
|
|
5377
|
+
await showSdkVersion(path15.join(installed.home, spec.binRelPath(platform)), type);
|
|
1900
5378
|
}
|
|
1901
5379
|
|
|
1902
5380
|
// src/cli/ls.ts
|
|
@@ -1976,7 +5454,7 @@ function currentCommand(types = SDK_TYPES) {
|
|
|
1976
5454
|
}
|
|
1977
5455
|
|
|
1978
5456
|
// src/cli/uninstall.ts
|
|
1979
|
-
import
|
|
5457
|
+
import fs14 from "fs";
|
|
1980
5458
|
async function uninstallCommand(type, specInput, opts) {
|
|
1981
5459
|
const spec = getSdkType(type);
|
|
1982
5460
|
const installed = findInstalled(type, specInput, opts.vendor);
|
|
@@ -1986,7 +5464,7 @@ async function uninstallCommand(type, specInput, opts) {
|
|
|
1986
5464
|
log.warn(`uninstalled the current ${spec.label}; ${spec.envVar} is now dangling`);
|
|
1987
5465
|
log.info(`select another: ${cmdPath(type)} use <version>`);
|
|
1988
5466
|
}
|
|
1989
|
-
|
|
5467
|
+
fs14.rmSync(installed.dirPath, { recursive: true, force: true });
|
|
1990
5468
|
});
|
|
1991
5469
|
log.ok(`removed ${installed.version.vendor}-${spec.formatVersion(installed.version)}`);
|
|
1992
5470
|
}
|
|
@@ -2044,8 +5522,8 @@ function normalizeMirrorUrl(url) {
|
|
|
2044
5522
|
const trimmed = url.trim().replace(/\/+$/, "");
|
|
2045
5523
|
try {
|
|
2046
5524
|
const u = new URL(trimmed);
|
|
2047
|
-
const
|
|
2048
|
-
return `${u.protocol.toLowerCase()}//${u.host.toLowerCase()}${
|
|
5525
|
+
const path17 = `${u.pathname}${u.search}${u.hash}`.replace(/\/+$/, "") || "";
|
|
5526
|
+
return `${u.protocol.toLowerCase()}//${u.host.toLowerCase()}${path17}`;
|
|
2049
5527
|
} catch {
|
|
2050
5528
|
return trimmed;
|
|
2051
5529
|
}
|
|
@@ -2280,23 +5758,23 @@ function mirrorCommand(type, action, arg1, arg2) {
|
|
|
2280
5758
|
|
|
2281
5759
|
// src/cli/upgrade.ts
|
|
2282
5760
|
import { spawn } from "child_process";
|
|
2283
|
-
import
|
|
2284
|
-
import
|
|
5761
|
+
import fs15 from "fs";
|
|
5762
|
+
import path16 from "path";
|
|
2285
5763
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2286
5764
|
var RELEASE_REPO = "QInJ1995/sdkvm";
|
|
2287
5765
|
var RELEASE_ASSET = "sdkvm.tgz";
|
|
2288
5766
|
var RELEASE_SUMS = "SHA256SUMS";
|
|
2289
5767
|
function packageRoot(metaUrl = import.meta.url) {
|
|
2290
|
-
return
|
|
5768
|
+
return path16.resolve(path16.dirname(fileURLToPath2(metaUrl)), "..");
|
|
2291
5769
|
}
|
|
2292
5770
|
function isScriptInstall(probe = {}) {
|
|
2293
|
-
const home =
|
|
2294
|
-
const cliRoot =
|
|
2295
|
-
const runtimeRoot =
|
|
2296
|
-
const pkg =
|
|
5771
|
+
const home = path16.resolve(probe.home ?? sdkvmHome());
|
|
5772
|
+
const cliRoot = path16.resolve(path16.join(home, "cli"));
|
|
5773
|
+
const runtimeRoot = path16.resolve(path16.join(home, "runtime"));
|
|
5774
|
+
const pkg = path16.resolve(probe.packageRoot ?? packageRoot());
|
|
2297
5775
|
if (pkg === cliRoot) return true;
|
|
2298
|
-
const exec =
|
|
2299
|
-
return exec === runtimeRoot || exec.startsWith(runtimeRoot +
|
|
5776
|
+
const exec = path16.resolve(probe.execPath ?? process.execPath);
|
|
5777
|
+
return exec === runtimeRoot || exec.startsWith(runtimeRoot + path16.sep);
|
|
2300
5778
|
}
|
|
2301
5779
|
function releaseBase() {
|
|
2302
5780
|
const fromEnv = process.env.SDKVM_RELEASE_BASE?.replace(/\/+$/, "");
|
|
@@ -2315,38 +5793,38 @@ function checksumFor(sumsText, fileName) {
|
|
|
2315
5793
|
return null;
|
|
2316
5794
|
}
|
|
2317
5795
|
async function prepareCliPackage(archiveFile, home = sdkvmHome()) {
|
|
2318
|
-
const staging =
|
|
2319
|
-
|
|
2320
|
-
|
|
5796
|
+
const staging = path16.join(home, "cli.next");
|
|
5797
|
+
fs15.rmSync(staging, { recursive: true, force: true });
|
|
5798
|
+
fs15.mkdirSync(home, { recursive: true });
|
|
2321
5799
|
await extractArchive(archiveFile, "tar.gz", staging, detectPlatform());
|
|
2322
|
-
const unpacked =
|
|
2323
|
-
if (!
|
|
2324
|
-
|
|
5800
|
+
const unpacked = path16.join(staging, "package");
|
|
5801
|
+
if (!fs15.existsSync(path16.join(unpacked, "package.json"))) {
|
|
5802
|
+
fs15.rmSync(staging, { recursive: true, force: true });
|
|
2325
5803
|
throw new SdkvmError("Release archive is missing package/package.json", { hint: archiveFile });
|
|
2326
5804
|
}
|
|
2327
5805
|
return unpacked;
|
|
2328
5806
|
}
|
|
2329
5807
|
async function replaceCliPackage(archiveFile, home = sdkvmHome()) {
|
|
2330
|
-
const staging =
|
|
2331
|
-
const bak =
|
|
2332
|
-
const cli =
|
|
5808
|
+
const staging = path16.join(home, "cli.next");
|
|
5809
|
+
const bak = path16.join(home, "cli.bak");
|
|
5810
|
+
const cli = path16.join(home, "cli");
|
|
2333
5811
|
const unpacked = await prepareCliPackage(archiveFile, home);
|
|
2334
|
-
|
|
2335
|
-
if (
|
|
5812
|
+
fs15.rmSync(bak, { recursive: true, force: true });
|
|
5813
|
+
if (fs15.existsSync(cli)) fs15.renameSync(cli, bak);
|
|
2336
5814
|
try {
|
|
2337
|
-
|
|
5815
|
+
fs15.renameSync(unpacked, cli);
|
|
2338
5816
|
} catch (err) {
|
|
2339
|
-
if (
|
|
5817
|
+
if (fs15.existsSync(bak) && !fs15.existsSync(cli)) {
|
|
2340
5818
|
try {
|
|
2341
|
-
|
|
5819
|
+
fs15.renameSync(bak, cli);
|
|
2342
5820
|
} catch {
|
|
2343
5821
|
}
|
|
2344
5822
|
}
|
|
2345
|
-
|
|
5823
|
+
fs15.rmSync(staging, { recursive: true, force: true });
|
|
2346
5824
|
throw err;
|
|
2347
5825
|
}
|
|
2348
|
-
|
|
2349
|
-
|
|
5826
|
+
fs15.rmSync(bak, { recursive: true, force: true });
|
|
5827
|
+
fs15.rmSync(staging, { recursive: true, force: true });
|
|
2350
5828
|
}
|
|
2351
5829
|
function windowsUpgradeScript(home) {
|
|
2352
5830
|
return [
|
|
@@ -2368,8 +5846,8 @@ function windowsUpgradeScript(home) {
|
|
|
2368
5846
|
].join("\r\n");
|
|
2369
5847
|
}
|
|
2370
5848
|
function scheduleWindowsCliReplace(home) {
|
|
2371
|
-
const script =
|
|
2372
|
-
|
|
5849
|
+
const script = path16.join(home, "upgrade-apply.cmd");
|
|
5850
|
+
fs15.writeFileSync(script, windowsUpgradeScript(home), "utf8");
|
|
2373
5851
|
const child = spawn("cmd.exe", ["/c", script], {
|
|
2374
5852
|
detached: true,
|
|
2375
5853
|
stdio: "ignore",
|
|
@@ -2391,8 +5869,8 @@ async function upgradeCommand() {
|
|
|
2391
5869
|
if (!expected) {
|
|
2392
5870
|
throw new SdkvmError(`No checksum for ${RELEASE_ASSET}`, { hint: sumsUrl });
|
|
2393
5871
|
}
|
|
2394
|
-
|
|
2395
|
-
const dest =
|
|
5872
|
+
fs15.mkdirSync(paths.cache(), { recursive: true });
|
|
5873
|
+
const dest = path16.join(paths.cache(), RELEASE_ASSET);
|
|
2396
5874
|
try {
|
|
2397
5875
|
const downloaded = await downloadFile(assetUrl, dest);
|
|
2398
5876
|
if (downloaded.sha256 !== expected) {
|
|
@@ -2406,18 +5884,18 @@ async function upgradeCommand() {
|
|
|
2406
5884
|
await prepareCliPackage(dest, home);
|
|
2407
5885
|
scheduleWindowsCliReplace(home);
|
|
2408
5886
|
log.ok(
|
|
2409
|
-
`upgrade ${before} scheduled; exit this process and wait a moment for ${
|
|
5887
|
+
`upgrade ${before} scheduled; exit this process and wait a moment for ${path16.join(home, "cli")} to refresh`
|
|
2410
5888
|
);
|
|
2411
5889
|
return;
|
|
2412
5890
|
}
|
|
2413
5891
|
await replaceCliPackage(dest, home);
|
|
2414
5892
|
const after = getVersion();
|
|
2415
5893
|
log.ok(
|
|
2416
|
-
`upgraded CLI ${before} \u2192 ${after} in ${
|
|
5894
|
+
`upgraded CLI ${before} \u2192 ${after} in ${path16.join(home, "cli")}; runtime and installed SDKs were left in place`
|
|
2417
5895
|
);
|
|
2418
5896
|
} finally {
|
|
2419
|
-
|
|
2420
|
-
|
|
5897
|
+
fs15.rmSync(dest, { force: true });
|
|
5898
|
+
fs15.rmSync(`${dest}.part`, { force: true });
|
|
2421
5899
|
}
|
|
2422
5900
|
});
|
|
2423
5901
|
}
|
|
@@ -2616,8 +6094,8 @@ async function nrmTest(name, opts = {}) {
|
|
|
2616
6094
|
}
|
|
2617
6095
|
|
|
2618
6096
|
// src/index.ts
|
|
2619
|
-
var
|
|
2620
|
-
|
|
6097
|
+
var program2 = new Command();
|
|
6098
|
+
program2.name("sdkvm").description("SDK version manager \u2014 install & switch JDKs (Temurin / Zulu / Corretto), Go toolchains, Flutter SDKs, and Node.js runtimes").version(getVersion());
|
|
2621
6099
|
function registerSdkCommands(cmd, type) {
|
|
2622
6100
|
const s = getSdkType(type);
|
|
2623
6101
|
const isJava = type === "java";
|
|
@@ -2632,23 +6110,23 @@ function registerSdkCommands(cmd, type) {
|
|
|
2632
6110
|
(a, v, u) => mirrorCommand(type, a, v, u)
|
|
2633
6111
|
);
|
|
2634
6112
|
}
|
|
2635
|
-
registerSdkCommands(
|
|
2636
|
-
var javaCmd =
|
|
6113
|
+
registerSdkCommands(program2, "java");
|
|
6114
|
+
var javaCmd = program2.command("java").description("Java (JDK) subcommands (same as the bare commands)");
|
|
2637
6115
|
registerSdkCommands(javaCmd, "java");
|
|
2638
6116
|
javaCmd.action(() => javaCmd.help());
|
|
2639
|
-
var goCmd =
|
|
6117
|
+
var goCmd = program2.command("go").description("Go toolchain subcommands");
|
|
2640
6118
|
registerSdkCommands(goCmd, "go");
|
|
2641
6119
|
goCmd.action(() => goCmd.help());
|
|
2642
|
-
var flutterCmd =
|
|
6120
|
+
var flutterCmd = program2.command("flutter").description("Flutter SDK subcommands");
|
|
2643
6121
|
registerSdkCommands(flutterCmd, "flutter");
|
|
2644
6122
|
flutterCmd.action(() => flutterCmd.help());
|
|
2645
|
-
var nodeCmd =
|
|
6123
|
+
var nodeCmd = program2.command("node").description("Node.js subcommands");
|
|
2646
6124
|
registerSdkCommands(nodeCmd, "node");
|
|
2647
6125
|
nodeCmd.action(() => nodeCmd.help());
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
var nrmCmd =
|
|
6126
|
+
program2.commands.find((c) => c.name() === "current")?.action(() => currentCommand());
|
|
6127
|
+
program2.command("version").description("print sdkvm CLI version").action(versionCommand);
|
|
6128
|
+
program2.command("upgrade").description("upgrade the sdkvm CLI (script install replaces ~/.sdkvm/cli; npm install prints npm update -g)").action(upgradeCommand);
|
|
6129
|
+
var nrmCmd = program2.command("nrm").description("npm registry manager (like nrm)");
|
|
2652
6130
|
nrmCmd.command("ls").alias("list").description("list npm registries (* marks current)").action(() => nrmLs());
|
|
2653
6131
|
nrmCmd.command("current").description("print the current npm registry").action(() => nrmCurrent());
|
|
2654
6132
|
nrmCmd.command("use").description("switch the user-level npm registry").argument("<name>", "registry name, e.g. npm / taobao / myprivate").action((name) => nrmUse(name));
|
|
@@ -2656,7 +6134,7 @@ nrmCmd.command("add").description("add a custom npm registry").argument("<name>"
|
|
|
2656
6134
|
nrmCmd.command("del").alias("delete").alias("rm").description("delete a custom npm registry").argument("<name>", "custom registry name").action((name) => nrmDel(name));
|
|
2657
6135
|
nrmCmd.command("test").description("ping registries and print latency").argument("[name]", "optional registry name; omit to test all").action((name) => nrmTest(name));
|
|
2658
6136
|
nrmCmd.action(() => nrmCmd.help());
|
|
2659
|
-
|
|
6137
|
+
program2.parseAsync(process.argv).catch((err) => {
|
|
2660
6138
|
const e = toSdkvmError(err);
|
|
2661
6139
|
log.error(e.message);
|
|
2662
6140
|
if (e.hint) log.info(e.hint);
|