oche-cli 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +40 -2
- package/dist/index.js +4825 -0
- package/package.json +37 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,4825 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// node_modules/commander/lib/error.js
|
|
4
|
+
var CommanderError = class extends Error {
|
|
5
|
+
/**
|
|
6
|
+
* Constructs the CommanderError class
|
|
7
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
8
|
+
* @param {string} code an id string representing the error
|
|
9
|
+
* @param {string} message human-readable description of the error
|
|
10
|
+
*/
|
|
11
|
+
constructor(exitCode, code, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
Error.captureStackTrace(this, this.constructor);
|
|
14
|
+
this.name = this.constructor.name;
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.exitCode = exitCode;
|
|
17
|
+
this.nestedError = void 0;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
21
|
+
/**
|
|
22
|
+
* Constructs the InvalidArgumentError class
|
|
23
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
24
|
+
*/
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(1, "commander.invalidArgument", message);
|
|
27
|
+
Error.captureStackTrace(this, this.constructor);
|
|
28
|
+
this.name = this.constructor.name;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// node_modules/commander/lib/argument.js
|
|
33
|
+
var Argument = class {
|
|
34
|
+
/**
|
|
35
|
+
* Initialize a new command argument with the given name and description.
|
|
36
|
+
* The default is that the argument is required, and you can explicitly
|
|
37
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
38
|
+
*
|
|
39
|
+
* @param {string} name
|
|
40
|
+
* @param {string} [description]
|
|
41
|
+
*/
|
|
42
|
+
constructor(name, description) {
|
|
43
|
+
this.description = description || "";
|
|
44
|
+
this.variadic = false;
|
|
45
|
+
this.parseArg = void 0;
|
|
46
|
+
this.defaultValue = void 0;
|
|
47
|
+
this.defaultValueDescription = void 0;
|
|
48
|
+
this.argChoices = void 0;
|
|
49
|
+
switch (name[0]) {
|
|
50
|
+
case "<":
|
|
51
|
+
this.required = true;
|
|
52
|
+
this._name = name.slice(1, -1);
|
|
53
|
+
break;
|
|
54
|
+
case "[":
|
|
55
|
+
this.required = false;
|
|
56
|
+
this._name = name.slice(1, -1);
|
|
57
|
+
break;
|
|
58
|
+
default:
|
|
59
|
+
this.required = true;
|
|
60
|
+
this._name = name;
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
if (this._name.endsWith("...")) {
|
|
64
|
+
this.variadic = true;
|
|
65
|
+
this._name = this._name.slice(0, -3);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Return argument name.
|
|
70
|
+
*
|
|
71
|
+
* @return {string}
|
|
72
|
+
*/
|
|
73
|
+
name() {
|
|
74
|
+
return this._name;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* @package
|
|
78
|
+
*/
|
|
79
|
+
_collectValue(value, previous) {
|
|
80
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
81
|
+
return [value];
|
|
82
|
+
}
|
|
83
|
+
previous.push(value);
|
|
84
|
+
return previous;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
88
|
+
*
|
|
89
|
+
* @param {*} value
|
|
90
|
+
* @param {string} [description]
|
|
91
|
+
* @return {Argument}
|
|
92
|
+
*/
|
|
93
|
+
default(value, description) {
|
|
94
|
+
this.defaultValue = value;
|
|
95
|
+
this.defaultValueDescription = description;
|
|
96
|
+
return this;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
100
|
+
*
|
|
101
|
+
* @param {Function} [fn]
|
|
102
|
+
* @return {Argument}
|
|
103
|
+
*/
|
|
104
|
+
argParser(fn) {
|
|
105
|
+
this.parseArg = fn;
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Only allow argument value to be one of choices.
|
|
110
|
+
*
|
|
111
|
+
* @param {string[]} values
|
|
112
|
+
* @return {Argument}
|
|
113
|
+
*/
|
|
114
|
+
choices(values) {
|
|
115
|
+
this.argChoices = values.slice();
|
|
116
|
+
this.parseArg = (arg, previous) => {
|
|
117
|
+
if (!this.argChoices.includes(arg)) {
|
|
118
|
+
throw new InvalidArgumentError(
|
|
119
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
if (this.variadic) {
|
|
123
|
+
return this._collectValue(arg, previous);
|
|
124
|
+
}
|
|
125
|
+
return arg;
|
|
126
|
+
};
|
|
127
|
+
return this;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Make argument required.
|
|
131
|
+
*
|
|
132
|
+
* @returns {Argument}
|
|
133
|
+
*/
|
|
134
|
+
argRequired() {
|
|
135
|
+
this.required = true;
|
|
136
|
+
return this;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Make argument optional.
|
|
140
|
+
*
|
|
141
|
+
* @returns {Argument}
|
|
142
|
+
*/
|
|
143
|
+
argOptional() {
|
|
144
|
+
this.required = false;
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
function humanReadableArgName(arg) {
|
|
149
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
150
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// node_modules/commander/lib/command.js
|
|
154
|
+
import { EventEmitter } from "events";
|
|
155
|
+
import childProcess from "child_process";
|
|
156
|
+
import path from "path";
|
|
157
|
+
import fs from "fs";
|
|
158
|
+
import process2 from "process";
|
|
159
|
+
import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
|
|
160
|
+
|
|
161
|
+
// node_modules/commander/lib/help.js
|
|
162
|
+
import { stripVTControlCharacters } from "util";
|
|
163
|
+
var Help = class {
|
|
164
|
+
constructor() {
|
|
165
|
+
this.helpWidth = void 0;
|
|
166
|
+
this.minWidthToWrap = 40;
|
|
167
|
+
this.sortSubcommands = false;
|
|
168
|
+
this.sortOptions = false;
|
|
169
|
+
this.showGlobalOptions = false;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
173
|
+
* and just before calling `formatHelp()`.
|
|
174
|
+
*
|
|
175
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
176
|
+
*
|
|
177
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
178
|
+
*/
|
|
179
|
+
prepareContext(contextOptions) {
|
|
180
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
184
|
+
*
|
|
185
|
+
* @param {Command} cmd
|
|
186
|
+
* @returns {Command[]}
|
|
187
|
+
*/
|
|
188
|
+
visibleCommands(cmd) {
|
|
189
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
190
|
+
const helpCommand = cmd._getHelpCommand();
|
|
191
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
192
|
+
visibleCommands.push(helpCommand);
|
|
193
|
+
}
|
|
194
|
+
if (this.sortSubcommands) {
|
|
195
|
+
visibleCommands.sort((a, b) => {
|
|
196
|
+
return a.name().localeCompare(b.name());
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return visibleCommands;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Compare options for sort.
|
|
203
|
+
*
|
|
204
|
+
* @param {Option} a
|
|
205
|
+
* @param {Option} b
|
|
206
|
+
* @returns {number}
|
|
207
|
+
*/
|
|
208
|
+
compareOptions(a, b) {
|
|
209
|
+
const getSortKey = (option) => {
|
|
210
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
211
|
+
};
|
|
212
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
216
|
+
*
|
|
217
|
+
* @param {Command} cmd
|
|
218
|
+
* @returns {Option[]}
|
|
219
|
+
*/
|
|
220
|
+
visibleOptions(cmd) {
|
|
221
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
222
|
+
const helpOption = cmd._getHelpOption();
|
|
223
|
+
if (helpOption && !helpOption.hidden) {
|
|
224
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
225
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
226
|
+
if (!removeShort && !removeLong) {
|
|
227
|
+
visibleOptions.push(helpOption);
|
|
228
|
+
} else if (helpOption.long && !removeLong) {
|
|
229
|
+
visibleOptions.push(
|
|
230
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
231
|
+
);
|
|
232
|
+
} else if (helpOption.short && !removeShort) {
|
|
233
|
+
visibleOptions.push(
|
|
234
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (this.sortOptions) {
|
|
239
|
+
visibleOptions.sort(this.compareOptions);
|
|
240
|
+
}
|
|
241
|
+
return visibleOptions;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Get an array of the visible global options. (Not including help.)
|
|
245
|
+
*
|
|
246
|
+
* @param {Command} cmd
|
|
247
|
+
* @returns {Option[]}
|
|
248
|
+
*/
|
|
249
|
+
visibleGlobalOptions(cmd) {
|
|
250
|
+
if (!this.showGlobalOptions) return [];
|
|
251
|
+
const globalOptions = [];
|
|
252
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
253
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
254
|
+
(option) => !option.hidden
|
|
255
|
+
);
|
|
256
|
+
globalOptions.push(...visibleOptions);
|
|
257
|
+
}
|
|
258
|
+
if (this.sortOptions) {
|
|
259
|
+
globalOptions.sort(this.compareOptions);
|
|
260
|
+
}
|
|
261
|
+
return globalOptions;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get an array of the arguments if any have a description.
|
|
265
|
+
*
|
|
266
|
+
* @param {Command} cmd
|
|
267
|
+
* @returns {Argument[]}
|
|
268
|
+
*/
|
|
269
|
+
visibleArguments(cmd) {
|
|
270
|
+
if (cmd._argsDescription) {
|
|
271
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
272
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
276
|
+
return cmd.registeredArguments;
|
|
277
|
+
}
|
|
278
|
+
return [];
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Get the command term to show in the list of subcommands.
|
|
282
|
+
*
|
|
283
|
+
* @param {Command} cmd
|
|
284
|
+
* @returns {string}
|
|
285
|
+
*/
|
|
286
|
+
subcommandTerm(cmd) {
|
|
287
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
288
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
289
|
+
(args ? " " + args : "");
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Get the option term to show in the list of options.
|
|
293
|
+
*
|
|
294
|
+
* @param {Option} option
|
|
295
|
+
* @returns {string}
|
|
296
|
+
*/
|
|
297
|
+
optionTerm(option) {
|
|
298
|
+
return option.flags;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Get the argument term to show in the list of arguments.
|
|
302
|
+
*
|
|
303
|
+
* @param {Argument} argument
|
|
304
|
+
* @returns {string}
|
|
305
|
+
*/
|
|
306
|
+
argumentTerm(argument) {
|
|
307
|
+
return argument.name();
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Get the longest command term length.
|
|
311
|
+
*
|
|
312
|
+
* @param {Command} cmd
|
|
313
|
+
* @param {Help} helper
|
|
314
|
+
* @returns {number}
|
|
315
|
+
*/
|
|
316
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
317
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
318
|
+
return Math.max(
|
|
319
|
+
max,
|
|
320
|
+
this.displayWidth(
|
|
321
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
322
|
+
)
|
|
323
|
+
);
|
|
324
|
+
}, 0);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Get the longest option term length.
|
|
328
|
+
*
|
|
329
|
+
* @param {Command} cmd
|
|
330
|
+
* @param {Help} helper
|
|
331
|
+
* @returns {number}
|
|
332
|
+
*/
|
|
333
|
+
longestOptionTermLength(cmd, helper) {
|
|
334
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
335
|
+
return Math.max(
|
|
336
|
+
max,
|
|
337
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
338
|
+
);
|
|
339
|
+
}, 0);
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Get the longest global option term length.
|
|
343
|
+
*
|
|
344
|
+
* @param {Command} cmd
|
|
345
|
+
* @param {Help} helper
|
|
346
|
+
* @returns {number}
|
|
347
|
+
*/
|
|
348
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
349
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
350
|
+
return Math.max(
|
|
351
|
+
max,
|
|
352
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
353
|
+
);
|
|
354
|
+
}, 0);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Get the longest argument term length.
|
|
358
|
+
*
|
|
359
|
+
* @param {Command} cmd
|
|
360
|
+
* @param {Help} helper
|
|
361
|
+
* @returns {number}
|
|
362
|
+
*/
|
|
363
|
+
longestArgumentTermLength(cmd, helper) {
|
|
364
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
365
|
+
return Math.max(
|
|
366
|
+
max,
|
|
367
|
+
this.displayWidth(
|
|
368
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
369
|
+
)
|
|
370
|
+
);
|
|
371
|
+
}, 0);
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
375
|
+
*
|
|
376
|
+
* @param {Command} cmd
|
|
377
|
+
* @returns {string}
|
|
378
|
+
*/
|
|
379
|
+
commandUsage(cmd) {
|
|
380
|
+
let cmdName = cmd._name;
|
|
381
|
+
if (cmd._aliases[0]) {
|
|
382
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
383
|
+
}
|
|
384
|
+
let ancestorCmdNames = "";
|
|
385
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
386
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
387
|
+
}
|
|
388
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Get the description for the command.
|
|
392
|
+
*
|
|
393
|
+
* @param {Command} cmd
|
|
394
|
+
* @returns {string}
|
|
395
|
+
*/
|
|
396
|
+
commandDescription(cmd) {
|
|
397
|
+
return cmd.description();
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
401
|
+
* (Fallback to description for backwards compatibility.)
|
|
402
|
+
*
|
|
403
|
+
* @param {Command} cmd
|
|
404
|
+
* @returns {string}
|
|
405
|
+
*/
|
|
406
|
+
subcommandDescription(cmd) {
|
|
407
|
+
return cmd.summary() || cmd.description();
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Get the option description to show in the list of options.
|
|
411
|
+
*
|
|
412
|
+
* @param {Option} option
|
|
413
|
+
* @return {string}
|
|
414
|
+
*/
|
|
415
|
+
optionDescription(option) {
|
|
416
|
+
const extraInfo = [];
|
|
417
|
+
if (option.argChoices) {
|
|
418
|
+
extraInfo.push(
|
|
419
|
+
// use stringify to match the display of the default value
|
|
420
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
if (option.defaultValue !== void 0) {
|
|
424
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
425
|
+
if (showDefault) {
|
|
426
|
+
extraInfo.push(
|
|
427
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
432
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
433
|
+
}
|
|
434
|
+
if (option.envVar !== void 0) {
|
|
435
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
436
|
+
}
|
|
437
|
+
if (extraInfo.length > 0) {
|
|
438
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
439
|
+
if (option.description) {
|
|
440
|
+
return `${option.description} ${extraDescription}`;
|
|
441
|
+
}
|
|
442
|
+
return extraDescription;
|
|
443
|
+
}
|
|
444
|
+
return option.description;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Get the argument description to show in the list of arguments.
|
|
448
|
+
*
|
|
449
|
+
* @param {Argument} argument
|
|
450
|
+
* @return {string}
|
|
451
|
+
*/
|
|
452
|
+
argumentDescription(argument) {
|
|
453
|
+
const extraInfo = [];
|
|
454
|
+
if (argument.argChoices) {
|
|
455
|
+
extraInfo.push(
|
|
456
|
+
// use stringify to match the display of the default value
|
|
457
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
if (argument.defaultValue !== void 0) {
|
|
461
|
+
extraInfo.push(
|
|
462
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
if (extraInfo.length > 0) {
|
|
466
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
467
|
+
if (argument.description) {
|
|
468
|
+
return `${argument.description} ${extraDescription}`;
|
|
469
|
+
}
|
|
470
|
+
return extraDescription;
|
|
471
|
+
}
|
|
472
|
+
return argument.description;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
476
|
+
*
|
|
477
|
+
* @param {string} heading
|
|
478
|
+
* @param {string[]} items
|
|
479
|
+
* @param {Help} helper
|
|
480
|
+
* @returns string[]
|
|
481
|
+
*/
|
|
482
|
+
formatItemList(heading, items, helper) {
|
|
483
|
+
if (items.length === 0) return [];
|
|
484
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Group items by their help group heading.
|
|
488
|
+
*
|
|
489
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
490
|
+
* @param {Command[] | Option[]} visibleItems
|
|
491
|
+
* @param {Function} getGroup
|
|
492
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
493
|
+
*/
|
|
494
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
495
|
+
const result = /* @__PURE__ */ new Map();
|
|
496
|
+
unsortedItems.forEach((item) => {
|
|
497
|
+
const group = getGroup(item);
|
|
498
|
+
if (!result.has(group)) result.set(group, []);
|
|
499
|
+
});
|
|
500
|
+
visibleItems.forEach((item) => {
|
|
501
|
+
const group = getGroup(item);
|
|
502
|
+
if (!result.has(group)) {
|
|
503
|
+
result.set(group, []);
|
|
504
|
+
}
|
|
505
|
+
result.get(group).push(item);
|
|
506
|
+
});
|
|
507
|
+
return result;
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Generate the built-in help text.
|
|
511
|
+
*
|
|
512
|
+
* @param {Command} cmd
|
|
513
|
+
* @param {Help} helper
|
|
514
|
+
* @returns {string}
|
|
515
|
+
*/
|
|
516
|
+
formatHelp(cmd, helper) {
|
|
517
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
518
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
519
|
+
function callFormatItem(term, description) {
|
|
520
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
521
|
+
}
|
|
522
|
+
let output = [
|
|
523
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
524
|
+
""
|
|
525
|
+
];
|
|
526
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
527
|
+
if (commandDescription.length > 0) {
|
|
528
|
+
output = output.concat([
|
|
529
|
+
helper.boxWrap(
|
|
530
|
+
helper.styleCommandDescription(commandDescription),
|
|
531
|
+
helpWidth
|
|
532
|
+
),
|
|
533
|
+
""
|
|
534
|
+
]);
|
|
535
|
+
}
|
|
536
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
537
|
+
return callFormatItem(
|
|
538
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
539
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
540
|
+
);
|
|
541
|
+
});
|
|
542
|
+
output = output.concat(
|
|
543
|
+
this.formatItemList("Arguments:", argumentList, helper)
|
|
544
|
+
);
|
|
545
|
+
const optionGroups = this.groupItems(
|
|
546
|
+
cmd.options,
|
|
547
|
+
helper.visibleOptions(cmd),
|
|
548
|
+
(option) => option.helpGroupHeading ?? "Options:"
|
|
549
|
+
);
|
|
550
|
+
optionGroups.forEach((options, group) => {
|
|
551
|
+
const optionList = options.map((option) => {
|
|
552
|
+
return callFormatItem(
|
|
553
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
554
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
555
|
+
);
|
|
556
|
+
});
|
|
557
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
558
|
+
});
|
|
559
|
+
if (helper.showGlobalOptions) {
|
|
560
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
561
|
+
return callFormatItem(
|
|
562
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
563
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
564
|
+
);
|
|
565
|
+
});
|
|
566
|
+
output = output.concat(
|
|
567
|
+
this.formatItemList("Global Options:", globalOptionList, helper)
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
const commandGroups = this.groupItems(
|
|
571
|
+
cmd.commands,
|
|
572
|
+
helper.visibleCommands(cmd),
|
|
573
|
+
(sub) => sub.helpGroup() || "Commands:"
|
|
574
|
+
);
|
|
575
|
+
commandGroups.forEach((commands, group) => {
|
|
576
|
+
const commandList = commands.map((sub) => {
|
|
577
|
+
return callFormatItem(
|
|
578
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
|
|
579
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(sub))
|
|
580
|
+
);
|
|
581
|
+
});
|
|
582
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
583
|
+
});
|
|
584
|
+
return output.join("\n");
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
588
|
+
*
|
|
589
|
+
* @param {string} str
|
|
590
|
+
* @returns {number}
|
|
591
|
+
*/
|
|
592
|
+
displayWidth(str) {
|
|
593
|
+
return stripVTControlCharacters(str).length;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
597
|
+
*
|
|
598
|
+
* @param {string} str
|
|
599
|
+
* @returns {string}
|
|
600
|
+
*/
|
|
601
|
+
styleTitle(str) {
|
|
602
|
+
return str;
|
|
603
|
+
}
|
|
604
|
+
styleUsage(str) {
|
|
605
|
+
return str.split(" ").map((word) => {
|
|
606
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
607
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
608
|
+
if (word[0] === "[" || word[0] === "<")
|
|
609
|
+
return this.styleArgumentText(word);
|
|
610
|
+
return this.styleCommandText(word);
|
|
611
|
+
}).join(" ");
|
|
612
|
+
}
|
|
613
|
+
styleCommandDescription(str) {
|
|
614
|
+
return this.styleDescriptionText(str);
|
|
615
|
+
}
|
|
616
|
+
styleOptionDescription(str) {
|
|
617
|
+
return this.styleDescriptionText(str);
|
|
618
|
+
}
|
|
619
|
+
styleSubcommandDescription(str) {
|
|
620
|
+
return this.styleDescriptionText(str);
|
|
621
|
+
}
|
|
622
|
+
styleArgumentDescription(str) {
|
|
623
|
+
return this.styleDescriptionText(str);
|
|
624
|
+
}
|
|
625
|
+
styleDescriptionText(str) {
|
|
626
|
+
return str;
|
|
627
|
+
}
|
|
628
|
+
styleOptionTerm(str) {
|
|
629
|
+
return this.styleOptionText(str);
|
|
630
|
+
}
|
|
631
|
+
styleSubcommandTerm(str) {
|
|
632
|
+
return str.split(" ").map((word) => {
|
|
633
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
634
|
+
if (word[0] === "[" || word[0] === "<")
|
|
635
|
+
return this.styleArgumentText(word);
|
|
636
|
+
return this.styleSubcommandText(word);
|
|
637
|
+
}).join(" ");
|
|
638
|
+
}
|
|
639
|
+
styleArgumentTerm(str) {
|
|
640
|
+
return this.styleArgumentText(str);
|
|
641
|
+
}
|
|
642
|
+
styleOptionText(str) {
|
|
643
|
+
return str;
|
|
644
|
+
}
|
|
645
|
+
styleArgumentText(str) {
|
|
646
|
+
return str;
|
|
647
|
+
}
|
|
648
|
+
styleSubcommandText(str) {
|
|
649
|
+
return str;
|
|
650
|
+
}
|
|
651
|
+
styleCommandText(str) {
|
|
652
|
+
return str;
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Calculate the pad width from the maximum term length.
|
|
656
|
+
*
|
|
657
|
+
* @param {Command} cmd
|
|
658
|
+
* @param {Help} helper
|
|
659
|
+
* @returns {number}
|
|
660
|
+
*/
|
|
661
|
+
padWidth(cmd, helper) {
|
|
662
|
+
return Math.max(
|
|
663
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
664
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
665
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
666
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
671
|
+
*
|
|
672
|
+
* @param {string} str
|
|
673
|
+
* @returns {boolean}
|
|
674
|
+
*/
|
|
675
|
+
preformatted(str) {
|
|
676
|
+
return /\n[^\S\r\n]/.test(str);
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
680
|
+
*
|
|
681
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
682
|
+
* TTT DDD DDDD
|
|
683
|
+
* DD DDD
|
|
684
|
+
*
|
|
685
|
+
* @param {string} term
|
|
686
|
+
* @param {number} termWidth
|
|
687
|
+
* @param {string} description
|
|
688
|
+
* @param {Help} helper
|
|
689
|
+
* @returns {string}
|
|
690
|
+
*/
|
|
691
|
+
formatItem(term, termWidth, description, helper) {
|
|
692
|
+
const itemIndent = 2;
|
|
693
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
694
|
+
if (!description) return itemIndentStr + term;
|
|
695
|
+
const paddedTerm = term.padEnd(
|
|
696
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
697
|
+
);
|
|
698
|
+
const spacerWidth = 2;
|
|
699
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
700
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
701
|
+
let formattedDescription;
|
|
702
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
703
|
+
formattedDescription = description;
|
|
704
|
+
} else {
|
|
705
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
706
|
+
formattedDescription = wrappedDescription.replace(
|
|
707
|
+
/\n/g,
|
|
708
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
712
|
+
${itemIndentStr}`);
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
716
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
717
|
+
*
|
|
718
|
+
* @param {string} str
|
|
719
|
+
* @param {number} width
|
|
720
|
+
* @returns {string}
|
|
721
|
+
*/
|
|
722
|
+
boxWrap(str, width) {
|
|
723
|
+
if (width < this.minWidthToWrap) return str;
|
|
724
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
725
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
726
|
+
const wrappedLines = [];
|
|
727
|
+
rawLines.forEach((line) => {
|
|
728
|
+
const chunks = line.match(chunkPattern);
|
|
729
|
+
if (chunks === null) {
|
|
730
|
+
wrappedLines.push("");
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
let sumChunks = [chunks.shift()];
|
|
734
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
735
|
+
chunks.forEach((chunk) => {
|
|
736
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
737
|
+
if (sumWidth + visibleWidth <= width) {
|
|
738
|
+
sumChunks.push(chunk);
|
|
739
|
+
sumWidth += visibleWidth;
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
wrappedLines.push(sumChunks.join(""));
|
|
743
|
+
const nextChunk = chunk.trimStart();
|
|
744
|
+
sumChunks = [nextChunk];
|
|
745
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
746
|
+
});
|
|
747
|
+
wrappedLines.push(sumChunks.join(""));
|
|
748
|
+
});
|
|
749
|
+
return wrappedLines.join("\n");
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
// node_modules/commander/lib/option.js
|
|
754
|
+
var Option = class {
|
|
755
|
+
/**
|
|
756
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
757
|
+
*
|
|
758
|
+
* @param {string} flags
|
|
759
|
+
* @param {string} [description]
|
|
760
|
+
*/
|
|
761
|
+
constructor(flags, description) {
|
|
762
|
+
this.flags = flags;
|
|
763
|
+
this.description = description || "";
|
|
764
|
+
this.required = flags.includes("<");
|
|
765
|
+
this.optional = flags.includes("[");
|
|
766
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
767
|
+
this.mandatory = false;
|
|
768
|
+
const optionFlags = splitOptionFlags(flags);
|
|
769
|
+
this.short = optionFlags.shortFlag;
|
|
770
|
+
this.long = optionFlags.longFlag;
|
|
771
|
+
this.negate = false;
|
|
772
|
+
if (this.long) {
|
|
773
|
+
this.negate = this.long.startsWith("--no-");
|
|
774
|
+
}
|
|
775
|
+
this.defaultValue = void 0;
|
|
776
|
+
this.defaultValueDescription = void 0;
|
|
777
|
+
this.presetArg = void 0;
|
|
778
|
+
this.envVar = void 0;
|
|
779
|
+
this.parseArg = void 0;
|
|
780
|
+
this.hidden = false;
|
|
781
|
+
this.argChoices = void 0;
|
|
782
|
+
this.conflictsWith = [];
|
|
783
|
+
this.implied = void 0;
|
|
784
|
+
this.helpGroupHeading = void 0;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
788
|
+
*
|
|
789
|
+
* @param {*} value
|
|
790
|
+
* @param {string} [description]
|
|
791
|
+
* @return {Option}
|
|
792
|
+
*/
|
|
793
|
+
default(value, description) {
|
|
794
|
+
this.defaultValue = value;
|
|
795
|
+
this.defaultValueDescription = description;
|
|
796
|
+
return this;
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
800
|
+
* The custom processing (parseArg) is called.
|
|
801
|
+
*
|
|
802
|
+
* @example
|
|
803
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
804
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
805
|
+
*
|
|
806
|
+
* @param {*} arg
|
|
807
|
+
* @return {Option}
|
|
808
|
+
*/
|
|
809
|
+
preset(arg) {
|
|
810
|
+
this.presetArg = arg;
|
|
811
|
+
return this;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Add option name(s) that conflict with this option.
|
|
815
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
816
|
+
*
|
|
817
|
+
* @example
|
|
818
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
819
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
820
|
+
*
|
|
821
|
+
* @param {(string | string[])} names
|
|
822
|
+
* @return {Option}
|
|
823
|
+
*/
|
|
824
|
+
conflicts(names) {
|
|
825
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
826
|
+
return this;
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
830
|
+
*
|
|
831
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
832
|
+
*
|
|
833
|
+
* @example
|
|
834
|
+
* program
|
|
835
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
836
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
837
|
+
*
|
|
838
|
+
* @param {object} impliedOptionValues
|
|
839
|
+
* @return {Option}
|
|
840
|
+
*/
|
|
841
|
+
implies(impliedOptionValues) {
|
|
842
|
+
let newImplied = impliedOptionValues;
|
|
843
|
+
if (typeof impliedOptionValues === "string") {
|
|
844
|
+
newImplied = { [impliedOptionValues]: true };
|
|
845
|
+
}
|
|
846
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
847
|
+
return this;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Set environment variable to check for option value.
|
|
851
|
+
*
|
|
852
|
+
* An environment variable is only used if when processed the current option value is
|
|
853
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
854
|
+
*
|
|
855
|
+
* @param {string} name
|
|
856
|
+
* @return {Option}
|
|
857
|
+
*/
|
|
858
|
+
env(name) {
|
|
859
|
+
this.envVar = name;
|
|
860
|
+
return this;
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
864
|
+
*
|
|
865
|
+
* @param {Function} [fn]
|
|
866
|
+
* @return {Option}
|
|
867
|
+
*/
|
|
868
|
+
argParser(fn) {
|
|
869
|
+
this.parseArg = fn;
|
|
870
|
+
return this;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
874
|
+
*
|
|
875
|
+
* @param {boolean} [mandatory=true]
|
|
876
|
+
* @return {Option}
|
|
877
|
+
*/
|
|
878
|
+
makeOptionMandatory(mandatory = true) {
|
|
879
|
+
this.mandatory = !!mandatory;
|
|
880
|
+
return this;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Hide option in help.
|
|
884
|
+
*
|
|
885
|
+
* @param {boolean} [hide=true]
|
|
886
|
+
* @return {Option}
|
|
887
|
+
*/
|
|
888
|
+
hideHelp(hide = true) {
|
|
889
|
+
this.hidden = !!hide;
|
|
890
|
+
return this;
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* @package
|
|
894
|
+
*/
|
|
895
|
+
_collectValue(value, previous) {
|
|
896
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
897
|
+
return [value];
|
|
898
|
+
}
|
|
899
|
+
previous.push(value);
|
|
900
|
+
return previous;
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Only allow option value to be one of choices.
|
|
904
|
+
*
|
|
905
|
+
* @param {string[]} values
|
|
906
|
+
* @return {Option}
|
|
907
|
+
*/
|
|
908
|
+
choices(values) {
|
|
909
|
+
this.argChoices = values.slice();
|
|
910
|
+
this.parseArg = (arg, previous) => {
|
|
911
|
+
if (!this.argChoices.includes(arg)) {
|
|
912
|
+
throw new InvalidArgumentError(
|
|
913
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
if (this.variadic) {
|
|
917
|
+
return this._collectValue(arg, previous);
|
|
918
|
+
}
|
|
919
|
+
return arg;
|
|
920
|
+
};
|
|
921
|
+
return this;
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Return option name.
|
|
925
|
+
*
|
|
926
|
+
* @return {string}
|
|
927
|
+
*/
|
|
928
|
+
name() {
|
|
929
|
+
if (this.long) {
|
|
930
|
+
return this.long.replace(/^--/, "");
|
|
931
|
+
}
|
|
932
|
+
return this.short.replace(/^-/, "");
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Return option name, in a camelcase format that can be used
|
|
936
|
+
* as an object attribute key.
|
|
937
|
+
*
|
|
938
|
+
* @return {string}
|
|
939
|
+
*/
|
|
940
|
+
attributeName() {
|
|
941
|
+
if (this.negate) {
|
|
942
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
943
|
+
}
|
|
944
|
+
return camelcase(this.name());
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Set the help group heading.
|
|
948
|
+
*
|
|
949
|
+
* @param {string} heading
|
|
950
|
+
* @return {Option}
|
|
951
|
+
*/
|
|
952
|
+
helpGroup(heading) {
|
|
953
|
+
this.helpGroupHeading = heading;
|
|
954
|
+
return this;
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Check if `arg` matches the short or long flag.
|
|
958
|
+
*
|
|
959
|
+
* @param {string} arg
|
|
960
|
+
* @return {boolean}
|
|
961
|
+
* @package
|
|
962
|
+
*/
|
|
963
|
+
is(arg) {
|
|
964
|
+
return this.short === arg || this.long === arg;
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Return whether a boolean option.
|
|
968
|
+
*
|
|
969
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
970
|
+
*
|
|
971
|
+
* @return {boolean}
|
|
972
|
+
* @package
|
|
973
|
+
*/
|
|
974
|
+
isBoolean() {
|
|
975
|
+
return !this.required && !this.optional && !this.negate;
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
var DualOptions = class {
|
|
979
|
+
/**
|
|
980
|
+
* @param {Option[]} options
|
|
981
|
+
*/
|
|
982
|
+
constructor(options) {
|
|
983
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
984
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
985
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
986
|
+
options.forEach((option) => {
|
|
987
|
+
if (option.negate) {
|
|
988
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
989
|
+
} else {
|
|
990
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
991
|
+
}
|
|
992
|
+
});
|
|
993
|
+
this.negativeOptions.forEach((value, key) => {
|
|
994
|
+
if (this.positiveOptions.has(key)) {
|
|
995
|
+
this.dualOptions.add(key);
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1001
|
+
*
|
|
1002
|
+
* @param {*} value
|
|
1003
|
+
* @param {Option} option
|
|
1004
|
+
* @returns {boolean}
|
|
1005
|
+
*/
|
|
1006
|
+
valueFromOption(value, option) {
|
|
1007
|
+
const optionKey = option.attributeName();
|
|
1008
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1009
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1010
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1011
|
+
return option.negate === (negativeValue === value);
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
function camelcase(str) {
|
|
1015
|
+
return str.split("-").reduce((str2, word) => {
|
|
1016
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
function splitOptionFlags(flags) {
|
|
1020
|
+
let shortFlag;
|
|
1021
|
+
let longFlag;
|
|
1022
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1023
|
+
const longFlagExp = /^--[^-]/;
|
|
1024
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1025
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1026
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1027
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1028
|
+
shortFlag = flagParts.shift();
|
|
1029
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1030
|
+
shortFlag = longFlag;
|
|
1031
|
+
longFlag = flagParts.shift();
|
|
1032
|
+
}
|
|
1033
|
+
if (flagParts[0].startsWith("-")) {
|
|
1034
|
+
const unsupportedFlag = flagParts[0];
|
|
1035
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1036
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1037
|
+
throw new Error(
|
|
1038
|
+
`${baseError}
|
|
1039
|
+
- a short flag is a single dash and a single character
|
|
1040
|
+
- either use a single dash and a single character (for a short flag)
|
|
1041
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1042
|
+
);
|
|
1043
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1044
|
+
throw new Error(`${baseError}
|
|
1045
|
+
- too many short flags`);
|
|
1046
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1047
|
+
throw new Error(`${baseError}
|
|
1048
|
+
- too many long flags`);
|
|
1049
|
+
throw new Error(`${baseError}
|
|
1050
|
+
- unrecognised flag format`);
|
|
1051
|
+
}
|
|
1052
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1053
|
+
throw new Error(
|
|
1054
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1055
|
+
);
|
|
1056
|
+
return { shortFlag, longFlag };
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1060
|
+
var maxDistance = 3;
|
|
1061
|
+
function editDistance(a, b) {
|
|
1062
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1063
|
+
return Math.max(a.length, b.length);
|
|
1064
|
+
const d = [];
|
|
1065
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1066
|
+
d[i] = [i];
|
|
1067
|
+
}
|
|
1068
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1069
|
+
d[0][j] = j;
|
|
1070
|
+
}
|
|
1071
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1072
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1073
|
+
let cost;
|
|
1074
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1075
|
+
cost = 0;
|
|
1076
|
+
} else {
|
|
1077
|
+
cost = 1;
|
|
1078
|
+
}
|
|
1079
|
+
d[i][j] = Math.min(
|
|
1080
|
+
d[i - 1][j] + 1,
|
|
1081
|
+
// deletion
|
|
1082
|
+
d[i][j - 1] + 1,
|
|
1083
|
+
// insertion
|
|
1084
|
+
d[i - 1][j - 1] + cost
|
|
1085
|
+
// substitution
|
|
1086
|
+
);
|
|
1087
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1088
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
return d[a.length][b.length];
|
|
1093
|
+
}
|
|
1094
|
+
function suggestSimilar(word, candidates) {
|
|
1095
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1096
|
+
candidates = Array.from(new Set(candidates));
|
|
1097
|
+
const searchingOptions = word.startsWith("--");
|
|
1098
|
+
if (searchingOptions) {
|
|
1099
|
+
word = word.slice(2);
|
|
1100
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1101
|
+
}
|
|
1102
|
+
let similar = [];
|
|
1103
|
+
let bestDistance = maxDistance;
|
|
1104
|
+
const minSimilarity = 0.4;
|
|
1105
|
+
candidates.forEach((candidate) => {
|
|
1106
|
+
if (candidate.length <= 1) return;
|
|
1107
|
+
const distance = editDistance(word, candidate);
|
|
1108
|
+
const length = Math.max(word.length, candidate.length);
|
|
1109
|
+
const similarity = (length - distance) / length;
|
|
1110
|
+
if (similarity > minSimilarity) {
|
|
1111
|
+
if (distance < bestDistance) {
|
|
1112
|
+
bestDistance = distance;
|
|
1113
|
+
similar = [candidate];
|
|
1114
|
+
} else if (distance === bestDistance) {
|
|
1115
|
+
similar.push(candidate);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1120
|
+
if (searchingOptions) {
|
|
1121
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1122
|
+
}
|
|
1123
|
+
if (similar.length > 1) {
|
|
1124
|
+
return `
|
|
1125
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1126
|
+
}
|
|
1127
|
+
if (similar.length === 1) {
|
|
1128
|
+
return `
|
|
1129
|
+
(Did you mean ${similar[0]}?)`;
|
|
1130
|
+
}
|
|
1131
|
+
return "";
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
// node_modules/commander/lib/command.js
|
|
1135
|
+
var Command = class _Command extends EventEmitter {
|
|
1136
|
+
/**
|
|
1137
|
+
* Initialize a new `Command`.
|
|
1138
|
+
*
|
|
1139
|
+
* @param {string} [name]
|
|
1140
|
+
*/
|
|
1141
|
+
constructor(name) {
|
|
1142
|
+
super();
|
|
1143
|
+
this.commands = [];
|
|
1144
|
+
this.options = [];
|
|
1145
|
+
this.parent = null;
|
|
1146
|
+
this._allowUnknownOption = false;
|
|
1147
|
+
this._allowExcessArguments = false;
|
|
1148
|
+
this.registeredArguments = [];
|
|
1149
|
+
this._args = this.registeredArguments;
|
|
1150
|
+
this.args = [];
|
|
1151
|
+
this.rawArgs = [];
|
|
1152
|
+
this.processedArgs = [];
|
|
1153
|
+
this._scriptPath = null;
|
|
1154
|
+
this._name = name || "";
|
|
1155
|
+
this._optionValues = {};
|
|
1156
|
+
this._optionValueSources = {};
|
|
1157
|
+
this._storeOptionsAsProperties = false;
|
|
1158
|
+
this._actionHandler = null;
|
|
1159
|
+
this._executableHandler = false;
|
|
1160
|
+
this._executableFile = null;
|
|
1161
|
+
this._executableDir = null;
|
|
1162
|
+
this._defaultCommandName = null;
|
|
1163
|
+
this._exitCallback = null;
|
|
1164
|
+
this._aliases = [];
|
|
1165
|
+
this._combineFlagAndOptionalValue = true;
|
|
1166
|
+
this._description = "";
|
|
1167
|
+
this._summary = "";
|
|
1168
|
+
this._argsDescription = void 0;
|
|
1169
|
+
this._enablePositionalOptions = false;
|
|
1170
|
+
this._passThroughOptions = false;
|
|
1171
|
+
this._lifeCycleHooks = {};
|
|
1172
|
+
this._showHelpAfterError = false;
|
|
1173
|
+
this._showSuggestionAfterError = true;
|
|
1174
|
+
this._savedState = null;
|
|
1175
|
+
this._outputConfiguration = {
|
|
1176
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1177
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1178
|
+
outputError: (str, write) => write(str),
|
|
1179
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1180
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1181
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1182
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1183
|
+
stripColor: (str) => stripVTControlCharacters2(str)
|
|
1184
|
+
};
|
|
1185
|
+
this._hidden = false;
|
|
1186
|
+
this._helpOption = void 0;
|
|
1187
|
+
this._addImplicitHelpCommand = void 0;
|
|
1188
|
+
this._helpCommand = void 0;
|
|
1189
|
+
this._helpConfiguration = {};
|
|
1190
|
+
this._helpGroupHeading = void 0;
|
|
1191
|
+
this._defaultCommandGroup = void 0;
|
|
1192
|
+
this._defaultOptionGroup = void 0;
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1196
|
+
*
|
|
1197
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1198
|
+
*
|
|
1199
|
+
* @param {Command} sourceCommand
|
|
1200
|
+
* @return {Command} `this` command for chaining
|
|
1201
|
+
*/
|
|
1202
|
+
copyInheritedSettings(sourceCommand) {
|
|
1203
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1204
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1205
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1206
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1207
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1208
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1209
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1210
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1211
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1212
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1213
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1214
|
+
return this;
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* @returns {Command[]}
|
|
1218
|
+
* @private
|
|
1219
|
+
*/
|
|
1220
|
+
_getCommandAndAncestors() {
|
|
1221
|
+
const result = [];
|
|
1222
|
+
for (let command = this; command; command = command.parent) {
|
|
1223
|
+
result.push(command);
|
|
1224
|
+
}
|
|
1225
|
+
return result;
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Define a command.
|
|
1229
|
+
*
|
|
1230
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1231
|
+
*
|
|
1232
|
+
* @example
|
|
1233
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1234
|
+
* program
|
|
1235
|
+
* .command('clone <source> [destination]')
|
|
1236
|
+
* .description('clone a repository into a newly created directory')
|
|
1237
|
+
* .action((source, destination) => {
|
|
1238
|
+
* console.log('clone command called');
|
|
1239
|
+
* });
|
|
1240
|
+
*
|
|
1241
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1242
|
+
* program
|
|
1243
|
+
* .command('start <service>', 'start named service')
|
|
1244
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1245
|
+
*
|
|
1246
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1247
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1248
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1249
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1250
|
+
*/
|
|
1251
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1252
|
+
let desc = actionOptsOrExecDesc;
|
|
1253
|
+
let opts = execOpts;
|
|
1254
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1255
|
+
opts = desc;
|
|
1256
|
+
desc = null;
|
|
1257
|
+
}
|
|
1258
|
+
opts = opts || {};
|
|
1259
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1260
|
+
const cmd = this.createCommand(name);
|
|
1261
|
+
if (desc) {
|
|
1262
|
+
cmd.description(desc);
|
|
1263
|
+
cmd._executableHandler = true;
|
|
1264
|
+
}
|
|
1265
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1266
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1267
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1268
|
+
if (args) cmd.arguments(args);
|
|
1269
|
+
this._registerCommand(cmd);
|
|
1270
|
+
cmd.parent = this;
|
|
1271
|
+
cmd.copyInheritedSettings(this);
|
|
1272
|
+
if (desc) return this;
|
|
1273
|
+
return cmd;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Factory routine to create a new unattached command.
|
|
1277
|
+
*
|
|
1278
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1279
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1280
|
+
*
|
|
1281
|
+
* @param {string} [name]
|
|
1282
|
+
* @return {Command} new command
|
|
1283
|
+
*/
|
|
1284
|
+
createCommand(name) {
|
|
1285
|
+
return new _Command(name);
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1289
|
+
* or by overriding Help properties using configureHelp().
|
|
1290
|
+
*
|
|
1291
|
+
* @return {Help}
|
|
1292
|
+
*/
|
|
1293
|
+
createHelp() {
|
|
1294
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1298
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1299
|
+
*
|
|
1300
|
+
* @param {object} [configuration] - configuration options
|
|
1301
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1302
|
+
*/
|
|
1303
|
+
configureHelp(configuration) {
|
|
1304
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1305
|
+
this._helpConfiguration = configuration;
|
|
1306
|
+
return this;
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1310
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1311
|
+
*
|
|
1312
|
+
* The configuration properties are all functions:
|
|
1313
|
+
*
|
|
1314
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1315
|
+
* writeOut(str)
|
|
1316
|
+
* writeErr(str)
|
|
1317
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1318
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1319
|
+
* // specify width for wrapping help
|
|
1320
|
+
* getOutHelpWidth()
|
|
1321
|
+
* getErrHelpWidth()
|
|
1322
|
+
* // color support, currently only used with Help
|
|
1323
|
+
* getOutHasColors()
|
|
1324
|
+
* getErrHasColors()
|
|
1325
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1326
|
+
*
|
|
1327
|
+
* @param {object} [configuration] - configuration options
|
|
1328
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1329
|
+
*/
|
|
1330
|
+
configureOutput(configuration) {
|
|
1331
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1332
|
+
this._outputConfiguration = {
|
|
1333
|
+
...this._outputConfiguration,
|
|
1334
|
+
...configuration
|
|
1335
|
+
};
|
|
1336
|
+
return this;
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Display the help or a custom message after an error occurs.
|
|
1340
|
+
*
|
|
1341
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1342
|
+
* @return {Command} `this` command for chaining
|
|
1343
|
+
*/
|
|
1344
|
+
showHelpAfterError(displayHelp = true) {
|
|
1345
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1346
|
+
this._showHelpAfterError = displayHelp;
|
|
1347
|
+
return this;
|
|
1348
|
+
}
|
|
1349
|
+
/**
|
|
1350
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1351
|
+
*
|
|
1352
|
+
* @param {boolean} [displaySuggestion]
|
|
1353
|
+
* @return {Command} `this` command for chaining
|
|
1354
|
+
*/
|
|
1355
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1356
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1357
|
+
return this;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Add a prepared subcommand.
|
|
1361
|
+
*
|
|
1362
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1363
|
+
*
|
|
1364
|
+
* @param {Command} cmd - new subcommand
|
|
1365
|
+
* @param {object} [opts] - configuration options
|
|
1366
|
+
* @return {Command} `this` command for chaining
|
|
1367
|
+
*/
|
|
1368
|
+
addCommand(cmd, opts) {
|
|
1369
|
+
if (!cmd._name) {
|
|
1370
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1371
|
+
- specify the name in Command constructor or using .name()`);
|
|
1372
|
+
}
|
|
1373
|
+
opts = opts || {};
|
|
1374
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1375
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1376
|
+
this._registerCommand(cmd);
|
|
1377
|
+
cmd.parent = this;
|
|
1378
|
+
cmd._checkForBrokenPassThrough();
|
|
1379
|
+
return this;
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Factory routine to create a new unattached argument.
|
|
1383
|
+
*
|
|
1384
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1385
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1386
|
+
*
|
|
1387
|
+
* @param {string} name
|
|
1388
|
+
* @param {string} [description]
|
|
1389
|
+
* @return {Argument} new argument
|
|
1390
|
+
*/
|
|
1391
|
+
createArgument(name, description) {
|
|
1392
|
+
return new Argument(name, description);
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Define argument syntax for command.
|
|
1396
|
+
*
|
|
1397
|
+
* The default is that the argument is required, and you can explicitly
|
|
1398
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1399
|
+
*
|
|
1400
|
+
* @example
|
|
1401
|
+
* program.argument('<input-file>');
|
|
1402
|
+
* program.argument('[output-file]');
|
|
1403
|
+
*
|
|
1404
|
+
* @param {string} name
|
|
1405
|
+
* @param {string} [description]
|
|
1406
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1407
|
+
* @param {*} [defaultValue]
|
|
1408
|
+
* @return {Command} `this` command for chaining
|
|
1409
|
+
*/
|
|
1410
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1411
|
+
const argument = this.createArgument(name, description);
|
|
1412
|
+
if (typeof parseArg === "function") {
|
|
1413
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
1414
|
+
} else {
|
|
1415
|
+
argument.default(parseArg);
|
|
1416
|
+
}
|
|
1417
|
+
this.addArgument(argument);
|
|
1418
|
+
return this;
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1422
|
+
*
|
|
1423
|
+
* See also .argument().
|
|
1424
|
+
*
|
|
1425
|
+
* @example
|
|
1426
|
+
* program.arguments('<cmd> [env]');
|
|
1427
|
+
*
|
|
1428
|
+
* @param {string} names
|
|
1429
|
+
* @return {Command} `this` command for chaining
|
|
1430
|
+
*/
|
|
1431
|
+
arguments(names) {
|
|
1432
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1433
|
+
this.argument(detail);
|
|
1434
|
+
});
|
|
1435
|
+
return this;
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1439
|
+
*
|
|
1440
|
+
* @param {Argument} argument
|
|
1441
|
+
* @return {Command} `this` command for chaining
|
|
1442
|
+
*/
|
|
1443
|
+
addArgument(argument) {
|
|
1444
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1445
|
+
if (previousArgument?.variadic) {
|
|
1446
|
+
throw new Error(
|
|
1447
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1451
|
+
throw new Error(
|
|
1452
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1453
|
+
);
|
|
1454
|
+
}
|
|
1455
|
+
this.registeredArguments.push(argument);
|
|
1456
|
+
return this;
|
|
1457
|
+
}
|
|
1458
|
+
/**
|
|
1459
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1460
|
+
*
|
|
1461
|
+
* @example
|
|
1462
|
+
* program.helpCommand('help [cmd]');
|
|
1463
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1464
|
+
* program.helpCommand(false); // suppress default help command
|
|
1465
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1466
|
+
*
|
|
1467
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1468
|
+
* @param {string} [description] - custom description
|
|
1469
|
+
* @return {Command} `this` command for chaining
|
|
1470
|
+
*/
|
|
1471
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1472
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1473
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1474
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
1475
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
1476
|
+
}
|
|
1477
|
+
return this;
|
|
1478
|
+
}
|
|
1479
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1480
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1481
|
+
const helpDescription = description ?? "display help for command";
|
|
1482
|
+
const helpCommand = this.createCommand(helpName);
|
|
1483
|
+
helpCommand.helpOption(false);
|
|
1484
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1485
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1486
|
+
this._addImplicitHelpCommand = true;
|
|
1487
|
+
this._helpCommand = helpCommand;
|
|
1488
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1489
|
+
return this;
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Add prepared custom help command.
|
|
1493
|
+
*
|
|
1494
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1495
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1496
|
+
* @return {Command} `this` command for chaining
|
|
1497
|
+
*/
|
|
1498
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1499
|
+
if (typeof helpCommand !== "object") {
|
|
1500
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1501
|
+
return this;
|
|
1502
|
+
}
|
|
1503
|
+
this._addImplicitHelpCommand = true;
|
|
1504
|
+
this._helpCommand = helpCommand;
|
|
1505
|
+
this._initCommandGroup(helpCommand);
|
|
1506
|
+
return this;
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Lazy create help command.
|
|
1510
|
+
*
|
|
1511
|
+
* @return {(Command|null)}
|
|
1512
|
+
* @package
|
|
1513
|
+
*/
|
|
1514
|
+
_getHelpCommand() {
|
|
1515
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1516
|
+
if (hasImplicitHelpCommand) {
|
|
1517
|
+
if (this._helpCommand === void 0) {
|
|
1518
|
+
this.helpCommand(void 0, void 0);
|
|
1519
|
+
}
|
|
1520
|
+
return this._helpCommand;
|
|
1521
|
+
}
|
|
1522
|
+
return null;
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Add hook for life cycle event.
|
|
1526
|
+
*
|
|
1527
|
+
* @param {string} event
|
|
1528
|
+
* @param {Function} listener
|
|
1529
|
+
* @return {Command} `this` command for chaining
|
|
1530
|
+
*/
|
|
1531
|
+
hook(event, listener) {
|
|
1532
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1533
|
+
if (!allowedValues.includes(event)) {
|
|
1534
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1535
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1536
|
+
}
|
|
1537
|
+
if (this._lifeCycleHooks[event]) {
|
|
1538
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1539
|
+
} else {
|
|
1540
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1541
|
+
}
|
|
1542
|
+
return this;
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1545
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1546
|
+
*
|
|
1547
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1548
|
+
* @return {Command} `this` command for chaining
|
|
1549
|
+
*/
|
|
1550
|
+
exitOverride(fn) {
|
|
1551
|
+
if (fn) {
|
|
1552
|
+
this._exitCallback = fn;
|
|
1553
|
+
} else {
|
|
1554
|
+
this._exitCallback = (err) => {
|
|
1555
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1556
|
+
throw err;
|
|
1557
|
+
} else {
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
}
|
|
1561
|
+
return this;
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1565
|
+
*
|
|
1566
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1567
|
+
* @param {string} code an id string representing the error
|
|
1568
|
+
* @param {string} message human-readable description of the error
|
|
1569
|
+
* @return never
|
|
1570
|
+
* @private
|
|
1571
|
+
*/
|
|
1572
|
+
_exit(exitCode, code, message) {
|
|
1573
|
+
if (this._exitCallback) {
|
|
1574
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1575
|
+
}
|
|
1576
|
+
process2.exit(exitCode);
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Register callback `fn` for the command.
|
|
1580
|
+
*
|
|
1581
|
+
* @example
|
|
1582
|
+
* program
|
|
1583
|
+
* .command('serve')
|
|
1584
|
+
* .description('start service')
|
|
1585
|
+
* .action(function() {
|
|
1586
|
+
* // do work here
|
|
1587
|
+
* });
|
|
1588
|
+
*
|
|
1589
|
+
* @param {Function} fn
|
|
1590
|
+
* @return {Command} `this` command for chaining
|
|
1591
|
+
*/
|
|
1592
|
+
action(fn) {
|
|
1593
|
+
const listener = (args) => {
|
|
1594
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1595
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1596
|
+
if (this._storeOptionsAsProperties) {
|
|
1597
|
+
actionArgs[expectedArgsCount] = this;
|
|
1598
|
+
} else {
|
|
1599
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1600
|
+
}
|
|
1601
|
+
actionArgs.push(this);
|
|
1602
|
+
return fn.apply(this, actionArgs);
|
|
1603
|
+
};
|
|
1604
|
+
this._actionHandler = listener;
|
|
1605
|
+
return this;
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* Factory routine to create a new unattached option.
|
|
1609
|
+
*
|
|
1610
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1611
|
+
* create the option. You can override createOption to return a custom option.
|
|
1612
|
+
*
|
|
1613
|
+
* @param {string} flags
|
|
1614
|
+
* @param {string} [description]
|
|
1615
|
+
* @return {Option} new option
|
|
1616
|
+
*/
|
|
1617
|
+
createOption(flags, description) {
|
|
1618
|
+
return new Option(flags, description);
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1622
|
+
*
|
|
1623
|
+
* @param {(Option | Argument)} target
|
|
1624
|
+
* @param {string} value
|
|
1625
|
+
* @param {*} previous
|
|
1626
|
+
* @param {string} invalidArgumentMessage
|
|
1627
|
+
* @private
|
|
1628
|
+
*/
|
|
1629
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1630
|
+
try {
|
|
1631
|
+
return target.parseArg(value, previous);
|
|
1632
|
+
} catch (err) {
|
|
1633
|
+
if (err.code === "commander.invalidArgument") {
|
|
1634
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1635
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1636
|
+
}
|
|
1637
|
+
throw err;
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Check for option flag conflicts.
|
|
1642
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1643
|
+
*
|
|
1644
|
+
* @param {Option} option
|
|
1645
|
+
* @private
|
|
1646
|
+
*/
|
|
1647
|
+
_registerOption(option) {
|
|
1648
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1649
|
+
if (matchingOption) {
|
|
1650
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1651
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1652
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1653
|
+
}
|
|
1654
|
+
this._initOptionGroup(option);
|
|
1655
|
+
this.options.push(option);
|
|
1656
|
+
}
|
|
1657
|
+
/**
|
|
1658
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1659
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1660
|
+
*
|
|
1661
|
+
* @param {Command} command
|
|
1662
|
+
* @private
|
|
1663
|
+
*/
|
|
1664
|
+
_registerCommand(command) {
|
|
1665
|
+
const knownBy = (cmd) => {
|
|
1666
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1667
|
+
};
|
|
1668
|
+
const alreadyUsed = knownBy(command).find(
|
|
1669
|
+
(name) => this._findCommand(name)
|
|
1670
|
+
);
|
|
1671
|
+
if (alreadyUsed) {
|
|
1672
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1673
|
+
const newCmd = knownBy(command).join("|");
|
|
1674
|
+
throw new Error(
|
|
1675
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
this._initCommandGroup(command);
|
|
1679
|
+
this.commands.push(command);
|
|
1680
|
+
}
|
|
1681
|
+
/**
|
|
1682
|
+
* Add an option.
|
|
1683
|
+
*
|
|
1684
|
+
* @param {Option} option
|
|
1685
|
+
* @return {Command} `this` command for chaining
|
|
1686
|
+
*/
|
|
1687
|
+
addOption(option) {
|
|
1688
|
+
this._registerOption(option);
|
|
1689
|
+
const oname = option.name();
|
|
1690
|
+
const name = option.attributeName();
|
|
1691
|
+
if (option.defaultValue !== void 0) {
|
|
1692
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1693
|
+
}
|
|
1694
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1695
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1696
|
+
val = option.presetArg;
|
|
1697
|
+
}
|
|
1698
|
+
const oldValue = this.getOptionValue(name);
|
|
1699
|
+
if (val !== null && option.parseArg) {
|
|
1700
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1701
|
+
} else if (val !== null && option.variadic) {
|
|
1702
|
+
val = option._collectValue(val, oldValue);
|
|
1703
|
+
}
|
|
1704
|
+
if (val == null) {
|
|
1705
|
+
if (option.negate) {
|
|
1706
|
+
val = false;
|
|
1707
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1708
|
+
val = true;
|
|
1709
|
+
} else {
|
|
1710
|
+
val = "";
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1714
|
+
};
|
|
1715
|
+
this.on("option:" + oname, (val) => {
|
|
1716
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1717
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1718
|
+
});
|
|
1719
|
+
if (option.envVar) {
|
|
1720
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1721
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1722
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
return this;
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1729
|
+
*
|
|
1730
|
+
* @return {Command} `this` command for chaining
|
|
1731
|
+
* @private
|
|
1732
|
+
*/
|
|
1733
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1734
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
1735
|
+
throw new Error(
|
|
1736
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1737
|
+
);
|
|
1738
|
+
}
|
|
1739
|
+
const option = this.createOption(flags, description);
|
|
1740
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1741
|
+
if (typeof fn === "function") {
|
|
1742
|
+
option.default(defaultValue).argParser(fn);
|
|
1743
|
+
} else if (fn instanceof RegExp) {
|
|
1744
|
+
const regex = fn;
|
|
1745
|
+
fn = (val, def) => {
|
|
1746
|
+
const m = regex.exec(val);
|
|
1747
|
+
return m ? m[0] : def;
|
|
1748
|
+
};
|
|
1749
|
+
option.default(defaultValue).argParser(fn);
|
|
1750
|
+
} else {
|
|
1751
|
+
option.default(fn);
|
|
1752
|
+
}
|
|
1753
|
+
return this.addOption(option);
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1757
|
+
*
|
|
1758
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1759
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1760
|
+
*
|
|
1761
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1762
|
+
*
|
|
1763
|
+
* @example
|
|
1764
|
+
* program
|
|
1765
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1766
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1767
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1768
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1769
|
+
*
|
|
1770
|
+
* @param {string} flags
|
|
1771
|
+
* @param {string} [description]
|
|
1772
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1773
|
+
* @param {*} [defaultValue]
|
|
1774
|
+
* @return {Command} `this` command for chaining
|
|
1775
|
+
*/
|
|
1776
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1777
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1778
|
+
}
|
|
1779
|
+
/**
|
|
1780
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1781
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1782
|
+
*
|
|
1783
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1784
|
+
*
|
|
1785
|
+
* @param {string} flags
|
|
1786
|
+
* @param {string} [description]
|
|
1787
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1788
|
+
* @param {*} [defaultValue]
|
|
1789
|
+
* @return {Command} `this` command for chaining
|
|
1790
|
+
*/
|
|
1791
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1792
|
+
return this._optionEx(
|
|
1793
|
+
{ mandatory: true },
|
|
1794
|
+
flags,
|
|
1795
|
+
description,
|
|
1796
|
+
parseArg,
|
|
1797
|
+
defaultValue
|
|
1798
|
+
);
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* Alter parsing of short flags with optional values.
|
|
1802
|
+
*
|
|
1803
|
+
* @example
|
|
1804
|
+
* // for `.option('-f,--flag [value]'):
|
|
1805
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1806
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1807
|
+
*
|
|
1808
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1809
|
+
* @return {Command} `this` command for chaining
|
|
1810
|
+
*/
|
|
1811
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1812
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1813
|
+
return this;
|
|
1814
|
+
}
|
|
1815
|
+
/**
|
|
1816
|
+
* Allow unknown options on the command line.
|
|
1817
|
+
*
|
|
1818
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1819
|
+
* @return {Command} `this` command for chaining
|
|
1820
|
+
*/
|
|
1821
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1822
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1823
|
+
return this;
|
|
1824
|
+
}
|
|
1825
|
+
/**
|
|
1826
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1827
|
+
*
|
|
1828
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1829
|
+
* @return {Command} `this` command for chaining
|
|
1830
|
+
*/
|
|
1831
|
+
allowExcessArguments(allowExcess = true) {
|
|
1832
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1833
|
+
return this;
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1837
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1838
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1839
|
+
*
|
|
1840
|
+
* @param {boolean} [positional]
|
|
1841
|
+
* @return {Command} `this` command for chaining
|
|
1842
|
+
*/
|
|
1843
|
+
enablePositionalOptions(positional = true) {
|
|
1844
|
+
this._enablePositionalOptions = !!positional;
|
|
1845
|
+
return this;
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1849
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1850
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1851
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1852
|
+
*
|
|
1853
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1854
|
+
* @return {Command} `this` command for chaining
|
|
1855
|
+
*/
|
|
1856
|
+
passThroughOptions(passThrough = true) {
|
|
1857
|
+
this._passThroughOptions = !!passThrough;
|
|
1858
|
+
this._checkForBrokenPassThrough();
|
|
1859
|
+
return this;
|
|
1860
|
+
}
|
|
1861
|
+
/**
|
|
1862
|
+
* @private
|
|
1863
|
+
*/
|
|
1864
|
+
_checkForBrokenPassThrough() {
|
|
1865
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1866
|
+
throw new Error(
|
|
1867
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1868
|
+
);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
/**
|
|
1872
|
+
* Whether to store option values as properties on command object,
|
|
1873
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1874
|
+
*
|
|
1875
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1876
|
+
* @return {Command} `this` command for chaining
|
|
1877
|
+
*/
|
|
1878
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1879
|
+
if (this.options.length) {
|
|
1880
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1881
|
+
}
|
|
1882
|
+
if (Object.keys(this._optionValues).length) {
|
|
1883
|
+
throw new Error(
|
|
1884
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1885
|
+
);
|
|
1886
|
+
}
|
|
1887
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1888
|
+
return this;
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* Retrieve option value.
|
|
1892
|
+
*
|
|
1893
|
+
* @param {string} key
|
|
1894
|
+
* @return {object} value
|
|
1895
|
+
*/
|
|
1896
|
+
getOptionValue(key) {
|
|
1897
|
+
if (this._storeOptionsAsProperties) {
|
|
1898
|
+
return this[key];
|
|
1899
|
+
}
|
|
1900
|
+
return this._optionValues[key];
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Store option value.
|
|
1904
|
+
*
|
|
1905
|
+
* @param {string} key
|
|
1906
|
+
* @param {object} value
|
|
1907
|
+
* @return {Command} `this` command for chaining
|
|
1908
|
+
*/
|
|
1909
|
+
setOptionValue(key, value) {
|
|
1910
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1911
|
+
}
|
|
1912
|
+
/**
|
|
1913
|
+
* Store option value and where the value came from.
|
|
1914
|
+
*
|
|
1915
|
+
* @param {string} key
|
|
1916
|
+
* @param {object} value
|
|
1917
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1918
|
+
* @return {Command} `this` command for chaining
|
|
1919
|
+
*/
|
|
1920
|
+
setOptionValueWithSource(key, value, source) {
|
|
1921
|
+
if (this._storeOptionsAsProperties) {
|
|
1922
|
+
this[key] = value;
|
|
1923
|
+
} else {
|
|
1924
|
+
this._optionValues[key] = value;
|
|
1925
|
+
}
|
|
1926
|
+
this._optionValueSources[key] = source;
|
|
1927
|
+
return this;
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Get source of option value.
|
|
1931
|
+
* Expected values are default | config | env | cli | implied
|
|
1932
|
+
*
|
|
1933
|
+
* @param {string} key
|
|
1934
|
+
* @return {string}
|
|
1935
|
+
*/
|
|
1936
|
+
getOptionValueSource(key) {
|
|
1937
|
+
return this._optionValueSources[key];
|
|
1938
|
+
}
|
|
1939
|
+
/**
|
|
1940
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1941
|
+
* Expected values are default | config | env | cli | implied
|
|
1942
|
+
*
|
|
1943
|
+
* @param {string} key
|
|
1944
|
+
* @return {string}
|
|
1945
|
+
*/
|
|
1946
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1947
|
+
let source;
|
|
1948
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1949
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
1950
|
+
source = cmd.getOptionValueSource(key);
|
|
1951
|
+
}
|
|
1952
|
+
});
|
|
1953
|
+
return source;
|
|
1954
|
+
}
|
|
1955
|
+
/**
|
|
1956
|
+
* Get user arguments from implied or explicit arguments.
|
|
1957
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1958
|
+
*
|
|
1959
|
+
* @private
|
|
1960
|
+
*/
|
|
1961
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1962
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
1963
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1964
|
+
}
|
|
1965
|
+
parseOptions = parseOptions || {};
|
|
1966
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1967
|
+
if (process2.versions?.electron) {
|
|
1968
|
+
parseOptions.from = "electron";
|
|
1969
|
+
}
|
|
1970
|
+
const execArgv = process2.execArgv ?? [];
|
|
1971
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
1972
|
+
parseOptions.from = "eval";
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
if (argv === void 0) {
|
|
1976
|
+
argv = process2.argv;
|
|
1977
|
+
}
|
|
1978
|
+
this.rawArgs = argv.slice();
|
|
1979
|
+
let userArgs;
|
|
1980
|
+
switch (parseOptions.from) {
|
|
1981
|
+
case void 0:
|
|
1982
|
+
case "node":
|
|
1983
|
+
this._scriptPath = argv[1];
|
|
1984
|
+
userArgs = argv.slice(2);
|
|
1985
|
+
break;
|
|
1986
|
+
case "electron":
|
|
1987
|
+
if (process2.defaultApp) {
|
|
1988
|
+
this._scriptPath = argv[1];
|
|
1989
|
+
userArgs = argv.slice(2);
|
|
1990
|
+
} else {
|
|
1991
|
+
userArgs = argv.slice(1);
|
|
1992
|
+
}
|
|
1993
|
+
break;
|
|
1994
|
+
case "user":
|
|
1995
|
+
userArgs = argv.slice(0);
|
|
1996
|
+
break;
|
|
1997
|
+
case "eval":
|
|
1998
|
+
userArgs = argv.slice(1);
|
|
1999
|
+
break;
|
|
2000
|
+
default:
|
|
2001
|
+
throw new Error(
|
|
2002
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2003
|
+
);
|
|
2004
|
+
}
|
|
2005
|
+
if (!this._name && this._scriptPath)
|
|
2006
|
+
this.nameFromFilename(this._scriptPath);
|
|
2007
|
+
this._name = this._name || "program";
|
|
2008
|
+
return userArgs;
|
|
2009
|
+
}
|
|
2010
|
+
/**
|
|
2011
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2012
|
+
*
|
|
2013
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2014
|
+
*
|
|
2015
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2016
|
+
*
|
|
2017
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2018
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2019
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2020
|
+
* - `'user'`: just user arguments
|
|
2021
|
+
*
|
|
2022
|
+
* @example
|
|
2023
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2024
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2025
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2026
|
+
*
|
|
2027
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2028
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2029
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2030
|
+
* @return {Command} `this` command for chaining
|
|
2031
|
+
*/
|
|
2032
|
+
parse(argv, parseOptions) {
|
|
2033
|
+
this._prepareForParse();
|
|
2034
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2035
|
+
this._parseCommand([], userArgs);
|
|
2036
|
+
return this;
|
|
2037
|
+
}
|
|
2038
|
+
/**
|
|
2039
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2040
|
+
*
|
|
2041
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2042
|
+
*
|
|
2043
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2044
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2045
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2046
|
+
* - `'user'`: just user arguments
|
|
2047
|
+
*
|
|
2048
|
+
* @example
|
|
2049
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2050
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2051
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2052
|
+
*
|
|
2053
|
+
* @param {string[]} [argv]
|
|
2054
|
+
* @param {object} [parseOptions]
|
|
2055
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2056
|
+
* @return {Promise}
|
|
2057
|
+
*/
|
|
2058
|
+
async parseAsync(argv, parseOptions) {
|
|
2059
|
+
this._prepareForParse();
|
|
2060
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2061
|
+
await this._parseCommand([], userArgs);
|
|
2062
|
+
return this;
|
|
2063
|
+
}
|
|
2064
|
+
_prepareForParse() {
|
|
2065
|
+
if (this._savedState === null) {
|
|
2066
|
+
this.options.filter(
|
|
2067
|
+
(option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
|
|
2068
|
+
).forEach((option) => {
|
|
2069
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
2070
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
2071
|
+
this.setOptionValueWithSource(
|
|
2072
|
+
option.attributeName(),
|
|
2073
|
+
true,
|
|
2074
|
+
"default"
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
});
|
|
2078
|
+
this.saveStateBeforeParse();
|
|
2079
|
+
} else {
|
|
2080
|
+
this.restoreStateBeforeParse();
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
/**
|
|
2084
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2085
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2086
|
+
*
|
|
2087
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2088
|
+
*/
|
|
2089
|
+
saveStateBeforeParse() {
|
|
2090
|
+
this._savedState = {
|
|
2091
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2092
|
+
_name: this._name,
|
|
2093
|
+
// option values before parse have default values (including false for negated options)
|
|
2094
|
+
// shallow clones
|
|
2095
|
+
_optionValues: { ...this._optionValues },
|
|
2096
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2097
|
+
};
|
|
2098
|
+
}
|
|
2099
|
+
/**
|
|
2100
|
+
* Restore state before parse for calls after the first.
|
|
2101
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2102
|
+
*
|
|
2103
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2104
|
+
*/
|
|
2105
|
+
restoreStateBeforeParse() {
|
|
2106
|
+
if (this._storeOptionsAsProperties)
|
|
2107
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2108
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2109
|
+
this._name = this._savedState._name;
|
|
2110
|
+
this._scriptPath = null;
|
|
2111
|
+
this.rawArgs = [];
|
|
2112
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2113
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2114
|
+
this.args = [];
|
|
2115
|
+
this.processedArgs = [];
|
|
2116
|
+
}
|
|
2117
|
+
/**
|
|
2118
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2119
|
+
*
|
|
2120
|
+
* @param {string} executableFile
|
|
2121
|
+
* @param {string} executableDir
|
|
2122
|
+
* @param {string} subcommandName
|
|
2123
|
+
*/
|
|
2124
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2125
|
+
if (fs.existsSync(executableFile)) return;
|
|
2126
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
2127
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2128
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2129
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2130
|
+
- ${executableDirMessage}`;
|
|
2131
|
+
throw new Error(executableMissing);
|
|
2132
|
+
}
|
|
2133
|
+
/**
|
|
2134
|
+
* Execute a sub-command executable.
|
|
2135
|
+
*
|
|
2136
|
+
* @private
|
|
2137
|
+
*/
|
|
2138
|
+
_executeSubCommand(subcommand, args) {
|
|
2139
|
+
args = args.slice();
|
|
2140
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2141
|
+
function findFile(baseDir, baseName) {
|
|
2142
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2143
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2144
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2145
|
+
const foundExt = sourceExt.find(
|
|
2146
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2147
|
+
);
|
|
2148
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2149
|
+
return void 0;
|
|
2150
|
+
}
|
|
2151
|
+
this._checkForMissingMandatoryOptions();
|
|
2152
|
+
this._checkForConflictingOptions();
|
|
2153
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2154
|
+
let executableDir = this._executableDir || "";
|
|
2155
|
+
if (this._scriptPath) {
|
|
2156
|
+
let resolvedScriptPath;
|
|
2157
|
+
try {
|
|
2158
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2159
|
+
} catch {
|
|
2160
|
+
resolvedScriptPath = this._scriptPath;
|
|
2161
|
+
}
|
|
2162
|
+
executableDir = path.resolve(
|
|
2163
|
+
path.dirname(resolvedScriptPath),
|
|
2164
|
+
executableDir
|
|
2165
|
+
);
|
|
2166
|
+
}
|
|
2167
|
+
if (executableDir) {
|
|
2168
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2169
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2170
|
+
const legacyName = path.basename(
|
|
2171
|
+
this._scriptPath,
|
|
2172
|
+
path.extname(this._scriptPath)
|
|
2173
|
+
);
|
|
2174
|
+
if (legacyName !== this._name) {
|
|
2175
|
+
localFile = findFile(
|
|
2176
|
+
executableDir,
|
|
2177
|
+
`${legacyName}-${subcommand._name}`
|
|
2178
|
+
);
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
executableFile = localFile || executableFile;
|
|
2182
|
+
}
|
|
2183
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2184
|
+
let proc;
|
|
2185
|
+
if (process2.platform !== "win32") {
|
|
2186
|
+
if (launchWithNode) {
|
|
2187
|
+
args.unshift(executableFile);
|
|
2188
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2189
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2190
|
+
} else {
|
|
2191
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2192
|
+
}
|
|
2193
|
+
} else {
|
|
2194
|
+
this._checkForMissingExecutable(
|
|
2195
|
+
executableFile,
|
|
2196
|
+
executableDir,
|
|
2197
|
+
subcommand._name
|
|
2198
|
+
);
|
|
2199
|
+
args.unshift(executableFile);
|
|
2200
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2201
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2202
|
+
}
|
|
2203
|
+
if (!proc.killed) {
|
|
2204
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2205
|
+
signals.forEach((signal) => {
|
|
2206
|
+
process2.on(signal, () => {
|
|
2207
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2208
|
+
proc.kill(signal);
|
|
2209
|
+
}
|
|
2210
|
+
});
|
|
2211
|
+
});
|
|
2212
|
+
}
|
|
2213
|
+
const exitCallback = this._exitCallback;
|
|
2214
|
+
proc.on("close", (code) => {
|
|
2215
|
+
code = code ?? 1;
|
|
2216
|
+
if (!exitCallback) {
|
|
2217
|
+
process2.exit(code);
|
|
2218
|
+
} else {
|
|
2219
|
+
exitCallback(
|
|
2220
|
+
new CommanderError(
|
|
2221
|
+
code,
|
|
2222
|
+
"commander.executeSubCommandAsync",
|
|
2223
|
+
"(close)"
|
|
2224
|
+
)
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
});
|
|
2228
|
+
proc.on("error", (err) => {
|
|
2229
|
+
if (err.code === "ENOENT") {
|
|
2230
|
+
this._checkForMissingExecutable(
|
|
2231
|
+
executableFile,
|
|
2232
|
+
executableDir,
|
|
2233
|
+
subcommand._name
|
|
2234
|
+
);
|
|
2235
|
+
} else if (err.code === "EACCES") {
|
|
2236
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2237
|
+
}
|
|
2238
|
+
if (!exitCallback) {
|
|
2239
|
+
process2.exit(1);
|
|
2240
|
+
} else {
|
|
2241
|
+
const wrappedError = new CommanderError(
|
|
2242
|
+
1,
|
|
2243
|
+
"commander.executeSubCommandAsync",
|
|
2244
|
+
"(error)"
|
|
2245
|
+
);
|
|
2246
|
+
wrappedError.nestedError = err;
|
|
2247
|
+
exitCallback(wrappedError);
|
|
2248
|
+
}
|
|
2249
|
+
});
|
|
2250
|
+
this.runningCommand = proc;
|
|
2251
|
+
}
|
|
2252
|
+
/**
|
|
2253
|
+
* @private
|
|
2254
|
+
*/
|
|
2255
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2256
|
+
const subCommand = this._findCommand(commandName);
|
|
2257
|
+
if (!subCommand) this.help({ error: true });
|
|
2258
|
+
subCommand._prepareForParse();
|
|
2259
|
+
let promiseChain;
|
|
2260
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2261
|
+
promiseChain,
|
|
2262
|
+
subCommand,
|
|
2263
|
+
"preSubcommand"
|
|
2264
|
+
);
|
|
2265
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2266
|
+
if (subCommand._executableHandler) {
|
|
2267
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2268
|
+
} else {
|
|
2269
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2270
|
+
}
|
|
2271
|
+
});
|
|
2272
|
+
return promiseChain;
|
|
2273
|
+
}
|
|
2274
|
+
/**
|
|
2275
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2276
|
+
* e.g. help foo
|
|
2277
|
+
*
|
|
2278
|
+
* @private
|
|
2279
|
+
*/
|
|
2280
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2281
|
+
if (!subcommandName) {
|
|
2282
|
+
this.help();
|
|
2283
|
+
}
|
|
2284
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2285
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2286
|
+
subCommand.help();
|
|
2287
|
+
}
|
|
2288
|
+
return this._dispatchSubcommand(
|
|
2289
|
+
subcommandName,
|
|
2290
|
+
[],
|
|
2291
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2292
|
+
);
|
|
2293
|
+
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Check this.args against expected this.registeredArguments.
|
|
2296
|
+
*
|
|
2297
|
+
* @private
|
|
2298
|
+
*/
|
|
2299
|
+
_checkNumberOfArguments() {
|
|
2300
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2301
|
+
if (arg.required && this.args[i] == null) {
|
|
2302
|
+
this.missingArgument(arg.name());
|
|
2303
|
+
}
|
|
2304
|
+
});
|
|
2305
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2306
|
+
return;
|
|
2307
|
+
}
|
|
2308
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2309
|
+
this._excessArguments(this.args);
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2314
|
+
*
|
|
2315
|
+
* @private
|
|
2316
|
+
*/
|
|
2317
|
+
_processArguments() {
|
|
2318
|
+
const myParseArg = (argument, value, previous) => {
|
|
2319
|
+
let parsedValue = value;
|
|
2320
|
+
if (value !== null && argument.parseArg) {
|
|
2321
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2322
|
+
parsedValue = this._callParseArg(
|
|
2323
|
+
argument,
|
|
2324
|
+
value,
|
|
2325
|
+
previous,
|
|
2326
|
+
invalidValueMessage
|
|
2327
|
+
);
|
|
2328
|
+
}
|
|
2329
|
+
return parsedValue;
|
|
2330
|
+
};
|
|
2331
|
+
this._checkNumberOfArguments();
|
|
2332
|
+
const processedArgs = [];
|
|
2333
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2334
|
+
let value = declaredArg.defaultValue;
|
|
2335
|
+
if (declaredArg.variadic) {
|
|
2336
|
+
if (index < this.args.length) {
|
|
2337
|
+
value = this.args.slice(index);
|
|
2338
|
+
if (declaredArg.parseArg) {
|
|
2339
|
+
value = value.reduce((processed, v) => {
|
|
2340
|
+
return myParseArg(declaredArg, v, processed);
|
|
2341
|
+
}, declaredArg.defaultValue);
|
|
2342
|
+
}
|
|
2343
|
+
} else if (value === void 0) {
|
|
2344
|
+
value = [];
|
|
2345
|
+
}
|
|
2346
|
+
} else if (index < this.args.length) {
|
|
2347
|
+
value = this.args[index];
|
|
2348
|
+
if (declaredArg.parseArg) {
|
|
2349
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
processedArgs[index] = value;
|
|
2353
|
+
});
|
|
2354
|
+
this.processedArgs = processedArgs;
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2358
|
+
*
|
|
2359
|
+
* @param {(Promise|undefined)} promise
|
|
2360
|
+
* @param {Function} fn
|
|
2361
|
+
* @return {(Promise|undefined)}
|
|
2362
|
+
* @private
|
|
2363
|
+
*/
|
|
2364
|
+
_chainOrCall(promise, fn) {
|
|
2365
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
2366
|
+
return promise.then(() => fn());
|
|
2367
|
+
}
|
|
2368
|
+
return fn();
|
|
2369
|
+
}
|
|
2370
|
+
/**
|
|
2371
|
+
*
|
|
2372
|
+
* @param {(Promise|undefined)} promise
|
|
2373
|
+
* @param {string} event
|
|
2374
|
+
* @return {(Promise|undefined)}
|
|
2375
|
+
* @private
|
|
2376
|
+
*/
|
|
2377
|
+
_chainOrCallHooks(promise, event) {
|
|
2378
|
+
let result = promise;
|
|
2379
|
+
const hooks = [];
|
|
2380
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2381
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2382
|
+
hooks.push({ hookedCommand, callback });
|
|
2383
|
+
});
|
|
2384
|
+
});
|
|
2385
|
+
if (event === "postAction") {
|
|
2386
|
+
hooks.reverse();
|
|
2387
|
+
}
|
|
2388
|
+
hooks.forEach((hookDetail) => {
|
|
2389
|
+
result = this._chainOrCall(result, () => {
|
|
2390
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2391
|
+
});
|
|
2392
|
+
});
|
|
2393
|
+
return result;
|
|
2394
|
+
}
|
|
2395
|
+
/**
|
|
2396
|
+
*
|
|
2397
|
+
* @param {(Promise|undefined)} promise
|
|
2398
|
+
* @param {Command} subCommand
|
|
2399
|
+
* @param {string} event
|
|
2400
|
+
* @return {(Promise|undefined)}
|
|
2401
|
+
* @private
|
|
2402
|
+
*/
|
|
2403
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2404
|
+
let result = promise;
|
|
2405
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2406
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2407
|
+
result = this._chainOrCall(result, () => {
|
|
2408
|
+
return hook(this, subCommand);
|
|
2409
|
+
});
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
return result;
|
|
2413
|
+
}
|
|
2414
|
+
/**
|
|
2415
|
+
* Process arguments in context of this command.
|
|
2416
|
+
* Returns action result, in case it is a promise.
|
|
2417
|
+
*
|
|
2418
|
+
* @private
|
|
2419
|
+
*/
|
|
2420
|
+
_parseCommand(operands, unknown) {
|
|
2421
|
+
const parsed = this.parseOptions(unknown);
|
|
2422
|
+
this._parseOptionsEnv();
|
|
2423
|
+
this._parseOptionsImplied();
|
|
2424
|
+
operands = operands.concat(parsed.operands);
|
|
2425
|
+
unknown = parsed.unknown;
|
|
2426
|
+
this.args = operands.concat(unknown);
|
|
2427
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2428
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2429
|
+
}
|
|
2430
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2431
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2432
|
+
}
|
|
2433
|
+
if (this._defaultCommandName) {
|
|
2434
|
+
this._outputHelpIfRequested(unknown);
|
|
2435
|
+
return this._dispatchSubcommand(
|
|
2436
|
+
this._defaultCommandName,
|
|
2437
|
+
operands,
|
|
2438
|
+
unknown
|
|
2439
|
+
);
|
|
2440
|
+
}
|
|
2441
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2442
|
+
this.help({ error: true });
|
|
2443
|
+
}
|
|
2444
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2445
|
+
this._checkForMissingMandatoryOptions();
|
|
2446
|
+
this._checkForConflictingOptions();
|
|
2447
|
+
const checkForUnknownOptions = () => {
|
|
2448
|
+
if (parsed.unknown.length > 0) {
|
|
2449
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2450
|
+
}
|
|
2451
|
+
};
|
|
2452
|
+
const commandEvent = `command:${this.name()}`;
|
|
2453
|
+
if (this._actionHandler) {
|
|
2454
|
+
checkForUnknownOptions();
|
|
2455
|
+
this._processArguments();
|
|
2456
|
+
let promiseChain;
|
|
2457
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2458
|
+
promiseChain = this._chainOrCall(
|
|
2459
|
+
promiseChain,
|
|
2460
|
+
() => this._actionHandler(this.processedArgs)
|
|
2461
|
+
);
|
|
2462
|
+
if (this.parent) {
|
|
2463
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2464
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2468
|
+
return promiseChain;
|
|
2469
|
+
}
|
|
2470
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2471
|
+
checkForUnknownOptions();
|
|
2472
|
+
this._processArguments();
|
|
2473
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2474
|
+
} else if (operands.length) {
|
|
2475
|
+
if (this._findCommand("*")) {
|
|
2476
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2477
|
+
}
|
|
2478
|
+
if (this.listenerCount("command:*")) {
|
|
2479
|
+
this.emit("command:*", operands, unknown);
|
|
2480
|
+
} else if (this.commands.length) {
|
|
2481
|
+
this.unknownCommand();
|
|
2482
|
+
} else {
|
|
2483
|
+
checkForUnknownOptions();
|
|
2484
|
+
this._processArguments();
|
|
2485
|
+
}
|
|
2486
|
+
} else if (this.commands.length) {
|
|
2487
|
+
checkForUnknownOptions();
|
|
2488
|
+
this.help({ error: true });
|
|
2489
|
+
} else {
|
|
2490
|
+
checkForUnknownOptions();
|
|
2491
|
+
this._processArguments();
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* Find matching command.
|
|
2496
|
+
*
|
|
2497
|
+
* @private
|
|
2498
|
+
* @return {Command | undefined}
|
|
2499
|
+
*/
|
|
2500
|
+
_findCommand(name) {
|
|
2501
|
+
if (!name) return void 0;
|
|
2502
|
+
return this.commands.find(
|
|
2503
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2504
|
+
);
|
|
2505
|
+
}
|
|
2506
|
+
/**
|
|
2507
|
+
* Return an option matching `arg` if any.
|
|
2508
|
+
*
|
|
2509
|
+
* @param {string} arg
|
|
2510
|
+
* @return {Option}
|
|
2511
|
+
* @package
|
|
2512
|
+
*/
|
|
2513
|
+
_findOption(arg) {
|
|
2514
|
+
return this.options.find((option) => option.is(arg));
|
|
2515
|
+
}
|
|
2516
|
+
/**
|
|
2517
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2518
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2519
|
+
*
|
|
2520
|
+
* @private
|
|
2521
|
+
*/
|
|
2522
|
+
_checkForMissingMandatoryOptions() {
|
|
2523
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2524
|
+
cmd.options.forEach((anOption) => {
|
|
2525
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2526
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2527
|
+
}
|
|
2528
|
+
});
|
|
2529
|
+
});
|
|
2530
|
+
}
|
|
2531
|
+
/**
|
|
2532
|
+
* Display an error message if conflicting options are used together in this.
|
|
2533
|
+
*
|
|
2534
|
+
* @private
|
|
2535
|
+
*/
|
|
2536
|
+
_checkForConflictingLocalOptions() {
|
|
2537
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2538
|
+
const optionKey = option.attributeName();
|
|
2539
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2540
|
+
return false;
|
|
2541
|
+
}
|
|
2542
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2543
|
+
});
|
|
2544
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2545
|
+
(option) => option.conflictsWith.length > 0
|
|
2546
|
+
);
|
|
2547
|
+
optionsWithConflicting.forEach((option) => {
|
|
2548
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2549
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2550
|
+
);
|
|
2551
|
+
if (conflictingAndDefined) {
|
|
2552
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2553
|
+
}
|
|
2554
|
+
});
|
|
2555
|
+
}
|
|
2556
|
+
/**
|
|
2557
|
+
* Display an error message if conflicting options are used together.
|
|
2558
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2559
|
+
*
|
|
2560
|
+
* @private
|
|
2561
|
+
*/
|
|
2562
|
+
_checkForConflictingOptions() {
|
|
2563
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2564
|
+
cmd._checkForConflictingLocalOptions();
|
|
2565
|
+
});
|
|
2566
|
+
}
|
|
2567
|
+
/**
|
|
2568
|
+
* Parse options from `argv` removing known options,
|
|
2569
|
+
* and return argv split into operands and unknown arguments.
|
|
2570
|
+
*
|
|
2571
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2572
|
+
*
|
|
2573
|
+
* Examples:
|
|
2574
|
+
*
|
|
2575
|
+
* argv => operands, unknown
|
|
2576
|
+
* --known kkk op => [op], []
|
|
2577
|
+
* op --known kkk => [op], []
|
|
2578
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2579
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2580
|
+
*
|
|
2581
|
+
* @param {string[]} args
|
|
2582
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2583
|
+
*/
|
|
2584
|
+
parseOptions(args) {
|
|
2585
|
+
const operands = [];
|
|
2586
|
+
const unknown = [];
|
|
2587
|
+
let dest = operands;
|
|
2588
|
+
function maybeOption(arg) {
|
|
2589
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2590
|
+
}
|
|
2591
|
+
const negativeNumberArg = (arg) => {
|
|
2592
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2593
|
+
return !this._getCommandAndAncestors().some(
|
|
2594
|
+
(cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
|
|
2595
|
+
);
|
|
2596
|
+
};
|
|
2597
|
+
let activeVariadicOption = null;
|
|
2598
|
+
let activeGroup = null;
|
|
2599
|
+
let i = 0;
|
|
2600
|
+
while (i < args.length || activeGroup) {
|
|
2601
|
+
const arg = activeGroup ?? args[i++];
|
|
2602
|
+
activeGroup = null;
|
|
2603
|
+
if (arg === "--") {
|
|
2604
|
+
if (dest === unknown) dest.push(arg);
|
|
2605
|
+
dest.push(...args.slice(i));
|
|
2606
|
+
break;
|
|
2607
|
+
}
|
|
2608
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2609
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2610
|
+
continue;
|
|
2611
|
+
}
|
|
2612
|
+
activeVariadicOption = null;
|
|
2613
|
+
if (maybeOption(arg)) {
|
|
2614
|
+
const option = this._findOption(arg);
|
|
2615
|
+
if (option) {
|
|
2616
|
+
if (option.required) {
|
|
2617
|
+
const value = args[i++];
|
|
2618
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2619
|
+
this.emit(`option:${option.name()}`, value);
|
|
2620
|
+
} else if (option.optional) {
|
|
2621
|
+
let value = null;
|
|
2622
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
2623
|
+
value = args[i++];
|
|
2624
|
+
}
|
|
2625
|
+
this.emit(`option:${option.name()}`, value);
|
|
2626
|
+
} else {
|
|
2627
|
+
this.emit(`option:${option.name()}`);
|
|
2628
|
+
}
|
|
2629
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2630
|
+
continue;
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2634
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2635
|
+
if (option) {
|
|
2636
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2637
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2638
|
+
} else {
|
|
2639
|
+
this.emit(`option:${option.name()}`);
|
|
2640
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2641
|
+
}
|
|
2642
|
+
continue;
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2646
|
+
const index = arg.indexOf("=");
|
|
2647
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2648
|
+
if (option && (option.required || option.optional)) {
|
|
2649
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2650
|
+
continue;
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
2654
|
+
dest = unknown;
|
|
2655
|
+
}
|
|
2656
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2657
|
+
if (this._findCommand(arg)) {
|
|
2658
|
+
operands.push(arg);
|
|
2659
|
+
unknown.push(...args.slice(i));
|
|
2660
|
+
break;
|
|
2661
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2662
|
+
operands.push(arg, ...args.slice(i));
|
|
2663
|
+
break;
|
|
2664
|
+
} else if (this._defaultCommandName) {
|
|
2665
|
+
unknown.push(arg, ...args.slice(i));
|
|
2666
|
+
break;
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
if (this._passThroughOptions) {
|
|
2670
|
+
dest.push(arg, ...args.slice(i));
|
|
2671
|
+
break;
|
|
2672
|
+
}
|
|
2673
|
+
dest.push(arg);
|
|
2674
|
+
}
|
|
2675
|
+
return { operands, unknown };
|
|
2676
|
+
}
|
|
2677
|
+
/**
|
|
2678
|
+
* Return an object containing local option values as key-value pairs.
|
|
2679
|
+
*
|
|
2680
|
+
* @return {object}
|
|
2681
|
+
*/
|
|
2682
|
+
opts() {
|
|
2683
|
+
if (this._storeOptionsAsProperties) {
|
|
2684
|
+
const result = {};
|
|
2685
|
+
const len = this.options.length;
|
|
2686
|
+
for (let i = 0; i < len; i++) {
|
|
2687
|
+
const key = this.options[i].attributeName();
|
|
2688
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2689
|
+
}
|
|
2690
|
+
return result;
|
|
2691
|
+
}
|
|
2692
|
+
return this._optionValues;
|
|
2693
|
+
}
|
|
2694
|
+
/**
|
|
2695
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2696
|
+
*
|
|
2697
|
+
* @return {object}
|
|
2698
|
+
*/
|
|
2699
|
+
optsWithGlobals() {
|
|
2700
|
+
return this._getCommandAndAncestors().reduce(
|
|
2701
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2702
|
+
{}
|
|
2703
|
+
);
|
|
2704
|
+
}
|
|
2705
|
+
/**
|
|
2706
|
+
* Display error message and exit (or call exitOverride).
|
|
2707
|
+
*
|
|
2708
|
+
* @param {string} message
|
|
2709
|
+
* @param {object} [errorOptions]
|
|
2710
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2711
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2712
|
+
*/
|
|
2713
|
+
error(message, errorOptions) {
|
|
2714
|
+
this._outputConfiguration.outputError(
|
|
2715
|
+
`${message}
|
|
2716
|
+
`,
|
|
2717
|
+
this._outputConfiguration.writeErr
|
|
2718
|
+
);
|
|
2719
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2720
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2721
|
+
`);
|
|
2722
|
+
} else if (this._showHelpAfterError) {
|
|
2723
|
+
this._outputConfiguration.writeErr("\n");
|
|
2724
|
+
this.outputHelp({ error: true });
|
|
2725
|
+
}
|
|
2726
|
+
const config = errorOptions || {};
|
|
2727
|
+
const exitCode = config.exitCode || 1;
|
|
2728
|
+
const code = config.code || "commander.error";
|
|
2729
|
+
this._exit(exitCode, code, message);
|
|
2730
|
+
}
|
|
2731
|
+
/**
|
|
2732
|
+
* Apply any option related environment variables, if option does
|
|
2733
|
+
* not have a value from cli or client code.
|
|
2734
|
+
*
|
|
2735
|
+
* @private
|
|
2736
|
+
*/
|
|
2737
|
+
_parseOptionsEnv() {
|
|
2738
|
+
this.options.forEach((option) => {
|
|
2739
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2740
|
+
const optionKey = option.attributeName();
|
|
2741
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2742
|
+
this.getOptionValueSource(optionKey)
|
|
2743
|
+
)) {
|
|
2744
|
+
if (option.required || option.optional) {
|
|
2745
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2746
|
+
} else {
|
|
2747
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
});
|
|
2752
|
+
}
|
|
2753
|
+
/**
|
|
2754
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2755
|
+
*
|
|
2756
|
+
* @private
|
|
2757
|
+
*/
|
|
2758
|
+
_parseOptionsImplied() {
|
|
2759
|
+
const dualHelper = new DualOptions(this.options);
|
|
2760
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2761
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2762
|
+
};
|
|
2763
|
+
this.options.filter(
|
|
2764
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2765
|
+
this.getOptionValue(option.attributeName()),
|
|
2766
|
+
option
|
|
2767
|
+
)
|
|
2768
|
+
).forEach((option) => {
|
|
2769
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2770
|
+
this.setOptionValueWithSource(
|
|
2771
|
+
impliedKey,
|
|
2772
|
+
option.implied[impliedKey],
|
|
2773
|
+
"implied"
|
|
2774
|
+
);
|
|
2775
|
+
});
|
|
2776
|
+
});
|
|
2777
|
+
}
|
|
2778
|
+
/**
|
|
2779
|
+
* Argument `name` is missing.
|
|
2780
|
+
*
|
|
2781
|
+
* @param {string} name
|
|
2782
|
+
* @private
|
|
2783
|
+
*/
|
|
2784
|
+
missingArgument(name) {
|
|
2785
|
+
const message = `error: missing required argument '${name}'`;
|
|
2786
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2787
|
+
}
|
|
2788
|
+
/**
|
|
2789
|
+
* `Option` is missing an argument.
|
|
2790
|
+
*
|
|
2791
|
+
* @param {Option} option
|
|
2792
|
+
* @private
|
|
2793
|
+
*/
|
|
2794
|
+
optionMissingArgument(option) {
|
|
2795
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2796
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2797
|
+
}
|
|
2798
|
+
/**
|
|
2799
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2800
|
+
*
|
|
2801
|
+
* @param {Option} option
|
|
2802
|
+
* @private
|
|
2803
|
+
*/
|
|
2804
|
+
missingMandatoryOptionValue(option) {
|
|
2805
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2806
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2807
|
+
}
|
|
2808
|
+
/**
|
|
2809
|
+
* `Option` conflicts with another option.
|
|
2810
|
+
*
|
|
2811
|
+
* @param {Option} option
|
|
2812
|
+
* @param {Option} conflictingOption
|
|
2813
|
+
* @private
|
|
2814
|
+
*/
|
|
2815
|
+
_conflictingOption(option, conflictingOption) {
|
|
2816
|
+
const findBestOptionFromValue = (option2) => {
|
|
2817
|
+
const optionKey = option2.attributeName();
|
|
2818
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2819
|
+
const negativeOption = this.options.find(
|
|
2820
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2821
|
+
);
|
|
2822
|
+
const positiveOption = this.options.find(
|
|
2823
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2824
|
+
);
|
|
2825
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2826
|
+
return negativeOption;
|
|
2827
|
+
}
|
|
2828
|
+
return positiveOption || option2;
|
|
2829
|
+
};
|
|
2830
|
+
const getErrorMessage = (option2) => {
|
|
2831
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2832
|
+
const optionKey = bestOption.attributeName();
|
|
2833
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2834
|
+
if (source === "env") {
|
|
2835
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2836
|
+
}
|
|
2837
|
+
return `option '${bestOption.flags}'`;
|
|
2838
|
+
};
|
|
2839
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2840
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2841
|
+
}
|
|
2842
|
+
/**
|
|
2843
|
+
* Unknown option `flag`.
|
|
2844
|
+
*
|
|
2845
|
+
* @param {string} flag
|
|
2846
|
+
* @private
|
|
2847
|
+
*/
|
|
2848
|
+
unknownOption(flag) {
|
|
2849
|
+
if (this._allowUnknownOption) return;
|
|
2850
|
+
let suggestion = "";
|
|
2851
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2852
|
+
let candidateFlags = [];
|
|
2853
|
+
let command = this;
|
|
2854
|
+
do {
|
|
2855
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2856
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2857
|
+
command = command.parent;
|
|
2858
|
+
} while (command && !command._enablePositionalOptions);
|
|
2859
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2860
|
+
}
|
|
2861
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2862
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2863
|
+
}
|
|
2864
|
+
/**
|
|
2865
|
+
* Excess arguments, more than expected.
|
|
2866
|
+
*
|
|
2867
|
+
* @param {string[]} receivedArgs
|
|
2868
|
+
* @private
|
|
2869
|
+
*/
|
|
2870
|
+
_excessArguments(receivedArgs) {
|
|
2871
|
+
if (this._allowExcessArguments) return;
|
|
2872
|
+
const expected = this.registeredArguments.length;
|
|
2873
|
+
const s = expected === 1 ? "" : "s";
|
|
2874
|
+
const received = receivedArgs.length;
|
|
2875
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2876
|
+
const details = receivedArgs.join(", ");
|
|
2877
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
|
|
2878
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2879
|
+
}
|
|
2880
|
+
/**
|
|
2881
|
+
* Unknown command.
|
|
2882
|
+
*
|
|
2883
|
+
* @private
|
|
2884
|
+
*/
|
|
2885
|
+
unknownCommand() {
|
|
2886
|
+
const unknownName = this.args[0];
|
|
2887
|
+
let suggestion = "";
|
|
2888
|
+
if (this._showSuggestionAfterError) {
|
|
2889
|
+
const candidateNames = [];
|
|
2890
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2891
|
+
candidateNames.push(command.name());
|
|
2892
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2893
|
+
});
|
|
2894
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2895
|
+
}
|
|
2896
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2897
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2898
|
+
}
|
|
2899
|
+
/**
|
|
2900
|
+
* Get or set the program version.
|
|
2901
|
+
*
|
|
2902
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2903
|
+
*
|
|
2904
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2905
|
+
*
|
|
2906
|
+
* @param {string} [str]
|
|
2907
|
+
* @param {string} [flags]
|
|
2908
|
+
* @param {string} [description]
|
|
2909
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2910
|
+
*/
|
|
2911
|
+
version(str, flags, description) {
|
|
2912
|
+
if (str === void 0) return this._version;
|
|
2913
|
+
this._version = str;
|
|
2914
|
+
flags = flags || "-V, --version";
|
|
2915
|
+
description = description || "output the version number";
|
|
2916
|
+
const versionOption = this.createOption(flags, description);
|
|
2917
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2918
|
+
this._registerOption(versionOption);
|
|
2919
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2920
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2921
|
+
`);
|
|
2922
|
+
this._exit(0, "commander.version", str);
|
|
2923
|
+
});
|
|
2924
|
+
return this;
|
|
2925
|
+
}
|
|
2926
|
+
/**
|
|
2927
|
+
* Set the description.
|
|
2928
|
+
*
|
|
2929
|
+
* @param {string} [str]
|
|
2930
|
+
* @param {object} [argsDescription]
|
|
2931
|
+
* @return {(string|Command)}
|
|
2932
|
+
*/
|
|
2933
|
+
description(str, argsDescription) {
|
|
2934
|
+
if (str === void 0 && argsDescription === void 0)
|
|
2935
|
+
return this._description;
|
|
2936
|
+
this._description = str;
|
|
2937
|
+
if (argsDescription) {
|
|
2938
|
+
this._argsDescription = argsDescription;
|
|
2939
|
+
}
|
|
2940
|
+
return this;
|
|
2941
|
+
}
|
|
2942
|
+
/**
|
|
2943
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2944
|
+
*
|
|
2945
|
+
* @param {string} [str]
|
|
2946
|
+
* @return {(string|Command)}
|
|
2947
|
+
*/
|
|
2948
|
+
summary(str) {
|
|
2949
|
+
if (str === void 0) return this._summary;
|
|
2950
|
+
this._summary = str;
|
|
2951
|
+
return this;
|
|
2952
|
+
}
|
|
2953
|
+
/**
|
|
2954
|
+
* Set an alias for the command.
|
|
2955
|
+
*
|
|
2956
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2957
|
+
*
|
|
2958
|
+
* @param {string} [alias]
|
|
2959
|
+
* @return {(string|Command)}
|
|
2960
|
+
*/
|
|
2961
|
+
alias(alias) {
|
|
2962
|
+
if (alias === void 0) return this._aliases[0];
|
|
2963
|
+
let command = this;
|
|
2964
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
2965
|
+
command = this.commands[this.commands.length - 1];
|
|
2966
|
+
}
|
|
2967
|
+
if (alias === command._name)
|
|
2968
|
+
throw new Error("Command alias can't be the same as its name");
|
|
2969
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2970
|
+
if (matchingCommand) {
|
|
2971
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2972
|
+
throw new Error(
|
|
2973
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
2974
|
+
);
|
|
2975
|
+
}
|
|
2976
|
+
command._aliases.push(alias);
|
|
2977
|
+
return this;
|
|
2978
|
+
}
|
|
2979
|
+
/**
|
|
2980
|
+
* Set aliases for the command.
|
|
2981
|
+
*
|
|
2982
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2983
|
+
*
|
|
2984
|
+
* @param {string[]} [aliases]
|
|
2985
|
+
* @return {(string[]|Command)}
|
|
2986
|
+
*/
|
|
2987
|
+
aliases(aliases) {
|
|
2988
|
+
if (aliases === void 0) return this._aliases;
|
|
2989
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2990
|
+
return this;
|
|
2991
|
+
}
|
|
2992
|
+
/**
|
|
2993
|
+
* Set / get the command usage `str`.
|
|
2994
|
+
*
|
|
2995
|
+
* @param {string} [str]
|
|
2996
|
+
* @return {(string|Command)}
|
|
2997
|
+
*/
|
|
2998
|
+
usage(str) {
|
|
2999
|
+
if (str === void 0) {
|
|
3000
|
+
if (this._usage) return this._usage;
|
|
3001
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3002
|
+
return humanReadableArgName(arg);
|
|
3003
|
+
});
|
|
3004
|
+
return [].concat(
|
|
3005
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3006
|
+
this.commands.length ? "[command]" : [],
|
|
3007
|
+
this.registeredArguments.length ? args : []
|
|
3008
|
+
).join(" ");
|
|
3009
|
+
}
|
|
3010
|
+
this._usage = str;
|
|
3011
|
+
return this;
|
|
3012
|
+
}
|
|
3013
|
+
/**
|
|
3014
|
+
* Get or set the name of the command.
|
|
3015
|
+
*
|
|
3016
|
+
* @param {string} [str]
|
|
3017
|
+
* @return {(string|Command)}
|
|
3018
|
+
*/
|
|
3019
|
+
name(str) {
|
|
3020
|
+
if (str === void 0) return this._name;
|
|
3021
|
+
this._name = str;
|
|
3022
|
+
return this;
|
|
3023
|
+
}
|
|
3024
|
+
/**
|
|
3025
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
3026
|
+
*
|
|
3027
|
+
* @param {string} [heading]
|
|
3028
|
+
* @return {Command | string}
|
|
3029
|
+
*/
|
|
3030
|
+
helpGroup(heading) {
|
|
3031
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
3032
|
+
this._helpGroupHeading = heading;
|
|
3033
|
+
return this;
|
|
3034
|
+
}
|
|
3035
|
+
/**
|
|
3036
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
3037
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
3038
|
+
*
|
|
3039
|
+
* @example
|
|
3040
|
+
* program.commandsGroup('Development Commands:);
|
|
3041
|
+
* program.command('watch')...
|
|
3042
|
+
* program.command('lint')...
|
|
3043
|
+
* ...
|
|
3044
|
+
*
|
|
3045
|
+
* @param {string} [heading]
|
|
3046
|
+
* @returns {Command | string}
|
|
3047
|
+
*/
|
|
3048
|
+
commandsGroup(heading) {
|
|
3049
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
3050
|
+
this._defaultCommandGroup = heading;
|
|
3051
|
+
return this;
|
|
3052
|
+
}
|
|
3053
|
+
/**
|
|
3054
|
+
* Set/get the default help group heading for options added to this command.
|
|
3055
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
3056
|
+
*
|
|
3057
|
+
* @example
|
|
3058
|
+
* program
|
|
3059
|
+
* .optionsGroup('Development Options:')
|
|
3060
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
3061
|
+
* .option('-p, --profile', 'output profiling information')
|
|
3062
|
+
*
|
|
3063
|
+
* @param {string} [heading]
|
|
3064
|
+
* @returns {Command | string}
|
|
3065
|
+
*/
|
|
3066
|
+
optionsGroup(heading) {
|
|
3067
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
3068
|
+
this._defaultOptionGroup = heading;
|
|
3069
|
+
return this;
|
|
3070
|
+
}
|
|
3071
|
+
/**
|
|
3072
|
+
* @param {Option} option
|
|
3073
|
+
* @private
|
|
3074
|
+
*/
|
|
3075
|
+
_initOptionGroup(option) {
|
|
3076
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
3077
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
3078
|
+
}
|
|
3079
|
+
/**
|
|
3080
|
+
* @param {Command} cmd
|
|
3081
|
+
* @private
|
|
3082
|
+
*/
|
|
3083
|
+
_initCommandGroup(cmd) {
|
|
3084
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
3085
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
3086
|
+
}
|
|
3087
|
+
/**
|
|
3088
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3089
|
+
* or import.meta.filename.
|
|
3090
|
+
*
|
|
3091
|
+
* (Used internally and public although not documented in README.)
|
|
3092
|
+
*
|
|
3093
|
+
* @example
|
|
3094
|
+
* program.nameFromFilename(import.meta.filename);
|
|
3095
|
+
*
|
|
3096
|
+
* @param {string} filename
|
|
3097
|
+
* @return {Command}
|
|
3098
|
+
*/
|
|
3099
|
+
nameFromFilename(filename) {
|
|
3100
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3101
|
+
return this;
|
|
3102
|
+
}
|
|
3103
|
+
/**
|
|
3104
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3105
|
+
*
|
|
3106
|
+
* @example
|
|
3107
|
+
* program.executableDir(import.meta.dirname);
|
|
3108
|
+
* // or
|
|
3109
|
+
* program.executableDir('subcommands');
|
|
3110
|
+
*
|
|
3111
|
+
* @param {string} [path]
|
|
3112
|
+
* @return {(string|null|Command)}
|
|
3113
|
+
*/
|
|
3114
|
+
executableDir(path2) {
|
|
3115
|
+
if (path2 === void 0) return this._executableDir;
|
|
3116
|
+
this._executableDir = path2;
|
|
3117
|
+
return this;
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* Return program help documentation.
|
|
3121
|
+
*
|
|
3122
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3123
|
+
* @return {string}
|
|
3124
|
+
*/
|
|
3125
|
+
helpInformation(contextOptions) {
|
|
3126
|
+
const helper = this.createHelp();
|
|
3127
|
+
const context = this._getOutputContext(contextOptions);
|
|
3128
|
+
helper.prepareContext({
|
|
3129
|
+
error: context.error,
|
|
3130
|
+
helpWidth: context.helpWidth,
|
|
3131
|
+
outputHasColors: context.hasColors
|
|
3132
|
+
});
|
|
3133
|
+
const text = helper.formatHelp(this, helper);
|
|
3134
|
+
if (context.hasColors) return text;
|
|
3135
|
+
return this._outputConfiguration.stripColor(text);
|
|
3136
|
+
}
|
|
3137
|
+
/**
|
|
3138
|
+
* @typedef HelpContext
|
|
3139
|
+
* @type {object}
|
|
3140
|
+
* @property {boolean} error
|
|
3141
|
+
* @property {number} helpWidth
|
|
3142
|
+
* @property {boolean} hasColors
|
|
3143
|
+
* @property {function} write - includes stripColor if needed
|
|
3144
|
+
*
|
|
3145
|
+
* @returns {HelpContext}
|
|
3146
|
+
* @private
|
|
3147
|
+
*/
|
|
3148
|
+
_getOutputContext(contextOptions) {
|
|
3149
|
+
contextOptions = contextOptions || {};
|
|
3150
|
+
const error = !!contextOptions.error;
|
|
3151
|
+
let baseWrite;
|
|
3152
|
+
let hasColors;
|
|
3153
|
+
let helpWidth;
|
|
3154
|
+
if (error) {
|
|
3155
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3156
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3157
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3158
|
+
} else {
|
|
3159
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3160
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3161
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3162
|
+
}
|
|
3163
|
+
const write = (str) => {
|
|
3164
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3165
|
+
return baseWrite(str);
|
|
3166
|
+
};
|
|
3167
|
+
return { error, write, hasColors, helpWidth };
|
|
3168
|
+
}
|
|
3169
|
+
/**
|
|
3170
|
+
* Output help information for this command.
|
|
3171
|
+
*
|
|
3172
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3173
|
+
*
|
|
3174
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3175
|
+
*/
|
|
3176
|
+
outputHelp(contextOptions) {
|
|
3177
|
+
let deprecatedCallback;
|
|
3178
|
+
if (typeof contextOptions === "function") {
|
|
3179
|
+
deprecatedCallback = contextOptions;
|
|
3180
|
+
contextOptions = void 0;
|
|
3181
|
+
}
|
|
3182
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3183
|
+
const eventContext = {
|
|
3184
|
+
error: outputContext.error,
|
|
3185
|
+
write: outputContext.write,
|
|
3186
|
+
command: this
|
|
3187
|
+
};
|
|
3188
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3189
|
+
this.emit("beforeHelp", eventContext);
|
|
3190
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3191
|
+
if (deprecatedCallback) {
|
|
3192
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3193
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3194
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
outputContext.write(helpInformation);
|
|
3198
|
+
if (this._getHelpOption()?.long) {
|
|
3199
|
+
this.emit(this._getHelpOption().long);
|
|
3200
|
+
}
|
|
3201
|
+
this.emit("afterHelp", eventContext);
|
|
3202
|
+
this._getCommandAndAncestors().forEach(
|
|
3203
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3204
|
+
);
|
|
3205
|
+
}
|
|
3206
|
+
/**
|
|
3207
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3208
|
+
* Pass in false to disable the built-in help option.
|
|
3209
|
+
*
|
|
3210
|
+
* @example
|
|
3211
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3212
|
+
* program.helpOption(false); // disable
|
|
3213
|
+
*
|
|
3214
|
+
* @param {(string | boolean)} flags
|
|
3215
|
+
* @param {string} [description]
|
|
3216
|
+
* @return {Command} `this` command for chaining
|
|
3217
|
+
*/
|
|
3218
|
+
helpOption(flags, description) {
|
|
3219
|
+
if (typeof flags === "boolean") {
|
|
3220
|
+
if (flags) {
|
|
3221
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
3222
|
+
if (this._defaultOptionGroup) {
|
|
3223
|
+
this._initOptionGroup(this._getHelpOption());
|
|
3224
|
+
}
|
|
3225
|
+
} else {
|
|
3226
|
+
this._helpOption = null;
|
|
3227
|
+
}
|
|
3228
|
+
return this;
|
|
3229
|
+
}
|
|
3230
|
+
this._helpOption = this.createOption(
|
|
3231
|
+
flags ?? "-h, --help",
|
|
3232
|
+
description ?? "display help for command"
|
|
3233
|
+
);
|
|
3234
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
3235
|
+
return this;
|
|
3236
|
+
}
|
|
3237
|
+
/**
|
|
3238
|
+
* Lazy create help option.
|
|
3239
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3240
|
+
*
|
|
3241
|
+
* @returns {(Option | null)} the help option
|
|
3242
|
+
* @package
|
|
3243
|
+
*/
|
|
3244
|
+
_getHelpOption() {
|
|
3245
|
+
if (this._helpOption === void 0) {
|
|
3246
|
+
this.helpOption(void 0, void 0);
|
|
3247
|
+
}
|
|
3248
|
+
return this._helpOption;
|
|
3249
|
+
}
|
|
3250
|
+
/**
|
|
3251
|
+
* Supply your own option to use for the built-in help option.
|
|
3252
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3253
|
+
*
|
|
3254
|
+
* @param {Option} option
|
|
3255
|
+
* @return {Command} `this` command for chaining
|
|
3256
|
+
*/
|
|
3257
|
+
addHelpOption(option) {
|
|
3258
|
+
this._helpOption = option;
|
|
3259
|
+
this._initOptionGroup(option);
|
|
3260
|
+
return this;
|
|
3261
|
+
}
|
|
3262
|
+
/**
|
|
3263
|
+
* Output help information and exit.
|
|
3264
|
+
*
|
|
3265
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3266
|
+
*
|
|
3267
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3268
|
+
*/
|
|
3269
|
+
help(contextOptions) {
|
|
3270
|
+
this.outputHelp(contextOptions);
|
|
3271
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3272
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3273
|
+
exitCode = 1;
|
|
3274
|
+
}
|
|
3275
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3276
|
+
}
|
|
3277
|
+
/**
|
|
3278
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3279
|
+
* @typedef HelpTextEventContext
|
|
3280
|
+
* @type {object}
|
|
3281
|
+
* @property {boolean} error
|
|
3282
|
+
* @property {Command} command
|
|
3283
|
+
* @property {function} write
|
|
3284
|
+
*/
|
|
3285
|
+
/**
|
|
3286
|
+
* Add additional text to be displayed with the built-in help.
|
|
3287
|
+
*
|
|
3288
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3289
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3290
|
+
*
|
|
3291
|
+
* @param {string} position - before or after built-in help
|
|
3292
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3293
|
+
* @return {Command} `this` command for chaining
|
|
3294
|
+
*/
|
|
3295
|
+
addHelpText(position, text) {
|
|
3296
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3297
|
+
if (!allowedValues.includes(position)) {
|
|
3298
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3299
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3300
|
+
}
|
|
3301
|
+
const helpEvent = `${position}Help`;
|
|
3302
|
+
this.on(helpEvent, (context) => {
|
|
3303
|
+
let helpStr;
|
|
3304
|
+
if (typeof text === "function") {
|
|
3305
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3306
|
+
} else {
|
|
3307
|
+
helpStr = text;
|
|
3308
|
+
}
|
|
3309
|
+
if (helpStr) {
|
|
3310
|
+
context.write(`${helpStr}
|
|
3311
|
+
`);
|
|
3312
|
+
}
|
|
3313
|
+
});
|
|
3314
|
+
return this;
|
|
3315
|
+
}
|
|
3316
|
+
/**
|
|
3317
|
+
* Output help information if help flags specified
|
|
3318
|
+
*
|
|
3319
|
+
* @param {Array} args - array of options to search for help flags
|
|
3320
|
+
* @private
|
|
3321
|
+
*/
|
|
3322
|
+
_outputHelpIfRequested(args) {
|
|
3323
|
+
const helpOption = this._getHelpOption();
|
|
3324
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3325
|
+
if (helpRequested) {
|
|
3326
|
+
this.outputHelp();
|
|
3327
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3328
|
+
}
|
|
3329
|
+
}
|
|
3330
|
+
};
|
|
3331
|
+
function incrementNodeInspectorPort(args) {
|
|
3332
|
+
return args.map((arg) => {
|
|
3333
|
+
if (!arg.startsWith("--inspect")) {
|
|
3334
|
+
return arg;
|
|
3335
|
+
}
|
|
3336
|
+
let debugOption;
|
|
3337
|
+
let debugHost = "127.0.0.1";
|
|
3338
|
+
let debugPort = "9229";
|
|
3339
|
+
let match;
|
|
3340
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3341
|
+
debugOption = match[1];
|
|
3342
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3343
|
+
debugOption = match[1];
|
|
3344
|
+
if (/^\d+$/.test(match[3])) {
|
|
3345
|
+
debugPort = match[3];
|
|
3346
|
+
} else {
|
|
3347
|
+
debugHost = match[3];
|
|
3348
|
+
}
|
|
3349
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3350
|
+
debugOption = match[1];
|
|
3351
|
+
debugHost = match[3];
|
|
3352
|
+
debugPort = match[4];
|
|
3353
|
+
}
|
|
3354
|
+
if (debugOption && debugPort !== "0") {
|
|
3355
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3356
|
+
}
|
|
3357
|
+
return arg;
|
|
3358
|
+
});
|
|
3359
|
+
}
|
|
3360
|
+
function useColor() {
|
|
3361
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3362
|
+
return false;
|
|
3363
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3364
|
+
return true;
|
|
3365
|
+
return void 0;
|
|
3366
|
+
}
|
|
3367
|
+
|
|
3368
|
+
// node_modules/commander/index.js
|
|
3369
|
+
var program = new Command();
|
|
3370
|
+
|
|
3371
|
+
// package.json
|
|
3372
|
+
var package_default = {
|
|
3373
|
+
name: "oche-cli",
|
|
3374
|
+
version: "0.1.2",
|
|
3375
|
+
description: "Command-line client for Oche: promote dev \u2192 staging \u2192 main from your terminal.",
|
|
3376
|
+
license: "MIT",
|
|
3377
|
+
repository: {
|
|
3378
|
+
type: "git",
|
|
3379
|
+
url: "git+https://github.com/Samso9th/oche-cli.git"
|
|
3380
|
+
},
|
|
3381
|
+
homepage: "https://oche.io",
|
|
3382
|
+
bugs: "https://github.com/Samso9th/oche-cli/issues",
|
|
3383
|
+
publishConfig: {
|
|
3384
|
+
access: "public",
|
|
3385
|
+
provenance: true
|
|
3386
|
+
},
|
|
3387
|
+
type: "module",
|
|
3388
|
+
bin: {
|
|
3389
|
+
oche: "./dist/index.js"
|
|
3390
|
+
},
|
|
3391
|
+
files: [
|
|
3392
|
+
"dist"
|
|
3393
|
+
],
|
|
3394
|
+
engines: {
|
|
3395
|
+
node: ">=22.12"
|
|
3396
|
+
},
|
|
3397
|
+
scripts: {
|
|
3398
|
+
build: "tsup",
|
|
3399
|
+
dev: "tsup --watch",
|
|
3400
|
+
test: "vitest run",
|
|
3401
|
+
typecheck: "tsc --noEmit"
|
|
3402
|
+
},
|
|
3403
|
+
devDependencies: {
|
|
3404
|
+
"@types/node": "^26.6.3",
|
|
3405
|
+
commander: "^15.0.0",
|
|
3406
|
+
tsup: "^8.5.1",
|
|
3407
|
+
typescript: "6.0.3",
|
|
3408
|
+
vitest: "^5.0.2"
|
|
3409
|
+
}
|
|
3410
|
+
};
|
|
3411
|
+
|
|
3412
|
+
// src/errors.ts
|
|
3413
|
+
var CliError = class extends Error {
|
|
3414
|
+
constructor(message, exitCode = 1) {
|
|
3415
|
+
super(message);
|
|
3416
|
+
this.exitCode = exitCode;
|
|
3417
|
+
this.name = "CliError";
|
|
3418
|
+
}
|
|
3419
|
+
exitCode;
|
|
3420
|
+
};
|
|
3421
|
+
var ApiRequestError = class extends CliError {
|
|
3422
|
+
constructor(message, status2) {
|
|
3423
|
+
super(message);
|
|
3424
|
+
this.status = status2;
|
|
3425
|
+
this.name = "ApiRequestError";
|
|
3426
|
+
}
|
|
3427
|
+
status;
|
|
3428
|
+
};
|
|
3429
|
+
|
|
3430
|
+
// src/api.ts
|
|
3431
|
+
var TIMEOUT_MS = 6e4;
|
|
3432
|
+
var repoPath = (r) => `/v1/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}`;
|
|
3433
|
+
var Client = class {
|
|
3434
|
+
constructor(baseUrl, token, tokenSource = "config") {
|
|
3435
|
+
this.baseUrl = baseUrl;
|
|
3436
|
+
this.token = token;
|
|
3437
|
+
this.tokenSource = tokenSource;
|
|
3438
|
+
}
|
|
3439
|
+
baseUrl;
|
|
3440
|
+
token;
|
|
3441
|
+
tokenSource;
|
|
3442
|
+
me() {
|
|
3443
|
+
return this.request("GET", "/v1/me");
|
|
3444
|
+
}
|
|
3445
|
+
repos() {
|
|
3446
|
+
return this.request("GET", "/v1/repos");
|
|
3447
|
+
}
|
|
3448
|
+
repo(r) {
|
|
3449
|
+
return this.request("GET", repoPath(r));
|
|
3450
|
+
}
|
|
3451
|
+
onboard(r, dryRun) {
|
|
3452
|
+
return this.request("POST", `${repoPath(r)}/onboard`, { dryRun });
|
|
3453
|
+
}
|
|
3454
|
+
promote(r, to) {
|
|
3455
|
+
return this.request("POST", `${repoPath(r)}/promote`, { to });
|
|
3456
|
+
}
|
|
3457
|
+
updateRepo(r, body) {
|
|
3458
|
+
return this.request("PATCH", repoPath(r), body);
|
|
3459
|
+
}
|
|
3460
|
+
/** Starts a ship run on the server (HTTP 202) and returns right away; follow it with shipRun(). */
|
|
3461
|
+
ship(r, body) {
|
|
3462
|
+
return this.request("POST", `${repoPath(r)}/ship`, body);
|
|
3463
|
+
}
|
|
3464
|
+
shipRun(id) {
|
|
3465
|
+
return this.request("GET", `/v1/ship-runs/${id}`);
|
|
3466
|
+
}
|
|
3467
|
+
cancelShipRun(id) {
|
|
3468
|
+
return this.request("POST", `/v1/ship-runs/${id}/cancel`);
|
|
3469
|
+
}
|
|
3470
|
+
/** The server writes it with the model it's configured for, so the CLI needs no AI key. */
|
|
3471
|
+
commitMessage(body) {
|
|
3472
|
+
return this.request("POST", "/v1/ai/commit-message", body, 9e4);
|
|
3473
|
+
}
|
|
3474
|
+
/* ---- Coolify ---- */
|
|
3475
|
+
deployments(r) {
|
|
3476
|
+
return this.request("GET", `${repoPath(r)}/deployments`);
|
|
3477
|
+
}
|
|
3478
|
+
/** One deployment with its build log, the failure excerpt and a pasteable report. */
|
|
3479
|
+
deployment(r, app, deployment) {
|
|
3480
|
+
return this.request("GET", `${repoPath(r)}/deployments/${encodeURIComponent(app)}/${encodeURIComponent(deployment)}`);
|
|
3481
|
+
}
|
|
3482
|
+
/** The running container's log, not the build log. */
|
|
3483
|
+
appLogs(r, app, lines) {
|
|
3484
|
+
return this.request("GET", `${repoPath(r)}/apps/${encodeURIComponent(app)}/logs?lines=${lines}`);
|
|
3485
|
+
}
|
|
3486
|
+
/** The server asks its AI model what broke, so the CLI needs no AI key. */
|
|
3487
|
+
explainDeployment(r, app, deployment) {
|
|
3488
|
+
const path2 = `${repoPath(r)}/deployments/${encodeURIComponent(app)}/${encodeURIComponent(deployment)}/explain`;
|
|
3489
|
+
return this.request("POST", path2, void 0, 12e4);
|
|
3490
|
+
}
|
|
3491
|
+
deploy(r, app, force) {
|
|
3492
|
+
return this.request("POST", `${repoPath(r)}/apps/${encodeURIComponent(app)}/deploy`, { force });
|
|
3493
|
+
}
|
|
3494
|
+
rollbackOptions(r, app) {
|
|
3495
|
+
return this.request("GET", `${repoPath(r)}/apps/${encodeURIComponent(app)}/rollback`);
|
|
3496
|
+
}
|
|
3497
|
+
rollback(r, app, commit2) {
|
|
3498
|
+
return this.request("POST", `${repoPath(r)}/apps/${encodeURIComponent(app)}/rollback`, { commit: commit2 });
|
|
3499
|
+
}
|
|
3500
|
+
envs(r) {
|
|
3501
|
+
return this.request("GET", `${repoPath(r)}/envs`);
|
|
3502
|
+
}
|
|
3503
|
+
preflight(r, to) {
|
|
3504
|
+
return this.request("GET", `${repoPath(r)}/preflight?to=${to}`);
|
|
3505
|
+
}
|
|
3506
|
+
events(repo, limit) {
|
|
3507
|
+
const q = new URLSearchParams({ limit: String(limit) });
|
|
3508
|
+
if (repo) q.set("repo", `${repo.owner}/${repo.repo}`);
|
|
3509
|
+
return this.request("GET", `/v1/events?${q}`);
|
|
3510
|
+
}
|
|
3511
|
+
async request(method, path2, body, timeoutMs = TIMEOUT_MS) {
|
|
3512
|
+
const url = `${this.baseUrl}${path2}`;
|
|
3513
|
+
let res;
|
|
3514
|
+
try {
|
|
3515
|
+
res = await fetch(url, {
|
|
3516
|
+
method,
|
|
3517
|
+
headers: {
|
|
3518
|
+
authorization: `Bearer ${this.token}`,
|
|
3519
|
+
accept: "application/json",
|
|
3520
|
+
"user-agent": `oche-cli/${package_default.version}`,
|
|
3521
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
3522
|
+
},
|
|
3523
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
3524
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
3525
|
+
redirect: "error"
|
|
3526
|
+
});
|
|
3527
|
+
} catch (e) {
|
|
3528
|
+
throw networkError(e, this.baseUrl, timeoutMs);
|
|
3529
|
+
}
|
|
3530
|
+
const text = await res.text().catch(() => "");
|
|
3531
|
+
let data;
|
|
3532
|
+
try {
|
|
3533
|
+
data = text ? JSON.parse(text) : null;
|
|
3534
|
+
} catch {
|
|
3535
|
+
data = void 0;
|
|
3536
|
+
}
|
|
3537
|
+
const serverMessage = data && typeof data === "object" && typeof data.error === "string" ? data.error : null;
|
|
3538
|
+
if (res.status === 401) {
|
|
3539
|
+
throw new ApiRequestError(
|
|
3540
|
+
this.tokenSource === "env" ? "OCHE_TOKEN was rejected (401). Fix it, or unset it and run `oche login`." : "Not logged in, or the token was revoked (401). Run `oche login`.",
|
|
3541
|
+
401
|
|
3542
|
+
);
|
|
3543
|
+
}
|
|
3544
|
+
if (!res.ok) {
|
|
3545
|
+
const detail = serverMessage ?? (data === void 0 ? `unexpected response from ${url}` : res.statusText);
|
|
3546
|
+
throw new ApiRequestError(`${detail} (HTTP ${res.status})`, res.status);
|
|
3547
|
+
}
|
|
3548
|
+
if (data === void 0 || data === null) {
|
|
3549
|
+
throw new CliError(`Unexpected response from ${url} (HTTP ${res.status}). Is ${this.baseUrl} an Oche server?`);
|
|
3550
|
+
}
|
|
3551
|
+
return data;
|
|
3552
|
+
}
|
|
3553
|
+
};
|
|
3554
|
+
function networkError(e, baseUrl, timeoutMs = TIMEOUT_MS) {
|
|
3555
|
+
const err = e;
|
|
3556
|
+
if (err?.name === "TimeoutError") {
|
|
3557
|
+
return new CliError(`Request to ${baseUrl} timed out after ${timeoutMs / 1e3}s.`);
|
|
3558
|
+
}
|
|
3559
|
+
const reason = err?.cause?.code ?? err?.cause?.message ?? err?.message ?? String(e);
|
|
3560
|
+
if (/redirect/i.test(reason)) {
|
|
3561
|
+
return new CliError(`${baseUrl} redirected the request. Use the server's final URL (e.g. https://).`);
|
|
3562
|
+
}
|
|
3563
|
+
return new CliError(`Couldn't reach ${baseUrl} (${reason}).`);
|
|
3564
|
+
}
|
|
3565
|
+
|
|
3566
|
+
// src/config.ts
|
|
3567
|
+
import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
|
|
3568
|
+
import { homedir } from "os";
|
|
3569
|
+
import { dirname, join } from "path";
|
|
3570
|
+
var DEFAULT_SERVER_URL = "https://deploy.oche.io";
|
|
3571
|
+
var DEFAULT_TOKEN_PAGE = "https://ship.oche.io/settings";
|
|
3572
|
+
function configPath(env = process.env) {
|
|
3573
|
+
const base = env.XDG_CONFIG_HOME?.trim() || join(homedir(), ".config");
|
|
3574
|
+
return join(base, "oche", "config.json");
|
|
3575
|
+
}
|
|
3576
|
+
var LOCAL_HOST = /^(localhost|127\.\d+\.\d+\.\d+|0\.0\.0\.0|\[::1\])(:\d+)?(\/|$)/i;
|
|
3577
|
+
function normalizeUrl(input) {
|
|
3578
|
+
let s = input.trim();
|
|
3579
|
+
if (!s) throw new CliError("Server URL is empty.");
|
|
3580
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = `${LOCAL_HOST.test(s) ? "http" : "https"}://${s}`;
|
|
3581
|
+
let u;
|
|
3582
|
+
try {
|
|
3583
|
+
u = new URL(s);
|
|
3584
|
+
} catch {
|
|
3585
|
+
throw new CliError(`"${input}" is not a valid URL.`);
|
|
3586
|
+
}
|
|
3587
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") {
|
|
3588
|
+
throw new CliError(`"${input}" must be an http(s) URL.`);
|
|
3589
|
+
}
|
|
3590
|
+
return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
|
|
3591
|
+
}
|
|
3592
|
+
function resolveConfig(file, env) {
|
|
3593
|
+
const envUrl = env.OCHE_URL?.trim() || null;
|
|
3594
|
+
const envToken = env.OCHE_TOKEN?.trim() || null;
|
|
3595
|
+
const fileUrl = file?.url ? safeNormalize(file.url) : null;
|
|
3596
|
+
const fileToken = file?.token?.trim() || null;
|
|
3597
|
+
const url = envUrl ? normalizeUrl(envUrl) : fileUrl;
|
|
3598
|
+
const urlSource = envUrl ? "env" : fileUrl ? "config" : "none";
|
|
3599
|
+
let token = null;
|
|
3600
|
+
let tokenSource = "none";
|
|
3601
|
+
if (envToken) {
|
|
3602
|
+
token = envToken;
|
|
3603
|
+
tokenSource = "env";
|
|
3604
|
+
} else if (fileToken && url && url === fileUrl) {
|
|
3605
|
+
token = fileToken;
|
|
3606
|
+
tokenSource = "config";
|
|
3607
|
+
}
|
|
3608
|
+
return { url, token, urlSource, tokenSource };
|
|
3609
|
+
}
|
|
3610
|
+
function safeNormalize(url) {
|
|
3611
|
+
try {
|
|
3612
|
+
return normalizeUrl(url);
|
|
3613
|
+
} catch {
|
|
3614
|
+
return null;
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
async function loadConfig(path2 = configPath()) {
|
|
3618
|
+
let raw;
|
|
3619
|
+
try {
|
|
3620
|
+
raw = await readFile(path2, "utf8");
|
|
3621
|
+
} catch (e) {
|
|
3622
|
+
if (e.code === "ENOENT") return null;
|
|
3623
|
+
throw new CliError(`Couldn't read ${path2}: ${e.message}`);
|
|
3624
|
+
}
|
|
3625
|
+
try {
|
|
3626
|
+
const parsed = JSON.parse(raw);
|
|
3627
|
+
if (typeof parsed.url !== "string" || typeof parsed.token !== "string") return null;
|
|
3628
|
+
return { url: parsed.url, token: parsed.token, login: parsed.login };
|
|
3629
|
+
} catch {
|
|
3630
|
+
throw new CliError(`${path2} is not valid JSON. Delete it or run \`oche login\` again.`);
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3633
|
+
async function saveConfig(cfg, path2 = configPath()) {
|
|
3634
|
+
await mkdir(dirname(path2), { recursive: true, mode: 448 });
|
|
3635
|
+
await writeFile(path2, `${JSON.stringify(cfg, null, 2)}
|
|
3636
|
+
`, { mode: 384 });
|
|
3637
|
+
await chmod(path2, 384);
|
|
3638
|
+
}
|
|
3639
|
+
async function deleteConfig(path2 = configPath()) {
|
|
3640
|
+
const existed = await loadConfig(path2).catch(() => ({})) !== null;
|
|
3641
|
+
await rm(path2, { force: true });
|
|
3642
|
+
return existed;
|
|
3643
|
+
}
|
|
3644
|
+
|
|
3645
|
+
// src/git.ts
|
|
3646
|
+
import { execFile } from "child_process";
|
|
3647
|
+
import { promisify } from "util";
|
|
3648
|
+
var slug = (r) => `${r.owner}/${r.repo}`;
|
|
3649
|
+
var GITHUB_HOST = /^(?:www\.|ssh\.)?github\.com(?:-[\w.-]+)?$/i;
|
|
3650
|
+
var OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
|
|
3651
|
+
var REPO = /^[A-Za-z0-9._-]{1,100}$/;
|
|
3652
|
+
var URL_SCHEMES = /* @__PURE__ */ new Set(["https:", "http:", "ssh:", "git:", "git+ssh:", "ssh+git:"]);
|
|
3653
|
+
function toSlug(path2) {
|
|
3654
|
+
const parts = path2.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
3655
|
+
if (parts.length !== 2) return null;
|
|
3656
|
+
const [owner, repo] = parts;
|
|
3657
|
+
if (!OWNER.test(owner) || !REPO.test(repo) || repo === "." || repo === "..") return null;
|
|
3658
|
+
return { owner, repo };
|
|
3659
|
+
}
|
|
3660
|
+
function parseGitHubRemote(remote) {
|
|
3661
|
+
const s = remote.trim();
|
|
3662
|
+
let host;
|
|
3663
|
+
let path2;
|
|
3664
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) {
|
|
3665
|
+
let u;
|
|
3666
|
+
try {
|
|
3667
|
+
u = new URL(s);
|
|
3668
|
+
} catch {
|
|
3669
|
+
return null;
|
|
3670
|
+
}
|
|
3671
|
+
if (!URL_SCHEMES.has(u.protocol)) return null;
|
|
3672
|
+
host = u.hostname;
|
|
3673
|
+
path2 = decodeURIComponent(u.pathname);
|
|
3674
|
+
} else {
|
|
3675
|
+
const m = /^(?:[^@\s/]+@)?([^:\s/]+):(.+)$/.exec(s);
|
|
3676
|
+
if (!m) return null;
|
|
3677
|
+
host = m[1];
|
|
3678
|
+
path2 = m[2];
|
|
3679
|
+
}
|
|
3680
|
+
if (!GITHUB_HOST.test(host)) return null;
|
|
3681
|
+
return toSlug(path2);
|
|
3682
|
+
}
|
|
3683
|
+
function parseRepoArg(arg) {
|
|
3684
|
+
const s = arg.trim();
|
|
3685
|
+
const found = /^[^/\s:@]+\/[^/\s:@]+$/.test(s) ? toSlug(s) : parseGitHubRemote(s);
|
|
3686
|
+
if (!found) throw new CliError(`Expected owner/repo, got "${arg}".`);
|
|
3687
|
+
return found;
|
|
3688
|
+
}
|
|
3689
|
+
var run = promisify(execFile);
|
|
3690
|
+
async function inferRepo(cwd = process.cwd()) {
|
|
3691
|
+
let url;
|
|
3692
|
+
try {
|
|
3693
|
+
const { stdout } = await run("git", ["remote", "get-url", "origin"], { cwd });
|
|
3694
|
+
url = stdout.trim();
|
|
3695
|
+
} catch (e) {
|
|
3696
|
+
if (e.code === "ENOENT") {
|
|
3697
|
+
throw new CliError("git isn't installed, so the repo can't be inferred. Pass owner/repo.");
|
|
3698
|
+
}
|
|
3699
|
+
throw new CliError('No repo given and no git remote "origin" here. Pass owner/repo.');
|
|
3700
|
+
}
|
|
3701
|
+
const found = parseGitHubRemote(url);
|
|
3702
|
+
if (!found) throw new CliError(`origin (${url}) isn't a GitHub repo. Pass owner/repo.`);
|
|
3703
|
+
return found;
|
|
3704
|
+
}
|
|
3705
|
+
async function resolveRepo(arg) {
|
|
3706
|
+
return arg ? parseRepoArg(arg) : inferRepo();
|
|
3707
|
+
}
|
|
3708
|
+
|
|
3709
|
+
// src/promotion.ts
|
|
3710
|
+
var DEFAULT_BRANCHES = { prod: "main", staging: "staging", dev: "dev" };
|
|
3711
|
+
function toPromotion(target, direct = false) {
|
|
3712
|
+
switch (target.trim().toLowerCase()) {
|
|
3713
|
+
case "staging":
|
|
3714
|
+
if (direct) throw new CliError("--direct only applies to prod (dev \u2192 main, skipping staging).");
|
|
3715
|
+
return "staging";
|
|
3716
|
+
case "prod":
|
|
3717
|
+
return direct ? "prod-direct" : "prod";
|
|
3718
|
+
default:
|
|
3719
|
+
throw new CliError(`Unknown target "${target}". Use staging or prod.`);
|
|
3720
|
+
}
|
|
3721
|
+
}
|
|
3722
|
+
var needsConfirmation = (p) => p !== "staging";
|
|
3723
|
+
function promotionRefs(p, branches = null) {
|
|
3724
|
+
const b = branches ?? DEFAULT_BRANCHES;
|
|
3725
|
+
switch (p) {
|
|
3726
|
+
case "staging":
|
|
3727
|
+
return { head: b.dev, base: b.staging };
|
|
3728
|
+
case "prod":
|
|
3729
|
+
return { head: b.staging, base: b.prod };
|
|
3730
|
+
case "prod-direct":
|
|
3731
|
+
return { head: b.dev, base: b.prod };
|
|
3732
|
+
}
|
|
3733
|
+
}
|
|
3734
|
+
|
|
3735
|
+
// src/local-config.ts
|
|
3736
|
+
import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
|
|
3737
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
3738
|
+
var DEFAULT_MODEL = "anthropic/claude-haiku-4.5";
|
|
3739
|
+
var localConfigPath = (env = process.env) => join2(dirname2(configPath(env)), "local.json");
|
|
3740
|
+
async function loadLocalConfig(path2 = localConfigPath()) {
|
|
3741
|
+
let raw;
|
|
3742
|
+
try {
|
|
3743
|
+
raw = await readFile2(path2, "utf8");
|
|
3744
|
+
} catch (e) {
|
|
3745
|
+
if (e.code === "ENOENT") return {};
|
|
3746
|
+
throw new CliError(`Couldn't read ${path2}: ${e.message}`);
|
|
3747
|
+
}
|
|
3748
|
+
try {
|
|
3749
|
+
const parsed = JSON.parse(raw);
|
|
3750
|
+
return {
|
|
3751
|
+
openrouterKey: typeof parsed.openrouterKey === "string" ? parsed.openrouterKey : void 0,
|
|
3752
|
+
model: typeof parsed.model === "string" ? parsed.model : void 0
|
|
3753
|
+
};
|
|
3754
|
+
} catch {
|
|
3755
|
+
throw new CliError(`${path2} is not valid JSON. Delete it or run \`oche ai-key\` again.`);
|
|
3756
|
+
}
|
|
3757
|
+
}
|
|
3758
|
+
async function saveLocalConfig(cfg, path2 = localConfigPath()) {
|
|
3759
|
+
await mkdir2(dirname2(path2), { recursive: true, mode: 448 });
|
|
3760
|
+
await writeFile2(path2, `${JSON.stringify(cfg, null, 2)}
|
|
3761
|
+
`, { mode: 384 });
|
|
3762
|
+
await chmod2(path2, 384);
|
|
3763
|
+
}
|
|
3764
|
+
function resolveAi(file, env) {
|
|
3765
|
+
return {
|
|
3766
|
+
key: env.OPENROUTER_API_KEY?.trim() || file.openrouterKey?.trim() || null,
|
|
3767
|
+
model: env.OCHE_AI_MODEL?.trim() || file.model?.trim() || DEFAULT_MODEL
|
|
3768
|
+
};
|
|
3769
|
+
}
|
|
3770
|
+
|
|
3771
|
+
// src/github.ts
|
|
3772
|
+
import { execFile as execFile2 } from "child_process";
|
|
3773
|
+
import { promisify as promisify2 } from "util";
|
|
3774
|
+
var API = "https://api.github.com";
|
|
3775
|
+
var run2 = promisify2(execFile2);
|
|
3776
|
+
async function githubToken(env = process.env) {
|
|
3777
|
+
const fromEnv = env.GH_TOKEN?.trim() || env.GITHUB_TOKEN?.trim();
|
|
3778
|
+
if (fromEnv) return fromEnv;
|
|
3779
|
+
try {
|
|
3780
|
+
const { stdout } = await run2("gh", ["auth", "token"]);
|
|
3781
|
+
if (stdout.trim()) return stdout.trim();
|
|
3782
|
+
} catch {
|
|
3783
|
+
}
|
|
3784
|
+
throw new CliError("No GitHub token. Run `gh auth login`, or set GH_TOKEN to a token with repo access.");
|
|
3785
|
+
}
|
|
3786
|
+
var GitHub = class {
|
|
3787
|
+
constructor(token, fetchImpl = fetch) {
|
|
3788
|
+
this.token = token;
|
|
3789
|
+
this.fetchImpl = fetchImpl;
|
|
3790
|
+
}
|
|
3791
|
+
token;
|
|
3792
|
+
fetchImpl;
|
|
3793
|
+
/** The first of `names` that exists on GitHub, in order. */
|
|
3794
|
+
async firstBranch(r, names) {
|
|
3795
|
+
for (const name of names) {
|
|
3796
|
+
const res = await this.raw("GET", `/repos/${slug(r)}/branches/${encodeURIComponent(name)}`);
|
|
3797
|
+
if (res.ok) return name;
|
|
3798
|
+
if (res.status !== 404) await this.fail(res, `look up ${name}`);
|
|
3799
|
+
}
|
|
3800
|
+
return null;
|
|
3801
|
+
}
|
|
3802
|
+
async openPull(r, head, base) {
|
|
3803
|
+
const q = new URLSearchParams({ state: "open", head: `${r.owner}:${head}`, base });
|
|
3804
|
+
const list = await this.json("GET", `/repos/${slug(r)}/pulls?${q}`, void 0, "list pull requests");
|
|
3805
|
+
return list[0] ?? null;
|
|
3806
|
+
}
|
|
3807
|
+
async createPull(r, body) {
|
|
3808
|
+
return this.json("POST", `/repos/${slug(r)}/pulls`, body, "open the pull request");
|
|
3809
|
+
}
|
|
3810
|
+
async pull(r, n) {
|
|
3811
|
+
return this.json("GET", `/repos/${slug(r)}/pulls/${n}`, void 0, `read PR #${n}`);
|
|
3812
|
+
}
|
|
3813
|
+
async merge(r, n, method) {
|
|
3814
|
+
await this.json("PUT", `/repos/${slug(r)}/pulls/${n}/merge`, { merge_method: method }, `merge PR #${n}`);
|
|
3815
|
+
}
|
|
3816
|
+
async deleteBranch(r, branch) {
|
|
3817
|
+
const res = await this.raw("DELETE", `/repos/${slug(r)}/git/refs/heads/${branch.split("/").map(encodeURIComponent).join("/")}`);
|
|
3818
|
+
if (!res.ok && res.status !== 422 && res.status !== 404) await this.fail(res, `delete ${branch}`);
|
|
3819
|
+
}
|
|
3820
|
+
async json(method, path2, body, what) {
|
|
3821
|
+
const res = await this.raw(method, path2, body);
|
|
3822
|
+
if (!res.ok) await this.fail(res, what);
|
|
3823
|
+
return await res.json();
|
|
3824
|
+
}
|
|
3825
|
+
async raw(method, path2, body) {
|
|
3826
|
+
try {
|
|
3827
|
+
return await this.fetchImpl(`${API}${path2}`, {
|
|
3828
|
+
method,
|
|
3829
|
+
headers: {
|
|
3830
|
+
accept: "application/vnd.github+json",
|
|
3831
|
+
authorization: `Bearer ${this.token}`,
|
|
3832
|
+
"x-github-api-version": "2022-11-28",
|
|
3833
|
+
"user-agent": "oche-cli",
|
|
3834
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
3835
|
+
},
|
|
3836
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
3837
|
+
signal: AbortSignal.timeout(3e4)
|
|
3838
|
+
});
|
|
3839
|
+
} catch (e) {
|
|
3840
|
+
throw new CliError(`Couldn't reach GitHub (${e.message}).`);
|
|
3841
|
+
}
|
|
3842
|
+
}
|
|
3843
|
+
async fail(res, what) {
|
|
3844
|
+
const data = await res.json().catch(() => null);
|
|
3845
|
+
const detail = [data?.message, ...(data?.errors ?? []).map((e) => e.message)].filter(Boolean).join(": ");
|
|
3846
|
+
if (res.status === 401) throw new CliError("GitHub rejected your token. Run `gh auth login` again, or check GH_TOKEN.");
|
|
3847
|
+
if (res.status === 404) throw new CliError(`Couldn't ${what}: GitHub says not found. Does your token have access to this repo?`);
|
|
3848
|
+
throw new CliError(`Couldn't ${what} (HTTP ${res.status})${detail ? `: ${detail}` : ""}.`);
|
|
3849
|
+
}
|
|
3850
|
+
};
|
|
3851
|
+
|
|
3852
|
+
// src/localgit.ts
|
|
3853
|
+
import { execFile as execFile3, spawn } from "child_process";
|
|
3854
|
+
import { copyFile, mkdtemp, rm as rm2 } from "fs/promises";
|
|
3855
|
+
import { tmpdir } from "os";
|
|
3856
|
+
import { join as join3 } from "path";
|
|
3857
|
+
import { promisify as promisify3 } from "util";
|
|
3858
|
+
var exec = promisify3(execFile3);
|
|
3859
|
+
var MAX_BUFFER = 64 * 1024 * 1024;
|
|
3860
|
+
async function git(args, env) {
|
|
3861
|
+
try {
|
|
3862
|
+
const { stdout } = await exec("git", args, { maxBuffer: MAX_BUFFER, env: env ? { ...process.env, ...env } : process.env });
|
|
3863
|
+
return stdout;
|
|
3864
|
+
} catch (e) {
|
|
3865
|
+
const err = e;
|
|
3866
|
+
if (err.code === "ENOENT") throw new CliError("git isn't installed.");
|
|
3867
|
+
throw new CliError(`git ${args[0]} failed: ${(err.stderr ?? err.message).trim()}`);
|
|
3868
|
+
}
|
|
3869
|
+
}
|
|
3870
|
+
async function currentBranch() {
|
|
3871
|
+
const name = (await git(["symbolic-ref", "--short", "-q", "HEAD"]).catch(() => "")).trim();
|
|
3872
|
+
if (!name) throw new CliError("You're on a detached HEAD. Switch to a branch first.");
|
|
3873
|
+
return name;
|
|
3874
|
+
}
|
|
3875
|
+
async function changes() {
|
|
3876
|
+
const out = await git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
|
|
3877
|
+
const entries = out.split("\0").filter(Boolean);
|
|
3878
|
+
const list = [];
|
|
3879
|
+
for (let i = 0; i < entries.length; i++) {
|
|
3880
|
+
const e = entries[i];
|
|
3881
|
+
const code = e.slice(0, 2);
|
|
3882
|
+
list.push({ code, path: e.slice(3) });
|
|
3883
|
+
if (code[0] === "R" || code[0] === "C") i++;
|
|
3884
|
+
}
|
|
3885
|
+
return list;
|
|
3886
|
+
}
|
|
3887
|
+
async function stagedDiff(maxChars = 6e4) {
|
|
3888
|
+
const [diff, stat] = await Promise.all([git(["diff", "--cached", "--no-color"]), git(["diff", "--cached", "--stat", "--no-color"])]);
|
|
3889
|
+
return { diff: diff.length > maxChars ? `${diff.slice(0, maxChars)}
|
|
3890
|
+
[diff truncated]` : diff, stat };
|
|
3891
|
+
}
|
|
3892
|
+
async function previewAddAll(maxChars = 6e4) {
|
|
3893
|
+
const indexPath = (await git(["rev-parse", "--path-format=absolute", "--git-path", "index"])).trim();
|
|
3894
|
+
const dir = await mkdtemp(join3(tmpdir(), "oche-index-"));
|
|
3895
|
+
const tmpIndex = join3(dir, "index");
|
|
3896
|
+
try {
|
|
3897
|
+
await copyFile(indexPath, tmpIndex).catch(() => {
|
|
3898
|
+
});
|
|
3899
|
+
const env = { GIT_INDEX_FILE: tmpIndex };
|
|
3900
|
+
await git(["add", "-A"], env);
|
|
3901
|
+
const [diff, stat] = await Promise.all([
|
|
3902
|
+
git(["diff", "--cached", "--no-color"], env),
|
|
3903
|
+
git(["diff", "--cached", "--stat", "--no-color"], env)
|
|
3904
|
+
]);
|
|
3905
|
+
return { diff: diff.length > maxChars ? `${diff.slice(0, maxChars)}
|
|
3906
|
+
[diff truncated]` : diff, stat };
|
|
3907
|
+
} finally {
|
|
3908
|
+
await rm2(dir, { recursive: true, force: true });
|
|
3909
|
+
}
|
|
3910
|
+
}
|
|
3911
|
+
async function recentSubjects(n = 10) {
|
|
3912
|
+
try {
|
|
3913
|
+
return (await git(["log", `-${n}`, "--format=%s"])).split("\n").filter(Boolean);
|
|
3914
|
+
} catch {
|
|
3915
|
+
return [];
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
var addAll = () => git(["add", "-A"]);
|
|
3919
|
+
var addTracked = () => git(["add", "-u"]);
|
|
3920
|
+
var commit = (message) => git(["commit", "-m", message]);
|
|
3921
|
+
function commitWithEditor(message) {
|
|
3922
|
+
return new Promise((resolve, reject) => {
|
|
3923
|
+
const child = spawn("git", ["commit", "-e", "-m", message], { stdio: "inherit" });
|
|
3924
|
+
child.on("error", reject);
|
|
3925
|
+
child.on("exit", (code) => code === 0 ? resolve() : reject(new CliError("Commit aborted.")));
|
|
3926
|
+
});
|
|
3927
|
+
}
|
|
3928
|
+
async function unpushed() {
|
|
3929
|
+
try {
|
|
3930
|
+
return Number((await git(["rev-list", "--count", "@{u}..HEAD"])).trim());
|
|
3931
|
+
} catch {
|
|
3932
|
+
return null;
|
|
3933
|
+
}
|
|
3934
|
+
}
|
|
3935
|
+
var push = (branch) => git(["push", "--set-upstream", "origin", branch]);
|
|
3936
|
+
var fetchBranch = (branch) => git(["fetch", "--quiet", "origin", branch]);
|
|
3937
|
+
async function subjectsAhead(base) {
|
|
3938
|
+
return (await git(["log", `origin/${base}..HEAD`, "--format=%s"])).split("\n").filter(Boolean);
|
|
3939
|
+
}
|
|
3940
|
+
|
|
3941
|
+
// src/openrouter.ts
|
|
3942
|
+
var ENDPOINT = "https://openrouter.ai/api/v1/chat/completions";
|
|
3943
|
+
var SYSTEM_PROMPT = `You write git commit messages.
|
|
3944
|
+
Use Conventional Commits: type(optional scope): subject.
|
|
3945
|
+
The subject is imperative, lower case after the colon, at most 72 characters, no trailing period.
|
|
3946
|
+
If the change isn't trivial, add a blank line and a short body (wrapped at 72) that says why, not how.
|
|
3947
|
+
Match the style of the recent commit subjects you're given.
|
|
3948
|
+
Reply with the message only: no code fences, no quotes, no emoji, no preamble.`;
|
|
3949
|
+
function buildMessages(input) {
|
|
3950
|
+
const parts = [
|
|
3951
|
+
input.branch ? `Branch: ${input.branch}` : null,
|
|
3952
|
+
input.recent?.length ? `Recent commit subjects:
|
|
3953
|
+
${input.recent.map((s) => `- ${s}`).join("\n")}` : null,
|
|
3954
|
+
`Files changed:
|
|
3955
|
+
${input.stat.trim()}`,
|
|
3956
|
+
`Diff:
|
|
3957
|
+
${input.diff}`
|
|
3958
|
+
].filter(Boolean);
|
|
3959
|
+
return [
|
|
3960
|
+
{ role: "system", content: SYSTEM_PROMPT },
|
|
3961
|
+
{ role: "user", content: parts.join("\n\n") }
|
|
3962
|
+
];
|
|
3963
|
+
}
|
|
3964
|
+
function parseMessage(data) {
|
|
3965
|
+
const content = data?.choices?.[0]?.message?.content;
|
|
3966
|
+
if (typeof content !== "string" || !content.trim()) throw new CliError("The model returned an empty message. Try again, or pass -m.");
|
|
3967
|
+
return content.trim().replace(/^```[a-z]*\n?|\n?```$/g, "").replace(/^["'`]|["'`]$/g, "").trim();
|
|
3968
|
+
}
|
|
3969
|
+
async function generateCommitMessage(input, opts) {
|
|
3970
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
3971
|
+
let res;
|
|
3972
|
+
try {
|
|
3973
|
+
res = await doFetch(ENDPOINT, {
|
|
3974
|
+
method: "POST",
|
|
3975
|
+
headers: { authorization: `Bearer ${opts.apiKey}`, "content-type": "application/json", "x-title": "Oche" },
|
|
3976
|
+
body: JSON.stringify({ model: opts.model, messages: buildMessages(input), max_tokens: 400, temperature: 0.2 }),
|
|
3977
|
+
signal: AbortSignal.timeout(6e4)
|
|
3978
|
+
});
|
|
3979
|
+
} catch (e) {
|
|
3980
|
+
throw new CliError(`Couldn't reach OpenRouter (${e.message}). Pass -m to skip AI.`);
|
|
3981
|
+
}
|
|
3982
|
+
if (res.status === 401 || res.status === 403) throw new CliError("OpenRouter rejected your API key. Run `oche ai-key` to replace it.");
|
|
3983
|
+
if (res.status === 402) throw new CliError("OpenRouter is out of credits. Pass -m to skip AI.");
|
|
3984
|
+
if (res.status === 429) throw new CliError("OpenRouter rate limit hit. Try again shortly, or pass -m.");
|
|
3985
|
+
if (res.status === 400 || res.status === 404) {
|
|
3986
|
+
const detail = (await res.json().catch(() => null))?.error?.message;
|
|
3987
|
+
throw new CliError(`OpenRouter refused the request for model ${opts.model}${detail ? `: ${detail}` : ""}.`);
|
|
3988
|
+
}
|
|
3989
|
+
if (!res.ok) throw new CliError(`OpenRouter failed (HTTP ${res.status}).`);
|
|
3990
|
+
return parseMessage(await res.json());
|
|
3991
|
+
}
|
|
3992
|
+
|
|
3993
|
+
// src/ui.ts
|
|
3994
|
+
import { createInterface } from "readline";
|
|
3995
|
+
import { styleText } from "util";
|
|
3996
|
+
function paint(format, text, stream = process.stdout) {
|
|
3997
|
+
if (process.env.NO_COLOR) return text;
|
|
3998
|
+
return styleText(format, text, { stream, validateStream: true });
|
|
3999
|
+
}
|
|
4000
|
+
var c = {
|
|
4001
|
+
bold: (s) => paint("bold", s),
|
|
4002
|
+
dim: (s) => paint("dim", s),
|
|
4003
|
+
green: (s) => paint("green", s),
|
|
4004
|
+
red: (s) => paint("red", s),
|
|
4005
|
+
yellow: (s) => paint("yellow", s),
|
|
4006
|
+
cyan: (s) => paint("cyan", s)
|
|
4007
|
+
};
|
|
4008
|
+
var print = (line = "") => void process.stdout.write(`${line}
|
|
4009
|
+
`);
|
|
4010
|
+
var printJson = (data) => print(JSON.stringify(data, null, 2));
|
|
4011
|
+
var ok = (msg) => print(`${c.green("\u2713")} ${msg}`);
|
|
4012
|
+
var warn = (msg) => process.stderr.write(`${paint("yellow", "!", process.stderr)} ${msg}
|
|
4013
|
+
`);
|
|
4014
|
+
var fail = (msg) => process.stderr.write(`${paint("red", "\u2717", process.stderr)} ${msg}
|
|
4015
|
+
`);
|
|
4016
|
+
function relativeTime(iso, now = Date.now()) {
|
|
4017
|
+
if (!iso) return "";
|
|
4018
|
+
const then = Date.parse(iso);
|
|
4019
|
+
if (Number.isNaN(then)) return "";
|
|
4020
|
+
const s = Math.max(0, Math.round((now - then) / 1e3));
|
|
4021
|
+
if (s < 45) return "just now";
|
|
4022
|
+
const m = Math.round(s / 60);
|
|
4023
|
+
if (m < 60) return `${m}m ago`;
|
|
4024
|
+
const h = Math.round(m / 60);
|
|
4025
|
+
if (h < 24) return `${h}h ago`;
|
|
4026
|
+
const d = Math.round(h / 24);
|
|
4027
|
+
if (d < 30) return `${d}d ago`;
|
|
4028
|
+
return new Date(then).toISOString().slice(0, 10);
|
|
4029
|
+
}
|
|
4030
|
+
function truncate(s, max) {
|
|
4031
|
+
return s.length <= max ? s : `${s.slice(0, max - 1)}\u2026`;
|
|
4032
|
+
}
|
|
4033
|
+
var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
4034
|
+
function columns(rows, indent = " ") {
|
|
4035
|
+
const plainOf = (cell) => typeof cell === "string" ? cell : cell[0];
|
|
4036
|
+
const styledOf = (cell) => typeof cell === "string" ? cell : cell[1];
|
|
4037
|
+
const widths = [];
|
|
4038
|
+
for (const row of rows) row.forEach((cell, i) => widths[i] = Math.max(widths[i] ?? 0, plainOf(cell).length));
|
|
4039
|
+
return rows.map(
|
|
4040
|
+
(row) => indent + row.map((cell, i) => i === row.length - 1 ? styledOf(cell) : styledOf(cell) + " ".repeat((widths[i] ?? 0) - plainOf(cell).length)).join(" ").trimEnd()
|
|
4041
|
+
);
|
|
4042
|
+
}
|
|
4043
|
+
var isInteractive = () => Boolean(process.stdin.isTTY);
|
|
4044
|
+
var reader = null;
|
|
4045
|
+
async function readLine() {
|
|
4046
|
+
if (!reader) {
|
|
4047
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity, terminal: false });
|
|
4048
|
+
reader = { rl, lines: rl[Symbol.asyncIterator]() };
|
|
4049
|
+
}
|
|
4050
|
+
const next = await reader.lines.next();
|
|
4051
|
+
if (next.done) throw new CliError("No input: stdin was closed.");
|
|
4052
|
+
return next.value;
|
|
4053
|
+
}
|
|
4054
|
+
function closeReader() {
|
|
4055
|
+
reader?.rl.close();
|
|
4056
|
+
reader = null;
|
|
4057
|
+
}
|
|
4058
|
+
async function ask(question, fallback) {
|
|
4059
|
+
process.stderr.write(fallback ? `${question} ${paint("dim", `(${fallback})`, process.stderr)}: ` : `${question}: `);
|
|
4060
|
+
const answer = (await readLine()).trim();
|
|
4061
|
+
if (isInteractive()) closeReader();
|
|
4062
|
+
else process.stderr.write("\n");
|
|
4063
|
+
return answer || fallback || "";
|
|
4064
|
+
}
|
|
4065
|
+
async function askHidden(question) {
|
|
4066
|
+
process.stderr.write(`${question}: `);
|
|
4067
|
+
if (!isInteractive()) {
|
|
4068
|
+
const line = (await readLine()).trim();
|
|
4069
|
+
process.stderr.write("\n");
|
|
4070
|
+
return line;
|
|
4071
|
+
}
|
|
4072
|
+
closeReader();
|
|
4073
|
+
const stdin = process.stdin;
|
|
4074
|
+
return new Promise((resolve, reject) => {
|
|
4075
|
+
let buf = "";
|
|
4076
|
+
const finish = (err) => {
|
|
4077
|
+
stdin.off("data", onData);
|
|
4078
|
+
stdin.setRawMode(false);
|
|
4079
|
+
stdin.pause();
|
|
4080
|
+
process.stderr.write("\n");
|
|
4081
|
+
if (err) reject(err);
|
|
4082
|
+
else resolve(buf.trim());
|
|
4083
|
+
};
|
|
4084
|
+
const onData = (chunk) => {
|
|
4085
|
+
const text = chunk.toString().replace(/\x1b\[[0-9;]*[A-Za-z~]/g, "");
|
|
4086
|
+
for (const ch of text) {
|
|
4087
|
+
if (ch === "\r" || ch === "\n") return finish();
|
|
4088
|
+
if (ch === "") return finish(new CliError("Cancelled.", 130));
|
|
4089
|
+
if (ch === "") return buf ? finish() : finish(new CliError("Cancelled.", 130));
|
|
4090
|
+
if (ch === "\x7F" || ch === "\b") buf = buf.slice(0, -1);
|
|
4091
|
+
else if (ch === "") buf = "";
|
|
4092
|
+
else if (ch >= " ") buf += ch;
|
|
4093
|
+
}
|
|
4094
|
+
};
|
|
4095
|
+
stdin.setRawMode(true);
|
|
4096
|
+
stdin.resume();
|
|
4097
|
+
stdin.on("data", onData);
|
|
4098
|
+
});
|
|
4099
|
+
}
|
|
4100
|
+
async function confirm(question, defaultYes = false) {
|
|
4101
|
+
if (!isInteractive()) throw new CliError(`${question} Needs confirmation; pass --yes to run without a prompt.`);
|
|
4102
|
+
const hint = defaultYes ? "Y/n" : "y/N";
|
|
4103
|
+
process.stderr.write(`${question} ${paint("dim", `[${hint}]`, process.stderr)} `);
|
|
4104
|
+
const answer = (await readLine()).trim().toLowerCase();
|
|
4105
|
+
closeReader();
|
|
4106
|
+
if (!answer) return defaultYes;
|
|
4107
|
+
return answer === "y" || answer === "yes";
|
|
4108
|
+
}
|
|
4109
|
+
|
|
4110
|
+
// src/ship-run.ts
|
|
4111
|
+
var MERGE_HOW = {
|
|
4112
|
+
merge: "open a PR and merge",
|
|
4113
|
+
squash: "open a PR and squash-merge",
|
|
4114
|
+
rebase: "open a PR and rebase-merge"
|
|
4115
|
+
};
|
|
4116
|
+
var STAGING_WAIT = "wait for staging to deploy healthy on Coolify";
|
|
4117
|
+
var PROD_WAIT = "wait for production to deploy healthy";
|
|
4118
|
+
function shipHops(branches, from, target, direct) {
|
|
4119
|
+
const hops = [];
|
|
4120
|
+
if (from !== branches.dev) hops.push({ head: from, base: branches.dev });
|
|
4121
|
+
if (target === "staging" || target === "prod" && !direct) hops.push({ head: branches.dev, base: branches.staging });
|
|
4122
|
+
if (target === "prod") hops.push(direct ? { head: branches.dev, base: branches.prod } : { head: branches.staging, base: branches.prod });
|
|
4123
|
+
return hops;
|
|
4124
|
+
}
|
|
4125
|
+
function planLines(repo, branch, target, direct) {
|
|
4126
|
+
const b = repo.branches;
|
|
4127
|
+
const review = repo.mode === "strict" ? c.yellow(` (needs ${plural(repo.requiredApprovals, "approval")})`) : "";
|
|
4128
|
+
const hops = shipHops(b, branch, target, direct);
|
|
4129
|
+
const toProd = hops.some((h) => h.base === b.prod);
|
|
4130
|
+
const lines = [];
|
|
4131
|
+
for (const h of hops) {
|
|
4132
|
+
const arrow = `${h.head} \u2192 ${h.base}`;
|
|
4133
|
+
if (h.base === b.dev) lines.push(`${arrow}${c.dim(` ${MERGE_HOW[repo.workMergeMethod] ?? MERGE_HOW.squash}`)}${review}`);
|
|
4134
|
+
else if (h.head === b.dev && h.base === b.prod) lines.push(`${arrow}${c.dim(` then Oche merges ${b.prod} into ${b.staging}`)}${review}`);
|
|
4135
|
+
else lines.push(`${arrow}${review}`);
|
|
4136
|
+
if (!repo.coolifyLinked) continue;
|
|
4137
|
+
if (h.base === b.staging && toProd && repo.gateOnStaging) lines.push(STAGING_WAIT);
|
|
4138
|
+
if (h.base === b.prod) lines.push(PROD_WAIT);
|
|
4139
|
+
if (h.base === b.staging && !toProd) lines.push(STAGING_WAIT);
|
|
4140
|
+
}
|
|
4141
|
+
return lines;
|
|
4142
|
+
}
|
|
4143
|
+
function stepLines(step) {
|
|
4144
|
+
const detail = step.detail ? ` ${step.detail}` : "";
|
|
4145
|
+
const pr = step.pr ? ` \u2192 ${step.pr.url}` : null;
|
|
4146
|
+
switch (step.status) {
|
|
4147
|
+
case "pending":
|
|
4148
|
+
return [];
|
|
4149
|
+
case "running":
|
|
4150
|
+
return [c.dim(`\u2026 ${step.label}${step.kind === "wait" ? detail : ""}`)];
|
|
4151
|
+
case "done":
|
|
4152
|
+
return [`${c.green("\u2713")} ${step.label}${step.pr ? ` ${c.dim(`#${step.pr.number}`)}` : ""}`];
|
|
4153
|
+
case "skipped":
|
|
4154
|
+
return [`${c.dim("\xB7")} ${step.label}${step.detail ? ` ${c.dim(step.detail)}` : ""}`];
|
|
4155
|
+
case "waiting-review":
|
|
4156
|
+
return [`${c.yellow("\u2026")} ${step.label} waiting for review${step.detail ? `: ${step.detail}` : ""}`, ...pr ? [pr] : []];
|
|
4157
|
+
case "failed":
|
|
4158
|
+
return [`${c.red("\u2717")} ${step.label}${detail}`, ...pr ? [pr] : []];
|
|
4159
|
+
}
|
|
4160
|
+
}
|
|
4161
|
+
function stepUpdates(prev, next) {
|
|
4162
|
+
const before = new Map(prev.map((s) => [s.id, s]));
|
|
4163
|
+
const lines = [];
|
|
4164
|
+
for (const step of next) {
|
|
4165
|
+
const old = before.get(step.id);
|
|
4166
|
+
const changed = !old || old.status !== step.status || step.status === "running" && step.kind === "wait" && (old.detail ?? "") !== (step.detail ?? "");
|
|
4167
|
+
if (changed) lines.push(...stepLines(step));
|
|
4168
|
+
}
|
|
4169
|
+
return lines;
|
|
4170
|
+
}
|
|
4171
|
+
|
|
4172
|
+
// src/ship.ts
|
|
4173
|
+
async function writeMessage(api, input) {
|
|
4174
|
+
process.stderr.write(c.dim("Writing a commit message\u2026\n"));
|
|
4175
|
+
return (await api.commitMessage(input)).message;
|
|
4176
|
+
}
|
|
4177
|
+
function showMessage(message) {
|
|
4178
|
+
print("");
|
|
4179
|
+
for (const line of message.split("\n")) print(` ${line ? c.bold(line) : ""}`);
|
|
4180
|
+
print("");
|
|
4181
|
+
}
|
|
4182
|
+
async function choose(question, canRewrite) {
|
|
4183
|
+
const keys = canRewrite ? "Y/n \xB7 e edit \xB7 r rewrite" : "Y/n \xB7 e edit";
|
|
4184
|
+
for (; ; ) {
|
|
4185
|
+
const a = (await ask(`${question} [${keys}]`, "y")).trim().toLowerCase();
|
|
4186
|
+
if (a === "" || a === "y" || a === "yes") return "yes";
|
|
4187
|
+
if (a === "n" || a === "no" || a === "q") return "no";
|
|
4188
|
+
if (a === "e" || a === "edit") return "edit";
|
|
4189
|
+
if (canRewrite && (a === "r" || a === "rewrite")) return "rewrite";
|
|
4190
|
+
}
|
|
4191
|
+
}
|
|
4192
|
+
async function commitCommand(getClient, opts) {
|
|
4193
|
+
if (opts.all) await addTracked();
|
|
4194
|
+
const staged = await stagedDiff();
|
|
4195
|
+
if (!staged.diff.trim()) throw new CliError("Nothing staged. Stage files with `git add`, or use -a for tracked changes.");
|
|
4196
|
+
const input = { ...staged, recent: await recentSubjects(), branch: await currentBranch() };
|
|
4197
|
+
const api = opts.message ? null : await getClient();
|
|
4198
|
+
let message = opts.message ?? await writeMessage(api, input);
|
|
4199
|
+
for (; ; ) {
|
|
4200
|
+
showMessage(message);
|
|
4201
|
+
if (opts.dryRun) return;
|
|
4202
|
+
if (opts.yes || !isInteractive()) break;
|
|
4203
|
+
const choice = await choose("Commit with this message?", !opts.message);
|
|
4204
|
+
if (choice === "no") return print("Nothing committed.");
|
|
4205
|
+
if (choice === "rewrite" && api) {
|
|
4206
|
+
message = await writeMessage(api, input);
|
|
4207
|
+
continue;
|
|
4208
|
+
}
|
|
4209
|
+
if (choice === "edit") {
|
|
4210
|
+
closeReader();
|
|
4211
|
+
await commitWithEditor(message);
|
|
4212
|
+
return ok("Committed.");
|
|
4213
|
+
}
|
|
4214
|
+
break;
|
|
4215
|
+
}
|
|
4216
|
+
await commit(message);
|
|
4217
|
+
ok("Committed.");
|
|
4218
|
+
}
|
|
4219
|
+
var TARGET_LABEL = { dev: "dev", staging: "staging", prod: "production" };
|
|
4220
|
+
function describeChange(ch) {
|
|
4221
|
+
const code = ch.code.trim() || "M";
|
|
4222
|
+
const tone = code === "??" || code.includes("A") ? c.green : code.includes("D") ? c.red : c.yellow;
|
|
4223
|
+
return `${tone(code === "??" ? "A" : code[0])} ${ch.path}`;
|
|
4224
|
+
}
|
|
4225
|
+
async function shipCommand(getClient, targetArg, repoArg, opts) {
|
|
4226
|
+
if (opts.cancel !== void 0) return cancelCommand(getClient, opts.cancel);
|
|
4227
|
+
const target = targetArg ?? "prod";
|
|
4228
|
+
if (!["dev", "staging", "prod"].includes(target)) throw new CliError(`Ship to dev, staging or prod, not "${targetArg}".`);
|
|
4229
|
+
if (opts.direct && target !== "prod") throw new CliError("--direct only applies when shipping to prod.");
|
|
4230
|
+
const [repoSlug, branch, changed] = await Promise.all([resolveRepo(repoArg), currentBranch(), changes()]);
|
|
4231
|
+
const api = await getClient();
|
|
4232
|
+
const { repo } = await api.repo(repoSlug);
|
|
4233
|
+
if (!repo.managed || !repo.branches) throw new CliError(`${repo.fullName} isn't set up in Oche yet. Run \`oche onboard\`.`);
|
|
4234
|
+
const b = repo.branches;
|
|
4235
|
+
if (branch === b.staging || branch === b.prod) {
|
|
4236
|
+
throw new CliError(`You're on ${branch}. Ship from ${b.dev} or a work branch; Oche moves things into ${branch} for you.`);
|
|
4237
|
+
}
|
|
4238
|
+
if (target === "dev" && branch === b.dev) throw new CliError(`You're already on ${b.dev}. Ship to staging or prod.`);
|
|
4239
|
+
let message = null;
|
|
4240
|
+
let input = null;
|
|
4241
|
+
if (changed.length) {
|
|
4242
|
+
input = { ...await previewAddAll(), recent: await recentSubjects(), branch };
|
|
4243
|
+
message = opts.message ?? await writeMessage(api, input);
|
|
4244
|
+
}
|
|
4245
|
+
const behind = await unpushed();
|
|
4246
|
+
const steps = planLines(repo, branch, target, Boolean(opts.direct));
|
|
4247
|
+
for (; ; ) {
|
|
4248
|
+
print(`${c.bold(`Ship ${branch} to ${TARGET_LABEL[target]}`)} ${c.dim(`${repo.fullName} \xB7 ${repo.mode}`)}`);
|
|
4249
|
+
print("");
|
|
4250
|
+
let n = 1;
|
|
4251
|
+
if (message) {
|
|
4252
|
+
print(` ${n++}. Commit ${plural(changed.length, "file")}:`);
|
|
4253
|
+
for (const line of message.split("\n")) print(` ${line ? c.bold(line) : ""}`);
|
|
4254
|
+
for (const ch of changed.slice(0, 12)) print(` ${describeChange(ch)}`);
|
|
4255
|
+
if (changed.length > 12) print(c.dim(` \u2026and ${changed.length - 12} more`));
|
|
4256
|
+
}
|
|
4257
|
+
print(` ${n++}. Push ${branch}${behind === null ? c.dim(" (new on GitHub)") : behind > 0 ? c.dim(` (${plural(behind, "commit")} not pushed yet)`) : ""}`);
|
|
4258
|
+
for (const s of steps) print(` ${n++}. ${s}`);
|
|
4259
|
+
if (target === "prod" && !repo.coolifyLinked) print(c.dim(`
|
|
4260
|
+
Coolify deploys ${b.prod} when the last step lands.`));
|
|
4261
|
+
print("");
|
|
4262
|
+
if (opts.yes) break;
|
|
4263
|
+
if (!isInteractive()) throw new CliError("Shipping needs confirmation. Run it in a terminal, or pass --yes.");
|
|
4264
|
+
const choice = await choose("Ship it?", Boolean(message && !opts.message));
|
|
4265
|
+
if (choice === "no") return print("Nothing shipped.");
|
|
4266
|
+
if (choice === "rewrite" && input) {
|
|
4267
|
+
message = await writeMessage(api, input);
|
|
4268
|
+
continue;
|
|
4269
|
+
}
|
|
4270
|
+
if (choice === "edit" && message) {
|
|
4271
|
+
const edited = await ask("Message (one line; use `oche commit` for a longer one)", message.split("\n")[0]);
|
|
4272
|
+
message = edited.trim() || message;
|
|
4273
|
+
continue;
|
|
4274
|
+
}
|
|
4275
|
+
break;
|
|
4276
|
+
}
|
|
4277
|
+
if (message) {
|
|
4278
|
+
await addAll();
|
|
4279
|
+
await commit(message);
|
|
4280
|
+
ok("Committed");
|
|
4281
|
+
}
|
|
4282
|
+
process.stderr.write(c.dim(`Pushing ${branch}\u2026
|
|
4283
|
+
`));
|
|
4284
|
+
await push(branch);
|
|
4285
|
+
ok(`Pushed ${branch}`);
|
|
4286
|
+
let run3;
|
|
4287
|
+
try {
|
|
4288
|
+
({ run: run3 } = await api.ship(repoSlug, { from: branch, to: target, direct: opts.direct }));
|
|
4289
|
+
} catch (e) {
|
|
4290
|
+
if (e instanceof ApiRequestError && e.status === 409) {
|
|
4291
|
+
const message2 = e.message.replace(/ \(HTTP 409\)$/, "");
|
|
4292
|
+
const id = /\(#(\d+)\)/.exec(message2)?.[1];
|
|
4293
|
+
throw new CliError(id ? `${message2}
|
|
4294
|
+
Follow it in the dashboard, or cancel it with \`oche ship --cancel ${id}\`.` : message2);
|
|
4295
|
+
}
|
|
4296
|
+
throw e;
|
|
4297
|
+
}
|
|
4298
|
+
print("");
|
|
4299
|
+
print(c.dim(`Ship #${run3.id} is running on the server.`));
|
|
4300
|
+
closeReader();
|
|
4301
|
+
run3 = await followRun(api, run3);
|
|
4302
|
+
switch (run3.status) {
|
|
4303
|
+
case "succeeded":
|
|
4304
|
+
ok(`Shipped to ${TARGET_LABEL[target]}`);
|
|
4305
|
+
if (branch !== b.dev) print(c.dim(`
|
|
4306
|
+
You're still on ${branch}. \`git switch ${b.dev} && git pull\` to carry on from ${b.dev}.`));
|
|
4307
|
+
break;
|
|
4308
|
+
case "stopped":
|
|
4309
|
+
warn("Stopped: a PR is waiting for review. Run `oche ship` again once it's approved; finished steps are skipped.");
|
|
4310
|
+
process.exitCode = 1;
|
|
4311
|
+
break;
|
|
4312
|
+
case "failed":
|
|
4313
|
+
warn("Stopped before the end. Sort out the step above, then run `oche ship` again; finished steps are skipped.");
|
|
4314
|
+
process.exitCode = 1;
|
|
4315
|
+
break;
|
|
4316
|
+
case "cancelled":
|
|
4317
|
+
warn(`Ship #${run3.id} was cancelled. Steps that already merged stay merged.`);
|
|
4318
|
+
process.exitCode = 1;
|
|
4319
|
+
break;
|
|
4320
|
+
}
|
|
4321
|
+
}
|
|
4322
|
+
var POLL_MS = 3e3;
|
|
4323
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4324
|
+
async function followRun(api, first) {
|
|
4325
|
+
const onSigint = () => {
|
|
4326
|
+
process.stderr.write(
|
|
4327
|
+
`
|
|
4328
|
+
The ship keeps running on the server. Follow it in the dashboard, or cancel it with \`oche ship --cancel ${first.id}\`.
|
|
4329
|
+
`
|
|
4330
|
+
);
|
|
4331
|
+
process.exit(130);
|
|
4332
|
+
};
|
|
4333
|
+
process.on("SIGINT", onSigint);
|
|
4334
|
+
try {
|
|
4335
|
+
let run3 = first;
|
|
4336
|
+
let shown = [];
|
|
4337
|
+
let misses = 0;
|
|
4338
|
+
for (; ; ) {
|
|
4339
|
+
for (const line of stepUpdates(shown, run3.steps)) print(line);
|
|
4340
|
+
shown = run3.steps;
|
|
4341
|
+
if (run3.status !== "running") return run3;
|
|
4342
|
+
await sleep(POLL_MS);
|
|
4343
|
+
try {
|
|
4344
|
+
run3 = (await api.shipRun(run3.id)).run;
|
|
4345
|
+
misses = 0;
|
|
4346
|
+
} catch (e) {
|
|
4347
|
+
if (e instanceof ApiRequestError || ++misses >= 5) throw e;
|
|
4348
|
+
}
|
|
4349
|
+
}
|
|
4350
|
+
} finally {
|
|
4351
|
+
process.off("SIGINT", onSigint);
|
|
4352
|
+
}
|
|
4353
|
+
}
|
|
4354
|
+
async function cancelCommand(getClient, idArg) {
|
|
4355
|
+
const id = Number(idArg.replace(/^#/, ""));
|
|
4356
|
+
if (!Number.isInteger(id) || id <= 0) throw new CliError(`"${idArg}" isn't a ship run id. Use the number from \`oche ship\`, like 12.`);
|
|
4357
|
+
const api = await getClient();
|
|
4358
|
+
const { run: run3 } = await api.cancelShipRun(id);
|
|
4359
|
+
print(`${c.bold(`Ship #${run3.id}`)} ${c.dim(`${run3.repo} \xB7 to ${TARGET_LABEL[run3.request.to]} \xB7 by ${run3.actor}`)}`);
|
|
4360
|
+
for (const line of stepUpdates([], run3.steps)) print(line);
|
|
4361
|
+
if (run3.status === "cancelled") ok(`Cancelled ship #${run3.id}. Steps that already merged stay merged.`);
|
|
4362
|
+
else print(c.dim(`Ship #${run3.id} had already finished: ${run3.status}.`));
|
|
4363
|
+
}
|
|
4364
|
+
|
|
4365
|
+
// src/pr.ts
|
|
4366
|
+
var PROTECTED = /* @__PURE__ */ new Set(["main", "master", "staging", "dev", "develop"]);
|
|
4367
|
+
var BASE_CANDIDATES = ["dev", "develop"];
|
|
4368
|
+
function titleFromBranch(branch) {
|
|
4369
|
+
const words = branch.replace(/^[^/]+\//, "").replace(/[-_]+/g, " ").trim();
|
|
4370
|
+
return words ? words[0].toUpperCase() + words.slice(1) : branch;
|
|
4371
|
+
}
|
|
4372
|
+
function prTitle(subjects, branch) {
|
|
4373
|
+
return subjects.length === 1 ? subjects[0] : titleFromBranch(branch);
|
|
4374
|
+
}
|
|
4375
|
+
function prBody(subjects) {
|
|
4376
|
+
if (!subjects.length) return "";
|
|
4377
|
+
return `${[...subjects].reverse().map((s) => `- ${s}`).join("\n")}
|
|
4378
|
+
|
|
4379
|
+
<sub>Opened with \`oche pr\`.</sub>`;
|
|
4380
|
+
}
|
|
4381
|
+
function mergeMethod(opts) {
|
|
4382
|
+
if (opts.squash && opts.rebase) throw new CliError("Pick one of --squash or --rebase.");
|
|
4383
|
+
return opts.squash ? "squash" : opts.rebase ? "rebase" : "merge";
|
|
4384
|
+
}
|
|
4385
|
+
async function writeMessage2(input) {
|
|
4386
|
+
const ai = resolveAi(await loadLocalConfig(), process.env);
|
|
4387
|
+
if (!ai.key) throw new CliError('No OpenRouter key. Run `oche ai-key` (or set OPENROUTER_API_KEY), or pass -m "message".');
|
|
4388
|
+
process.stderr.write(c.dim(`Writing a commit message with ${ai.model}\u2026
|
|
4389
|
+
`));
|
|
4390
|
+
return generateCommitMessage(input, { apiKey: ai.key, model: ai.model });
|
|
4391
|
+
}
|
|
4392
|
+
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4393
|
+
async function waitForMergeable(gh, repo, n) {
|
|
4394
|
+
let pr = await gh.pull(repo, n);
|
|
4395
|
+
for (let i = 0; pr.mergeable === null && i < 10; i++) {
|
|
4396
|
+
await sleep2(1500);
|
|
4397
|
+
pr = await gh.pull(repo, n);
|
|
4398
|
+
}
|
|
4399
|
+
return pr;
|
|
4400
|
+
}
|
|
4401
|
+
async function prCommand(opts) {
|
|
4402
|
+
const method = opts.merge ? mergeMethod(opts) : null;
|
|
4403
|
+
if (opts.draft && opts.merge) throw new CliError("A draft PR can't be merged. Drop --draft or --merge.");
|
|
4404
|
+
if (opts.deleteBranch && !opts.merge) throw new CliError("--delete-branch only applies with --merge.");
|
|
4405
|
+
if (opts.json && !opts.yes && !opts.dryRun) throw new CliError("--json needs --yes or --dry-run.");
|
|
4406
|
+
const done = opts.json ? (m) => void process.stderr.write(`\u2713 ${m}
|
|
4407
|
+
`) : ok;
|
|
4408
|
+
const [repo, branch, changed] = await Promise.all([inferRepo(), currentBranch(), changes()]);
|
|
4409
|
+
if (PROTECTED.has(branch)) {
|
|
4410
|
+
throw new CliError(`You're on ${branch}. \`oche pr\` ships work branches; create one with \`git switch -c feature/<name>\`.`);
|
|
4411
|
+
}
|
|
4412
|
+
const gh = new GitHub(await githubToken());
|
|
4413
|
+
const base = opts.base ?? await gh.firstBranch(repo, BASE_CANDIDATES);
|
|
4414
|
+
if (!base) throw new CliError(`${slug(repo)} has no dev or develop branch on GitHub (or your GitHub token can't see the repo). Pass --base <branch>.`);
|
|
4415
|
+
if (base === branch) throw new CliError(`You're on ${base}, the branch the PR would go into.`);
|
|
4416
|
+
let message = null;
|
|
4417
|
+
let input = null;
|
|
4418
|
+
if (changed.length) {
|
|
4419
|
+
input = { ...await previewAddAll(), recent: await recentSubjects(), branch };
|
|
4420
|
+
message = opts.message ?? await writeMessage2(input);
|
|
4421
|
+
}
|
|
4422
|
+
const [behind, existing] = await Promise.all([unpushed(), gh.openPull(repo, branch, base)]);
|
|
4423
|
+
if (opts.dryRun && opts.json) {
|
|
4424
|
+
return printJson({
|
|
4425
|
+
repo: slug(repo),
|
|
4426
|
+
branch,
|
|
4427
|
+
base,
|
|
4428
|
+
message,
|
|
4429
|
+
files: changed,
|
|
4430
|
+
unpushed: behind,
|
|
4431
|
+
existingPr: existing ? { number: existing.number, url: existing.html_url } : null
|
|
4432
|
+
});
|
|
4433
|
+
}
|
|
4434
|
+
for (; ; ) {
|
|
4435
|
+
if (opts.json) break;
|
|
4436
|
+
print(`${c.bold(`${branch} \u2192 ${base}`)} ${c.dim(slug(repo))}`);
|
|
4437
|
+
print("");
|
|
4438
|
+
let n = 1;
|
|
4439
|
+
if (message) {
|
|
4440
|
+
print(` ${n++}. Commit ${plural(changed.length, "file")}:`);
|
|
4441
|
+
for (const line of message.split("\n")) print(` ${line ? c.bold(line) : ""}`);
|
|
4442
|
+
for (const ch of changed.slice(0, 12)) print(` ${describeChange(ch)}`);
|
|
4443
|
+
if (changed.length > 12) print(c.dim(` \u2026and ${changed.length - 12} more`));
|
|
4444
|
+
}
|
|
4445
|
+
print(` ${n++}. Push ${branch}${behind === null ? c.dim(" (publishes it to GitHub)") : behind > 0 ? c.dim(` (${plural(behind, "commit")} not pushed yet)`) : ""}`);
|
|
4446
|
+
print(` ${n++}. ${existing ? `Update PR #${existing.number} ${c.dim("(already open)")}` : `Open a ${opts.draft ? "draft " : ""}PR into ${base}`}`);
|
|
4447
|
+
if (method) print(` ${n++}. Merge it into ${base} ${c.dim(`(${method}${opts.deleteBranch ? ", then delete the branch on GitHub" : ""})`)}`);
|
|
4448
|
+
print("");
|
|
4449
|
+
if (opts.dryRun) return;
|
|
4450
|
+
if (opts.yes) break;
|
|
4451
|
+
if (!isInteractive()) throw new CliError("This needs confirmation. Run it in a terminal, or pass --yes.");
|
|
4452
|
+
const choice = await choose(method ? "Commit, push and merge?" : "Commit, push and open the PR?", Boolean(message && !opts.message));
|
|
4453
|
+
if (choice === "no") return print("Nothing done.");
|
|
4454
|
+
if (choice === "rewrite" && input) {
|
|
4455
|
+
message = await writeMessage2(input);
|
|
4456
|
+
continue;
|
|
4457
|
+
}
|
|
4458
|
+
if (choice === "edit" && message) {
|
|
4459
|
+
const edited = await ask("Message (one line; use `oche commit` for a longer one)", message.split("\n")[0]);
|
|
4460
|
+
message = edited.trim() || message;
|
|
4461
|
+
continue;
|
|
4462
|
+
}
|
|
4463
|
+
break;
|
|
4464
|
+
}
|
|
4465
|
+
closeReader();
|
|
4466
|
+
if (message) {
|
|
4467
|
+
await addAll();
|
|
4468
|
+
await commit(message);
|
|
4469
|
+
done("Committed");
|
|
4470
|
+
}
|
|
4471
|
+
process.stderr.write(c.dim(`Pushing ${branch}\u2026
|
|
4472
|
+
`));
|
|
4473
|
+
await push(branch);
|
|
4474
|
+
done(`Pushed ${branch}`);
|
|
4475
|
+
let pr = existing;
|
|
4476
|
+
if (!pr) {
|
|
4477
|
+
await fetchBranch(base);
|
|
4478
|
+
const subjects = await subjectsAhead(base);
|
|
4479
|
+
if (!subjects.length) throw new CliError(`${branch} has nothing that isn't already on ${base}, so there's no PR to open.`);
|
|
4480
|
+
pr = await gh.createPull(repo, {
|
|
4481
|
+
head: branch,
|
|
4482
|
+
base,
|
|
4483
|
+
title: opts.title ?? prTitle(subjects, branch),
|
|
4484
|
+
body: prBody(subjects),
|
|
4485
|
+
draft: opts.draft
|
|
4486
|
+
});
|
|
4487
|
+
done(`Opened PR #${pr.number} ${c.cyan(pr.html_url)}`);
|
|
4488
|
+
} else {
|
|
4489
|
+
done(`PR #${pr.number} has the new commits ${c.cyan(pr.html_url)}`);
|
|
4490
|
+
}
|
|
4491
|
+
const result = (merged) => ({
|
|
4492
|
+
committed: Boolean(message),
|
|
4493
|
+
pr: { number: pr.number, url: pr.html_url, created: !existing },
|
|
4494
|
+
merged,
|
|
4495
|
+
base,
|
|
4496
|
+
branch
|
|
4497
|
+
});
|
|
4498
|
+
if (!method) return opts.json ? printJson(result(false)) : void 0;
|
|
4499
|
+
if (pr.draft) throw new CliError(`PR #${pr.number} is a draft. Mark it ready for review on GitHub, then run \`oche pr --merge\` again.`);
|
|
4500
|
+
process.stderr.write(c.dim("Checking it can merge\u2026\n"));
|
|
4501
|
+
pr = await waitForMergeable(gh, repo, pr.number);
|
|
4502
|
+
if (pr.mergeable === false) {
|
|
4503
|
+
throw new CliError(`PR #${pr.number} conflicts with ${base}. Merge ${base} into ${branch}, fix the conflicts, then run \`oche pr --merge\` again.`);
|
|
4504
|
+
}
|
|
4505
|
+
if (pr.mergeable === null) warn("GitHub hasn't finished checking mergeability; trying the merge anyway.");
|
|
4506
|
+
await gh.merge(repo, pr.number, method);
|
|
4507
|
+
done(`Merged #${pr.number} into ${base}`);
|
|
4508
|
+
if (opts.deleteBranch) {
|
|
4509
|
+
await gh.deleteBranch(repo, branch);
|
|
4510
|
+
done(`Deleted ${branch} on GitHub`);
|
|
4511
|
+
}
|
|
4512
|
+
if (opts.json) return printJson(result(true));
|
|
4513
|
+
print(c.dim(`
|
|
4514
|
+
You're still on ${branch}. \`git switch ${base} && git pull\` to carry on from ${base}.`));
|
|
4515
|
+
}
|
|
4516
|
+
|
|
4517
|
+
// src/commands.ts
|
|
4518
|
+
async function client() {
|
|
4519
|
+
const cfg = resolveConfig(await loadConfig(), process.env);
|
|
4520
|
+
if (!cfg.url || !cfg.token) {
|
|
4521
|
+
throw new CliError(
|
|
4522
|
+
cfg.url && cfg.urlSource === "env" ? `No token for ${cfg.url}. Set OCHE_TOKEN or run \`oche login\`.` : "Not logged in. Run `oche login` (or set OCHE_URL and OCHE_TOKEN)."
|
|
4523
|
+
);
|
|
4524
|
+
}
|
|
4525
|
+
return new Client(cfg.url, cfg.token, cfg.tokenSource);
|
|
4526
|
+
}
|
|
4527
|
+
function positiveInt(value) {
|
|
4528
|
+
const n = Number(value);
|
|
4529
|
+
if (!Number.isInteger(n) || n < 1) throw new InvalidArgumentError("Must be a whole number of 1 or more.");
|
|
4530
|
+
return n;
|
|
4531
|
+
}
|
|
4532
|
+
function nonNegativeInt(value) {
|
|
4533
|
+
const n = Number(value);
|
|
4534
|
+
if (!Number.isInteger(n) || n < 0) throw new InvalidArgumentError("Must be a whole number of 0 or more.");
|
|
4535
|
+
return n;
|
|
4536
|
+
}
|
|
4537
|
+
var modeLabel = (repo) => repo.mode === "strict" ? `strict \xB7 ${plural(repo.requiredApprovals, "approval")}` : "fast";
|
|
4538
|
+
var BAD_EVENTS = /* @__PURE__ */ new Set(["promotion-conflict", "sync-conflict", "pr-blocked", "direct-push", "deploy-failed", "app-stopped"]);
|
|
4539
|
+
var GOOD_EVENTS = /* @__PURE__ */ new Set(["promoted", "synced", "onboarded", "deploy-succeeded"]);
|
|
4540
|
+
var newestFirst = (events) => [...events].sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id - a.id);
|
|
4541
|
+
function eventLines(events, showRepo) {
|
|
4542
|
+
return columns(
|
|
4543
|
+
newestFirst(events).map((e) => {
|
|
4544
|
+
const when = relativeTime(e.createdAt);
|
|
4545
|
+
const type = BAD_EVENTS.has(e.type) ? c.red(e.type) : GOOD_EVENTS.has(e.type) ? c.green(e.type) : e.type;
|
|
4546
|
+
const tail = [e.prNumber ? `#${e.prNumber}` : "", e.actor ? `@${e.actor}` : ""].filter(Boolean).join(" ");
|
|
4547
|
+
const row = [[when, c.dim(when)]];
|
|
4548
|
+
if (showRepo) row.push(e.repo);
|
|
4549
|
+
row.push([e.type, type], `${e.summary}${tail ? ` ${c.dim(tail)}` : ""}`);
|
|
4550
|
+
return row;
|
|
4551
|
+
})
|
|
4552
|
+
);
|
|
4553
|
+
}
|
|
4554
|
+
async function login(urlArg) {
|
|
4555
|
+
const saved = await loadConfig().catch(() => null);
|
|
4556
|
+
const url = normalizeUrl(urlArg ?? process.env.OCHE_URL ?? saved?.url ?? DEFAULT_SERVER_URL);
|
|
4557
|
+
const where = url === DEFAULT_SERVER_URL ? DEFAULT_TOKEN_PAGE : "your Oche dashboard under Settings";
|
|
4558
|
+
process.stderr.write(`Logging in to ${c.bold(url)}
|
|
4559
|
+
`);
|
|
4560
|
+
process.stderr.write(c.dim(`Create a CLI token at ${where}, then paste it here.
|
|
4561
|
+
`));
|
|
4562
|
+
const token = await askHidden("CLI token");
|
|
4563
|
+
if (!token) throw new CliError("No token entered.");
|
|
4564
|
+
const me = await new Client(url, token, "config").me().catch((e) => {
|
|
4565
|
+
if (e instanceof ApiRequestError && e.status === 401) {
|
|
4566
|
+
throw new CliError(`${url} rejected that token (401). Check it and try again.`);
|
|
4567
|
+
}
|
|
4568
|
+
throw e;
|
|
4569
|
+
});
|
|
4570
|
+
const path2 = configPath();
|
|
4571
|
+
await saveConfig({ url, token, login: me.login }, path2);
|
|
4572
|
+
ok(`Logged in to ${url} as ${c.bold(me.login)} (${me.role}).`);
|
|
4573
|
+
print(c.dim(`Saved to ${path2}`));
|
|
4574
|
+
if (process.env.OCHE_TOKEN || process.env.OCHE_URL) {
|
|
4575
|
+
warn("OCHE_URL / OCHE_TOKEN are set and take precedence over the saved login.");
|
|
4576
|
+
}
|
|
4577
|
+
}
|
|
4578
|
+
async function logout() {
|
|
4579
|
+
const saved = await loadConfig().catch(() => null);
|
|
4580
|
+
if (await deleteConfig()) {
|
|
4581
|
+
ok(`Logged out${saved?.url ? ` of ${saved.url}` : ""}.`);
|
|
4582
|
+
print(c.dim("The token keeps working until you revoke it in the dashboard (Settings \u2192 CLI tokens)."));
|
|
4583
|
+
} else {
|
|
4584
|
+
print("Not logged in.");
|
|
4585
|
+
}
|
|
4586
|
+
if (process.env.OCHE_TOKEN) warn("OCHE_TOKEN is still set in your environment.");
|
|
4587
|
+
}
|
|
4588
|
+
function settingsLine(repo) {
|
|
4589
|
+
const parts = [];
|
|
4590
|
+
if (repo.workMergeMethod) parts.push(`work PRs: ${repo.workMergeMethod}`);
|
|
4591
|
+
if (repo.coolifyLinked) parts.push(`production waits for staging: ${repo.gateOnStaging ? "yes" : "no"} (Coolify linked)`);
|
|
4592
|
+
return parts.length ? parts.join(" \xB7 ") : null;
|
|
4593
|
+
}
|
|
4594
|
+
function printStatus({ repo, status: status2, events }) {
|
|
4595
|
+
print(`${c.bold(repo.fullName)} ${repo.managed ? modeLabel(repo) : c.yellow("not managed")}`);
|
|
4596
|
+
print(c.dim(repo.htmlUrl));
|
|
4597
|
+
const settings = settingsLine(repo);
|
|
4598
|
+
if (repo.managed && settings) print(c.dim(settings));
|
|
4599
|
+
if (!repo.managed) {
|
|
4600
|
+
print();
|
|
4601
|
+
print(`Run ${c.cyan(`oche onboard ${repo.fullName}`)} to set up the dev \u2192 staging \u2192 main flow.`);
|
|
4602
|
+
return;
|
|
4603
|
+
}
|
|
4604
|
+
const b = repo.branches;
|
|
4605
|
+
if (!status2 || !b) {
|
|
4606
|
+
print();
|
|
4607
|
+
print(c.yellow("Branch status is unavailable right now (GitHub didn't answer)."));
|
|
4608
|
+
} else {
|
|
4609
|
+
print();
|
|
4610
|
+
print(c.bold("Branches"));
|
|
4611
|
+
const heads = ["prod", "staging", "dev"].map((stage) => {
|
|
4612
|
+
const h = status2.heads[stage];
|
|
4613
|
+
if (!h) return [b[stage], ["missing", c.red("missing")]];
|
|
4614
|
+
const sha = h.sha.slice(0, 7);
|
|
4615
|
+
const meta = [h.author ? `@${h.author}` : "", relativeTime(h.date)].filter(Boolean).join(" \xB7 ");
|
|
4616
|
+
return [b[stage], [sha, c.dim(sha)], `${truncate(h.message, 56)} ${c.dim(meta)}`];
|
|
4617
|
+
});
|
|
4618
|
+
columns(heads).forEach((l) => print(l));
|
|
4619
|
+
print();
|
|
4620
|
+
print(c.bold("Pending"));
|
|
4621
|
+
const count = (n) => n ? [plural(n, "commit"), c.yellow(plural(n, "commit"))] : ["none", c.dim("none")];
|
|
4622
|
+
columns([
|
|
4623
|
+
[`${b.dev} \u2192 ${b.staging}`, count(status2.pending.staging)],
|
|
4624
|
+
[`${b.staging} \u2192 ${b.prod}`, count(status2.pending.prod)],
|
|
4625
|
+
[`${b.dev} \u2192 ${b.prod}`, count(status2.pending.prodDirect)]
|
|
4626
|
+
]).forEach((l) => print(l));
|
|
4627
|
+
print();
|
|
4628
|
+
print(c.bold("Pull requests"));
|
|
4629
|
+
if (status2.openPromotions.length) {
|
|
4630
|
+
columns(status2.openPromotions.map((p) => [`#${p.number}`, `${p.head} \u2192 ${p.base}`, c.dim(p.url)])).forEach(
|
|
4631
|
+
(l) => print(l)
|
|
4632
|
+
);
|
|
4633
|
+
} else {
|
|
4634
|
+
print(c.dim(" no open promotion PRs"));
|
|
4635
|
+
}
|
|
4636
|
+
const blocked = status2.blockedPullRequests;
|
|
4637
|
+
print(` ${blocked ? c.red(`${plural(blocked, "PR")} blocked by the flow`) : c.dim("none blocked")}`);
|
|
4638
|
+
}
|
|
4639
|
+
print();
|
|
4640
|
+
print(c.bold("Recent events"));
|
|
4641
|
+
if (events.length) eventLines(newestFirst(events).slice(0, 5), false).forEach((l) => print(l));
|
|
4642
|
+
else print(c.dim(" none yet"));
|
|
4643
|
+
}
|
|
4644
|
+
async function status(repoArg, opts) {
|
|
4645
|
+
const repo = await resolveRepo(repoArg);
|
|
4646
|
+
const data = await (await client()).repo(repo);
|
|
4647
|
+
if (opts.json) return printJson(data);
|
|
4648
|
+
printStatus(data);
|
|
4649
|
+
}
|
|
4650
|
+
async function repos(opts) {
|
|
4651
|
+
const { repos: repos2 } = await (await client()).repos();
|
|
4652
|
+
const sorted = [...repos2].sort((a, b) => Number(b.managed) - Number(a.managed) || a.fullName.localeCompare(b.fullName));
|
|
4653
|
+
if (opts.json) return printJson({ repos: sorted });
|
|
4654
|
+
if (!sorted.length) {
|
|
4655
|
+
print("No repos yet. Install the Oche GitHub App on a repo, then run `oche onboard owner/repo`.");
|
|
4656
|
+
return;
|
|
4657
|
+
}
|
|
4658
|
+
columns(
|
|
4659
|
+
sorted.map(
|
|
4660
|
+
(r) => r.managed ? [["\u2713", c.green("\u2713")], r.fullName, modeLabel(r)] : [" ", [r.fullName, c.dim(r.fullName)], c.dim("not managed")]
|
|
4661
|
+
),
|
|
4662
|
+
""
|
|
4663
|
+
).forEach((l) => print(l));
|
|
4664
|
+
const managed = sorted.filter((r) => r.managed).length;
|
|
4665
|
+
print(c.dim(`
|
|
4666
|
+
${managed} managed, ${sorted.length - managed} not managed`));
|
|
4667
|
+
}
|
|
4668
|
+
async function log(repoArg, opts) {
|
|
4669
|
+
const repo = repoArg ? await resolveRepo(repoArg) : await resolveRepo(void 0).catch(() => null);
|
|
4670
|
+
const { events } = await (await client()).events(repo, opts.limit);
|
|
4671
|
+
if (opts.json) return printJson({ events });
|
|
4672
|
+
if (!events.length) {
|
|
4673
|
+
print(c.dim(repo ? `No events for ${slug(repo)} yet.` : "No events yet."));
|
|
4674
|
+
return;
|
|
4675
|
+
}
|
|
4676
|
+
eventLines(events, !repo).forEach((l) => print(l));
|
|
4677
|
+
}
|
|
4678
|
+
async function promote(target, repoArg, opts) {
|
|
4679
|
+
const promotion = toPromotion(target, opts.direct);
|
|
4680
|
+
const repo = await resolveRepo(repoArg);
|
|
4681
|
+
const api = await client();
|
|
4682
|
+
let branches = null;
|
|
4683
|
+
if (needsConfirmation(promotion) && !opts.yes) {
|
|
4684
|
+
const { repo: info, status: st } = await api.repo(repo);
|
|
4685
|
+
if (!info.managed) throw new CliError(`${info.fullName} isn't managed by Oche yet. Run \`oche onboard ${info.fullName}\`.`);
|
|
4686
|
+
branches = info.branches;
|
|
4687
|
+
const { head: head2, base: base2 } = promotionRefs(promotion, branches);
|
|
4688
|
+
const pending = st ? promotion === "prod" ? st.pending.prod : st.pending.prodDirect : null;
|
|
4689
|
+
if (pending === 0) {
|
|
4690
|
+
print(`Nothing to promote: ${base2} already has everything in ${head2}.`);
|
|
4691
|
+
return;
|
|
4692
|
+
}
|
|
4693
|
+
const what = pending === null ? `${head2} \u2192 ${base2}` : `${plural(pending, "commit")} ${head2} \u2192 ${base2}`;
|
|
4694
|
+
if (!await confirm(`Promote ${what} on ${slug(repo)} (production)?`)) {
|
|
4695
|
+
print("Cancelled.");
|
|
4696
|
+
return;
|
|
4697
|
+
}
|
|
4698
|
+
}
|
|
4699
|
+
const { head, base } = promotionRefs(promotion, branches);
|
|
4700
|
+
process.stderr.write(c.dim(`Promoting ${head} \u2192 ${base} on ${slug(repo)}\u2026
|
|
4701
|
+
`));
|
|
4702
|
+
const result = await api.promote(repo, promotion);
|
|
4703
|
+
switch (result.status) {
|
|
4704
|
+
case "merged":
|
|
4705
|
+
ok(`Merged #${result.pr.number} ${result.pr.head} \u2192 ${result.pr.base}`);
|
|
4706
|
+
print(` \u2192 ${result.pr.url}`);
|
|
4707
|
+
return;
|
|
4708
|
+
case "waiting-review": {
|
|
4709
|
+
const a = result.approval;
|
|
4710
|
+
const note = a.changesRequested ? ", changes requested" : "";
|
|
4711
|
+
print(`#${result.pr.number} ${result.pr.head} \u2192 ${result.pr.base} is waiting for review: ${c.yellow(`${a.approvals}/${a.required} approvals`)}${note}`);
|
|
4712
|
+
print(` \u2192 ${result.pr.url}`);
|
|
4713
|
+
return;
|
|
4714
|
+
}
|
|
4715
|
+
case "nothing-to-promote":
|
|
4716
|
+
print(`Nothing to promote: ${base} already has everything in ${head}.`);
|
|
4717
|
+
return;
|
|
4718
|
+
case "conflict":
|
|
4719
|
+
print(`${c.red("\u2717")} #${result.pr.number} ${result.pr.head} \u2192 ${result.pr.base} has merge conflicts. Resolve them on GitHub, then run this again.`);
|
|
4720
|
+
print(` \u2192 ${result.pr.url}`);
|
|
4721
|
+
process.exitCode = 1;
|
|
4722
|
+
return;
|
|
4723
|
+
case "blocked":
|
|
4724
|
+
print(`${c.red("\u2717")} Blocked: ${result.reason}`);
|
|
4725
|
+
process.exitCode = 1;
|
|
4726
|
+
return;
|
|
4727
|
+
}
|
|
4728
|
+
}
|
|
4729
|
+
async function onboard(repoArg, opts) {
|
|
4730
|
+
const repo = await resolveRepo(repoArg);
|
|
4731
|
+
const api = await client();
|
|
4732
|
+
const { plan, repo: info } = await api.onboard(repo, true);
|
|
4733
|
+
const b = plan.branches;
|
|
4734
|
+
print(`${c.bold(info.fullName)} ${c.dim(`${b.dev} \u2192 ${b.staging} \u2192 ${b.prod}`)}`);
|
|
4735
|
+
for (const s of plan.steps) print(` ${s.done ? c.green("\u2713") : c.dim("\xB7")} ${s.done ? c.dim(s.label) : s.label}`);
|
|
4736
|
+
const todo = plan.steps.filter((s) => !s.done).length;
|
|
4737
|
+
if (info.managed && todo === 0) {
|
|
4738
|
+
ok(`${info.fullName} is already onboarded.`);
|
|
4739
|
+
return;
|
|
4740
|
+
}
|
|
4741
|
+
if (opts.dryRun) {
|
|
4742
|
+
print(c.dim(`
|
|
4743
|
+
Dry run: ${plural(todo, "step")} to apply.`));
|
|
4744
|
+
return;
|
|
4745
|
+
}
|
|
4746
|
+
if (!opts.yes && !await confirm(`Apply ${plural(todo, "step")} to ${info.fullName}?`, true)) {
|
|
4747
|
+
print("Cancelled.");
|
|
4748
|
+
return;
|
|
4749
|
+
}
|
|
4750
|
+
const applied = await api.onboard(repo, false);
|
|
4751
|
+
ok(`${applied.repo.fullName} is managed by Oche (${modeLabel(applied.repo)}).`);
|
|
4752
|
+
}
|
|
4753
|
+
async function setMode(mode, repoArg, opts) {
|
|
4754
|
+
if (mode !== "fast" && mode !== "strict") throw new CliError(`Unknown mode "${mode}". Use fast or strict.`);
|
|
4755
|
+
const repo = await resolveRepo(repoArg);
|
|
4756
|
+
const { repo: updated } = await (await client()).updateRepo(repo, {
|
|
4757
|
+
mode,
|
|
4758
|
+
...opts.approvals === void 0 ? {} : { requiredApprovals: opts.approvals }
|
|
4759
|
+
});
|
|
4760
|
+
if (updated.mode === "strict") {
|
|
4761
|
+
ok(`${updated.fullName} is now strict: ${plural(updated.requiredApprovals, "approval")} required to promote.`);
|
|
4762
|
+
} else {
|
|
4763
|
+
ok(`${updated.fullName} is now fast: promotions merge without review.`);
|
|
4764
|
+
if (opts.approvals !== void 0) {
|
|
4765
|
+
print(c.dim(` ${plural(updated.requiredApprovals, "approval")} will apply if you switch to strict.`));
|
|
4766
|
+
}
|
|
4767
|
+
}
|
|
4768
|
+
}
|
|
4769
|
+
async function aiKey(opts) {
|
|
4770
|
+
const saved = await loadLocalConfig();
|
|
4771
|
+
const path2 = localConfigPath();
|
|
4772
|
+
if (opts.clear) {
|
|
4773
|
+
await saveLocalConfig({ ...saved, openrouterKey: void 0 }, path2);
|
|
4774
|
+
return ok("Forgot the OpenRouter key.");
|
|
4775
|
+
}
|
|
4776
|
+
let key = saved.openrouterKey;
|
|
4777
|
+
if (!opts.model || !key) {
|
|
4778
|
+
if (isInteractive()) process.stderr.write(c.dim("Create one at https://openrouter.ai/settings/keys\n"));
|
|
4779
|
+
key = await askHidden("OpenRouter API key") || key;
|
|
4780
|
+
}
|
|
4781
|
+
if (!key) throw new CliError("No key entered.");
|
|
4782
|
+
const model = opts.model?.trim() || saved.model;
|
|
4783
|
+
await saveLocalConfig({ openrouterKey: key, model }, path2);
|
|
4784
|
+
ok(`Saved. \`oche pr\` will write commit messages with ${c.bold(model ?? DEFAULT_MODEL)}.`);
|
|
4785
|
+
print(c.dim(`Saved to ${path2}`));
|
|
4786
|
+
if (process.env.OPENROUTER_API_KEY) warn("OPENROUTER_API_KEY is set and takes precedence over the saved key.");
|
|
4787
|
+
}
|
|
4788
|
+
function buildProgram() {
|
|
4789
|
+
const program2 = new Command().name("oche").description("Promote dev \u2192 staging \u2192 main from your terminal.").version(package_default.version, "-v, --version").showSuggestionAfterError();
|
|
4790
|
+
const repoArg = "[owner/repo]";
|
|
4791
|
+
const repoHelp = "defaults to the GitHub repo of git remote origin";
|
|
4792
|
+
program2.command("login").description("Sign in with a CLI token from the dashboard").argument("[url]", "Oche server URL (only if you self-host)").action(login);
|
|
4793
|
+
program2.command("logout").description("Forget the saved login").action(logout);
|
|
4794
|
+
program2.command("status").description("Branches, pending commits, promotion PRs and recent events").argument(repoArg, repoHelp).option("--json", "print raw JSON").action(status);
|
|
4795
|
+
program2.command("repos").description("List repos, managed first").option("--json", "print raw JSON").action(repos);
|
|
4796
|
+
program2.command("promote").description("Promote dev \u2192 staging, or staging \u2192 main").argument("<target>", "staging or prod").argument(repoArg, repoHelp).option("--direct", "with prod: ship dev straight to main, skipping staging").option("-y, --yes", "don't ask for confirmation").action(promote);
|
|
4797
|
+
program2.command("ship").description("Commit what's changed, push, and take it all the way up with one confirmation").argument("[target]", "dev, staging or prod", "prod").argument(repoArg, repoHelp).option("--direct", "with prod: dev \u2192 main, skipping staging (Oche syncs staging after)").option("-m, --message <message>", "commit message to use instead of writing one with AI").option("-y, --yes", "don't ask for confirmation").option("--cancel <runId>", "cancel a running ship by its number instead of starting one").action((target, repo, opts) => shipCommand(client, target, repo, opts));
|
|
4798
|
+
program2.command("pr").description("Commit what's changed with AI, push this work branch and open a PR into dev \u2014 no Oche server needed").option("--base <branch>", "branch the PR goes into (default: dev, or develop if there's no dev)").option("--merge", "merge the PR once it's open").option("--squash", "with --merge: squash merge").option("--rebase", "with --merge: rebase merge").option("-d, --delete-branch", "with --merge: delete the work branch on GitHub afterwards").option("--draft", "open the PR as a draft").option("-t, --title <title>", "PR title (default: the commit subject, or the branch name for several commits)").option("-m, --message <message>", "commit message to use instead of writing one with AI").option("-y, --yes", "don't ask for confirmation").option("--dry-run", "only show the plan, with the AI commit message").option("--json", "machine-readable output (needs --yes or --dry-run)").action((opts) => prCommand(opts));
|
|
4799
|
+
program2.command("ai-key").description("Save the OpenRouter key (and model) `oche pr` writes commit messages with").option("--model <id>", `OpenRouter model id (default ${DEFAULT_MODEL})`).option("--clear", "forget the saved key").action(aiKey);
|
|
4800
|
+
program2.command("commit").description("Write a commit message for what's staged with AI (via your Oche server) and commit").option("-a, --all", "stage changes to tracked files first, like git commit -a").option("-m, --message <message>", "skip AI and use this message").option("--dry-run", "only print the message").option("-y, --yes", "commit without asking").action((opts) => commitCommand(client, opts));
|
|
4801
|
+
program2.command("onboard").description("Set up the dev \u2192 staging \u2192 main flow on a repo").argument(repoArg, repoHelp).option("--dry-run", "only show the plan").option("-y, --yes", "don't ask for confirmation").action(onboard);
|
|
4802
|
+
program2.command("mode").description("Switch between fast (no review) and strict (approvals required)").argument("<mode>", "fast or strict").argument(repoArg, repoHelp).option("--approvals <n>", "approvals required in strict mode", nonNegativeInt).action(setMode);
|
|
4803
|
+
program2.command("log").description("Recent events (all repos when run outside a checkout)").argument(repoArg, repoHelp).addOption(new Option("-n, --limit <n>", "how many events").default(20).argParser(positiveInt)).option("--json", "print raw JSON").action(log);
|
|
4804
|
+
return program2;
|
|
4805
|
+
}
|
|
4806
|
+
|
|
4807
|
+
// src/index.ts
|
|
4808
|
+
process.stdout.on("error", (e) => {
|
|
4809
|
+
if (e.code === "EPIPE") process.exit(0);
|
|
4810
|
+
throw e;
|
|
4811
|
+
});
|
|
4812
|
+
try {
|
|
4813
|
+
await buildProgram().parseAsync(process.argv);
|
|
4814
|
+
} catch (e) {
|
|
4815
|
+
if (e instanceof CliError) {
|
|
4816
|
+
fail(e.message);
|
|
4817
|
+
process.exitCode = e.exitCode;
|
|
4818
|
+
} else {
|
|
4819
|
+
fail(e instanceof Error ? e.message : String(e));
|
|
4820
|
+
if (process.env.OCHE_DEBUG && e instanceof Error) console.error(e.stack);
|
|
4821
|
+
process.exitCode = 1;
|
|
4822
|
+
}
|
|
4823
|
+
} finally {
|
|
4824
|
+
closeReader();
|
|
4825
|
+
}
|