@statechange/ssh-tunnel-manager 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.mjs +563 -0
- package/dist/cli.mjs +4194 -0
- package/dist/preload.js +10 -0
- package/package.json +27 -0
- package/renderer/add-tunnel.html +127 -0
- package/renderer/add-tunnel.js +48 -0
- package/scripts/postinstall.mjs +117 -0
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,4194 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "module"; const require = createRequire(import.meta.url);
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
10
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
11
|
+
}) : x)(function(x) {
|
|
12
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
13
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
14
|
+
});
|
|
15
|
+
var __esm = (fn, res) => function __init() {
|
|
16
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
17
|
+
};
|
|
18
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
19
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
20
|
+
};
|
|
21
|
+
var __export = (target, all) => {
|
|
22
|
+
for (var name in all)
|
|
23
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
24
|
+
};
|
|
25
|
+
var __copyProps = (to, from, except, desc) => {
|
|
26
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
27
|
+
for (let key of __getOwnPropNames(from))
|
|
28
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
29
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
30
|
+
}
|
|
31
|
+
return to;
|
|
32
|
+
};
|
|
33
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
34
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
35
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
36
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
37
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
38
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
39
|
+
mod
|
|
40
|
+
));
|
|
41
|
+
|
|
42
|
+
// node_modules/commander/lib/error.js
|
|
43
|
+
var require_error = __commonJS({
|
|
44
|
+
"node_modules/commander/lib/error.js"(exports) {
|
|
45
|
+
var CommanderError2 = class extends Error {
|
|
46
|
+
/**
|
|
47
|
+
* Constructs the CommanderError class
|
|
48
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
49
|
+
* @param {string} code an id string representing the error
|
|
50
|
+
* @param {string} message human-readable description of the error
|
|
51
|
+
*/
|
|
52
|
+
constructor(exitCode, code, message) {
|
|
53
|
+
super(message);
|
|
54
|
+
Error.captureStackTrace(this, this.constructor);
|
|
55
|
+
this.name = this.constructor.name;
|
|
56
|
+
this.code = code;
|
|
57
|
+
this.exitCode = exitCode;
|
|
58
|
+
this.nestedError = void 0;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var InvalidArgumentError2 = class extends CommanderError2 {
|
|
62
|
+
/**
|
|
63
|
+
* Constructs the InvalidArgumentError class
|
|
64
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
65
|
+
*/
|
|
66
|
+
constructor(message) {
|
|
67
|
+
super(1, "commander.invalidArgument", message);
|
|
68
|
+
Error.captureStackTrace(this, this.constructor);
|
|
69
|
+
this.name = this.constructor.name;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
exports.CommanderError = CommanderError2;
|
|
73
|
+
exports.InvalidArgumentError = InvalidArgumentError2;
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// node_modules/commander/lib/argument.js
|
|
78
|
+
var require_argument = __commonJS({
|
|
79
|
+
"node_modules/commander/lib/argument.js"(exports) {
|
|
80
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
81
|
+
var Argument2 = class {
|
|
82
|
+
/**
|
|
83
|
+
* Initialize a new command argument with the given name and description.
|
|
84
|
+
* The default is that the argument is required, and you can explicitly
|
|
85
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
86
|
+
*
|
|
87
|
+
* @param {string} name
|
|
88
|
+
* @param {string} [description]
|
|
89
|
+
*/
|
|
90
|
+
constructor(name, description) {
|
|
91
|
+
this.description = description || "";
|
|
92
|
+
this.variadic = false;
|
|
93
|
+
this.parseArg = void 0;
|
|
94
|
+
this.defaultValue = void 0;
|
|
95
|
+
this.defaultValueDescription = void 0;
|
|
96
|
+
this.argChoices = void 0;
|
|
97
|
+
switch (name[0]) {
|
|
98
|
+
case "<":
|
|
99
|
+
this.required = true;
|
|
100
|
+
this._name = name.slice(1, -1);
|
|
101
|
+
break;
|
|
102
|
+
case "[":
|
|
103
|
+
this.required = false;
|
|
104
|
+
this._name = name.slice(1, -1);
|
|
105
|
+
break;
|
|
106
|
+
default:
|
|
107
|
+
this.required = true;
|
|
108
|
+
this._name = name;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
if (this._name.length > 3 && this._name.slice(-3) === "...") {
|
|
112
|
+
this.variadic = true;
|
|
113
|
+
this._name = this._name.slice(0, -3);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Return argument name.
|
|
118
|
+
*
|
|
119
|
+
* @return {string}
|
|
120
|
+
*/
|
|
121
|
+
name() {
|
|
122
|
+
return this._name;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* @package
|
|
126
|
+
*/
|
|
127
|
+
_concatValue(value, previous) {
|
|
128
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
129
|
+
return [value];
|
|
130
|
+
}
|
|
131
|
+
return previous.concat(value);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
135
|
+
*
|
|
136
|
+
* @param {*} value
|
|
137
|
+
* @param {string} [description]
|
|
138
|
+
* @return {Argument}
|
|
139
|
+
*/
|
|
140
|
+
default(value, description) {
|
|
141
|
+
this.defaultValue = value;
|
|
142
|
+
this.defaultValueDescription = description;
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
147
|
+
*
|
|
148
|
+
* @param {Function} [fn]
|
|
149
|
+
* @return {Argument}
|
|
150
|
+
*/
|
|
151
|
+
argParser(fn) {
|
|
152
|
+
this.parseArg = fn;
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Only allow argument value to be one of choices.
|
|
157
|
+
*
|
|
158
|
+
* @param {string[]} values
|
|
159
|
+
* @return {Argument}
|
|
160
|
+
*/
|
|
161
|
+
choices(values) {
|
|
162
|
+
this.argChoices = values.slice();
|
|
163
|
+
this.parseArg = (arg, previous) => {
|
|
164
|
+
if (!this.argChoices.includes(arg)) {
|
|
165
|
+
throw new InvalidArgumentError2(
|
|
166
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
if (this.variadic) {
|
|
170
|
+
return this._concatValue(arg, previous);
|
|
171
|
+
}
|
|
172
|
+
return arg;
|
|
173
|
+
};
|
|
174
|
+
return this;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Make argument required.
|
|
178
|
+
*
|
|
179
|
+
* @returns {Argument}
|
|
180
|
+
*/
|
|
181
|
+
argRequired() {
|
|
182
|
+
this.required = true;
|
|
183
|
+
return this;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Make argument optional.
|
|
187
|
+
*
|
|
188
|
+
* @returns {Argument}
|
|
189
|
+
*/
|
|
190
|
+
argOptional() {
|
|
191
|
+
this.required = false;
|
|
192
|
+
return this;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
function humanReadableArgName(arg) {
|
|
196
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
197
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
198
|
+
}
|
|
199
|
+
exports.Argument = Argument2;
|
|
200
|
+
exports.humanReadableArgName = humanReadableArgName;
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
// node_modules/commander/lib/help.js
|
|
205
|
+
var require_help = __commonJS({
|
|
206
|
+
"node_modules/commander/lib/help.js"(exports) {
|
|
207
|
+
var { humanReadableArgName } = require_argument();
|
|
208
|
+
var Help2 = class {
|
|
209
|
+
constructor() {
|
|
210
|
+
this.helpWidth = void 0;
|
|
211
|
+
this.minWidthToWrap = 40;
|
|
212
|
+
this.sortSubcommands = false;
|
|
213
|
+
this.sortOptions = false;
|
|
214
|
+
this.showGlobalOptions = false;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
218
|
+
* and just before calling `formatHelp()`.
|
|
219
|
+
*
|
|
220
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
221
|
+
*
|
|
222
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
223
|
+
*/
|
|
224
|
+
prepareContext(contextOptions) {
|
|
225
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
229
|
+
*
|
|
230
|
+
* @param {Command} cmd
|
|
231
|
+
* @returns {Command[]}
|
|
232
|
+
*/
|
|
233
|
+
visibleCommands(cmd) {
|
|
234
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
235
|
+
const helpCommand = cmd._getHelpCommand();
|
|
236
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
237
|
+
visibleCommands.push(helpCommand);
|
|
238
|
+
}
|
|
239
|
+
if (this.sortSubcommands) {
|
|
240
|
+
visibleCommands.sort((a, b) => {
|
|
241
|
+
return a.name().localeCompare(b.name());
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
return visibleCommands;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Compare options for sort.
|
|
248
|
+
*
|
|
249
|
+
* @param {Option} a
|
|
250
|
+
* @param {Option} b
|
|
251
|
+
* @returns {number}
|
|
252
|
+
*/
|
|
253
|
+
compareOptions(a, b) {
|
|
254
|
+
const getSortKey = (option) => {
|
|
255
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
256
|
+
};
|
|
257
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
261
|
+
*
|
|
262
|
+
* @param {Command} cmd
|
|
263
|
+
* @returns {Option[]}
|
|
264
|
+
*/
|
|
265
|
+
visibleOptions(cmd) {
|
|
266
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
267
|
+
const helpOption = cmd._getHelpOption();
|
|
268
|
+
if (helpOption && !helpOption.hidden) {
|
|
269
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
270
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
271
|
+
if (!removeShort && !removeLong) {
|
|
272
|
+
visibleOptions.push(helpOption);
|
|
273
|
+
} else if (helpOption.long && !removeLong) {
|
|
274
|
+
visibleOptions.push(
|
|
275
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
276
|
+
);
|
|
277
|
+
} else if (helpOption.short && !removeShort) {
|
|
278
|
+
visibleOptions.push(
|
|
279
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (this.sortOptions) {
|
|
284
|
+
visibleOptions.sort(this.compareOptions);
|
|
285
|
+
}
|
|
286
|
+
return visibleOptions;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Get an array of the visible global options. (Not including help.)
|
|
290
|
+
*
|
|
291
|
+
* @param {Command} cmd
|
|
292
|
+
* @returns {Option[]}
|
|
293
|
+
*/
|
|
294
|
+
visibleGlobalOptions(cmd) {
|
|
295
|
+
if (!this.showGlobalOptions) return [];
|
|
296
|
+
const globalOptions = [];
|
|
297
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
298
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
299
|
+
(option) => !option.hidden
|
|
300
|
+
);
|
|
301
|
+
globalOptions.push(...visibleOptions);
|
|
302
|
+
}
|
|
303
|
+
if (this.sortOptions) {
|
|
304
|
+
globalOptions.sort(this.compareOptions);
|
|
305
|
+
}
|
|
306
|
+
return globalOptions;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Get an array of the arguments if any have a description.
|
|
310
|
+
*
|
|
311
|
+
* @param {Command} cmd
|
|
312
|
+
* @returns {Argument[]}
|
|
313
|
+
*/
|
|
314
|
+
visibleArguments(cmd) {
|
|
315
|
+
if (cmd._argsDescription) {
|
|
316
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
317
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
321
|
+
return cmd.registeredArguments;
|
|
322
|
+
}
|
|
323
|
+
return [];
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Get the command term to show in the list of subcommands.
|
|
327
|
+
*
|
|
328
|
+
* @param {Command} cmd
|
|
329
|
+
* @returns {string}
|
|
330
|
+
*/
|
|
331
|
+
subcommandTerm(cmd) {
|
|
332
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
333
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
334
|
+
(args ? " " + args : "");
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Get the option term to show in the list of options.
|
|
338
|
+
*
|
|
339
|
+
* @param {Option} option
|
|
340
|
+
* @returns {string}
|
|
341
|
+
*/
|
|
342
|
+
optionTerm(option) {
|
|
343
|
+
return option.flags;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Get the argument term to show in the list of arguments.
|
|
347
|
+
*
|
|
348
|
+
* @param {Argument} argument
|
|
349
|
+
* @returns {string}
|
|
350
|
+
*/
|
|
351
|
+
argumentTerm(argument) {
|
|
352
|
+
return argument.name();
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Get the longest command term length.
|
|
356
|
+
*
|
|
357
|
+
* @param {Command} cmd
|
|
358
|
+
* @param {Help} helper
|
|
359
|
+
* @returns {number}
|
|
360
|
+
*/
|
|
361
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
362
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
363
|
+
return Math.max(
|
|
364
|
+
max,
|
|
365
|
+
this.displayWidth(
|
|
366
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
367
|
+
)
|
|
368
|
+
);
|
|
369
|
+
}, 0);
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Get the longest option term length.
|
|
373
|
+
*
|
|
374
|
+
* @param {Command} cmd
|
|
375
|
+
* @param {Help} helper
|
|
376
|
+
* @returns {number}
|
|
377
|
+
*/
|
|
378
|
+
longestOptionTermLength(cmd, helper) {
|
|
379
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
380
|
+
return Math.max(
|
|
381
|
+
max,
|
|
382
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
383
|
+
);
|
|
384
|
+
}, 0);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Get the longest global option term length.
|
|
388
|
+
*
|
|
389
|
+
* @param {Command} cmd
|
|
390
|
+
* @param {Help} helper
|
|
391
|
+
* @returns {number}
|
|
392
|
+
*/
|
|
393
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
394
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
395
|
+
return Math.max(
|
|
396
|
+
max,
|
|
397
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
398
|
+
);
|
|
399
|
+
}, 0);
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Get the longest argument term length.
|
|
403
|
+
*
|
|
404
|
+
* @param {Command} cmd
|
|
405
|
+
* @param {Help} helper
|
|
406
|
+
* @returns {number}
|
|
407
|
+
*/
|
|
408
|
+
longestArgumentTermLength(cmd, helper) {
|
|
409
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
410
|
+
return Math.max(
|
|
411
|
+
max,
|
|
412
|
+
this.displayWidth(
|
|
413
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
414
|
+
)
|
|
415
|
+
);
|
|
416
|
+
}, 0);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
420
|
+
*
|
|
421
|
+
* @param {Command} cmd
|
|
422
|
+
* @returns {string}
|
|
423
|
+
*/
|
|
424
|
+
commandUsage(cmd) {
|
|
425
|
+
let cmdName = cmd._name;
|
|
426
|
+
if (cmd._aliases[0]) {
|
|
427
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
428
|
+
}
|
|
429
|
+
let ancestorCmdNames = "";
|
|
430
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
431
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
432
|
+
}
|
|
433
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Get the description for the command.
|
|
437
|
+
*
|
|
438
|
+
* @param {Command} cmd
|
|
439
|
+
* @returns {string}
|
|
440
|
+
*/
|
|
441
|
+
commandDescription(cmd) {
|
|
442
|
+
return cmd.description();
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
446
|
+
* (Fallback to description for backwards compatibility.)
|
|
447
|
+
*
|
|
448
|
+
* @param {Command} cmd
|
|
449
|
+
* @returns {string}
|
|
450
|
+
*/
|
|
451
|
+
subcommandDescription(cmd) {
|
|
452
|
+
return cmd.summary() || cmd.description();
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Get the option description to show in the list of options.
|
|
456
|
+
*
|
|
457
|
+
* @param {Option} option
|
|
458
|
+
* @return {string}
|
|
459
|
+
*/
|
|
460
|
+
optionDescription(option) {
|
|
461
|
+
const extraInfo = [];
|
|
462
|
+
if (option.argChoices) {
|
|
463
|
+
extraInfo.push(
|
|
464
|
+
// use stringify to match the display of the default value
|
|
465
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
if (option.defaultValue !== void 0) {
|
|
469
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
470
|
+
if (showDefault) {
|
|
471
|
+
extraInfo.push(
|
|
472
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
477
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
478
|
+
}
|
|
479
|
+
if (option.envVar !== void 0) {
|
|
480
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
481
|
+
}
|
|
482
|
+
if (extraInfo.length > 0) {
|
|
483
|
+
return `${option.description} (${extraInfo.join(", ")})`;
|
|
484
|
+
}
|
|
485
|
+
return option.description;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Get the argument description to show in the list of arguments.
|
|
489
|
+
*
|
|
490
|
+
* @param {Argument} argument
|
|
491
|
+
* @return {string}
|
|
492
|
+
*/
|
|
493
|
+
argumentDescription(argument) {
|
|
494
|
+
const extraInfo = [];
|
|
495
|
+
if (argument.argChoices) {
|
|
496
|
+
extraInfo.push(
|
|
497
|
+
// use stringify to match the display of the default value
|
|
498
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
if (argument.defaultValue !== void 0) {
|
|
502
|
+
extraInfo.push(
|
|
503
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
if (extraInfo.length > 0) {
|
|
507
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
508
|
+
if (argument.description) {
|
|
509
|
+
return `${argument.description} ${extraDescription}`;
|
|
510
|
+
}
|
|
511
|
+
return extraDescription;
|
|
512
|
+
}
|
|
513
|
+
return argument.description;
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Generate the built-in help text.
|
|
517
|
+
*
|
|
518
|
+
* @param {Command} cmd
|
|
519
|
+
* @param {Help} helper
|
|
520
|
+
* @returns {string}
|
|
521
|
+
*/
|
|
522
|
+
formatHelp(cmd, helper) {
|
|
523
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
524
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
525
|
+
function callFormatItem(term, description) {
|
|
526
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
527
|
+
}
|
|
528
|
+
let output2 = [
|
|
529
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
530
|
+
""
|
|
531
|
+
];
|
|
532
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
533
|
+
if (commandDescription.length > 0) {
|
|
534
|
+
output2 = output2.concat([
|
|
535
|
+
helper.boxWrap(
|
|
536
|
+
helper.styleCommandDescription(commandDescription),
|
|
537
|
+
helpWidth
|
|
538
|
+
),
|
|
539
|
+
""
|
|
540
|
+
]);
|
|
541
|
+
}
|
|
542
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
543
|
+
return callFormatItem(
|
|
544
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
545
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
546
|
+
);
|
|
547
|
+
});
|
|
548
|
+
if (argumentList.length > 0) {
|
|
549
|
+
output2 = output2.concat([
|
|
550
|
+
helper.styleTitle("Arguments:"),
|
|
551
|
+
...argumentList,
|
|
552
|
+
""
|
|
553
|
+
]);
|
|
554
|
+
}
|
|
555
|
+
const optionList = helper.visibleOptions(cmd).map((option) => {
|
|
556
|
+
return callFormatItem(
|
|
557
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
558
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
559
|
+
);
|
|
560
|
+
});
|
|
561
|
+
if (optionList.length > 0) {
|
|
562
|
+
output2 = output2.concat([
|
|
563
|
+
helper.styleTitle("Options:"),
|
|
564
|
+
...optionList,
|
|
565
|
+
""
|
|
566
|
+
]);
|
|
567
|
+
}
|
|
568
|
+
if (helper.showGlobalOptions) {
|
|
569
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
570
|
+
return callFormatItem(
|
|
571
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
572
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
573
|
+
);
|
|
574
|
+
});
|
|
575
|
+
if (globalOptionList.length > 0) {
|
|
576
|
+
output2 = output2.concat([
|
|
577
|
+
helper.styleTitle("Global Options:"),
|
|
578
|
+
...globalOptionList,
|
|
579
|
+
""
|
|
580
|
+
]);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
|
|
584
|
+
return callFormatItem(
|
|
585
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
|
|
586
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
|
|
587
|
+
);
|
|
588
|
+
});
|
|
589
|
+
if (commandList.length > 0) {
|
|
590
|
+
output2 = output2.concat([
|
|
591
|
+
helper.styleTitle("Commands:"),
|
|
592
|
+
...commandList,
|
|
593
|
+
""
|
|
594
|
+
]);
|
|
595
|
+
}
|
|
596
|
+
return output2.join("\n");
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
600
|
+
*
|
|
601
|
+
* @param {string} str
|
|
602
|
+
* @returns {number}
|
|
603
|
+
*/
|
|
604
|
+
displayWidth(str) {
|
|
605
|
+
return stripColor(str).length;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
609
|
+
*
|
|
610
|
+
* @param {string} str
|
|
611
|
+
* @returns {string}
|
|
612
|
+
*/
|
|
613
|
+
styleTitle(str) {
|
|
614
|
+
return str;
|
|
615
|
+
}
|
|
616
|
+
styleUsage(str) {
|
|
617
|
+
return str.split(" ").map((word) => {
|
|
618
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
619
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
620
|
+
if (word[0] === "[" || word[0] === "<")
|
|
621
|
+
return this.styleArgumentText(word);
|
|
622
|
+
return this.styleCommandText(word);
|
|
623
|
+
}).join(" ");
|
|
624
|
+
}
|
|
625
|
+
styleCommandDescription(str) {
|
|
626
|
+
return this.styleDescriptionText(str);
|
|
627
|
+
}
|
|
628
|
+
styleOptionDescription(str) {
|
|
629
|
+
return this.styleDescriptionText(str);
|
|
630
|
+
}
|
|
631
|
+
styleSubcommandDescription(str) {
|
|
632
|
+
return this.styleDescriptionText(str);
|
|
633
|
+
}
|
|
634
|
+
styleArgumentDescription(str) {
|
|
635
|
+
return this.styleDescriptionText(str);
|
|
636
|
+
}
|
|
637
|
+
styleDescriptionText(str) {
|
|
638
|
+
return str;
|
|
639
|
+
}
|
|
640
|
+
styleOptionTerm(str) {
|
|
641
|
+
return this.styleOptionText(str);
|
|
642
|
+
}
|
|
643
|
+
styleSubcommandTerm(str) {
|
|
644
|
+
return str.split(" ").map((word) => {
|
|
645
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
646
|
+
if (word[0] === "[" || word[0] === "<")
|
|
647
|
+
return this.styleArgumentText(word);
|
|
648
|
+
return this.styleSubcommandText(word);
|
|
649
|
+
}).join(" ");
|
|
650
|
+
}
|
|
651
|
+
styleArgumentTerm(str) {
|
|
652
|
+
return this.styleArgumentText(str);
|
|
653
|
+
}
|
|
654
|
+
styleOptionText(str) {
|
|
655
|
+
return str;
|
|
656
|
+
}
|
|
657
|
+
styleArgumentText(str) {
|
|
658
|
+
return str;
|
|
659
|
+
}
|
|
660
|
+
styleSubcommandText(str) {
|
|
661
|
+
return str;
|
|
662
|
+
}
|
|
663
|
+
styleCommandText(str) {
|
|
664
|
+
return str;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Calculate the pad width from the maximum term length.
|
|
668
|
+
*
|
|
669
|
+
* @param {Command} cmd
|
|
670
|
+
* @param {Help} helper
|
|
671
|
+
* @returns {number}
|
|
672
|
+
*/
|
|
673
|
+
padWidth(cmd, helper) {
|
|
674
|
+
return Math.max(
|
|
675
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
676
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
677
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
678
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
683
|
+
*
|
|
684
|
+
* @param {string} str
|
|
685
|
+
* @returns {boolean}
|
|
686
|
+
*/
|
|
687
|
+
preformatted(str) {
|
|
688
|
+
return /\n[^\S\r\n]/.test(str);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
692
|
+
*
|
|
693
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
694
|
+
* TTT DDD DDDD
|
|
695
|
+
* DD DDD
|
|
696
|
+
*
|
|
697
|
+
* @param {string} term
|
|
698
|
+
* @param {number} termWidth
|
|
699
|
+
* @param {string} description
|
|
700
|
+
* @param {Help} helper
|
|
701
|
+
* @returns {string}
|
|
702
|
+
*/
|
|
703
|
+
formatItem(term, termWidth, description, helper) {
|
|
704
|
+
const itemIndent = 2;
|
|
705
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
706
|
+
if (!description) return itemIndentStr + term;
|
|
707
|
+
const paddedTerm = term.padEnd(
|
|
708
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
709
|
+
);
|
|
710
|
+
const spacerWidth = 2;
|
|
711
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
712
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
713
|
+
let formattedDescription;
|
|
714
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
715
|
+
formattedDescription = description;
|
|
716
|
+
} else {
|
|
717
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
718
|
+
formattedDescription = wrappedDescription.replace(
|
|
719
|
+
/\n/g,
|
|
720
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
724
|
+
${itemIndentStr}`);
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
728
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
729
|
+
*
|
|
730
|
+
* @param {string} str
|
|
731
|
+
* @param {number} width
|
|
732
|
+
* @returns {string}
|
|
733
|
+
*/
|
|
734
|
+
boxWrap(str, width) {
|
|
735
|
+
if (width < this.minWidthToWrap) return str;
|
|
736
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
737
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
738
|
+
const wrappedLines = [];
|
|
739
|
+
rawLines.forEach((line) => {
|
|
740
|
+
const chunks = line.match(chunkPattern);
|
|
741
|
+
if (chunks === null) {
|
|
742
|
+
wrappedLines.push("");
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
let sumChunks = [chunks.shift()];
|
|
746
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
747
|
+
chunks.forEach((chunk) => {
|
|
748
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
749
|
+
if (sumWidth + visibleWidth <= width) {
|
|
750
|
+
sumChunks.push(chunk);
|
|
751
|
+
sumWidth += visibleWidth;
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
wrappedLines.push(sumChunks.join(""));
|
|
755
|
+
const nextChunk = chunk.trimStart();
|
|
756
|
+
sumChunks = [nextChunk];
|
|
757
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
758
|
+
});
|
|
759
|
+
wrappedLines.push(sumChunks.join(""));
|
|
760
|
+
});
|
|
761
|
+
return wrappedLines.join("\n");
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
function stripColor(str) {
|
|
765
|
+
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
|
|
766
|
+
return str.replace(sgrPattern, "");
|
|
767
|
+
}
|
|
768
|
+
exports.Help = Help2;
|
|
769
|
+
exports.stripColor = stripColor;
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
|
|
773
|
+
// node_modules/commander/lib/option.js
|
|
774
|
+
var require_option = __commonJS({
|
|
775
|
+
"node_modules/commander/lib/option.js"(exports) {
|
|
776
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
777
|
+
var Option2 = class {
|
|
778
|
+
/**
|
|
779
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
780
|
+
*
|
|
781
|
+
* @param {string} flags
|
|
782
|
+
* @param {string} [description]
|
|
783
|
+
*/
|
|
784
|
+
constructor(flags, description) {
|
|
785
|
+
this.flags = flags;
|
|
786
|
+
this.description = description || "";
|
|
787
|
+
this.required = flags.includes("<");
|
|
788
|
+
this.optional = flags.includes("[");
|
|
789
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
790
|
+
this.mandatory = false;
|
|
791
|
+
const optionFlags = splitOptionFlags(flags);
|
|
792
|
+
this.short = optionFlags.shortFlag;
|
|
793
|
+
this.long = optionFlags.longFlag;
|
|
794
|
+
this.negate = false;
|
|
795
|
+
if (this.long) {
|
|
796
|
+
this.negate = this.long.startsWith("--no-");
|
|
797
|
+
}
|
|
798
|
+
this.defaultValue = void 0;
|
|
799
|
+
this.defaultValueDescription = void 0;
|
|
800
|
+
this.presetArg = void 0;
|
|
801
|
+
this.envVar = void 0;
|
|
802
|
+
this.parseArg = void 0;
|
|
803
|
+
this.hidden = false;
|
|
804
|
+
this.argChoices = void 0;
|
|
805
|
+
this.conflictsWith = [];
|
|
806
|
+
this.implied = void 0;
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
810
|
+
*
|
|
811
|
+
* @param {*} value
|
|
812
|
+
* @param {string} [description]
|
|
813
|
+
* @return {Option}
|
|
814
|
+
*/
|
|
815
|
+
default(value, description) {
|
|
816
|
+
this.defaultValue = value;
|
|
817
|
+
this.defaultValueDescription = description;
|
|
818
|
+
return this;
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
822
|
+
* The custom processing (parseArg) is called.
|
|
823
|
+
*
|
|
824
|
+
* @example
|
|
825
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
826
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
827
|
+
*
|
|
828
|
+
* @param {*} arg
|
|
829
|
+
* @return {Option}
|
|
830
|
+
*/
|
|
831
|
+
preset(arg) {
|
|
832
|
+
this.presetArg = arg;
|
|
833
|
+
return this;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Add option name(s) that conflict with this option.
|
|
837
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
838
|
+
*
|
|
839
|
+
* @example
|
|
840
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
841
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
842
|
+
*
|
|
843
|
+
* @param {(string | string[])} names
|
|
844
|
+
* @return {Option}
|
|
845
|
+
*/
|
|
846
|
+
conflicts(names) {
|
|
847
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
848
|
+
return this;
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
852
|
+
*
|
|
853
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
854
|
+
*
|
|
855
|
+
* @example
|
|
856
|
+
* program
|
|
857
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
858
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
859
|
+
*
|
|
860
|
+
* @param {object} impliedOptionValues
|
|
861
|
+
* @return {Option}
|
|
862
|
+
*/
|
|
863
|
+
implies(impliedOptionValues) {
|
|
864
|
+
let newImplied = impliedOptionValues;
|
|
865
|
+
if (typeof impliedOptionValues === "string") {
|
|
866
|
+
newImplied = { [impliedOptionValues]: true };
|
|
867
|
+
}
|
|
868
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
869
|
+
return this;
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Set environment variable to check for option value.
|
|
873
|
+
*
|
|
874
|
+
* An environment variable is only used if when processed the current option value is
|
|
875
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
876
|
+
*
|
|
877
|
+
* @param {string} name
|
|
878
|
+
* @return {Option}
|
|
879
|
+
*/
|
|
880
|
+
env(name) {
|
|
881
|
+
this.envVar = name;
|
|
882
|
+
return this;
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
886
|
+
*
|
|
887
|
+
* @param {Function} [fn]
|
|
888
|
+
* @return {Option}
|
|
889
|
+
*/
|
|
890
|
+
argParser(fn) {
|
|
891
|
+
this.parseArg = fn;
|
|
892
|
+
return this;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
896
|
+
*
|
|
897
|
+
* @param {boolean} [mandatory=true]
|
|
898
|
+
* @return {Option}
|
|
899
|
+
*/
|
|
900
|
+
makeOptionMandatory(mandatory = true) {
|
|
901
|
+
this.mandatory = !!mandatory;
|
|
902
|
+
return this;
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Hide option in help.
|
|
906
|
+
*
|
|
907
|
+
* @param {boolean} [hide=true]
|
|
908
|
+
* @return {Option}
|
|
909
|
+
*/
|
|
910
|
+
hideHelp(hide = true) {
|
|
911
|
+
this.hidden = !!hide;
|
|
912
|
+
return this;
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* @package
|
|
916
|
+
*/
|
|
917
|
+
_concatValue(value, previous) {
|
|
918
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
919
|
+
return [value];
|
|
920
|
+
}
|
|
921
|
+
return previous.concat(value);
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Only allow option value to be one of choices.
|
|
925
|
+
*
|
|
926
|
+
* @param {string[]} values
|
|
927
|
+
* @return {Option}
|
|
928
|
+
*/
|
|
929
|
+
choices(values) {
|
|
930
|
+
this.argChoices = values.slice();
|
|
931
|
+
this.parseArg = (arg, previous) => {
|
|
932
|
+
if (!this.argChoices.includes(arg)) {
|
|
933
|
+
throw new InvalidArgumentError2(
|
|
934
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
if (this.variadic) {
|
|
938
|
+
return this._concatValue(arg, previous);
|
|
939
|
+
}
|
|
940
|
+
return arg;
|
|
941
|
+
};
|
|
942
|
+
return this;
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* Return option name.
|
|
946
|
+
*
|
|
947
|
+
* @return {string}
|
|
948
|
+
*/
|
|
949
|
+
name() {
|
|
950
|
+
if (this.long) {
|
|
951
|
+
return this.long.replace(/^--/, "");
|
|
952
|
+
}
|
|
953
|
+
return this.short.replace(/^-/, "");
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Return option name, in a camelcase format that can be used
|
|
957
|
+
* as an object attribute key.
|
|
958
|
+
*
|
|
959
|
+
* @return {string}
|
|
960
|
+
*/
|
|
961
|
+
attributeName() {
|
|
962
|
+
if (this.negate) {
|
|
963
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
964
|
+
}
|
|
965
|
+
return camelcase(this.name());
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Check if `arg` matches the short or long flag.
|
|
969
|
+
*
|
|
970
|
+
* @param {string} arg
|
|
971
|
+
* @return {boolean}
|
|
972
|
+
* @package
|
|
973
|
+
*/
|
|
974
|
+
is(arg) {
|
|
975
|
+
return this.short === arg || this.long === arg;
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Return whether a boolean option.
|
|
979
|
+
*
|
|
980
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
981
|
+
*
|
|
982
|
+
* @return {boolean}
|
|
983
|
+
* @package
|
|
984
|
+
*/
|
|
985
|
+
isBoolean() {
|
|
986
|
+
return !this.required && !this.optional && !this.negate;
|
|
987
|
+
}
|
|
988
|
+
};
|
|
989
|
+
var DualOptions = class {
|
|
990
|
+
/**
|
|
991
|
+
* @param {Option[]} options
|
|
992
|
+
*/
|
|
993
|
+
constructor(options) {
|
|
994
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
995
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
996
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
997
|
+
options.forEach((option) => {
|
|
998
|
+
if (option.negate) {
|
|
999
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
1000
|
+
} else {
|
|
1001
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
this.negativeOptions.forEach((value, key) => {
|
|
1005
|
+
if (this.positiveOptions.has(key)) {
|
|
1006
|
+
this.dualOptions.add(key);
|
|
1007
|
+
}
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1012
|
+
*
|
|
1013
|
+
* @param {*} value
|
|
1014
|
+
* @param {Option} option
|
|
1015
|
+
* @returns {boolean}
|
|
1016
|
+
*/
|
|
1017
|
+
valueFromOption(value, option) {
|
|
1018
|
+
const optionKey = option.attributeName();
|
|
1019
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1020
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1021
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1022
|
+
return option.negate === (negativeValue === value);
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
function camelcase(str) {
|
|
1026
|
+
return str.split("-").reduce((str2, word) => {
|
|
1027
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
1028
|
+
});
|
|
1029
|
+
}
|
|
1030
|
+
function splitOptionFlags(flags) {
|
|
1031
|
+
let shortFlag;
|
|
1032
|
+
let longFlag;
|
|
1033
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1034
|
+
const longFlagExp = /^--[^-]/;
|
|
1035
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1036
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1037
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1038
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1039
|
+
shortFlag = flagParts.shift();
|
|
1040
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1041
|
+
shortFlag = longFlag;
|
|
1042
|
+
longFlag = flagParts.shift();
|
|
1043
|
+
}
|
|
1044
|
+
if (flagParts[0].startsWith("-")) {
|
|
1045
|
+
const unsupportedFlag = flagParts[0];
|
|
1046
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1047
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1048
|
+
throw new Error(
|
|
1049
|
+
`${baseError}
|
|
1050
|
+
- a short flag is a single dash and a single character
|
|
1051
|
+
- either use a single dash and a single character (for a short flag)
|
|
1052
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1053
|
+
);
|
|
1054
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1055
|
+
throw new Error(`${baseError}
|
|
1056
|
+
- too many short flags`);
|
|
1057
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1058
|
+
throw new Error(`${baseError}
|
|
1059
|
+
- too many long flags`);
|
|
1060
|
+
throw new Error(`${baseError}
|
|
1061
|
+
- unrecognised flag format`);
|
|
1062
|
+
}
|
|
1063
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1064
|
+
throw new Error(
|
|
1065
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1066
|
+
);
|
|
1067
|
+
return { shortFlag, longFlag };
|
|
1068
|
+
}
|
|
1069
|
+
exports.Option = Option2;
|
|
1070
|
+
exports.DualOptions = DualOptions;
|
|
1071
|
+
}
|
|
1072
|
+
});
|
|
1073
|
+
|
|
1074
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1075
|
+
var require_suggestSimilar = __commonJS({
|
|
1076
|
+
"node_modules/commander/lib/suggestSimilar.js"(exports) {
|
|
1077
|
+
var maxDistance = 3;
|
|
1078
|
+
function editDistance(a, b) {
|
|
1079
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1080
|
+
return Math.max(a.length, b.length);
|
|
1081
|
+
const d = [];
|
|
1082
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1083
|
+
d[i] = [i];
|
|
1084
|
+
}
|
|
1085
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1086
|
+
d[0][j] = j;
|
|
1087
|
+
}
|
|
1088
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1089
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1090
|
+
let cost = 1;
|
|
1091
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1092
|
+
cost = 0;
|
|
1093
|
+
} else {
|
|
1094
|
+
cost = 1;
|
|
1095
|
+
}
|
|
1096
|
+
d[i][j] = Math.min(
|
|
1097
|
+
d[i - 1][j] + 1,
|
|
1098
|
+
// deletion
|
|
1099
|
+
d[i][j - 1] + 1,
|
|
1100
|
+
// insertion
|
|
1101
|
+
d[i - 1][j - 1] + cost
|
|
1102
|
+
// substitution
|
|
1103
|
+
);
|
|
1104
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1105
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
return d[a.length][b.length];
|
|
1110
|
+
}
|
|
1111
|
+
function suggestSimilar(word, candidates) {
|
|
1112
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1113
|
+
candidates = Array.from(new Set(candidates));
|
|
1114
|
+
const searchingOptions = word.startsWith("--");
|
|
1115
|
+
if (searchingOptions) {
|
|
1116
|
+
word = word.slice(2);
|
|
1117
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1118
|
+
}
|
|
1119
|
+
let similar = [];
|
|
1120
|
+
let bestDistance = maxDistance;
|
|
1121
|
+
const minSimilarity = 0.4;
|
|
1122
|
+
candidates.forEach((candidate) => {
|
|
1123
|
+
if (candidate.length <= 1) return;
|
|
1124
|
+
const distance = editDistance(word, candidate);
|
|
1125
|
+
const length = Math.max(word.length, candidate.length);
|
|
1126
|
+
const similarity = (length - distance) / length;
|
|
1127
|
+
if (similarity > minSimilarity) {
|
|
1128
|
+
if (distance < bestDistance) {
|
|
1129
|
+
bestDistance = distance;
|
|
1130
|
+
similar = [candidate];
|
|
1131
|
+
} else if (distance === bestDistance) {
|
|
1132
|
+
similar.push(candidate);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
});
|
|
1136
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1137
|
+
if (searchingOptions) {
|
|
1138
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1139
|
+
}
|
|
1140
|
+
if (similar.length > 1) {
|
|
1141
|
+
return `
|
|
1142
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1143
|
+
}
|
|
1144
|
+
if (similar.length === 1) {
|
|
1145
|
+
return `
|
|
1146
|
+
(Did you mean ${similar[0]}?)`;
|
|
1147
|
+
}
|
|
1148
|
+
return "";
|
|
1149
|
+
}
|
|
1150
|
+
exports.suggestSimilar = suggestSimilar;
|
|
1151
|
+
}
|
|
1152
|
+
});
|
|
1153
|
+
|
|
1154
|
+
// node_modules/commander/lib/command.js
|
|
1155
|
+
var require_command = __commonJS({
|
|
1156
|
+
"node_modules/commander/lib/command.js"(exports) {
|
|
1157
|
+
var EventEmitter = __require("node:events").EventEmitter;
|
|
1158
|
+
var childProcess = __require("node:child_process");
|
|
1159
|
+
var path = __require("node:path");
|
|
1160
|
+
var fs = __require("node:fs");
|
|
1161
|
+
var process2 = __require("node:process");
|
|
1162
|
+
var { Argument: Argument2, humanReadableArgName } = require_argument();
|
|
1163
|
+
var { CommanderError: CommanderError2 } = require_error();
|
|
1164
|
+
var { Help: Help2, stripColor } = require_help();
|
|
1165
|
+
var { Option: Option2, DualOptions } = require_option();
|
|
1166
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
1167
|
+
var Command2 = class _Command extends EventEmitter {
|
|
1168
|
+
/**
|
|
1169
|
+
* Initialize a new `Command`.
|
|
1170
|
+
*
|
|
1171
|
+
* @param {string} [name]
|
|
1172
|
+
*/
|
|
1173
|
+
constructor(name) {
|
|
1174
|
+
super();
|
|
1175
|
+
this.commands = [];
|
|
1176
|
+
this.options = [];
|
|
1177
|
+
this.parent = null;
|
|
1178
|
+
this._allowUnknownOption = false;
|
|
1179
|
+
this._allowExcessArguments = false;
|
|
1180
|
+
this.registeredArguments = [];
|
|
1181
|
+
this._args = this.registeredArguments;
|
|
1182
|
+
this.args = [];
|
|
1183
|
+
this.rawArgs = [];
|
|
1184
|
+
this.processedArgs = [];
|
|
1185
|
+
this._scriptPath = null;
|
|
1186
|
+
this._name = name || "";
|
|
1187
|
+
this._optionValues = {};
|
|
1188
|
+
this._optionValueSources = {};
|
|
1189
|
+
this._storeOptionsAsProperties = false;
|
|
1190
|
+
this._actionHandler = null;
|
|
1191
|
+
this._executableHandler = false;
|
|
1192
|
+
this._executableFile = null;
|
|
1193
|
+
this._executableDir = null;
|
|
1194
|
+
this._defaultCommandName = null;
|
|
1195
|
+
this._exitCallback = null;
|
|
1196
|
+
this._aliases = [];
|
|
1197
|
+
this._combineFlagAndOptionalValue = true;
|
|
1198
|
+
this._description = "";
|
|
1199
|
+
this._summary = "";
|
|
1200
|
+
this._argsDescription = void 0;
|
|
1201
|
+
this._enablePositionalOptions = false;
|
|
1202
|
+
this._passThroughOptions = false;
|
|
1203
|
+
this._lifeCycleHooks = {};
|
|
1204
|
+
this._showHelpAfterError = false;
|
|
1205
|
+
this._showSuggestionAfterError = true;
|
|
1206
|
+
this._savedState = null;
|
|
1207
|
+
this._outputConfiguration = {
|
|
1208
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1209
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1210
|
+
outputError: (str, write) => write(str),
|
|
1211
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1212
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1213
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1214
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1215
|
+
stripColor: (str) => stripColor(str)
|
|
1216
|
+
};
|
|
1217
|
+
this._hidden = false;
|
|
1218
|
+
this._helpOption = void 0;
|
|
1219
|
+
this._addImplicitHelpCommand = void 0;
|
|
1220
|
+
this._helpCommand = void 0;
|
|
1221
|
+
this._helpConfiguration = {};
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1225
|
+
*
|
|
1226
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1227
|
+
*
|
|
1228
|
+
* @param {Command} sourceCommand
|
|
1229
|
+
* @return {Command} `this` command for chaining
|
|
1230
|
+
*/
|
|
1231
|
+
copyInheritedSettings(sourceCommand) {
|
|
1232
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1233
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1234
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1235
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1236
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1237
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1238
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1239
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1240
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1241
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1242
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1243
|
+
return this;
|
|
1244
|
+
}
|
|
1245
|
+
/**
|
|
1246
|
+
* @returns {Command[]}
|
|
1247
|
+
* @private
|
|
1248
|
+
*/
|
|
1249
|
+
_getCommandAndAncestors() {
|
|
1250
|
+
const result = [];
|
|
1251
|
+
for (let command = this; command; command = command.parent) {
|
|
1252
|
+
result.push(command);
|
|
1253
|
+
}
|
|
1254
|
+
return result;
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Define a command.
|
|
1258
|
+
*
|
|
1259
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1260
|
+
*
|
|
1261
|
+
* @example
|
|
1262
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1263
|
+
* program
|
|
1264
|
+
* .command('clone <source> [destination]')
|
|
1265
|
+
* .description('clone a repository into a newly created directory')
|
|
1266
|
+
* .action((source, destination) => {
|
|
1267
|
+
* console.log('clone command called');
|
|
1268
|
+
* });
|
|
1269
|
+
*
|
|
1270
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1271
|
+
* program
|
|
1272
|
+
* .command('start <service>', 'start named service')
|
|
1273
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1274
|
+
*
|
|
1275
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1276
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1277
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1278
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1279
|
+
*/
|
|
1280
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1281
|
+
let desc = actionOptsOrExecDesc;
|
|
1282
|
+
let opts = execOpts;
|
|
1283
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1284
|
+
opts = desc;
|
|
1285
|
+
desc = null;
|
|
1286
|
+
}
|
|
1287
|
+
opts = opts || {};
|
|
1288
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1289
|
+
const cmd = this.createCommand(name);
|
|
1290
|
+
if (desc) {
|
|
1291
|
+
cmd.description(desc);
|
|
1292
|
+
cmd._executableHandler = true;
|
|
1293
|
+
}
|
|
1294
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1295
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1296
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1297
|
+
if (args) cmd.arguments(args);
|
|
1298
|
+
this._registerCommand(cmd);
|
|
1299
|
+
cmd.parent = this;
|
|
1300
|
+
cmd.copyInheritedSettings(this);
|
|
1301
|
+
if (desc) return this;
|
|
1302
|
+
return cmd;
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Factory routine to create a new unattached command.
|
|
1306
|
+
*
|
|
1307
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1308
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1309
|
+
*
|
|
1310
|
+
* @param {string} [name]
|
|
1311
|
+
* @return {Command} new command
|
|
1312
|
+
*/
|
|
1313
|
+
createCommand(name) {
|
|
1314
|
+
return new _Command(name);
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1318
|
+
* or by overriding Help properties using configureHelp().
|
|
1319
|
+
*
|
|
1320
|
+
* @return {Help}
|
|
1321
|
+
*/
|
|
1322
|
+
createHelp() {
|
|
1323
|
+
return Object.assign(new Help2(), this.configureHelp());
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1327
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1328
|
+
*
|
|
1329
|
+
* @param {object} [configuration] - configuration options
|
|
1330
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1331
|
+
*/
|
|
1332
|
+
configureHelp(configuration) {
|
|
1333
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1334
|
+
this._helpConfiguration = configuration;
|
|
1335
|
+
return this;
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1339
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1340
|
+
*
|
|
1341
|
+
* The configuration properties are all functions:
|
|
1342
|
+
*
|
|
1343
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1344
|
+
* writeOut(str)
|
|
1345
|
+
* writeErr(str)
|
|
1346
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1347
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1348
|
+
* // specify width for wrapping help
|
|
1349
|
+
* getOutHelpWidth()
|
|
1350
|
+
* getErrHelpWidth()
|
|
1351
|
+
* // color support, currently only used with Help
|
|
1352
|
+
* getOutHasColors()
|
|
1353
|
+
* getErrHasColors()
|
|
1354
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1355
|
+
*
|
|
1356
|
+
* @param {object} [configuration] - configuration options
|
|
1357
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1358
|
+
*/
|
|
1359
|
+
configureOutput(configuration) {
|
|
1360
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1361
|
+
Object.assign(this._outputConfiguration, configuration);
|
|
1362
|
+
return this;
|
|
1363
|
+
}
|
|
1364
|
+
/**
|
|
1365
|
+
* Display the help or a custom message after an error occurs.
|
|
1366
|
+
*
|
|
1367
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1368
|
+
* @return {Command} `this` command for chaining
|
|
1369
|
+
*/
|
|
1370
|
+
showHelpAfterError(displayHelp = true) {
|
|
1371
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1372
|
+
this._showHelpAfterError = displayHelp;
|
|
1373
|
+
return this;
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1377
|
+
*
|
|
1378
|
+
* @param {boolean} [displaySuggestion]
|
|
1379
|
+
* @return {Command} `this` command for chaining
|
|
1380
|
+
*/
|
|
1381
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1382
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1383
|
+
return this;
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* Add a prepared subcommand.
|
|
1387
|
+
*
|
|
1388
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1389
|
+
*
|
|
1390
|
+
* @param {Command} cmd - new subcommand
|
|
1391
|
+
* @param {object} [opts] - configuration options
|
|
1392
|
+
* @return {Command} `this` command for chaining
|
|
1393
|
+
*/
|
|
1394
|
+
addCommand(cmd, opts) {
|
|
1395
|
+
if (!cmd._name) {
|
|
1396
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1397
|
+
- specify the name in Command constructor or using .name()`);
|
|
1398
|
+
}
|
|
1399
|
+
opts = opts || {};
|
|
1400
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1401
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1402
|
+
this._registerCommand(cmd);
|
|
1403
|
+
cmd.parent = this;
|
|
1404
|
+
cmd._checkForBrokenPassThrough();
|
|
1405
|
+
return this;
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* Factory routine to create a new unattached argument.
|
|
1409
|
+
*
|
|
1410
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1411
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1412
|
+
*
|
|
1413
|
+
* @param {string} name
|
|
1414
|
+
* @param {string} [description]
|
|
1415
|
+
* @return {Argument} new argument
|
|
1416
|
+
*/
|
|
1417
|
+
createArgument(name, description) {
|
|
1418
|
+
return new Argument2(name, description);
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Define argument syntax for command.
|
|
1422
|
+
*
|
|
1423
|
+
* The default is that the argument is required, and you can explicitly
|
|
1424
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1425
|
+
*
|
|
1426
|
+
* @example
|
|
1427
|
+
* program.argument('<input-file>');
|
|
1428
|
+
* program.argument('[output-file]');
|
|
1429
|
+
*
|
|
1430
|
+
* @param {string} name
|
|
1431
|
+
* @param {string} [description]
|
|
1432
|
+
* @param {(Function|*)} [fn] - custom argument processing function
|
|
1433
|
+
* @param {*} [defaultValue]
|
|
1434
|
+
* @return {Command} `this` command for chaining
|
|
1435
|
+
*/
|
|
1436
|
+
argument(name, description, fn, defaultValue) {
|
|
1437
|
+
const argument = this.createArgument(name, description);
|
|
1438
|
+
if (typeof fn === "function") {
|
|
1439
|
+
argument.default(defaultValue).argParser(fn);
|
|
1440
|
+
} else {
|
|
1441
|
+
argument.default(fn);
|
|
1442
|
+
}
|
|
1443
|
+
this.addArgument(argument);
|
|
1444
|
+
return this;
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1448
|
+
*
|
|
1449
|
+
* See also .argument().
|
|
1450
|
+
*
|
|
1451
|
+
* @example
|
|
1452
|
+
* program.arguments('<cmd> [env]');
|
|
1453
|
+
*
|
|
1454
|
+
* @param {string} names
|
|
1455
|
+
* @return {Command} `this` command for chaining
|
|
1456
|
+
*/
|
|
1457
|
+
arguments(names) {
|
|
1458
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1459
|
+
this.argument(detail);
|
|
1460
|
+
});
|
|
1461
|
+
return this;
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1465
|
+
*
|
|
1466
|
+
* @param {Argument} argument
|
|
1467
|
+
* @return {Command} `this` command for chaining
|
|
1468
|
+
*/
|
|
1469
|
+
addArgument(argument) {
|
|
1470
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1471
|
+
if (previousArgument && previousArgument.variadic) {
|
|
1472
|
+
throw new Error(
|
|
1473
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1474
|
+
);
|
|
1475
|
+
}
|
|
1476
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1477
|
+
throw new Error(
|
|
1478
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1479
|
+
);
|
|
1480
|
+
}
|
|
1481
|
+
this.registeredArguments.push(argument);
|
|
1482
|
+
return this;
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1486
|
+
*
|
|
1487
|
+
* @example
|
|
1488
|
+
* program.helpCommand('help [cmd]');
|
|
1489
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1490
|
+
* program.helpCommand(false); // suppress default help command
|
|
1491
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1492
|
+
*
|
|
1493
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1494
|
+
* @param {string} [description] - custom description
|
|
1495
|
+
* @return {Command} `this` command for chaining
|
|
1496
|
+
*/
|
|
1497
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1498
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1499
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1500
|
+
return this;
|
|
1501
|
+
}
|
|
1502
|
+
enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1503
|
+
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1504
|
+
const helpDescription = description ?? "display help for command";
|
|
1505
|
+
const helpCommand = this.createCommand(helpName);
|
|
1506
|
+
helpCommand.helpOption(false);
|
|
1507
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1508
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1509
|
+
this._addImplicitHelpCommand = true;
|
|
1510
|
+
this._helpCommand = helpCommand;
|
|
1511
|
+
return this;
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* Add prepared custom help command.
|
|
1515
|
+
*
|
|
1516
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1517
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1518
|
+
* @return {Command} `this` command for chaining
|
|
1519
|
+
*/
|
|
1520
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1521
|
+
if (typeof helpCommand !== "object") {
|
|
1522
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1523
|
+
return this;
|
|
1524
|
+
}
|
|
1525
|
+
this._addImplicitHelpCommand = true;
|
|
1526
|
+
this._helpCommand = helpCommand;
|
|
1527
|
+
return this;
|
|
1528
|
+
}
|
|
1529
|
+
/**
|
|
1530
|
+
* Lazy create help command.
|
|
1531
|
+
*
|
|
1532
|
+
* @return {(Command|null)}
|
|
1533
|
+
* @package
|
|
1534
|
+
*/
|
|
1535
|
+
_getHelpCommand() {
|
|
1536
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1537
|
+
if (hasImplicitHelpCommand) {
|
|
1538
|
+
if (this._helpCommand === void 0) {
|
|
1539
|
+
this.helpCommand(void 0, void 0);
|
|
1540
|
+
}
|
|
1541
|
+
return this._helpCommand;
|
|
1542
|
+
}
|
|
1543
|
+
return null;
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* Add hook for life cycle event.
|
|
1547
|
+
*
|
|
1548
|
+
* @param {string} event
|
|
1549
|
+
* @param {Function} listener
|
|
1550
|
+
* @return {Command} `this` command for chaining
|
|
1551
|
+
*/
|
|
1552
|
+
hook(event, listener) {
|
|
1553
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1554
|
+
if (!allowedValues.includes(event)) {
|
|
1555
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1556
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1557
|
+
}
|
|
1558
|
+
if (this._lifeCycleHooks[event]) {
|
|
1559
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1560
|
+
} else {
|
|
1561
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1562
|
+
}
|
|
1563
|
+
return this;
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1567
|
+
*
|
|
1568
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1569
|
+
* @return {Command} `this` command for chaining
|
|
1570
|
+
*/
|
|
1571
|
+
exitOverride(fn) {
|
|
1572
|
+
if (fn) {
|
|
1573
|
+
this._exitCallback = fn;
|
|
1574
|
+
} else {
|
|
1575
|
+
this._exitCallback = (err) => {
|
|
1576
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1577
|
+
throw err;
|
|
1578
|
+
} else {
|
|
1579
|
+
}
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
return this;
|
|
1583
|
+
}
|
|
1584
|
+
/**
|
|
1585
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1586
|
+
*
|
|
1587
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1588
|
+
* @param {string} code an id string representing the error
|
|
1589
|
+
* @param {string} message human-readable description of the error
|
|
1590
|
+
* @return never
|
|
1591
|
+
* @private
|
|
1592
|
+
*/
|
|
1593
|
+
_exit(exitCode, code, message) {
|
|
1594
|
+
if (this._exitCallback) {
|
|
1595
|
+
this._exitCallback(new CommanderError2(exitCode, code, message));
|
|
1596
|
+
}
|
|
1597
|
+
process2.exit(exitCode);
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* Register callback `fn` for the command.
|
|
1601
|
+
*
|
|
1602
|
+
* @example
|
|
1603
|
+
* program
|
|
1604
|
+
* .command('serve')
|
|
1605
|
+
* .description('start service')
|
|
1606
|
+
* .action(function() {
|
|
1607
|
+
* // do work here
|
|
1608
|
+
* });
|
|
1609
|
+
*
|
|
1610
|
+
* @param {Function} fn
|
|
1611
|
+
* @return {Command} `this` command for chaining
|
|
1612
|
+
*/
|
|
1613
|
+
action(fn) {
|
|
1614
|
+
const listener = (args) => {
|
|
1615
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1616
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1617
|
+
if (this._storeOptionsAsProperties) {
|
|
1618
|
+
actionArgs[expectedArgsCount] = this;
|
|
1619
|
+
} else {
|
|
1620
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1621
|
+
}
|
|
1622
|
+
actionArgs.push(this);
|
|
1623
|
+
return fn.apply(this, actionArgs);
|
|
1624
|
+
};
|
|
1625
|
+
this._actionHandler = listener;
|
|
1626
|
+
return this;
|
|
1627
|
+
}
|
|
1628
|
+
/**
|
|
1629
|
+
* Factory routine to create a new unattached option.
|
|
1630
|
+
*
|
|
1631
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1632
|
+
* create the option. You can override createOption to return a custom option.
|
|
1633
|
+
*
|
|
1634
|
+
* @param {string} flags
|
|
1635
|
+
* @param {string} [description]
|
|
1636
|
+
* @return {Option} new option
|
|
1637
|
+
*/
|
|
1638
|
+
createOption(flags, description) {
|
|
1639
|
+
return new Option2(flags, description);
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1643
|
+
*
|
|
1644
|
+
* @param {(Option | Argument)} target
|
|
1645
|
+
* @param {string} value
|
|
1646
|
+
* @param {*} previous
|
|
1647
|
+
* @param {string} invalidArgumentMessage
|
|
1648
|
+
* @private
|
|
1649
|
+
*/
|
|
1650
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1651
|
+
try {
|
|
1652
|
+
return target.parseArg(value, previous);
|
|
1653
|
+
} catch (err) {
|
|
1654
|
+
if (err.code === "commander.invalidArgument") {
|
|
1655
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1656
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1657
|
+
}
|
|
1658
|
+
throw err;
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Check for option flag conflicts.
|
|
1663
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1664
|
+
*
|
|
1665
|
+
* @param {Option} option
|
|
1666
|
+
* @private
|
|
1667
|
+
*/
|
|
1668
|
+
_registerOption(option) {
|
|
1669
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1670
|
+
if (matchingOption) {
|
|
1671
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1672
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1673
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1674
|
+
}
|
|
1675
|
+
this.options.push(option);
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1679
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1680
|
+
*
|
|
1681
|
+
* @param {Command} command
|
|
1682
|
+
* @private
|
|
1683
|
+
*/
|
|
1684
|
+
_registerCommand(command) {
|
|
1685
|
+
const knownBy = (cmd) => {
|
|
1686
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1687
|
+
};
|
|
1688
|
+
const alreadyUsed = knownBy(command).find(
|
|
1689
|
+
(name) => this._findCommand(name)
|
|
1690
|
+
);
|
|
1691
|
+
if (alreadyUsed) {
|
|
1692
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1693
|
+
const newCmd = knownBy(command).join("|");
|
|
1694
|
+
throw new Error(
|
|
1695
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1696
|
+
);
|
|
1697
|
+
}
|
|
1698
|
+
this.commands.push(command);
|
|
1699
|
+
}
|
|
1700
|
+
/**
|
|
1701
|
+
* Add an option.
|
|
1702
|
+
*
|
|
1703
|
+
* @param {Option} option
|
|
1704
|
+
* @return {Command} `this` command for chaining
|
|
1705
|
+
*/
|
|
1706
|
+
addOption(option) {
|
|
1707
|
+
this._registerOption(option);
|
|
1708
|
+
const oname = option.name();
|
|
1709
|
+
const name = option.attributeName();
|
|
1710
|
+
if (option.negate) {
|
|
1711
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1712
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1713
|
+
this.setOptionValueWithSource(
|
|
1714
|
+
name,
|
|
1715
|
+
option.defaultValue === void 0 ? true : option.defaultValue,
|
|
1716
|
+
"default"
|
|
1717
|
+
);
|
|
1718
|
+
}
|
|
1719
|
+
} else if (option.defaultValue !== void 0) {
|
|
1720
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1721
|
+
}
|
|
1722
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1723
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1724
|
+
val = option.presetArg;
|
|
1725
|
+
}
|
|
1726
|
+
const oldValue = this.getOptionValue(name);
|
|
1727
|
+
if (val !== null && option.parseArg) {
|
|
1728
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1729
|
+
} else if (val !== null && option.variadic) {
|
|
1730
|
+
val = option._concatValue(val, oldValue);
|
|
1731
|
+
}
|
|
1732
|
+
if (val == null) {
|
|
1733
|
+
if (option.negate) {
|
|
1734
|
+
val = false;
|
|
1735
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1736
|
+
val = true;
|
|
1737
|
+
} else {
|
|
1738
|
+
val = "";
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1742
|
+
};
|
|
1743
|
+
this.on("option:" + oname, (val) => {
|
|
1744
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1745
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1746
|
+
});
|
|
1747
|
+
if (option.envVar) {
|
|
1748
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1749
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1750
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
return this;
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1757
|
+
*
|
|
1758
|
+
* @return {Command} `this` command for chaining
|
|
1759
|
+
* @private
|
|
1760
|
+
*/
|
|
1761
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1762
|
+
if (typeof flags === "object" && flags instanceof Option2) {
|
|
1763
|
+
throw new Error(
|
|
1764
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1765
|
+
);
|
|
1766
|
+
}
|
|
1767
|
+
const option = this.createOption(flags, description);
|
|
1768
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1769
|
+
if (typeof fn === "function") {
|
|
1770
|
+
option.default(defaultValue).argParser(fn);
|
|
1771
|
+
} else if (fn instanceof RegExp) {
|
|
1772
|
+
const regex = fn;
|
|
1773
|
+
fn = (val, def) => {
|
|
1774
|
+
const m = regex.exec(val);
|
|
1775
|
+
return m ? m[0] : def;
|
|
1776
|
+
};
|
|
1777
|
+
option.default(defaultValue).argParser(fn);
|
|
1778
|
+
} else {
|
|
1779
|
+
option.default(fn);
|
|
1780
|
+
}
|
|
1781
|
+
return this.addOption(option);
|
|
1782
|
+
}
|
|
1783
|
+
/**
|
|
1784
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1785
|
+
*
|
|
1786
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1787
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1788
|
+
*
|
|
1789
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1790
|
+
*
|
|
1791
|
+
* @example
|
|
1792
|
+
* program
|
|
1793
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1794
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1795
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1796
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1797
|
+
*
|
|
1798
|
+
* @param {string} flags
|
|
1799
|
+
* @param {string} [description]
|
|
1800
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1801
|
+
* @param {*} [defaultValue]
|
|
1802
|
+
* @return {Command} `this` command for chaining
|
|
1803
|
+
*/
|
|
1804
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1805
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1806
|
+
}
|
|
1807
|
+
/**
|
|
1808
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1809
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1810
|
+
*
|
|
1811
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1812
|
+
*
|
|
1813
|
+
* @param {string} flags
|
|
1814
|
+
* @param {string} [description]
|
|
1815
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1816
|
+
* @param {*} [defaultValue]
|
|
1817
|
+
* @return {Command} `this` command for chaining
|
|
1818
|
+
*/
|
|
1819
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1820
|
+
return this._optionEx(
|
|
1821
|
+
{ mandatory: true },
|
|
1822
|
+
flags,
|
|
1823
|
+
description,
|
|
1824
|
+
parseArg,
|
|
1825
|
+
defaultValue
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
1829
|
+
* Alter parsing of short flags with optional values.
|
|
1830
|
+
*
|
|
1831
|
+
* @example
|
|
1832
|
+
* // for `.option('-f,--flag [value]'):
|
|
1833
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1834
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1835
|
+
*
|
|
1836
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1837
|
+
* @return {Command} `this` command for chaining
|
|
1838
|
+
*/
|
|
1839
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1840
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1841
|
+
return this;
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* Allow unknown options on the command line.
|
|
1845
|
+
*
|
|
1846
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1847
|
+
* @return {Command} `this` command for chaining
|
|
1848
|
+
*/
|
|
1849
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1850
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1851
|
+
return this;
|
|
1852
|
+
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1855
|
+
*
|
|
1856
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1857
|
+
* @return {Command} `this` command for chaining
|
|
1858
|
+
*/
|
|
1859
|
+
allowExcessArguments(allowExcess = true) {
|
|
1860
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1861
|
+
return this;
|
|
1862
|
+
}
|
|
1863
|
+
/**
|
|
1864
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1865
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1866
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1867
|
+
*
|
|
1868
|
+
* @param {boolean} [positional]
|
|
1869
|
+
* @return {Command} `this` command for chaining
|
|
1870
|
+
*/
|
|
1871
|
+
enablePositionalOptions(positional = true) {
|
|
1872
|
+
this._enablePositionalOptions = !!positional;
|
|
1873
|
+
return this;
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1877
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1878
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1879
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1880
|
+
*
|
|
1881
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1882
|
+
* @return {Command} `this` command for chaining
|
|
1883
|
+
*/
|
|
1884
|
+
passThroughOptions(passThrough = true) {
|
|
1885
|
+
this._passThroughOptions = !!passThrough;
|
|
1886
|
+
this._checkForBrokenPassThrough();
|
|
1887
|
+
return this;
|
|
1888
|
+
}
|
|
1889
|
+
/**
|
|
1890
|
+
* @private
|
|
1891
|
+
*/
|
|
1892
|
+
_checkForBrokenPassThrough() {
|
|
1893
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1894
|
+
throw new Error(
|
|
1895
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1896
|
+
);
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
/**
|
|
1900
|
+
* Whether to store option values as properties on command object,
|
|
1901
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1902
|
+
*
|
|
1903
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1904
|
+
* @return {Command} `this` command for chaining
|
|
1905
|
+
*/
|
|
1906
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1907
|
+
if (this.options.length) {
|
|
1908
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1909
|
+
}
|
|
1910
|
+
if (Object.keys(this._optionValues).length) {
|
|
1911
|
+
throw new Error(
|
|
1912
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1913
|
+
);
|
|
1914
|
+
}
|
|
1915
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1916
|
+
return this;
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* Retrieve option value.
|
|
1920
|
+
*
|
|
1921
|
+
* @param {string} key
|
|
1922
|
+
* @return {object} value
|
|
1923
|
+
*/
|
|
1924
|
+
getOptionValue(key) {
|
|
1925
|
+
if (this._storeOptionsAsProperties) {
|
|
1926
|
+
return this[key];
|
|
1927
|
+
}
|
|
1928
|
+
return this._optionValues[key];
|
|
1929
|
+
}
|
|
1930
|
+
/**
|
|
1931
|
+
* Store option value.
|
|
1932
|
+
*
|
|
1933
|
+
* @param {string} key
|
|
1934
|
+
* @param {object} value
|
|
1935
|
+
* @return {Command} `this` command for chaining
|
|
1936
|
+
*/
|
|
1937
|
+
setOptionValue(key, value) {
|
|
1938
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1939
|
+
}
|
|
1940
|
+
/**
|
|
1941
|
+
* Store option value and where the value came from.
|
|
1942
|
+
*
|
|
1943
|
+
* @param {string} key
|
|
1944
|
+
* @param {object} value
|
|
1945
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1946
|
+
* @return {Command} `this` command for chaining
|
|
1947
|
+
*/
|
|
1948
|
+
setOptionValueWithSource(key, value, source) {
|
|
1949
|
+
if (this._storeOptionsAsProperties) {
|
|
1950
|
+
this[key] = value;
|
|
1951
|
+
} else {
|
|
1952
|
+
this._optionValues[key] = value;
|
|
1953
|
+
}
|
|
1954
|
+
this._optionValueSources[key] = source;
|
|
1955
|
+
return this;
|
|
1956
|
+
}
|
|
1957
|
+
/**
|
|
1958
|
+
* Get source of option value.
|
|
1959
|
+
* Expected values are default | config | env | cli | implied
|
|
1960
|
+
*
|
|
1961
|
+
* @param {string} key
|
|
1962
|
+
* @return {string}
|
|
1963
|
+
*/
|
|
1964
|
+
getOptionValueSource(key) {
|
|
1965
|
+
return this._optionValueSources[key];
|
|
1966
|
+
}
|
|
1967
|
+
/**
|
|
1968
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1969
|
+
* Expected values are default | config | env | cli | implied
|
|
1970
|
+
*
|
|
1971
|
+
* @param {string} key
|
|
1972
|
+
* @return {string}
|
|
1973
|
+
*/
|
|
1974
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1975
|
+
let source;
|
|
1976
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1977
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
1978
|
+
source = cmd.getOptionValueSource(key);
|
|
1979
|
+
}
|
|
1980
|
+
});
|
|
1981
|
+
return source;
|
|
1982
|
+
}
|
|
1983
|
+
/**
|
|
1984
|
+
* Get user arguments from implied or explicit arguments.
|
|
1985
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1986
|
+
*
|
|
1987
|
+
* @private
|
|
1988
|
+
*/
|
|
1989
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1990
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
1991
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1992
|
+
}
|
|
1993
|
+
parseOptions = parseOptions || {};
|
|
1994
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1995
|
+
if (process2.versions?.electron) {
|
|
1996
|
+
parseOptions.from = "electron";
|
|
1997
|
+
}
|
|
1998
|
+
const execArgv = process2.execArgv ?? [];
|
|
1999
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
2000
|
+
parseOptions.from = "eval";
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
if (argv === void 0) {
|
|
2004
|
+
argv = process2.argv;
|
|
2005
|
+
}
|
|
2006
|
+
this.rawArgs = argv.slice();
|
|
2007
|
+
let userArgs;
|
|
2008
|
+
switch (parseOptions.from) {
|
|
2009
|
+
case void 0:
|
|
2010
|
+
case "node":
|
|
2011
|
+
this._scriptPath = argv[1];
|
|
2012
|
+
userArgs = argv.slice(2);
|
|
2013
|
+
break;
|
|
2014
|
+
case "electron":
|
|
2015
|
+
if (process2.defaultApp) {
|
|
2016
|
+
this._scriptPath = argv[1];
|
|
2017
|
+
userArgs = argv.slice(2);
|
|
2018
|
+
} else {
|
|
2019
|
+
userArgs = argv.slice(1);
|
|
2020
|
+
}
|
|
2021
|
+
break;
|
|
2022
|
+
case "user":
|
|
2023
|
+
userArgs = argv.slice(0);
|
|
2024
|
+
break;
|
|
2025
|
+
case "eval":
|
|
2026
|
+
userArgs = argv.slice(1);
|
|
2027
|
+
break;
|
|
2028
|
+
default:
|
|
2029
|
+
throw new Error(
|
|
2030
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2031
|
+
);
|
|
2032
|
+
}
|
|
2033
|
+
if (!this._name && this._scriptPath)
|
|
2034
|
+
this.nameFromFilename(this._scriptPath);
|
|
2035
|
+
this._name = this._name || "program";
|
|
2036
|
+
return userArgs;
|
|
2037
|
+
}
|
|
2038
|
+
/**
|
|
2039
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2040
|
+
*
|
|
2041
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2042
|
+
*
|
|
2043
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2044
|
+
*
|
|
2045
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2046
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2047
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2048
|
+
* - `'user'`: just user arguments
|
|
2049
|
+
*
|
|
2050
|
+
* @example
|
|
2051
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2052
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2053
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2054
|
+
*
|
|
2055
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2056
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2057
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2058
|
+
* @return {Command} `this` command for chaining
|
|
2059
|
+
*/
|
|
2060
|
+
parse(argv, parseOptions) {
|
|
2061
|
+
this._prepareForParse();
|
|
2062
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2063
|
+
this._parseCommand([], userArgs);
|
|
2064
|
+
return this;
|
|
2065
|
+
}
|
|
2066
|
+
/**
|
|
2067
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2068
|
+
*
|
|
2069
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2070
|
+
*
|
|
2071
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2072
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2073
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2074
|
+
* - `'user'`: just user arguments
|
|
2075
|
+
*
|
|
2076
|
+
* @example
|
|
2077
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2078
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2079
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2080
|
+
*
|
|
2081
|
+
* @param {string[]} [argv]
|
|
2082
|
+
* @param {object} [parseOptions]
|
|
2083
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2084
|
+
* @return {Promise}
|
|
2085
|
+
*/
|
|
2086
|
+
async parseAsync(argv, parseOptions) {
|
|
2087
|
+
this._prepareForParse();
|
|
2088
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2089
|
+
await this._parseCommand([], userArgs);
|
|
2090
|
+
return this;
|
|
2091
|
+
}
|
|
2092
|
+
_prepareForParse() {
|
|
2093
|
+
if (this._savedState === null) {
|
|
2094
|
+
this.saveStateBeforeParse();
|
|
2095
|
+
} else {
|
|
2096
|
+
this.restoreStateBeforeParse();
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
/**
|
|
2100
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2101
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2102
|
+
*
|
|
2103
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2104
|
+
*/
|
|
2105
|
+
saveStateBeforeParse() {
|
|
2106
|
+
this._savedState = {
|
|
2107
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2108
|
+
_name: this._name,
|
|
2109
|
+
// option values before parse have default values (including false for negated options)
|
|
2110
|
+
// shallow clones
|
|
2111
|
+
_optionValues: { ...this._optionValues },
|
|
2112
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2113
|
+
};
|
|
2114
|
+
}
|
|
2115
|
+
/**
|
|
2116
|
+
* Restore state before parse for calls after the first.
|
|
2117
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2118
|
+
*
|
|
2119
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2120
|
+
*/
|
|
2121
|
+
restoreStateBeforeParse() {
|
|
2122
|
+
if (this._storeOptionsAsProperties)
|
|
2123
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2124
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2125
|
+
this._name = this._savedState._name;
|
|
2126
|
+
this._scriptPath = null;
|
|
2127
|
+
this.rawArgs = [];
|
|
2128
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2129
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2130
|
+
this.args = [];
|
|
2131
|
+
this.processedArgs = [];
|
|
2132
|
+
}
|
|
2133
|
+
/**
|
|
2134
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2135
|
+
*
|
|
2136
|
+
* @param {string} executableFile
|
|
2137
|
+
* @param {string} executableDir
|
|
2138
|
+
* @param {string} subcommandName
|
|
2139
|
+
*/
|
|
2140
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2141
|
+
if (fs.existsSync(executableFile)) return;
|
|
2142
|
+
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";
|
|
2143
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2144
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2145
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2146
|
+
- ${executableDirMessage}`;
|
|
2147
|
+
throw new Error(executableMissing);
|
|
2148
|
+
}
|
|
2149
|
+
/**
|
|
2150
|
+
* Execute a sub-command executable.
|
|
2151
|
+
*
|
|
2152
|
+
* @private
|
|
2153
|
+
*/
|
|
2154
|
+
_executeSubCommand(subcommand, args) {
|
|
2155
|
+
args = args.slice();
|
|
2156
|
+
let launchWithNode = false;
|
|
2157
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2158
|
+
function findFile(baseDir, baseName) {
|
|
2159
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2160
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2161
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2162
|
+
const foundExt = sourceExt.find(
|
|
2163
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2164
|
+
);
|
|
2165
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2166
|
+
return void 0;
|
|
2167
|
+
}
|
|
2168
|
+
this._checkForMissingMandatoryOptions();
|
|
2169
|
+
this._checkForConflictingOptions();
|
|
2170
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2171
|
+
let executableDir = this._executableDir || "";
|
|
2172
|
+
if (this._scriptPath) {
|
|
2173
|
+
let resolvedScriptPath;
|
|
2174
|
+
try {
|
|
2175
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2176
|
+
} catch {
|
|
2177
|
+
resolvedScriptPath = this._scriptPath;
|
|
2178
|
+
}
|
|
2179
|
+
executableDir = path.resolve(
|
|
2180
|
+
path.dirname(resolvedScriptPath),
|
|
2181
|
+
executableDir
|
|
2182
|
+
);
|
|
2183
|
+
}
|
|
2184
|
+
if (executableDir) {
|
|
2185
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2186
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2187
|
+
const legacyName = path.basename(
|
|
2188
|
+
this._scriptPath,
|
|
2189
|
+
path.extname(this._scriptPath)
|
|
2190
|
+
);
|
|
2191
|
+
if (legacyName !== this._name) {
|
|
2192
|
+
localFile = findFile(
|
|
2193
|
+
executableDir,
|
|
2194
|
+
`${legacyName}-${subcommand._name}`
|
|
2195
|
+
);
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
executableFile = localFile || executableFile;
|
|
2199
|
+
}
|
|
2200
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2201
|
+
let proc;
|
|
2202
|
+
if (process2.platform !== "win32") {
|
|
2203
|
+
if (launchWithNode) {
|
|
2204
|
+
args.unshift(executableFile);
|
|
2205
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2206
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2207
|
+
} else {
|
|
2208
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2209
|
+
}
|
|
2210
|
+
} else {
|
|
2211
|
+
this._checkForMissingExecutable(
|
|
2212
|
+
executableFile,
|
|
2213
|
+
executableDir,
|
|
2214
|
+
subcommand._name
|
|
2215
|
+
);
|
|
2216
|
+
args.unshift(executableFile);
|
|
2217
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2218
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2219
|
+
}
|
|
2220
|
+
if (!proc.killed) {
|
|
2221
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2222
|
+
signals.forEach((signal) => {
|
|
2223
|
+
process2.on(signal, () => {
|
|
2224
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2225
|
+
proc.kill(signal);
|
|
2226
|
+
}
|
|
2227
|
+
});
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
const exitCallback = this._exitCallback;
|
|
2231
|
+
proc.on("close", (code) => {
|
|
2232
|
+
code = code ?? 1;
|
|
2233
|
+
if (!exitCallback) {
|
|
2234
|
+
process2.exit(code);
|
|
2235
|
+
} else {
|
|
2236
|
+
exitCallback(
|
|
2237
|
+
new CommanderError2(
|
|
2238
|
+
code,
|
|
2239
|
+
"commander.executeSubCommandAsync",
|
|
2240
|
+
"(close)"
|
|
2241
|
+
)
|
|
2242
|
+
);
|
|
2243
|
+
}
|
|
2244
|
+
});
|
|
2245
|
+
proc.on("error", (err) => {
|
|
2246
|
+
if (err.code === "ENOENT") {
|
|
2247
|
+
this._checkForMissingExecutable(
|
|
2248
|
+
executableFile,
|
|
2249
|
+
executableDir,
|
|
2250
|
+
subcommand._name
|
|
2251
|
+
);
|
|
2252
|
+
} else if (err.code === "EACCES") {
|
|
2253
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2254
|
+
}
|
|
2255
|
+
if (!exitCallback) {
|
|
2256
|
+
process2.exit(1);
|
|
2257
|
+
} else {
|
|
2258
|
+
const wrappedError = new CommanderError2(
|
|
2259
|
+
1,
|
|
2260
|
+
"commander.executeSubCommandAsync",
|
|
2261
|
+
"(error)"
|
|
2262
|
+
);
|
|
2263
|
+
wrappedError.nestedError = err;
|
|
2264
|
+
exitCallback(wrappedError);
|
|
2265
|
+
}
|
|
2266
|
+
});
|
|
2267
|
+
this.runningCommand = proc;
|
|
2268
|
+
}
|
|
2269
|
+
/**
|
|
2270
|
+
* @private
|
|
2271
|
+
*/
|
|
2272
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2273
|
+
const subCommand = this._findCommand(commandName);
|
|
2274
|
+
if (!subCommand) this.help({ error: true });
|
|
2275
|
+
subCommand._prepareForParse();
|
|
2276
|
+
let promiseChain;
|
|
2277
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2278
|
+
promiseChain,
|
|
2279
|
+
subCommand,
|
|
2280
|
+
"preSubcommand"
|
|
2281
|
+
);
|
|
2282
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2283
|
+
if (subCommand._executableHandler) {
|
|
2284
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2285
|
+
} else {
|
|
2286
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2287
|
+
}
|
|
2288
|
+
});
|
|
2289
|
+
return promiseChain;
|
|
2290
|
+
}
|
|
2291
|
+
/**
|
|
2292
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2293
|
+
* e.g. help foo
|
|
2294
|
+
*
|
|
2295
|
+
* @private
|
|
2296
|
+
*/
|
|
2297
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2298
|
+
if (!subcommandName) {
|
|
2299
|
+
this.help();
|
|
2300
|
+
}
|
|
2301
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2302
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2303
|
+
subCommand.help();
|
|
2304
|
+
}
|
|
2305
|
+
return this._dispatchSubcommand(
|
|
2306
|
+
subcommandName,
|
|
2307
|
+
[],
|
|
2308
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2309
|
+
);
|
|
2310
|
+
}
|
|
2311
|
+
/**
|
|
2312
|
+
* Check this.args against expected this.registeredArguments.
|
|
2313
|
+
*
|
|
2314
|
+
* @private
|
|
2315
|
+
*/
|
|
2316
|
+
_checkNumberOfArguments() {
|
|
2317
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2318
|
+
if (arg.required && this.args[i] == null) {
|
|
2319
|
+
this.missingArgument(arg.name());
|
|
2320
|
+
}
|
|
2321
|
+
});
|
|
2322
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2323
|
+
return;
|
|
2324
|
+
}
|
|
2325
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2326
|
+
this._excessArguments(this.args);
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
/**
|
|
2330
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2331
|
+
*
|
|
2332
|
+
* @private
|
|
2333
|
+
*/
|
|
2334
|
+
_processArguments() {
|
|
2335
|
+
const myParseArg = (argument, value, previous) => {
|
|
2336
|
+
let parsedValue = value;
|
|
2337
|
+
if (value !== null && argument.parseArg) {
|
|
2338
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2339
|
+
parsedValue = this._callParseArg(
|
|
2340
|
+
argument,
|
|
2341
|
+
value,
|
|
2342
|
+
previous,
|
|
2343
|
+
invalidValueMessage
|
|
2344
|
+
);
|
|
2345
|
+
}
|
|
2346
|
+
return parsedValue;
|
|
2347
|
+
};
|
|
2348
|
+
this._checkNumberOfArguments();
|
|
2349
|
+
const processedArgs = [];
|
|
2350
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2351
|
+
let value = declaredArg.defaultValue;
|
|
2352
|
+
if (declaredArg.variadic) {
|
|
2353
|
+
if (index < this.args.length) {
|
|
2354
|
+
value = this.args.slice(index);
|
|
2355
|
+
if (declaredArg.parseArg) {
|
|
2356
|
+
value = value.reduce((processed, v) => {
|
|
2357
|
+
return myParseArg(declaredArg, v, processed);
|
|
2358
|
+
}, declaredArg.defaultValue);
|
|
2359
|
+
}
|
|
2360
|
+
} else if (value === void 0) {
|
|
2361
|
+
value = [];
|
|
2362
|
+
}
|
|
2363
|
+
} else if (index < this.args.length) {
|
|
2364
|
+
value = this.args[index];
|
|
2365
|
+
if (declaredArg.parseArg) {
|
|
2366
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
processedArgs[index] = value;
|
|
2370
|
+
});
|
|
2371
|
+
this.processedArgs = processedArgs;
|
|
2372
|
+
}
|
|
2373
|
+
/**
|
|
2374
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2375
|
+
*
|
|
2376
|
+
* @param {(Promise|undefined)} promise
|
|
2377
|
+
* @param {Function} fn
|
|
2378
|
+
* @return {(Promise|undefined)}
|
|
2379
|
+
* @private
|
|
2380
|
+
*/
|
|
2381
|
+
_chainOrCall(promise, fn) {
|
|
2382
|
+
if (promise && promise.then && typeof promise.then === "function") {
|
|
2383
|
+
return promise.then(() => fn());
|
|
2384
|
+
}
|
|
2385
|
+
return fn();
|
|
2386
|
+
}
|
|
2387
|
+
/**
|
|
2388
|
+
*
|
|
2389
|
+
* @param {(Promise|undefined)} promise
|
|
2390
|
+
* @param {string} event
|
|
2391
|
+
* @return {(Promise|undefined)}
|
|
2392
|
+
* @private
|
|
2393
|
+
*/
|
|
2394
|
+
_chainOrCallHooks(promise, event) {
|
|
2395
|
+
let result = promise;
|
|
2396
|
+
const hooks = [];
|
|
2397
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2398
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2399
|
+
hooks.push({ hookedCommand, callback });
|
|
2400
|
+
});
|
|
2401
|
+
});
|
|
2402
|
+
if (event === "postAction") {
|
|
2403
|
+
hooks.reverse();
|
|
2404
|
+
}
|
|
2405
|
+
hooks.forEach((hookDetail) => {
|
|
2406
|
+
result = this._chainOrCall(result, () => {
|
|
2407
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2408
|
+
});
|
|
2409
|
+
});
|
|
2410
|
+
return result;
|
|
2411
|
+
}
|
|
2412
|
+
/**
|
|
2413
|
+
*
|
|
2414
|
+
* @param {(Promise|undefined)} promise
|
|
2415
|
+
* @param {Command} subCommand
|
|
2416
|
+
* @param {string} event
|
|
2417
|
+
* @return {(Promise|undefined)}
|
|
2418
|
+
* @private
|
|
2419
|
+
*/
|
|
2420
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2421
|
+
let result = promise;
|
|
2422
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2423
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2424
|
+
result = this._chainOrCall(result, () => {
|
|
2425
|
+
return hook(this, subCommand);
|
|
2426
|
+
});
|
|
2427
|
+
});
|
|
2428
|
+
}
|
|
2429
|
+
return result;
|
|
2430
|
+
}
|
|
2431
|
+
/**
|
|
2432
|
+
* Process arguments in context of this command.
|
|
2433
|
+
* Returns action result, in case it is a promise.
|
|
2434
|
+
*
|
|
2435
|
+
* @private
|
|
2436
|
+
*/
|
|
2437
|
+
_parseCommand(operands, unknown) {
|
|
2438
|
+
const parsed = this.parseOptions(unknown);
|
|
2439
|
+
this._parseOptionsEnv();
|
|
2440
|
+
this._parseOptionsImplied();
|
|
2441
|
+
operands = operands.concat(parsed.operands);
|
|
2442
|
+
unknown = parsed.unknown;
|
|
2443
|
+
this.args = operands.concat(unknown);
|
|
2444
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2445
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2446
|
+
}
|
|
2447
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2448
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2449
|
+
}
|
|
2450
|
+
if (this._defaultCommandName) {
|
|
2451
|
+
this._outputHelpIfRequested(unknown);
|
|
2452
|
+
return this._dispatchSubcommand(
|
|
2453
|
+
this._defaultCommandName,
|
|
2454
|
+
operands,
|
|
2455
|
+
unknown
|
|
2456
|
+
);
|
|
2457
|
+
}
|
|
2458
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2459
|
+
this.help({ error: true });
|
|
2460
|
+
}
|
|
2461
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2462
|
+
this._checkForMissingMandatoryOptions();
|
|
2463
|
+
this._checkForConflictingOptions();
|
|
2464
|
+
const checkForUnknownOptions = () => {
|
|
2465
|
+
if (parsed.unknown.length > 0) {
|
|
2466
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2467
|
+
}
|
|
2468
|
+
};
|
|
2469
|
+
const commandEvent = `command:${this.name()}`;
|
|
2470
|
+
if (this._actionHandler) {
|
|
2471
|
+
checkForUnknownOptions();
|
|
2472
|
+
this._processArguments();
|
|
2473
|
+
let promiseChain;
|
|
2474
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2475
|
+
promiseChain = this._chainOrCall(
|
|
2476
|
+
promiseChain,
|
|
2477
|
+
() => this._actionHandler(this.processedArgs)
|
|
2478
|
+
);
|
|
2479
|
+
if (this.parent) {
|
|
2480
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2481
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2482
|
+
});
|
|
2483
|
+
}
|
|
2484
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2485
|
+
return promiseChain;
|
|
2486
|
+
}
|
|
2487
|
+
if (this.parent && this.parent.listenerCount(commandEvent)) {
|
|
2488
|
+
checkForUnknownOptions();
|
|
2489
|
+
this._processArguments();
|
|
2490
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2491
|
+
} else if (operands.length) {
|
|
2492
|
+
if (this._findCommand("*")) {
|
|
2493
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2494
|
+
}
|
|
2495
|
+
if (this.listenerCount("command:*")) {
|
|
2496
|
+
this.emit("command:*", operands, unknown);
|
|
2497
|
+
} else if (this.commands.length) {
|
|
2498
|
+
this.unknownCommand();
|
|
2499
|
+
} else {
|
|
2500
|
+
checkForUnknownOptions();
|
|
2501
|
+
this._processArguments();
|
|
2502
|
+
}
|
|
2503
|
+
} else if (this.commands.length) {
|
|
2504
|
+
checkForUnknownOptions();
|
|
2505
|
+
this.help({ error: true });
|
|
2506
|
+
} else {
|
|
2507
|
+
checkForUnknownOptions();
|
|
2508
|
+
this._processArguments();
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
/**
|
|
2512
|
+
* Find matching command.
|
|
2513
|
+
*
|
|
2514
|
+
* @private
|
|
2515
|
+
* @return {Command | undefined}
|
|
2516
|
+
*/
|
|
2517
|
+
_findCommand(name) {
|
|
2518
|
+
if (!name) return void 0;
|
|
2519
|
+
return this.commands.find(
|
|
2520
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2521
|
+
);
|
|
2522
|
+
}
|
|
2523
|
+
/**
|
|
2524
|
+
* Return an option matching `arg` if any.
|
|
2525
|
+
*
|
|
2526
|
+
* @param {string} arg
|
|
2527
|
+
* @return {Option}
|
|
2528
|
+
* @package
|
|
2529
|
+
*/
|
|
2530
|
+
_findOption(arg) {
|
|
2531
|
+
return this.options.find((option) => option.is(arg));
|
|
2532
|
+
}
|
|
2533
|
+
/**
|
|
2534
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2535
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2536
|
+
*
|
|
2537
|
+
* @private
|
|
2538
|
+
*/
|
|
2539
|
+
_checkForMissingMandatoryOptions() {
|
|
2540
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2541
|
+
cmd.options.forEach((anOption) => {
|
|
2542
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2543
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2544
|
+
}
|
|
2545
|
+
});
|
|
2546
|
+
});
|
|
2547
|
+
}
|
|
2548
|
+
/**
|
|
2549
|
+
* Display an error message if conflicting options are used together in this.
|
|
2550
|
+
*
|
|
2551
|
+
* @private
|
|
2552
|
+
*/
|
|
2553
|
+
_checkForConflictingLocalOptions() {
|
|
2554
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2555
|
+
const optionKey = option.attributeName();
|
|
2556
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2557
|
+
return false;
|
|
2558
|
+
}
|
|
2559
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2560
|
+
});
|
|
2561
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2562
|
+
(option) => option.conflictsWith.length > 0
|
|
2563
|
+
);
|
|
2564
|
+
optionsWithConflicting.forEach((option) => {
|
|
2565
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2566
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2567
|
+
);
|
|
2568
|
+
if (conflictingAndDefined) {
|
|
2569
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2570
|
+
}
|
|
2571
|
+
});
|
|
2572
|
+
}
|
|
2573
|
+
/**
|
|
2574
|
+
* Display an error message if conflicting options are used together.
|
|
2575
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2576
|
+
*
|
|
2577
|
+
* @private
|
|
2578
|
+
*/
|
|
2579
|
+
_checkForConflictingOptions() {
|
|
2580
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2581
|
+
cmd._checkForConflictingLocalOptions();
|
|
2582
|
+
});
|
|
2583
|
+
}
|
|
2584
|
+
/**
|
|
2585
|
+
* Parse options from `argv` removing known options,
|
|
2586
|
+
* and return argv split into operands and unknown arguments.
|
|
2587
|
+
*
|
|
2588
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2589
|
+
*
|
|
2590
|
+
* Examples:
|
|
2591
|
+
*
|
|
2592
|
+
* argv => operands, unknown
|
|
2593
|
+
* --known kkk op => [op], []
|
|
2594
|
+
* op --known kkk => [op], []
|
|
2595
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2596
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2597
|
+
*
|
|
2598
|
+
* @param {string[]} argv
|
|
2599
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2600
|
+
*/
|
|
2601
|
+
parseOptions(argv) {
|
|
2602
|
+
const operands = [];
|
|
2603
|
+
const unknown = [];
|
|
2604
|
+
let dest = operands;
|
|
2605
|
+
const args = argv.slice();
|
|
2606
|
+
function maybeOption(arg) {
|
|
2607
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2608
|
+
}
|
|
2609
|
+
let activeVariadicOption = null;
|
|
2610
|
+
while (args.length) {
|
|
2611
|
+
const arg = args.shift();
|
|
2612
|
+
if (arg === "--") {
|
|
2613
|
+
if (dest === unknown) dest.push(arg);
|
|
2614
|
+
dest.push(...args);
|
|
2615
|
+
break;
|
|
2616
|
+
}
|
|
2617
|
+
if (activeVariadicOption && !maybeOption(arg)) {
|
|
2618
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2619
|
+
continue;
|
|
2620
|
+
}
|
|
2621
|
+
activeVariadicOption = null;
|
|
2622
|
+
if (maybeOption(arg)) {
|
|
2623
|
+
const option = this._findOption(arg);
|
|
2624
|
+
if (option) {
|
|
2625
|
+
if (option.required) {
|
|
2626
|
+
const value = args.shift();
|
|
2627
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2628
|
+
this.emit(`option:${option.name()}`, value);
|
|
2629
|
+
} else if (option.optional) {
|
|
2630
|
+
let value = null;
|
|
2631
|
+
if (args.length > 0 && !maybeOption(args[0])) {
|
|
2632
|
+
value = args.shift();
|
|
2633
|
+
}
|
|
2634
|
+
this.emit(`option:${option.name()}`, value);
|
|
2635
|
+
} else {
|
|
2636
|
+
this.emit(`option:${option.name()}`);
|
|
2637
|
+
}
|
|
2638
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2639
|
+
continue;
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2643
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2644
|
+
if (option) {
|
|
2645
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2646
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2647
|
+
} else {
|
|
2648
|
+
this.emit(`option:${option.name()}`);
|
|
2649
|
+
args.unshift(`-${arg.slice(2)}`);
|
|
2650
|
+
}
|
|
2651
|
+
continue;
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2655
|
+
const index = arg.indexOf("=");
|
|
2656
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2657
|
+
if (option && (option.required || option.optional)) {
|
|
2658
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2659
|
+
continue;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
if (maybeOption(arg)) {
|
|
2663
|
+
dest = unknown;
|
|
2664
|
+
}
|
|
2665
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2666
|
+
if (this._findCommand(arg)) {
|
|
2667
|
+
operands.push(arg);
|
|
2668
|
+
if (args.length > 0) unknown.push(...args);
|
|
2669
|
+
break;
|
|
2670
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2671
|
+
operands.push(arg);
|
|
2672
|
+
if (args.length > 0) operands.push(...args);
|
|
2673
|
+
break;
|
|
2674
|
+
} else if (this._defaultCommandName) {
|
|
2675
|
+
unknown.push(arg);
|
|
2676
|
+
if (args.length > 0) unknown.push(...args);
|
|
2677
|
+
break;
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
if (this._passThroughOptions) {
|
|
2681
|
+
dest.push(arg);
|
|
2682
|
+
if (args.length > 0) dest.push(...args);
|
|
2683
|
+
break;
|
|
2684
|
+
}
|
|
2685
|
+
dest.push(arg);
|
|
2686
|
+
}
|
|
2687
|
+
return { operands, unknown };
|
|
2688
|
+
}
|
|
2689
|
+
/**
|
|
2690
|
+
* Return an object containing local option values as key-value pairs.
|
|
2691
|
+
*
|
|
2692
|
+
* @return {object}
|
|
2693
|
+
*/
|
|
2694
|
+
opts() {
|
|
2695
|
+
if (this._storeOptionsAsProperties) {
|
|
2696
|
+
const result = {};
|
|
2697
|
+
const len = this.options.length;
|
|
2698
|
+
for (let i = 0; i < len; i++) {
|
|
2699
|
+
const key = this.options[i].attributeName();
|
|
2700
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2701
|
+
}
|
|
2702
|
+
return result;
|
|
2703
|
+
}
|
|
2704
|
+
return this._optionValues;
|
|
2705
|
+
}
|
|
2706
|
+
/**
|
|
2707
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2708
|
+
*
|
|
2709
|
+
* @return {object}
|
|
2710
|
+
*/
|
|
2711
|
+
optsWithGlobals() {
|
|
2712
|
+
return this._getCommandAndAncestors().reduce(
|
|
2713
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2714
|
+
{}
|
|
2715
|
+
);
|
|
2716
|
+
}
|
|
2717
|
+
/**
|
|
2718
|
+
* Display error message and exit (or call exitOverride).
|
|
2719
|
+
*
|
|
2720
|
+
* @param {string} message
|
|
2721
|
+
* @param {object} [errorOptions]
|
|
2722
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2723
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2724
|
+
*/
|
|
2725
|
+
error(message, errorOptions) {
|
|
2726
|
+
this._outputConfiguration.outputError(
|
|
2727
|
+
`${message}
|
|
2728
|
+
`,
|
|
2729
|
+
this._outputConfiguration.writeErr
|
|
2730
|
+
);
|
|
2731
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2732
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2733
|
+
`);
|
|
2734
|
+
} else if (this._showHelpAfterError) {
|
|
2735
|
+
this._outputConfiguration.writeErr("\n");
|
|
2736
|
+
this.outputHelp({ error: true });
|
|
2737
|
+
}
|
|
2738
|
+
const config = errorOptions || {};
|
|
2739
|
+
const exitCode = config.exitCode || 1;
|
|
2740
|
+
const code = config.code || "commander.error";
|
|
2741
|
+
this._exit(exitCode, code, message);
|
|
2742
|
+
}
|
|
2743
|
+
/**
|
|
2744
|
+
* Apply any option related environment variables, if option does
|
|
2745
|
+
* not have a value from cli or client code.
|
|
2746
|
+
*
|
|
2747
|
+
* @private
|
|
2748
|
+
*/
|
|
2749
|
+
_parseOptionsEnv() {
|
|
2750
|
+
this.options.forEach((option) => {
|
|
2751
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2752
|
+
const optionKey = option.attributeName();
|
|
2753
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2754
|
+
this.getOptionValueSource(optionKey)
|
|
2755
|
+
)) {
|
|
2756
|
+
if (option.required || option.optional) {
|
|
2757
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2758
|
+
} else {
|
|
2759
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
});
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2767
|
+
*
|
|
2768
|
+
* @private
|
|
2769
|
+
*/
|
|
2770
|
+
_parseOptionsImplied() {
|
|
2771
|
+
const dualHelper = new DualOptions(this.options);
|
|
2772
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2773
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2774
|
+
};
|
|
2775
|
+
this.options.filter(
|
|
2776
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2777
|
+
this.getOptionValue(option.attributeName()),
|
|
2778
|
+
option
|
|
2779
|
+
)
|
|
2780
|
+
).forEach((option) => {
|
|
2781
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2782
|
+
this.setOptionValueWithSource(
|
|
2783
|
+
impliedKey,
|
|
2784
|
+
option.implied[impliedKey],
|
|
2785
|
+
"implied"
|
|
2786
|
+
);
|
|
2787
|
+
});
|
|
2788
|
+
});
|
|
2789
|
+
}
|
|
2790
|
+
/**
|
|
2791
|
+
* Argument `name` is missing.
|
|
2792
|
+
*
|
|
2793
|
+
* @param {string} name
|
|
2794
|
+
* @private
|
|
2795
|
+
*/
|
|
2796
|
+
missingArgument(name) {
|
|
2797
|
+
const message = `error: missing required argument '${name}'`;
|
|
2798
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2799
|
+
}
|
|
2800
|
+
/**
|
|
2801
|
+
* `Option` is missing an argument.
|
|
2802
|
+
*
|
|
2803
|
+
* @param {Option} option
|
|
2804
|
+
* @private
|
|
2805
|
+
*/
|
|
2806
|
+
optionMissingArgument(option) {
|
|
2807
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2808
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2809
|
+
}
|
|
2810
|
+
/**
|
|
2811
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2812
|
+
*
|
|
2813
|
+
* @param {Option} option
|
|
2814
|
+
* @private
|
|
2815
|
+
*/
|
|
2816
|
+
missingMandatoryOptionValue(option) {
|
|
2817
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2818
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2819
|
+
}
|
|
2820
|
+
/**
|
|
2821
|
+
* `Option` conflicts with another option.
|
|
2822
|
+
*
|
|
2823
|
+
* @param {Option} option
|
|
2824
|
+
* @param {Option} conflictingOption
|
|
2825
|
+
* @private
|
|
2826
|
+
*/
|
|
2827
|
+
_conflictingOption(option, conflictingOption) {
|
|
2828
|
+
const findBestOptionFromValue = (option2) => {
|
|
2829
|
+
const optionKey = option2.attributeName();
|
|
2830
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2831
|
+
const negativeOption = this.options.find(
|
|
2832
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2833
|
+
);
|
|
2834
|
+
const positiveOption = this.options.find(
|
|
2835
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2836
|
+
);
|
|
2837
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2838
|
+
return negativeOption;
|
|
2839
|
+
}
|
|
2840
|
+
return positiveOption || option2;
|
|
2841
|
+
};
|
|
2842
|
+
const getErrorMessage = (option2) => {
|
|
2843
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2844
|
+
const optionKey = bestOption.attributeName();
|
|
2845
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2846
|
+
if (source === "env") {
|
|
2847
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2848
|
+
}
|
|
2849
|
+
return `option '${bestOption.flags}'`;
|
|
2850
|
+
};
|
|
2851
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2852
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2855
|
+
* Unknown option `flag`.
|
|
2856
|
+
*
|
|
2857
|
+
* @param {string} flag
|
|
2858
|
+
* @private
|
|
2859
|
+
*/
|
|
2860
|
+
unknownOption(flag) {
|
|
2861
|
+
if (this._allowUnknownOption) return;
|
|
2862
|
+
let suggestion = "";
|
|
2863
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2864
|
+
let candidateFlags = [];
|
|
2865
|
+
let command = this;
|
|
2866
|
+
do {
|
|
2867
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2868
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2869
|
+
command = command.parent;
|
|
2870
|
+
} while (command && !command._enablePositionalOptions);
|
|
2871
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2872
|
+
}
|
|
2873
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2874
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2875
|
+
}
|
|
2876
|
+
/**
|
|
2877
|
+
* Excess arguments, more than expected.
|
|
2878
|
+
*
|
|
2879
|
+
* @param {string[]} receivedArgs
|
|
2880
|
+
* @private
|
|
2881
|
+
*/
|
|
2882
|
+
_excessArguments(receivedArgs) {
|
|
2883
|
+
if (this._allowExcessArguments) return;
|
|
2884
|
+
const expected = this.registeredArguments.length;
|
|
2885
|
+
const s = expected === 1 ? "" : "s";
|
|
2886
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2887
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
2888
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2889
|
+
}
|
|
2890
|
+
/**
|
|
2891
|
+
* Unknown command.
|
|
2892
|
+
*
|
|
2893
|
+
* @private
|
|
2894
|
+
*/
|
|
2895
|
+
unknownCommand() {
|
|
2896
|
+
const unknownName = this.args[0];
|
|
2897
|
+
let suggestion = "";
|
|
2898
|
+
if (this._showSuggestionAfterError) {
|
|
2899
|
+
const candidateNames = [];
|
|
2900
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2901
|
+
candidateNames.push(command.name());
|
|
2902
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2903
|
+
});
|
|
2904
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2905
|
+
}
|
|
2906
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2907
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2908
|
+
}
|
|
2909
|
+
/**
|
|
2910
|
+
* Get or set the program version.
|
|
2911
|
+
*
|
|
2912
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2913
|
+
*
|
|
2914
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2915
|
+
*
|
|
2916
|
+
* @param {string} [str]
|
|
2917
|
+
* @param {string} [flags]
|
|
2918
|
+
* @param {string} [description]
|
|
2919
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2920
|
+
*/
|
|
2921
|
+
version(str, flags, description) {
|
|
2922
|
+
if (str === void 0) return this._version;
|
|
2923
|
+
this._version = str;
|
|
2924
|
+
flags = flags || "-V, --version";
|
|
2925
|
+
description = description || "output the version number";
|
|
2926
|
+
const versionOption = this.createOption(flags, description);
|
|
2927
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2928
|
+
this._registerOption(versionOption);
|
|
2929
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2930
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2931
|
+
`);
|
|
2932
|
+
this._exit(0, "commander.version", str);
|
|
2933
|
+
});
|
|
2934
|
+
return this;
|
|
2935
|
+
}
|
|
2936
|
+
/**
|
|
2937
|
+
* Set the description.
|
|
2938
|
+
*
|
|
2939
|
+
* @param {string} [str]
|
|
2940
|
+
* @param {object} [argsDescription]
|
|
2941
|
+
* @return {(string|Command)}
|
|
2942
|
+
*/
|
|
2943
|
+
description(str, argsDescription) {
|
|
2944
|
+
if (str === void 0 && argsDescription === void 0)
|
|
2945
|
+
return this._description;
|
|
2946
|
+
this._description = str;
|
|
2947
|
+
if (argsDescription) {
|
|
2948
|
+
this._argsDescription = argsDescription;
|
|
2949
|
+
}
|
|
2950
|
+
return this;
|
|
2951
|
+
}
|
|
2952
|
+
/**
|
|
2953
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2954
|
+
*
|
|
2955
|
+
* @param {string} [str]
|
|
2956
|
+
* @return {(string|Command)}
|
|
2957
|
+
*/
|
|
2958
|
+
summary(str) {
|
|
2959
|
+
if (str === void 0) return this._summary;
|
|
2960
|
+
this._summary = str;
|
|
2961
|
+
return this;
|
|
2962
|
+
}
|
|
2963
|
+
/**
|
|
2964
|
+
* Set an alias for the command.
|
|
2965
|
+
*
|
|
2966
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2967
|
+
*
|
|
2968
|
+
* @param {string} [alias]
|
|
2969
|
+
* @return {(string|Command)}
|
|
2970
|
+
*/
|
|
2971
|
+
alias(alias) {
|
|
2972
|
+
if (alias === void 0) return this._aliases[0];
|
|
2973
|
+
let command = this;
|
|
2974
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
2975
|
+
command = this.commands[this.commands.length - 1];
|
|
2976
|
+
}
|
|
2977
|
+
if (alias === command._name)
|
|
2978
|
+
throw new Error("Command alias can't be the same as its name");
|
|
2979
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2980
|
+
if (matchingCommand) {
|
|
2981
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2982
|
+
throw new Error(
|
|
2983
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
2984
|
+
);
|
|
2985
|
+
}
|
|
2986
|
+
command._aliases.push(alias);
|
|
2987
|
+
return this;
|
|
2988
|
+
}
|
|
2989
|
+
/**
|
|
2990
|
+
* Set aliases for the command.
|
|
2991
|
+
*
|
|
2992
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2993
|
+
*
|
|
2994
|
+
* @param {string[]} [aliases]
|
|
2995
|
+
* @return {(string[]|Command)}
|
|
2996
|
+
*/
|
|
2997
|
+
aliases(aliases) {
|
|
2998
|
+
if (aliases === void 0) return this._aliases;
|
|
2999
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
3000
|
+
return this;
|
|
3001
|
+
}
|
|
3002
|
+
/**
|
|
3003
|
+
* Set / get the command usage `str`.
|
|
3004
|
+
*
|
|
3005
|
+
* @param {string} [str]
|
|
3006
|
+
* @return {(string|Command)}
|
|
3007
|
+
*/
|
|
3008
|
+
usage(str) {
|
|
3009
|
+
if (str === void 0) {
|
|
3010
|
+
if (this._usage) return this._usage;
|
|
3011
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3012
|
+
return humanReadableArgName(arg);
|
|
3013
|
+
});
|
|
3014
|
+
return [].concat(
|
|
3015
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3016
|
+
this.commands.length ? "[command]" : [],
|
|
3017
|
+
this.registeredArguments.length ? args : []
|
|
3018
|
+
).join(" ");
|
|
3019
|
+
}
|
|
3020
|
+
this._usage = str;
|
|
3021
|
+
return this;
|
|
3022
|
+
}
|
|
3023
|
+
/**
|
|
3024
|
+
* Get or set the name of the command.
|
|
3025
|
+
*
|
|
3026
|
+
* @param {string} [str]
|
|
3027
|
+
* @return {(string|Command)}
|
|
3028
|
+
*/
|
|
3029
|
+
name(str) {
|
|
3030
|
+
if (str === void 0) return this._name;
|
|
3031
|
+
this._name = str;
|
|
3032
|
+
return this;
|
|
3033
|
+
}
|
|
3034
|
+
/**
|
|
3035
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3036
|
+
* or require.main.filename, or __filename.
|
|
3037
|
+
*
|
|
3038
|
+
* (Used internally and public although not documented in README.)
|
|
3039
|
+
*
|
|
3040
|
+
* @example
|
|
3041
|
+
* program.nameFromFilename(require.main.filename);
|
|
3042
|
+
*
|
|
3043
|
+
* @param {string} filename
|
|
3044
|
+
* @return {Command}
|
|
3045
|
+
*/
|
|
3046
|
+
nameFromFilename(filename) {
|
|
3047
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3048
|
+
return this;
|
|
3049
|
+
}
|
|
3050
|
+
/**
|
|
3051
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3052
|
+
*
|
|
3053
|
+
* @example
|
|
3054
|
+
* program.executableDir(__dirname);
|
|
3055
|
+
* // or
|
|
3056
|
+
* program.executableDir('subcommands');
|
|
3057
|
+
*
|
|
3058
|
+
* @param {string} [path]
|
|
3059
|
+
* @return {(string|null|Command)}
|
|
3060
|
+
*/
|
|
3061
|
+
executableDir(path2) {
|
|
3062
|
+
if (path2 === void 0) return this._executableDir;
|
|
3063
|
+
this._executableDir = path2;
|
|
3064
|
+
return this;
|
|
3065
|
+
}
|
|
3066
|
+
/**
|
|
3067
|
+
* Return program help documentation.
|
|
3068
|
+
*
|
|
3069
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3070
|
+
* @return {string}
|
|
3071
|
+
*/
|
|
3072
|
+
helpInformation(contextOptions) {
|
|
3073
|
+
const helper = this.createHelp();
|
|
3074
|
+
const context = this._getOutputContext(contextOptions);
|
|
3075
|
+
helper.prepareContext({
|
|
3076
|
+
error: context.error,
|
|
3077
|
+
helpWidth: context.helpWidth,
|
|
3078
|
+
outputHasColors: context.hasColors
|
|
3079
|
+
});
|
|
3080
|
+
const text = helper.formatHelp(this, helper);
|
|
3081
|
+
if (context.hasColors) return text;
|
|
3082
|
+
return this._outputConfiguration.stripColor(text);
|
|
3083
|
+
}
|
|
3084
|
+
/**
|
|
3085
|
+
* @typedef HelpContext
|
|
3086
|
+
* @type {object}
|
|
3087
|
+
* @property {boolean} error
|
|
3088
|
+
* @property {number} helpWidth
|
|
3089
|
+
* @property {boolean} hasColors
|
|
3090
|
+
* @property {function} write - includes stripColor if needed
|
|
3091
|
+
*
|
|
3092
|
+
* @returns {HelpContext}
|
|
3093
|
+
* @private
|
|
3094
|
+
*/
|
|
3095
|
+
_getOutputContext(contextOptions) {
|
|
3096
|
+
contextOptions = contextOptions || {};
|
|
3097
|
+
const error = !!contextOptions.error;
|
|
3098
|
+
let baseWrite;
|
|
3099
|
+
let hasColors;
|
|
3100
|
+
let helpWidth;
|
|
3101
|
+
if (error) {
|
|
3102
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3103
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3104
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3105
|
+
} else {
|
|
3106
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3107
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3108
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3109
|
+
}
|
|
3110
|
+
const write = (str) => {
|
|
3111
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3112
|
+
return baseWrite(str);
|
|
3113
|
+
};
|
|
3114
|
+
return { error, write, hasColors, helpWidth };
|
|
3115
|
+
}
|
|
3116
|
+
/**
|
|
3117
|
+
* Output help information for this command.
|
|
3118
|
+
*
|
|
3119
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3120
|
+
*
|
|
3121
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3122
|
+
*/
|
|
3123
|
+
outputHelp(contextOptions) {
|
|
3124
|
+
let deprecatedCallback;
|
|
3125
|
+
if (typeof contextOptions === "function") {
|
|
3126
|
+
deprecatedCallback = contextOptions;
|
|
3127
|
+
contextOptions = void 0;
|
|
3128
|
+
}
|
|
3129
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3130
|
+
const eventContext = {
|
|
3131
|
+
error: outputContext.error,
|
|
3132
|
+
write: outputContext.write,
|
|
3133
|
+
command: this
|
|
3134
|
+
};
|
|
3135
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3136
|
+
this.emit("beforeHelp", eventContext);
|
|
3137
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3138
|
+
if (deprecatedCallback) {
|
|
3139
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3140
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3141
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
outputContext.write(helpInformation);
|
|
3145
|
+
if (this._getHelpOption()?.long) {
|
|
3146
|
+
this.emit(this._getHelpOption().long);
|
|
3147
|
+
}
|
|
3148
|
+
this.emit("afterHelp", eventContext);
|
|
3149
|
+
this._getCommandAndAncestors().forEach(
|
|
3150
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3151
|
+
);
|
|
3152
|
+
}
|
|
3153
|
+
/**
|
|
3154
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3155
|
+
* Pass in false to disable the built-in help option.
|
|
3156
|
+
*
|
|
3157
|
+
* @example
|
|
3158
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3159
|
+
* program.helpOption(false); // disable
|
|
3160
|
+
*
|
|
3161
|
+
* @param {(string | boolean)} flags
|
|
3162
|
+
* @param {string} [description]
|
|
3163
|
+
* @return {Command} `this` command for chaining
|
|
3164
|
+
*/
|
|
3165
|
+
helpOption(flags, description) {
|
|
3166
|
+
if (typeof flags === "boolean") {
|
|
3167
|
+
if (flags) {
|
|
3168
|
+
this._helpOption = this._helpOption ?? void 0;
|
|
3169
|
+
} else {
|
|
3170
|
+
this._helpOption = null;
|
|
3171
|
+
}
|
|
3172
|
+
return this;
|
|
3173
|
+
}
|
|
3174
|
+
flags = flags ?? "-h, --help";
|
|
3175
|
+
description = description ?? "display help for command";
|
|
3176
|
+
this._helpOption = this.createOption(flags, description);
|
|
3177
|
+
return this;
|
|
3178
|
+
}
|
|
3179
|
+
/**
|
|
3180
|
+
* Lazy create help option.
|
|
3181
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3182
|
+
*
|
|
3183
|
+
* @returns {(Option | null)} the help option
|
|
3184
|
+
* @package
|
|
3185
|
+
*/
|
|
3186
|
+
_getHelpOption() {
|
|
3187
|
+
if (this._helpOption === void 0) {
|
|
3188
|
+
this.helpOption(void 0, void 0);
|
|
3189
|
+
}
|
|
3190
|
+
return this._helpOption;
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Supply your own option to use for the built-in help option.
|
|
3194
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3195
|
+
*
|
|
3196
|
+
* @param {Option} option
|
|
3197
|
+
* @return {Command} `this` command for chaining
|
|
3198
|
+
*/
|
|
3199
|
+
addHelpOption(option) {
|
|
3200
|
+
this._helpOption = option;
|
|
3201
|
+
return this;
|
|
3202
|
+
}
|
|
3203
|
+
/**
|
|
3204
|
+
* Output help information and exit.
|
|
3205
|
+
*
|
|
3206
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3207
|
+
*
|
|
3208
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3209
|
+
*/
|
|
3210
|
+
help(contextOptions) {
|
|
3211
|
+
this.outputHelp(contextOptions);
|
|
3212
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3213
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3214
|
+
exitCode = 1;
|
|
3215
|
+
}
|
|
3216
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3217
|
+
}
|
|
3218
|
+
/**
|
|
3219
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3220
|
+
* @typedef HelpTextEventContext
|
|
3221
|
+
* @type {object}
|
|
3222
|
+
* @property {boolean} error
|
|
3223
|
+
* @property {Command} command
|
|
3224
|
+
* @property {function} write
|
|
3225
|
+
*/
|
|
3226
|
+
/**
|
|
3227
|
+
* Add additional text to be displayed with the built-in help.
|
|
3228
|
+
*
|
|
3229
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3230
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3231
|
+
*
|
|
3232
|
+
* @param {string} position - before or after built-in help
|
|
3233
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3234
|
+
* @return {Command} `this` command for chaining
|
|
3235
|
+
*/
|
|
3236
|
+
addHelpText(position, text) {
|
|
3237
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3238
|
+
if (!allowedValues.includes(position)) {
|
|
3239
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3240
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3241
|
+
}
|
|
3242
|
+
const helpEvent = `${position}Help`;
|
|
3243
|
+
this.on(helpEvent, (context) => {
|
|
3244
|
+
let helpStr;
|
|
3245
|
+
if (typeof text === "function") {
|
|
3246
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3247
|
+
} else {
|
|
3248
|
+
helpStr = text;
|
|
3249
|
+
}
|
|
3250
|
+
if (helpStr) {
|
|
3251
|
+
context.write(`${helpStr}
|
|
3252
|
+
`);
|
|
3253
|
+
}
|
|
3254
|
+
});
|
|
3255
|
+
return this;
|
|
3256
|
+
}
|
|
3257
|
+
/**
|
|
3258
|
+
* Output help information if help flags specified
|
|
3259
|
+
*
|
|
3260
|
+
* @param {Array} args - array of options to search for help flags
|
|
3261
|
+
* @private
|
|
3262
|
+
*/
|
|
3263
|
+
_outputHelpIfRequested(args) {
|
|
3264
|
+
const helpOption = this._getHelpOption();
|
|
3265
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3266
|
+
if (helpRequested) {
|
|
3267
|
+
this.outputHelp();
|
|
3268
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
3271
|
+
};
|
|
3272
|
+
function incrementNodeInspectorPort(args) {
|
|
3273
|
+
return args.map((arg) => {
|
|
3274
|
+
if (!arg.startsWith("--inspect")) {
|
|
3275
|
+
return arg;
|
|
3276
|
+
}
|
|
3277
|
+
let debugOption;
|
|
3278
|
+
let debugHost = "127.0.0.1";
|
|
3279
|
+
let debugPort = "9229";
|
|
3280
|
+
let match;
|
|
3281
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3282
|
+
debugOption = match[1];
|
|
3283
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3284
|
+
debugOption = match[1];
|
|
3285
|
+
if (/^\d+$/.test(match[3])) {
|
|
3286
|
+
debugPort = match[3];
|
|
3287
|
+
} else {
|
|
3288
|
+
debugHost = match[3];
|
|
3289
|
+
}
|
|
3290
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3291
|
+
debugOption = match[1];
|
|
3292
|
+
debugHost = match[3];
|
|
3293
|
+
debugPort = match[4];
|
|
3294
|
+
}
|
|
3295
|
+
if (debugOption && debugPort !== "0") {
|
|
3296
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3297
|
+
}
|
|
3298
|
+
return arg;
|
|
3299
|
+
});
|
|
3300
|
+
}
|
|
3301
|
+
function useColor() {
|
|
3302
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3303
|
+
return false;
|
|
3304
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3305
|
+
return true;
|
|
3306
|
+
return void 0;
|
|
3307
|
+
}
|
|
3308
|
+
exports.Command = Command2;
|
|
3309
|
+
exports.useColor = useColor;
|
|
3310
|
+
}
|
|
3311
|
+
});
|
|
3312
|
+
|
|
3313
|
+
// node_modules/commander/index.js
|
|
3314
|
+
var require_commander = __commonJS({
|
|
3315
|
+
"node_modules/commander/index.js"(exports) {
|
|
3316
|
+
var { Argument: Argument2 } = require_argument();
|
|
3317
|
+
var { Command: Command2 } = require_command();
|
|
3318
|
+
var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
3319
|
+
var { Help: Help2 } = require_help();
|
|
3320
|
+
var { Option: Option2 } = require_option();
|
|
3321
|
+
exports.program = new Command2();
|
|
3322
|
+
exports.createCommand = (name) => new Command2(name);
|
|
3323
|
+
exports.createOption = (flags, description) => new Option2(flags, description);
|
|
3324
|
+
exports.createArgument = (name, description) => new Argument2(name, description);
|
|
3325
|
+
exports.Command = Command2;
|
|
3326
|
+
exports.Option = Option2;
|
|
3327
|
+
exports.Argument = Argument2;
|
|
3328
|
+
exports.Help = Help2;
|
|
3329
|
+
exports.CommanderError = CommanderError2;
|
|
3330
|
+
exports.InvalidArgumentError = InvalidArgumentError2;
|
|
3331
|
+
exports.InvalidOptionArgumentError = InvalidArgumentError2;
|
|
3332
|
+
}
|
|
3333
|
+
});
|
|
3334
|
+
|
|
3335
|
+
// src/core/config.ts
|
|
3336
|
+
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
|
3337
|
+
import { homedir } from "node:os";
|
|
3338
|
+
import { join } from "node:path";
|
|
3339
|
+
function getBaseDir() {
|
|
3340
|
+
return BASE_DIR;
|
|
3341
|
+
}
|
|
3342
|
+
function getConfigPath() {
|
|
3343
|
+
return CONFIG_PATH;
|
|
3344
|
+
}
|
|
3345
|
+
function getPidsDir() {
|
|
3346
|
+
return PIDS_DIR;
|
|
3347
|
+
}
|
|
3348
|
+
function getHistoryDir() {
|
|
3349
|
+
return HISTORY_DIR;
|
|
3350
|
+
}
|
|
3351
|
+
async function ensureDirs() {
|
|
3352
|
+
await mkdir(BASE_DIR, { recursive: true });
|
|
3353
|
+
await mkdir(PIDS_DIR, { recursive: true });
|
|
3354
|
+
await mkdir(HISTORY_DIR, { recursive: true });
|
|
3355
|
+
}
|
|
3356
|
+
async function readConfig() {
|
|
3357
|
+
await ensureDirs();
|
|
3358
|
+
try {
|
|
3359
|
+
const raw = await readFile(CONFIG_PATH, "utf-8");
|
|
3360
|
+
const parsed = JSON.parse(raw);
|
|
3361
|
+
return validateConfig(parsed);
|
|
3362
|
+
} catch (err) {
|
|
3363
|
+
if (err.code === "ENOENT") {
|
|
3364
|
+
const defaultConfig = { tunnels: [] };
|
|
3365
|
+
await writeConfig(defaultConfig);
|
|
3366
|
+
return defaultConfig;
|
|
3367
|
+
}
|
|
3368
|
+
throw err;
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
async function writeConfig(config) {
|
|
3372
|
+
await ensureDirs();
|
|
3373
|
+
await writeFile(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", "utf-8");
|
|
3374
|
+
}
|
|
3375
|
+
function validateConfig(data) {
|
|
3376
|
+
if (!data || typeof data !== "object") {
|
|
3377
|
+
throw new Error("Invalid config: expected an object");
|
|
3378
|
+
}
|
|
3379
|
+
const obj = data;
|
|
3380
|
+
if (!Array.isArray(obj.tunnels)) {
|
|
3381
|
+
throw new Error("Invalid config: expected tunnels array");
|
|
3382
|
+
}
|
|
3383
|
+
for (const t of obj.tunnels) {
|
|
3384
|
+
if (!t.id || typeof t.id !== "string") throw new Error("Invalid tunnel: missing id");
|
|
3385
|
+
if (!t.host || typeof t.host !== "string") throw new Error(`Invalid tunnel ${t.id}: missing host`);
|
|
3386
|
+
if (typeof t.localPort !== "number") throw new Error(`Invalid tunnel ${t.id}: missing localPort`);
|
|
3387
|
+
if (!t.remoteHost || typeof t.remoteHost !== "string") throw new Error(`Invalid tunnel ${t.id}: missing remoteHost`);
|
|
3388
|
+
if (typeof t.remotePort !== "number") throw new Error(`Invalid tunnel ${t.id}: missing remotePort`);
|
|
3389
|
+
}
|
|
3390
|
+
return data;
|
|
3391
|
+
}
|
|
3392
|
+
function slugify(name) {
|
|
3393
|
+
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
3394
|
+
}
|
|
3395
|
+
var BASE_DIR, CONFIG_PATH, PIDS_DIR, HISTORY_DIR;
|
|
3396
|
+
var init_config = __esm({
|
|
3397
|
+
"src/core/config.ts"() {
|
|
3398
|
+
"use strict";
|
|
3399
|
+
BASE_DIR = join(homedir(), ".ssh-tunnels");
|
|
3400
|
+
CONFIG_PATH = join(BASE_DIR, "config.json");
|
|
3401
|
+
PIDS_DIR = join(BASE_DIR, "pids");
|
|
3402
|
+
HISTORY_DIR = join(BASE_DIR, "history");
|
|
3403
|
+
}
|
|
3404
|
+
});
|
|
3405
|
+
|
|
3406
|
+
// src/core/tunnel.ts
|
|
3407
|
+
import { spawn } from "node:child_process";
|
|
3408
|
+
import { readFile as readFile2, writeFile as writeFile2, unlink } from "node:fs/promises";
|
|
3409
|
+
import { join as join2 } from "node:path";
|
|
3410
|
+
import { createConnection } from "node:net";
|
|
3411
|
+
function pidFilePath(id) {
|
|
3412
|
+
return join2(getPidsDir(), `${id}.pid`);
|
|
3413
|
+
}
|
|
3414
|
+
function logFilePath(id) {
|
|
3415
|
+
return join2(getHistoryDir(), `${id}.log`);
|
|
3416
|
+
}
|
|
3417
|
+
function getLogFilePath(id) {
|
|
3418
|
+
return logFilePath(id);
|
|
3419
|
+
}
|
|
3420
|
+
async function readPid(id) {
|
|
3421
|
+
try {
|
|
3422
|
+
const raw = await readFile2(pidFilePath(id), "utf-8");
|
|
3423
|
+
const pid = parseInt(raw.trim(), 10);
|
|
3424
|
+
return isNaN(pid) ? null : pid;
|
|
3425
|
+
} catch {
|
|
3426
|
+
return null;
|
|
3427
|
+
}
|
|
3428
|
+
}
|
|
3429
|
+
function isProcessAlive(pid) {
|
|
3430
|
+
try {
|
|
3431
|
+
process.kill(pid, 0);
|
|
3432
|
+
return true;
|
|
3433
|
+
} catch {
|
|
3434
|
+
return false;
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
3437
|
+
function probePort(port, host = "127.0.0.1", timeoutMs = 1e3) {
|
|
3438
|
+
return new Promise((resolve) => {
|
|
3439
|
+
const socket = createConnection({ port, host, timeout: timeoutMs });
|
|
3440
|
+
socket.on("connect", () => {
|
|
3441
|
+
socket.destroy();
|
|
3442
|
+
resolve(true);
|
|
3443
|
+
});
|
|
3444
|
+
socket.on("error", () => {
|
|
3445
|
+
socket.destroy();
|
|
3446
|
+
resolve(false);
|
|
3447
|
+
});
|
|
3448
|
+
socket.on("timeout", () => {
|
|
3449
|
+
socket.destroy();
|
|
3450
|
+
resolve(false);
|
|
3451
|
+
});
|
|
3452
|
+
});
|
|
3453
|
+
}
|
|
3454
|
+
async function getTunnelStatus(tunnel) {
|
|
3455
|
+
const pid = await readPid(tunnel.id);
|
|
3456
|
+
const alive = pid !== null && isProcessAlive(pid);
|
|
3457
|
+
const portOpen = alive ? await probePort(tunnel.localPort) : false;
|
|
3458
|
+
return {
|
|
3459
|
+
id: tunnel.id,
|
|
3460
|
+
name: tunnel.name,
|
|
3461
|
+
enabled: tunnel.enabled,
|
|
3462
|
+
pid,
|
|
3463
|
+
alive,
|
|
3464
|
+
portOpen,
|
|
3465
|
+
localPort: tunnel.localPort,
|
|
3466
|
+
remoteHost: tunnel.remoteHost,
|
|
3467
|
+
remotePort: tunnel.remotePort,
|
|
3468
|
+
host: tunnel.host
|
|
3469
|
+
};
|
|
3470
|
+
}
|
|
3471
|
+
async function startTunnel(tunnel) {
|
|
3472
|
+
const args = [
|
|
3473
|
+
"-N",
|
|
3474
|
+
// No remote command
|
|
3475
|
+
"-L",
|
|
3476
|
+
`${tunnel.localPort}:${tunnel.remoteHost}:${tunnel.remotePort}`,
|
|
3477
|
+
"-o",
|
|
3478
|
+
"ServerAliveInterval=30",
|
|
3479
|
+
"-o",
|
|
3480
|
+
"ServerAliveCountMax=3",
|
|
3481
|
+
"-o",
|
|
3482
|
+
"ExitOnForwardFailure=yes",
|
|
3483
|
+
"-o",
|
|
3484
|
+
"StrictHostKeyChecking=accept-new"
|
|
3485
|
+
];
|
|
3486
|
+
if (tunnel.user) {
|
|
3487
|
+
args.push("-l", tunnel.user);
|
|
3488
|
+
}
|
|
3489
|
+
if (tunnel.sshPort && tunnel.sshPort !== 22) {
|
|
3490
|
+
args.push("-p", String(tunnel.sshPort));
|
|
3491
|
+
}
|
|
3492
|
+
if (tunnel.identityFile) {
|
|
3493
|
+
const expandedPath = tunnel.identityFile.replace(/^~/, process.env.HOME || "");
|
|
3494
|
+
args.push("-i", expandedPath);
|
|
3495
|
+
}
|
|
3496
|
+
if (tunnel.extraArgs) {
|
|
3497
|
+
args.push(...tunnel.extraArgs);
|
|
3498
|
+
}
|
|
3499
|
+
args.push(tunnel.host);
|
|
3500
|
+
const { openSync } = await import("node:fs");
|
|
3501
|
+
const logFd = openSync(logFilePath(tunnel.id), "a");
|
|
3502
|
+
const child = spawn("ssh", args, {
|
|
3503
|
+
detached: true,
|
|
3504
|
+
stdio: ["ignore", logFd, logFd]
|
|
3505
|
+
});
|
|
3506
|
+
const { closeSync } = await import("node:fs");
|
|
3507
|
+
closeSync(logFd);
|
|
3508
|
+
child.unref();
|
|
3509
|
+
if (child.pid === void 0) {
|
|
3510
|
+
throw new Error(`Failed to start tunnel ${tunnel.id}`);
|
|
3511
|
+
}
|
|
3512
|
+
await writeFile2(pidFilePath(tunnel.id), String(child.pid), "utf-8");
|
|
3513
|
+
return child.pid;
|
|
3514
|
+
}
|
|
3515
|
+
async function stopTunnel(id) {
|
|
3516
|
+
const pid = await readPid(id);
|
|
3517
|
+
if (pid === null) return;
|
|
3518
|
+
if (isProcessAlive(pid)) {
|
|
3519
|
+
const treeKill = (await import("tree-kill")).default;
|
|
3520
|
+
await new Promise((resolve, reject) => {
|
|
3521
|
+
treeKill(pid, "SIGTERM", (err) => {
|
|
3522
|
+
if (err) {
|
|
3523
|
+
treeKill(pid, "SIGKILL", () => resolve());
|
|
3524
|
+
} else {
|
|
3525
|
+
resolve();
|
|
3526
|
+
}
|
|
3527
|
+
});
|
|
3528
|
+
});
|
|
3529
|
+
}
|
|
3530
|
+
try {
|
|
3531
|
+
await unlink(pidFilePath(id));
|
|
3532
|
+
} catch {
|
|
3533
|
+
}
|
|
3534
|
+
}
|
|
3535
|
+
async function cleanStalePid(id) {
|
|
3536
|
+
const pid = await readPid(id);
|
|
3537
|
+
if (pid !== null && !isProcessAlive(pid)) {
|
|
3538
|
+
try {
|
|
3539
|
+
await unlink(pidFilePath(id));
|
|
3540
|
+
} catch {
|
|
3541
|
+
}
|
|
3542
|
+
}
|
|
3543
|
+
}
|
|
3544
|
+
var init_tunnel = __esm({
|
|
3545
|
+
"src/core/tunnel.ts"() {
|
|
3546
|
+
"use strict";
|
|
3547
|
+
init_config();
|
|
3548
|
+
}
|
|
3549
|
+
});
|
|
3550
|
+
|
|
3551
|
+
// src/core/sync.ts
|
|
3552
|
+
async function sync(config) {
|
|
3553
|
+
const cfg = config ?? await readConfig();
|
|
3554
|
+
const result = {
|
|
3555
|
+
started: [],
|
|
3556
|
+
stopped: [],
|
|
3557
|
+
alreadyRunning: [],
|
|
3558
|
+
alreadyStopped: [],
|
|
3559
|
+
errors: []
|
|
3560
|
+
};
|
|
3561
|
+
for (const tunnel of cfg.tunnels) {
|
|
3562
|
+
try {
|
|
3563
|
+
await cleanStalePid(tunnel.id);
|
|
3564
|
+
const status = await getTunnelStatus(tunnel);
|
|
3565
|
+
if (tunnel.enabled) {
|
|
3566
|
+
if (status.alive && status.portOpen) {
|
|
3567
|
+
result.alreadyRunning.push(tunnel.id);
|
|
3568
|
+
} else {
|
|
3569
|
+
if (status.alive && !status.portOpen) {
|
|
3570
|
+
await stopTunnel(tunnel.id);
|
|
3571
|
+
}
|
|
3572
|
+
await startTunnel(tunnel);
|
|
3573
|
+
result.started.push(tunnel.id);
|
|
3574
|
+
}
|
|
3575
|
+
} else {
|
|
3576
|
+
if (status.alive) {
|
|
3577
|
+
await stopTunnel(tunnel.id);
|
|
3578
|
+
result.stopped.push(tunnel.id);
|
|
3579
|
+
} else {
|
|
3580
|
+
result.alreadyStopped.push(tunnel.id);
|
|
3581
|
+
}
|
|
3582
|
+
}
|
|
3583
|
+
} catch (err) {
|
|
3584
|
+
result.errors.push({
|
|
3585
|
+
id: tunnel.id,
|
|
3586
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3587
|
+
});
|
|
3588
|
+
}
|
|
3589
|
+
}
|
|
3590
|
+
return result;
|
|
3591
|
+
}
|
|
3592
|
+
async function getStatus(config) {
|
|
3593
|
+
const cfg = config ?? await readConfig();
|
|
3594
|
+
const statuses = [];
|
|
3595
|
+
for (const tunnel of cfg.tunnels) {
|
|
3596
|
+
await cleanStalePid(tunnel.id);
|
|
3597
|
+
statuses.push(await getTunnelStatus(tunnel));
|
|
3598
|
+
}
|
|
3599
|
+
return statuses;
|
|
3600
|
+
}
|
|
3601
|
+
var init_sync = __esm({
|
|
3602
|
+
"src/core/sync.ts"() {
|
|
3603
|
+
"use strict";
|
|
3604
|
+
init_config();
|
|
3605
|
+
init_tunnel();
|
|
3606
|
+
}
|
|
3607
|
+
});
|
|
3608
|
+
|
|
3609
|
+
// src/core/watch.ts
|
|
3610
|
+
import { watch as chokidarWatch } from "chokidar";
|
|
3611
|
+
function watchConfig(options) {
|
|
3612
|
+
const configPath = getConfigPath();
|
|
3613
|
+
const debounceMs = options?.debounceMs ?? 500;
|
|
3614
|
+
let debounceTimer = null;
|
|
3615
|
+
let syncing = false;
|
|
3616
|
+
const doSync = async () => {
|
|
3617
|
+
if (syncing) return;
|
|
3618
|
+
syncing = true;
|
|
3619
|
+
try {
|
|
3620
|
+
const result = await sync();
|
|
3621
|
+
options?.onSync?.(result);
|
|
3622
|
+
} catch (err) {
|
|
3623
|
+
options?.onError?.(err instanceof Error ? err : new Error(String(err)));
|
|
3624
|
+
} finally {
|
|
3625
|
+
syncing = false;
|
|
3626
|
+
}
|
|
3627
|
+
};
|
|
3628
|
+
const watcher = chokidarWatch(configPath, {
|
|
3629
|
+
persistent: true,
|
|
3630
|
+
ignoreInitial: true
|
|
3631
|
+
});
|
|
3632
|
+
watcher.on("change", () => {
|
|
3633
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
3634
|
+
debounceTimer = setTimeout(doSync, debounceMs);
|
|
3635
|
+
});
|
|
3636
|
+
return {
|
|
3637
|
+
close: async () => {
|
|
3638
|
+
if (debounceTimer) clearTimeout(debounceTimer);
|
|
3639
|
+
await watcher.close();
|
|
3640
|
+
}
|
|
3641
|
+
};
|
|
3642
|
+
}
|
|
3643
|
+
var init_watch = __esm({
|
|
3644
|
+
"src/core/watch.ts"() {
|
|
3645
|
+
"use strict";
|
|
3646
|
+
init_config();
|
|
3647
|
+
init_sync();
|
|
3648
|
+
}
|
|
3649
|
+
});
|
|
3650
|
+
|
|
3651
|
+
// src/core/index.ts
|
|
3652
|
+
var core_exports = {};
|
|
3653
|
+
__export(core_exports, {
|
|
3654
|
+
cleanStalePid: () => cleanStalePid,
|
|
3655
|
+
ensureDirs: () => ensureDirs,
|
|
3656
|
+
getBaseDir: () => getBaseDir,
|
|
3657
|
+
getConfigPath: () => getConfigPath,
|
|
3658
|
+
getHistoryDir: () => getHistoryDir,
|
|
3659
|
+
getLogFilePath: () => getLogFilePath,
|
|
3660
|
+
getPidsDir: () => getPidsDir,
|
|
3661
|
+
getStatus: () => getStatus,
|
|
3662
|
+
getTunnelStatus: () => getTunnelStatus,
|
|
3663
|
+
readConfig: () => readConfig,
|
|
3664
|
+
slugify: () => slugify,
|
|
3665
|
+
startTunnel: () => startTunnel,
|
|
3666
|
+
stopTunnel: () => stopTunnel,
|
|
3667
|
+
sync: () => sync,
|
|
3668
|
+
watchConfig: () => watchConfig,
|
|
3669
|
+
writeConfig: () => writeConfig
|
|
3670
|
+
});
|
|
3671
|
+
var init_core = __esm({
|
|
3672
|
+
"src/core/index.ts"() {
|
|
3673
|
+
"use strict";
|
|
3674
|
+
init_config();
|
|
3675
|
+
init_tunnel();
|
|
3676
|
+
init_sync();
|
|
3677
|
+
init_watch();
|
|
3678
|
+
}
|
|
3679
|
+
});
|
|
3680
|
+
|
|
3681
|
+
// node_modules/commander/esm.mjs
|
|
3682
|
+
var import_index = __toESM(require_commander(), 1);
|
|
3683
|
+
var {
|
|
3684
|
+
program,
|
|
3685
|
+
createCommand,
|
|
3686
|
+
createArgument,
|
|
3687
|
+
createOption,
|
|
3688
|
+
CommanderError,
|
|
3689
|
+
InvalidArgumentError,
|
|
3690
|
+
InvalidOptionArgumentError,
|
|
3691
|
+
// deprecated old name
|
|
3692
|
+
Command,
|
|
3693
|
+
Argument,
|
|
3694
|
+
Option,
|
|
3695
|
+
Help
|
|
3696
|
+
} = import_index.default;
|
|
3697
|
+
|
|
3698
|
+
// src/cli/index.ts
|
|
3699
|
+
init_core();
|
|
3700
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
3701
|
+
import { createReadStream } from "node:fs";
|
|
3702
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
3703
|
+
var program2 = new Command();
|
|
3704
|
+
program2.name("ssh-tunnels").description(
|
|
3705
|
+
`Declarative SSH tunnel manager.
|
|
3706
|
+
|
|
3707
|
+
Manages SSH tunnels via a JSON config file at ~/.ssh-tunnels/config.json.
|
|
3708
|
+
Each tunnel defines a local port that forwards through an SSH host to a
|
|
3709
|
+
remote host:port. The CLI synchronizes running SSH processes to match
|
|
3710
|
+
the desired state in the config.
|
|
3711
|
+
|
|
3712
|
+
COMMON PORTS:
|
|
3713
|
+
5432 PostgreSQL
|
|
3714
|
+
3306 MySQL
|
|
3715
|
+
6379 Redis
|
|
3716
|
+
27017 MongoDB
|
|
3717
|
+
80/443 HTTP/HTTPS (web interfaces)
|
|
3718
|
+
8080 Common dev server / admin UI
|
|
3719
|
+
8089 Splunk / custom services
|
|
3720
|
+
18789 OpenClaw admin
|
|
3721
|
+
3000 Node.js dev server
|
|
3722
|
+
9200 Elasticsearch
|
|
3723
|
+
|
|
3724
|
+
WORKFLOW:
|
|
3725
|
+
1. Add a tunnel: ssh-tunnels add --name "My DB" --host bastion.example.com ...
|
|
3726
|
+
2. Enable & start: ssh-tunnels enable my-db
|
|
3727
|
+
3. Check status: ssh-tunnels status
|
|
3728
|
+
4. View logs: ssh-tunnels logs my-db
|
|
3729
|
+
5. Disable & stop: ssh-tunnels disable my-db
|
|
3730
|
+
|
|
3731
|
+
GOTCHAS:
|
|
3732
|
+
- The --user flag defaults to your local OS username ($USER). Many servers
|
|
3733
|
+
require "root" or a specific service account. If you see "Permission denied
|
|
3734
|
+
(publickey)" in the logs, the username is likely wrong.
|
|
3735
|
+
- The --remoteHost is resolved FROM the SSH host, not from your machine.
|
|
3736
|
+
Use "localhost" if the service runs on the SSH host itself.
|
|
3737
|
+
- If a tunnel shows "stopped" right after enabling, check the logs with
|
|
3738
|
+
"ssh-tunnels logs <id>" \u2014 common causes are wrong username, missing SSH
|
|
3739
|
+
key, host key verification failure, or the remote port not being open.
|
|
3740
|
+
- The tunnel ID is auto-generated from the name (slugified). Use the ID
|
|
3741
|
+
(not the name) for enable/disable/remove/logs commands.
|
|
3742
|
+
- If your SSH key is not the default (~/.ssh/id_rsa or ~/.ssh/id_ed25519),
|
|
3743
|
+
pass --identityFile explicitly.
|
|
3744
|
+
- Local port conflicts will cause the tunnel to fail immediately. Check
|
|
3745
|
+
"lsof -i :<port>" if a tunnel won't start.`
|
|
3746
|
+
).version("0.1.0");
|
|
3747
|
+
var jsonOutput = false;
|
|
3748
|
+
program2.option("--json", "Output as JSON (for programmatic/AI consumption)").hook("preAction", (cmd) => {
|
|
3749
|
+
jsonOutput = cmd.opts().json ?? false;
|
|
3750
|
+
});
|
|
3751
|
+
function output(data) {
|
|
3752
|
+
if (jsonOutput) {
|
|
3753
|
+
console.log(JSON.stringify(data, null, 2));
|
|
3754
|
+
} else if (typeof data === "string") {
|
|
3755
|
+
console.log(data);
|
|
3756
|
+
} else {
|
|
3757
|
+
console.log(data);
|
|
3758
|
+
}
|
|
3759
|
+
}
|
|
3760
|
+
async function verboseStatusCheck(id, expectRunning) {
|
|
3761
|
+
await new Promise((r) => setTimeout(r, 2500));
|
|
3762
|
+
const statuses = await getStatus();
|
|
3763
|
+
const s = statuses.find((t) => t.id === id);
|
|
3764
|
+
if (!s) return;
|
|
3765
|
+
const running = s.alive && s.portOpen;
|
|
3766
|
+
if (expectRunning && !running) {
|
|
3767
|
+
console.log("");
|
|
3768
|
+
console.log(`WARNING: Tunnel '${s.name}' (${id}) was started but is not running.`);
|
|
3769
|
+
console.log(` Expected state: running on localhost:${s.localPort}`);
|
|
3770
|
+
console.log(` Actual state: ${s.alive ? "process alive but port not open" : "process not running"}`);
|
|
3771
|
+
console.log("");
|
|
3772
|
+
console.log(" Troubleshooting:");
|
|
3773
|
+
console.log(` 1. Check logs: ssh-tunnels logs ${id}`);
|
|
3774
|
+
console.log(" 2. Common causes:");
|
|
3775
|
+
console.log(" - Wrong SSH user (use --user root if the server requires root)");
|
|
3776
|
+
console.log(" - SSH key not authorized on the remote host");
|
|
3777
|
+
console.log(" - Host key verification failed (first connection to this host)");
|
|
3778
|
+
console.log(` - Local port ${s.localPort} already in use (check: lsof -i :${s.localPort})`);
|
|
3779
|
+
console.log(` - Remote service not listening on ${s.remoteHost}:${s.remotePort}`);
|
|
3780
|
+
try {
|
|
3781
|
+
const logContent = await readFile3(getLogFilePath(id), "utf-8");
|
|
3782
|
+
const lines = logContent.trim().split("\n").slice(-5);
|
|
3783
|
+
if (lines.length > 0 && lines[0].length > 0) {
|
|
3784
|
+
console.log("");
|
|
3785
|
+
console.log(` Recent log output (${getLogFilePath(id)}):`);
|
|
3786
|
+
for (const line of lines) {
|
|
3787
|
+
console.log(` ${line}`);
|
|
3788
|
+
}
|
|
3789
|
+
}
|
|
3790
|
+
} catch {
|
|
3791
|
+
}
|
|
3792
|
+
} else if (expectRunning && running) {
|
|
3793
|
+
console.log(`Verified: tunnel is running \u2014 localhost:${s.localPort} is accepting connections.`);
|
|
3794
|
+
}
|
|
3795
|
+
}
|
|
3796
|
+
program2.command("sync").description(
|
|
3797
|
+
`One-shot reconciliation: start all enabled tunnels, stop all disabled ones.
|
|
3798
|
+
|
|
3799
|
+
Compares the desired state in ~/.ssh-tunnels/config.json against actually
|
|
3800
|
+
running SSH processes. Starts missing tunnels, kills ones that should be
|
|
3801
|
+
off, and cleans up stale PID files from crashed processes.
|
|
3802
|
+
|
|
3803
|
+
Examples:
|
|
3804
|
+
ssh-tunnels sync # Reconcile everything
|
|
3805
|
+
ssh-tunnels sync --json # Machine-readable output`
|
|
3806
|
+
).action(async () => {
|
|
3807
|
+
const result = await sync();
|
|
3808
|
+
if (jsonOutput) {
|
|
3809
|
+
output(result);
|
|
3810
|
+
} else {
|
|
3811
|
+
if (result.started.length) console.log(`Started: ${result.started.join(", ")}`);
|
|
3812
|
+
if (result.stopped.length) console.log(`Stopped: ${result.stopped.join(", ")}`);
|
|
3813
|
+
if (result.alreadyRunning.length) console.log(`Already running: ${result.alreadyRunning.join(", ")}`);
|
|
3814
|
+
if (result.alreadyStopped.length) console.log(`Already stopped: ${result.alreadyStopped.join(", ")}`);
|
|
3815
|
+
if (result.errors.length) {
|
|
3816
|
+
for (const e of result.errors) {
|
|
3817
|
+
console.error(`Error [${e.id}]: ${e.error}`);
|
|
3818
|
+
}
|
|
3819
|
+
}
|
|
3820
|
+
if (!result.started.length && !result.stopped.length && !result.errors.length) {
|
|
3821
|
+
console.log("Everything in sync.");
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
3824
|
+
});
|
|
3825
|
+
program2.command("status").description(
|
|
3826
|
+
`Show the current state of all configured tunnels.
|
|
3827
|
+
|
|
3828
|
+
Displays each tunnel's name, ID, running/stopped state, enabled/disabled
|
|
3829
|
+
flag, and port mapping. Use --json for structured output.
|
|
3830
|
+
|
|
3831
|
+
Examples:
|
|
3832
|
+
ssh-tunnels status # Human-readable table
|
|
3833
|
+
ssh-tunnels status --json # JSON array of tunnel status objects
|
|
3834
|
+
|
|
3835
|
+
Status indicators:
|
|
3836
|
+
\u25CF = running (SSH process alive + local port accepting connections)
|
|
3837
|
+
\u25CB = stopped (process dead or port not responding)`
|
|
3838
|
+
).action(async () => {
|
|
3839
|
+
const statuses = await getStatus();
|
|
3840
|
+
if (jsonOutput) {
|
|
3841
|
+
output(statuses);
|
|
3842
|
+
} else {
|
|
3843
|
+
if (statuses.length === 0) {
|
|
3844
|
+
console.log("No tunnels configured.");
|
|
3845
|
+
console.log("");
|
|
3846
|
+
console.log("Get started by adding a tunnel:");
|
|
3847
|
+
console.log(' ssh-tunnels add --name "My Database" --host bastion.example.com --user root --localPort 5432 --remoteHost localhost --remotePort 5432 --enabled');
|
|
3848
|
+
console.log("");
|
|
3849
|
+
console.log(`Config file: ${getConfigPath()}`);
|
|
3850
|
+
return;
|
|
3851
|
+
}
|
|
3852
|
+
console.log(`Tunnels (config: ${getConfigPath()}):`);
|
|
3853
|
+
console.log("");
|
|
3854
|
+
for (const s of statuses) {
|
|
3855
|
+
const stateIcon = s.alive && s.portOpen ? "\u25CF" : "\u25CB";
|
|
3856
|
+
const stateText = s.alive && s.portOpen ? "running" : "stopped";
|
|
3857
|
+
const enabledText = s.enabled ? "enabled" : "disabled";
|
|
3858
|
+
console.log(` ${stateIcon} ${s.name} (${s.id})`);
|
|
3859
|
+
console.log(` State: ${stateText}, ${enabledText}`);
|
|
3860
|
+
console.log(` Local: localhost:${s.localPort}`);
|
|
3861
|
+
console.log(` Remote: ${s.remoteHost}:${s.remotePort} via ${s.host}`);
|
|
3862
|
+
if (s.pid) console.log(` PID: ${s.pid}`);
|
|
3863
|
+
if (s.enabled && !s.alive) {
|
|
3864
|
+
console.log(` Issue: Tunnel is enabled but not running. Check: ssh-tunnels logs ${s.id}`);
|
|
3865
|
+
}
|
|
3866
|
+
console.log("");
|
|
3867
|
+
}
|
|
3868
|
+
}
|
|
3869
|
+
});
|
|
3870
|
+
program2.command("add").description(
|
|
3871
|
+
`Add a new SSH tunnel to the config.
|
|
3872
|
+
|
|
3873
|
+
Creates a tunnel definition that forwards a local port through an SSH host
|
|
3874
|
+
to a remote host:port. The tunnel is saved to ~/.ssh-tunnels/config.json.
|
|
3875
|
+
|
|
3876
|
+
IMPORTANT: --user defaults to your current OS user ("${process.env.USER ?? "unknown"}").
|
|
3877
|
+
Many servers require "root" or a dedicated user. If the tunnel fails with
|
|
3878
|
+
"Permission denied (publickey)", try a different --user value.
|
|
3879
|
+
|
|
3880
|
+
The --remoteHost is resolved FROM the SSH host's perspective. Use "localhost"
|
|
3881
|
+
when the target service runs on the SSH host itself.
|
|
3882
|
+
|
|
3883
|
+
Examples:
|
|
3884
|
+
# PostgreSQL through a bastion (connect as root):
|
|
3885
|
+
ssh-tunnels add --name "Prod Postgres" --host bastion.example.com \\
|
|
3886
|
+
--user root --localPort 5433 --remoteHost db.internal --remotePort 5432 --enabled
|
|
3887
|
+
|
|
3888
|
+
# Web admin UI on a remote server (port 8089, service on the host itself):
|
|
3889
|
+
ssh-tunnels add --name "Admin Panel" --host admin.example.com \\
|
|
3890
|
+
--user root --localPort 8089 --remoteHost localhost --remotePort 8089 --enabled
|
|
3891
|
+
|
|
3892
|
+
# Redis on an internal network, non-default SSH port:
|
|
3893
|
+
ssh-tunnels add --name "Staging Redis" --host jump.example.com \\
|
|
3894
|
+
--user deploy --localPort 6380 --remoteHost redis.staging --remotePort 6379 \\
|
|
3895
|
+
--sshPort 2222 --identityFile ~/.ssh/staging_key --enabled
|
|
3896
|
+
|
|
3897
|
+
# Add without enabling (start later with "ssh-tunnels enable <id>"):
|
|
3898
|
+
ssh-tunnels add --name "Dev Server" --host dev.example.com \\
|
|
3899
|
+
--user ray --localPort 3000 --remoteHost localhost --remotePort 3000
|
|
3900
|
+
|
|
3901
|
+
Common port reference:
|
|
3902
|
+
5432=PostgreSQL 3306=MySQL 6379=Redis 27017=MongoDB
|
|
3903
|
+
80/443=HTTP(S) 8080=Dev server 8089=Splunk 18789=OpenClaw admin`
|
|
3904
|
+
).requiredOption("--name <name>", "Display name for the tunnel (used to generate the ID)").requiredOption("--host <host>", "SSH host to connect through (IP or hostname)").requiredOption("--localPort <port>", "Port on your machine to listen on", parseInt).requiredOption("--remoteHost <host>", `Target host from the SSH server's perspective (often "localhost")`).requiredOption("--remotePort <port>", "Target port on the remote host", parseInt).option("--user <user>", `SSH username (default: "${process.env.USER ?? ""}" \u2014 many servers need "root")`, process.env.USER ?? "").option("--identityFile <path>", "Path to SSH private key (e.g., ~/.ssh/id_ed25519)").option("--sshPort <port>", "SSH port if not 22", parseInt).option("--enabled", "Enable and start the tunnel immediately", false).action(async (opts) => {
|
|
3905
|
+
const config = await readConfig();
|
|
3906
|
+
const id = slugify(opts.name);
|
|
3907
|
+
if (config.tunnels.some((t) => t.id === id)) {
|
|
3908
|
+
console.error(`Error: Tunnel with id '${id}' already exists.`);
|
|
3909
|
+
console.error(` To update it, remove it first: ssh-tunnels remove ${id}`);
|
|
3910
|
+
console.error(` To see existing tunnels: ssh-tunnels status`);
|
|
3911
|
+
process.exit(1);
|
|
3912
|
+
}
|
|
3913
|
+
if (opts.localPort < 1 || opts.localPort > 65535) {
|
|
3914
|
+
console.error(`Error: --localPort must be between 1 and 65535 (got ${opts.localPort}).`);
|
|
3915
|
+
process.exit(1);
|
|
3916
|
+
}
|
|
3917
|
+
if (opts.remotePort < 1 || opts.remotePort > 65535) {
|
|
3918
|
+
console.error(`Error: --remotePort must be between 1 and 65535 (got ${opts.remotePort}).`);
|
|
3919
|
+
process.exit(1);
|
|
3920
|
+
}
|
|
3921
|
+
const tunnel = {
|
|
3922
|
+
id,
|
|
3923
|
+
name: opts.name,
|
|
3924
|
+
host: opts.host,
|
|
3925
|
+
user: opts.user,
|
|
3926
|
+
localPort: opts.localPort,
|
|
3927
|
+
remoteHost: opts.remoteHost,
|
|
3928
|
+
remotePort: opts.remotePort,
|
|
3929
|
+
enabled: opts.enabled ?? false,
|
|
3930
|
+
...opts.identityFile && { identityFile: opts.identityFile },
|
|
3931
|
+
...opts.sshPort && { sshPort: opts.sshPort },
|
|
3932
|
+
extraArgs: []
|
|
3933
|
+
};
|
|
3934
|
+
config.tunnels.push(tunnel);
|
|
3935
|
+
await writeConfig(config);
|
|
3936
|
+
if (jsonOutput) {
|
|
3937
|
+
const result = tunnel.enabled ? await sync(config) : null;
|
|
3938
|
+
if (tunnel.enabled) await new Promise((r) => setTimeout(r, 2500));
|
|
3939
|
+
const statuses = await getStatus(config);
|
|
3940
|
+
const status = statuses.find((s) => s.id === id);
|
|
3941
|
+
output({
|
|
3942
|
+
action: "added",
|
|
3943
|
+
tunnel,
|
|
3944
|
+
sync: result,
|
|
3945
|
+
status: status ?? null,
|
|
3946
|
+
healthy: status ? status.alive && status.portOpen : null,
|
|
3947
|
+
logFile: getLogFilePath(id),
|
|
3948
|
+
configFile: getConfigPath()
|
|
3949
|
+
});
|
|
3950
|
+
} else {
|
|
3951
|
+
console.log(`Added tunnel '${tunnel.name}' (${tunnel.id})`);
|
|
3952
|
+
console.log(` SSH: ${tunnel.user}@${tunnel.host}${tunnel.sshPort ? `:${tunnel.sshPort}` : ""}`);
|
|
3953
|
+
console.log(` Forward: localhost:${tunnel.localPort} \u2192 ${tunnel.remoteHost}:${tunnel.remotePort}`);
|
|
3954
|
+
console.log(` Enabled: ${tunnel.enabled}`);
|
|
3955
|
+
console.log(` Config: ${getConfigPath()}`);
|
|
3956
|
+
console.log(` Logs: ${getLogFilePath(id)}`);
|
|
3957
|
+
if (tunnel.enabled) {
|
|
3958
|
+
console.log("");
|
|
3959
|
+
console.log("Starting tunnel...");
|
|
3960
|
+
const result = await sync(config);
|
|
3961
|
+
if (result.started.length) {
|
|
3962
|
+
console.log(`SSH process spawned for: ${result.started.join(", ")}`);
|
|
3963
|
+
}
|
|
3964
|
+
if (result.errors.length) {
|
|
3965
|
+
for (const e of result.errors) {
|
|
3966
|
+
console.error(`Error starting ${e.id}: ${e.error}`);
|
|
3967
|
+
}
|
|
3968
|
+
}
|
|
3969
|
+
await verboseStatusCheck(id, true);
|
|
3970
|
+
} else {
|
|
3971
|
+
console.log("");
|
|
3972
|
+
console.log(`Tunnel saved but not started. To start it:`);
|
|
3973
|
+
console.log(` ssh-tunnels enable ${id}`);
|
|
3974
|
+
}
|
|
3975
|
+
}
|
|
3976
|
+
});
|
|
3977
|
+
program2.command("remove <id>").description(
|
|
3978
|
+
`Remove a tunnel from the config and stop it if running.
|
|
3979
|
+
|
|
3980
|
+
The tunnel definition is deleted from ~/.ssh-tunnels/config.json and any
|
|
3981
|
+
running SSH process for it is terminated.
|
|
3982
|
+
|
|
3983
|
+
To find the tunnel ID, run: ssh-tunnels status
|
|
3984
|
+
|
|
3985
|
+
Examples:
|
|
3986
|
+
ssh-tunnels remove my-database
|
|
3987
|
+
ssh-tunnels remove prod-postgres`
|
|
3988
|
+
).action(async (id) => {
|
|
3989
|
+
const config = await readConfig();
|
|
3990
|
+
const idx = config.tunnels.findIndex((t) => t.id === id);
|
|
3991
|
+
if (idx === -1) {
|
|
3992
|
+
console.error(`Error: Tunnel '${id}' not found.`);
|
|
3993
|
+
console.error("");
|
|
3994
|
+
console.error("Available tunnels:");
|
|
3995
|
+
for (const t of config.tunnels) {
|
|
3996
|
+
console.error(` - ${t.id} (${t.name})`);
|
|
3997
|
+
}
|
|
3998
|
+
if (config.tunnels.length === 0) {
|
|
3999
|
+
console.error(" (none configured)");
|
|
4000
|
+
}
|
|
4001
|
+
process.exit(1);
|
|
4002
|
+
}
|
|
4003
|
+
const [removed] = config.tunnels.splice(idx, 1);
|
|
4004
|
+
await writeConfig(config);
|
|
4005
|
+
const { stopTunnel: stopTunnel2 } = await Promise.resolve().then(() => (init_core(), core_exports));
|
|
4006
|
+
await stopTunnel2(id);
|
|
4007
|
+
if (jsonOutput) {
|
|
4008
|
+
output({ action: "removed", tunnel: removed, configFile: getConfigPath() });
|
|
4009
|
+
} else {
|
|
4010
|
+
console.log(`Removed tunnel '${removed.name}' (${id})`);
|
|
4011
|
+
console.log(` SSH process stopped (if it was running).`);
|
|
4012
|
+
console.log(` Config updated: ${getConfigPath()}`);
|
|
4013
|
+
}
|
|
4014
|
+
});
|
|
4015
|
+
program2.command("enable <id>").description(
|
|
4016
|
+
`Enable a tunnel and start it.
|
|
4017
|
+
|
|
4018
|
+
Sets enabled=true in the config and immediately starts the SSH process.
|
|
4019
|
+
After starting, verifies the tunnel is healthy (process alive + port open).
|
|
4020
|
+
|
|
4021
|
+
Examples:
|
|
4022
|
+
ssh-tunnels enable my-database
|
|
4023
|
+
ssh-tunnels enable prod-postgres --json`
|
|
4024
|
+
).action(async (id) => {
|
|
4025
|
+
const config = await readConfig();
|
|
4026
|
+
const tunnel = config.tunnels.find((t) => t.id === id);
|
|
4027
|
+
if (!tunnel) {
|
|
4028
|
+
console.error(`Error: Tunnel '${id}' not found.`);
|
|
4029
|
+
console.error("");
|
|
4030
|
+
console.error("Available tunnels:");
|
|
4031
|
+
for (const t of config.tunnels) {
|
|
4032
|
+
console.error(` - ${t.id} (${t.name}) [${t.enabled ? "enabled" : "disabled"}]`);
|
|
4033
|
+
}
|
|
4034
|
+
process.exit(1);
|
|
4035
|
+
}
|
|
4036
|
+
if (tunnel.enabled) {
|
|
4037
|
+
console.log(`Tunnel '${tunnel.name}' (${id}) is already enabled. Running sync...`);
|
|
4038
|
+
}
|
|
4039
|
+
tunnel.enabled = true;
|
|
4040
|
+
await writeConfig(config);
|
|
4041
|
+
const result = await sync(config);
|
|
4042
|
+
if (jsonOutput) {
|
|
4043
|
+
await new Promise((r) => setTimeout(r, 2500));
|
|
4044
|
+
const statuses = await getStatus(config);
|
|
4045
|
+
const status = statuses.find((s) => s.id === id);
|
|
4046
|
+
output({
|
|
4047
|
+
action: "enabled",
|
|
4048
|
+
id,
|
|
4049
|
+
tunnel: { name: tunnel.name, host: tunnel.host, user: tunnel.user, localPort: tunnel.localPort, remoteHost: tunnel.remoteHost, remotePort: tunnel.remotePort },
|
|
4050
|
+
sync: result,
|
|
4051
|
+
status: status ?? null,
|
|
4052
|
+
healthy: status ? status.alive && status.portOpen : null,
|
|
4053
|
+
logFile: getLogFilePath(id)
|
|
4054
|
+
});
|
|
4055
|
+
} else {
|
|
4056
|
+
console.log(`Enabled tunnel '${tunnel.name}' (${id})`);
|
|
4057
|
+
console.log(` Forward: localhost:${tunnel.localPort} \u2192 ${tunnel.remoteHost}:${tunnel.remotePort} via ${tunnel.user}@${tunnel.host}`);
|
|
4058
|
+
if (result.started.length) console.log(` SSH process spawned.`);
|
|
4059
|
+
await verboseStatusCheck(id, true);
|
|
4060
|
+
}
|
|
4061
|
+
});
|
|
4062
|
+
program2.command("disable <id>").description(
|
|
4063
|
+
`Disable a tunnel and stop it.
|
|
4064
|
+
|
|
4065
|
+
Sets enabled=false in the config and terminates the SSH process (SIGTERM,
|
|
4066
|
+
then SIGKILL if needed).
|
|
4067
|
+
|
|
4068
|
+
Examples:
|
|
4069
|
+
ssh-tunnels disable my-database
|
|
4070
|
+
ssh-tunnels disable prod-postgres --json`
|
|
4071
|
+
).action(async (id) => {
|
|
4072
|
+
const config = await readConfig();
|
|
4073
|
+
const tunnel = config.tunnels.find((t) => t.id === id);
|
|
4074
|
+
if (!tunnel) {
|
|
4075
|
+
console.error(`Error: Tunnel '${id}' not found.`);
|
|
4076
|
+
console.error("");
|
|
4077
|
+
console.error("Available tunnels:");
|
|
4078
|
+
for (const t of config.tunnels) {
|
|
4079
|
+
console.error(` - ${t.id} (${t.name}) [${t.enabled ? "enabled" : "disabled"}]`);
|
|
4080
|
+
}
|
|
4081
|
+
process.exit(1);
|
|
4082
|
+
}
|
|
4083
|
+
tunnel.enabled = false;
|
|
4084
|
+
await writeConfig(config);
|
|
4085
|
+
const result = await sync(config);
|
|
4086
|
+
if (jsonOutput) {
|
|
4087
|
+
output({ action: "disabled", id, tunnel: { name: tunnel.name }, sync: result });
|
|
4088
|
+
} else {
|
|
4089
|
+
console.log(`Disabled tunnel '${tunnel.name}' (${id})`);
|
|
4090
|
+
if (result.stopped.length) {
|
|
4091
|
+
console.log(` SSH process terminated.`);
|
|
4092
|
+
console.log(` Port ${tunnel.localPort} is now free.`);
|
|
4093
|
+
} else {
|
|
4094
|
+
console.log(` (tunnel was already stopped)`);
|
|
4095
|
+
}
|
|
4096
|
+
}
|
|
4097
|
+
});
|
|
4098
|
+
program2.command("watch").description(
|
|
4099
|
+
`Watch the config file and auto-sync on changes.
|
|
4100
|
+
|
|
4101
|
+
Performs an initial sync, then monitors ~/.ssh-tunnels/config.json for
|
|
4102
|
+
changes. When the config is modified (by the CLI, the Electron app, or
|
|
4103
|
+
a text editor), tunnels are automatically started/stopped to match.
|
|
4104
|
+
|
|
4105
|
+
This is useful for keeping tunnels in sync when editing config.json
|
|
4106
|
+
directly or when the Electron app modifies the config.
|
|
4107
|
+
|
|
4108
|
+
Examples:
|
|
4109
|
+
ssh-tunnels watch # Run in foreground (Ctrl+C to stop)`
|
|
4110
|
+
).action(async () => {
|
|
4111
|
+
console.log(`Watching for config changes: ${getConfigPath()}`);
|
|
4112
|
+
console.log("Press Ctrl+C to stop.\n");
|
|
4113
|
+
const initial = await sync();
|
|
4114
|
+
if (initial.started.length) console.log(`Initial sync \u2014 started: ${initial.started.join(", ")}`);
|
|
4115
|
+
if (initial.stopped.length) console.log(`Initial sync \u2014 stopped: ${initial.stopped.join(", ")}`);
|
|
4116
|
+
if (!initial.started.length && !initial.stopped.length) console.log("Initial sync \u2014 everything in sync.");
|
|
4117
|
+
console.log("");
|
|
4118
|
+
const watcher = watchConfig({
|
|
4119
|
+
onSync: (result) => {
|
|
4120
|
+
const ts = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
4121
|
+
if (result.started.length) console.log(`[${ts}] Started: ${result.started.join(", ")}`);
|
|
4122
|
+
if (result.stopped.length) console.log(`[${ts}] Stopped: ${result.stopped.join(", ")}`);
|
|
4123
|
+
if (result.errors.length) {
|
|
4124
|
+
for (const e of result.errors) console.error(`[${ts}] Error [${e.id}]: ${e.error}`);
|
|
4125
|
+
}
|
|
4126
|
+
if (!result.started.length && !result.stopped.length && !result.errors.length) {
|
|
4127
|
+
console.log(`[${ts}] Config changed \u2014 no tunnel changes needed.`);
|
|
4128
|
+
}
|
|
4129
|
+
},
|
|
4130
|
+
onError: (err) => {
|
|
4131
|
+
console.error(`Watch error: ${err.message}`);
|
|
4132
|
+
}
|
|
4133
|
+
});
|
|
4134
|
+
const shutdown = async () => {
|
|
4135
|
+
console.log("\nShutting down watcher...");
|
|
4136
|
+
await watcher.close();
|
|
4137
|
+
process.exit(0);
|
|
4138
|
+
};
|
|
4139
|
+
process.on("SIGINT", shutdown);
|
|
4140
|
+
process.on("SIGTERM", shutdown);
|
|
4141
|
+
});
|
|
4142
|
+
program2.command("logs <id>").description(
|
|
4143
|
+
`Show log output for a tunnel.
|
|
4144
|
+
|
|
4145
|
+
Displays the SSH process output for the given tunnel. This is the first
|
|
4146
|
+
place to look when a tunnel fails to connect.
|
|
4147
|
+
|
|
4148
|
+
Common log messages and what they mean:
|
|
4149
|
+
"Permission denied (publickey)"
|
|
4150
|
+
\u2192 Wrong SSH username or key not authorized. Try --user root.
|
|
4151
|
+
"Connection refused"
|
|
4152
|
+
\u2192 SSH server not running or wrong port.
|
|
4153
|
+
"Connection timed out"
|
|
4154
|
+
\u2192 Host unreachable, firewall blocking, or wrong hostname.
|
|
4155
|
+
"Host key verification failed"
|
|
4156
|
+
\u2192 First connection to host; remove old key or set StrictHostKeyChecking.
|
|
4157
|
+
"bind: Address already in use"
|
|
4158
|
+
\u2192 Another process is using the local port. Check with lsof -i :<port>.
|
|
4159
|
+
|
|
4160
|
+
Examples:
|
|
4161
|
+
ssh-tunnels logs my-database # Show full log
|
|
4162
|
+
ssh-tunnels logs my-database -f # Follow (tail -f) the log`
|
|
4163
|
+
).option("-f, --follow", "Follow log output in real-time").action(async (id, opts) => {
|
|
4164
|
+
const config = await readConfig();
|
|
4165
|
+
const tunnel = config.tunnels.find((t) => t.id === id);
|
|
4166
|
+
if (!tunnel) {
|
|
4167
|
+
console.error(`Error: Tunnel '${id}' not found.`);
|
|
4168
|
+
console.error("");
|
|
4169
|
+
console.error("Available tunnels:");
|
|
4170
|
+
for (const t of config.tunnels) {
|
|
4171
|
+
console.error(` - ${t.id} (${t.name})`);
|
|
4172
|
+
}
|
|
4173
|
+
process.exit(1);
|
|
4174
|
+
}
|
|
4175
|
+
const logPath = getLogFilePath(id);
|
|
4176
|
+
console.log(`Log file: ${logPath}`);
|
|
4177
|
+
console.log(`Tunnel: ${tunnel.name} (${tunnel.user}@${tunnel.host} \u2192 ${tunnel.remoteHost}:${tunnel.remotePort})`);
|
|
4178
|
+
console.log("---");
|
|
4179
|
+
if (opts.follow) {
|
|
4180
|
+
const child = spawn2("tail", ["-f", logPath], { stdio: "inherit" });
|
|
4181
|
+
child.on("error", () => {
|
|
4182
|
+
console.error(`No logs found for tunnel '${id}'. The tunnel may not have been started yet.`);
|
|
4183
|
+
console.error(` Try: ssh-tunnels enable ${id}`);
|
|
4184
|
+
});
|
|
4185
|
+
} else {
|
|
4186
|
+
const stream = createReadStream(logPath, "utf-8");
|
|
4187
|
+
stream.on("error", () => {
|
|
4188
|
+
console.error(`No logs found for tunnel '${id}'. The tunnel may not have been started yet.`);
|
|
4189
|
+
console.error(` Try: ssh-tunnels enable ${id}`);
|
|
4190
|
+
});
|
|
4191
|
+
stream.pipe(process.stdout);
|
|
4192
|
+
}
|
|
4193
|
+
});
|
|
4194
|
+
program2.parse();
|