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