@mutmutco/cli 0.8.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/README.md +40 -0
- package/dist/index.cjs +4432 -0
- package/package.json +41 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,4432 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
10
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
|
|
29
|
+
// node_modules/commander/lib/error.js
|
|
30
|
+
var require_error = __commonJS({
|
|
31
|
+
"node_modules/commander/lib/error.js"(exports2) {
|
|
32
|
+
var CommanderError2 = class extends Error {
|
|
33
|
+
/**
|
|
34
|
+
* Constructs the CommanderError class
|
|
35
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
36
|
+
* @param {string} code an id string representing the error
|
|
37
|
+
* @param {string} message human-readable description of the error
|
|
38
|
+
*/
|
|
39
|
+
constructor(exitCode, code, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
Error.captureStackTrace(this, this.constructor);
|
|
42
|
+
this.name = this.constructor.name;
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.exitCode = exitCode;
|
|
45
|
+
this.nestedError = void 0;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var InvalidArgumentError2 = class extends CommanderError2 {
|
|
49
|
+
/**
|
|
50
|
+
* Constructs the InvalidArgumentError class
|
|
51
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
52
|
+
*/
|
|
53
|
+
constructor(message) {
|
|
54
|
+
super(1, "commander.invalidArgument", message);
|
|
55
|
+
Error.captureStackTrace(this, this.constructor);
|
|
56
|
+
this.name = this.constructor.name;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
exports2.CommanderError = CommanderError2;
|
|
60
|
+
exports2.InvalidArgumentError = InvalidArgumentError2;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// node_modules/commander/lib/argument.js
|
|
65
|
+
var require_argument = __commonJS({
|
|
66
|
+
"node_modules/commander/lib/argument.js"(exports2) {
|
|
67
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
68
|
+
var Argument2 = class {
|
|
69
|
+
/**
|
|
70
|
+
* Initialize a new command argument with the given name and description.
|
|
71
|
+
* The default is that the argument is required, and you can explicitly
|
|
72
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
73
|
+
*
|
|
74
|
+
* @param {string} name
|
|
75
|
+
* @param {string} [description]
|
|
76
|
+
*/
|
|
77
|
+
constructor(name, description) {
|
|
78
|
+
this.description = description || "";
|
|
79
|
+
this.variadic = false;
|
|
80
|
+
this.parseArg = void 0;
|
|
81
|
+
this.defaultValue = void 0;
|
|
82
|
+
this.defaultValueDescription = void 0;
|
|
83
|
+
this.argChoices = void 0;
|
|
84
|
+
switch (name[0]) {
|
|
85
|
+
case "<":
|
|
86
|
+
this.required = true;
|
|
87
|
+
this._name = name.slice(1, -1);
|
|
88
|
+
break;
|
|
89
|
+
case "[":
|
|
90
|
+
this.required = false;
|
|
91
|
+
this._name = name.slice(1, -1);
|
|
92
|
+
break;
|
|
93
|
+
default:
|
|
94
|
+
this.required = true;
|
|
95
|
+
this._name = name;
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
if (this._name.length > 3 && this._name.slice(-3) === "...") {
|
|
99
|
+
this.variadic = true;
|
|
100
|
+
this._name = this._name.slice(0, -3);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Return argument name.
|
|
105
|
+
*
|
|
106
|
+
* @return {string}
|
|
107
|
+
*/
|
|
108
|
+
name() {
|
|
109
|
+
return this._name;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* @package
|
|
113
|
+
*/
|
|
114
|
+
_concatValue(value, previous) {
|
|
115
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
116
|
+
return [value];
|
|
117
|
+
}
|
|
118
|
+
return previous.concat(value);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
122
|
+
*
|
|
123
|
+
* @param {*} value
|
|
124
|
+
* @param {string} [description]
|
|
125
|
+
* @return {Argument}
|
|
126
|
+
*/
|
|
127
|
+
default(value, description) {
|
|
128
|
+
this.defaultValue = value;
|
|
129
|
+
this.defaultValueDescription = description;
|
|
130
|
+
return this;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
134
|
+
*
|
|
135
|
+
* @param {Function} [fn]
|
|
136
|
+
* @return {Argument}
|
|
137
|
+
*/
|
|
138
|
+
argParser(fn) {
|
|
139
|
+
this.parseArg = fn;
|
|
140
|
+
return this;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Only allow argument value to be one of choices.
|
|
144
|
+
*
|
|
145
|
+
* @param {string[]} values
|
|
146
|
+
* @return {Argument}
|
|
147
|
+
*/
|
|
148
|
+
choices(values) {
|
|
149
|
+
this.argChoices = values.slice();
|
|
150
|
+
this.parseArg = (arg, previous) => {
|
|
151
|
+
if (!this.argChoices.includes(arg)) {
|
|
152
|
+
throw new InvalidArgumentError2(
|
|
153
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (this.variadic) {
|
|
157
|
+
return this._concatValue(arg, previous);
|
|
158
|
+
}
|
|
159
|
+
return arg;
|
|
160
|
+
};
|
|
161
|
+
return this;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Make argument required.
|
|
165
|
+
*
|
|
166
|
+
* @returns {Argument}
|
|
167
|
+
*/
|
|
168
|
+
argRequired() {
|
|
169
|
+
this.required = true;
|
|
170
|
+
return this;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Make argument optional.
|
|
174
|
+
*
|
|
175
|
+
* @returns {Argument}
|
|
176
|
+
*/
|
|
177
|
+
argOptional() {
|
|
178
|
+
this.required = false;
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
function humanReadableArgName(arg) {
|
|
183
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
184
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
185
|
+
}
|
|
186
|
+
exports2.Argument = Argument2;
|
|
187
|
+
exports2.humanReadableArgName = humanReadableArgName;
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// node_modules/commander/lib/help.js
|
|
192
|
+
var require_help = __commonJS({
|
|
193
|
+
"node_modules/commander/lib/help.js"(exports2) {
|
|
194
|
+
var { humanReadableArgName } = require_argument();
|
|
195
|
+
var Help2 = class {
|
|
196
|
+
constructor() {
|
|
197
|
+
this.helpWidth = void 0;
|
|
198
|
+
this.sortSubcommands = false;
|
|
199
|
+
this.sortOptions = false;
|
|
200
|
+
this.showGlobalOptions = false;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
204
|
+
*
|
|
205
|
+
* @param {Command} cmd
|
|
206
|
+
* @returns {Command[]}
|
|
207
|
+
*/
|
|
208
|
+
visibleCommands(cmd) {
|
|
209
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
210
|
+
const helpCommand = cmd._getHelpCommand();
|
|
211
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
212
|
+
visibleCommands.push(helpCommand);
|
|
213
|
+
}
|
|
214
|
+
if (this.sortSubcommands) {
|
|
215
|
+
visibleCommands.sort((a, b) => {
|
|
216
|
+
return a.name().localeCompare(b.name());
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
return visibleCommands;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Compare options for sort.
|
|
223
|
+
*
|
|
224
|
+
* @param {Option} a
|
|
225
|
+
* @param {Option} b
|
|
226
|
+
* @returns {number}
|
|
227
|
+
*/
|
|
228
|
+
compareOptions(a, b) {
|
|
229
|
+
const getSortKey = (option) => {
|
|
230
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
231
|
+
};
|
|
232
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
236
|
+
*
|
|
237
|
+
* @param {Command} cmd
|
|
238
|
+
* @returns {Option[]}
|
|
239
|
+
*/
|
|
240
|
+
visibleOptions(cmd) {
|
|
241
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
242
|
+
const helpOption = cmd._getHelpOption();
|
|
243
|
+
if (helpOption && !helpOption.hidden) {
|
|
244
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
245
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
246
|
+
if (!removeShort && !removeLong) {
|
|
247
|
+
visibleOptions.push(helpOption);
|
|
248
|
+
} else if (helpOption.long && !removeLong) {
|
|
249
|
+
visibleOptions.push(
|
|
250
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
251
|
+
);
|
|
252
|
+
} else if (helpOption.short && !removeShort) {
|
|
253
|
+
visibleOptions.push(
|
|
254
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (this.sortOptions) {
|
|
259
|
+
visibleOptions.sort(this.compareOptions);
|
|
260
|
+
}
|
|
261
|
+
return visibleOptions;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get an array of the visible global options. (Not including help.)
|
|
265
|
+
*
|
|
266
|
+
* @param {Command} cmd
|
|
267
|
+
* @returns {Option[]}
|
|
268
|
+
*/
|
|
269
|
+
visibleGlobalOptions(cmd) {
|
|
270
|
+
if (!this.showGlobalOptions) return [];
|
|
271
|
+
const globalOptions = [];
|
|
272
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
273
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
274
|
+
(option) => !option.hidden
|
|
275
|
+
);
|
|
276
|
+
globalOptions.push(...visibleOptions);
|
|
277
|
+
}
|
|
278
|
+
if (this.sortOptions) {
|
|
279
|
+
globalOptions.sort(this.compareOptions);
|
|
280
|
+
}
|
|
281
|
+
return globalOptions;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Get an array of the arguments if any have a description.
|
|
285
|
+
*
|
|
286
|
+
* @param {Command} cmd
|
|
287
|
+
* @returns {Argument[]}
|
|
288
|
+
*/
|
|
289
|
+
visibleArguments(cmd) {
|
|
290
|
+
if (cmd._argsDescription) {
|
|
291
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
292
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
296
|
+
return cmd.registeredArguments;
|
|
297
|
+
}
|
|
298
|
+
return [];
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Get the command term to show in the list of subcommands.
|
|
302
|
+
*
|
|
303
|
+
* @param {Command} cmd
|
|
304
|
+
* @returns {string}
|
|
305
|
+
*/
|
|
306
|
+
subcommandTerm(cmd) {
|
|
307
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
308
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
309
|
+
(args ? " " + args : "");
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Get the option term to show in the list of options.
|
|
313
|
+
*
|
|
314
|
+
* @param {Option} option
|
|
315
|
+
* @returns {string}
|
|
316
|
+
*/
|
|
317
|
+
optionTerm(option) {
|
|
318
|
+
return option.flags;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Get the argument term to show in the list of arguments.
|
|
322
|
+
*
|
|
323
|
+
* @param {Argument} argument
|
|
324
|
+
* @returns {string}
|
|
325
|
+
*/
|
|
326
|
+
argumentTerm(argument) {
|
|
327
|
+
return argument.name();
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Get the longest command term length.
|
|
331
|
+
*
|
|
332
|
+
* @param {Command} cmd
|
|
333
|
+
* @param {Help} helper
|
|
334
|
+
* @returns {number}
|
|
335
|
+
*/
|
|
336
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
337
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
338
|
+
return Math.max(max, helper.subcommandTerm(command).length);
|
|
339
|
+
}, 0);
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Get the longest option term length.
|
|
343
|
+
*
|
|
344
|
+
* @param {Command} cmd
|
|
345
|
+
* @param {Help} helper
|
|
346
|
+
* @returns {number}
|
|
347
|
+
*/
|
|
348
|
+
longestOptionTermLength(cmd, helper) {
|
|
349
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
350
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
351
|
+
}, 0);
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Get the longest global option term length.
|
|
355
|
+
*
|
|
356
|
+
* @param {Command} cmd
|
|
357
|
+
* @param {Help} helper
|
|
358
|
+
* @returns {number}
|
|
359
|
+
*/
|
|
360
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
361
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
362
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
363
|
+
}, 0);
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Get the longest argument term length.
|
|
367
|
+
*
|
|
368
|
+
* @param {Command} cmd
|
|
369
|
+
* @param {Help} helper
|
|
370
|
+
* @returns {number}
|
|
371
|
+
*/
|
|
372
|
+
longestArgumentTermLength(cmd, helper) {
|
|
373
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
374
|
+
return Math.max(max, helper.argumentTerm(argument).length);
|
|
375
|
+
}, 0);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
379
|
+
*
|
|
380
|
+
* @param {Command} cmd
|
|
381
|
+
* @returns {string}
|
|
382
|
+
*/
|
|
383
|
+
commandUsage(cmd) {
|
|
384
|
+
let cmdName = cmd._name;
|
|
385
|
+
if (cmd._aliases[0]) {
|
|
386
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
387
|
+
}
|
|
388
|
+
let ancestorCmdNames = "";
|
|
389
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
390
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
391
|
+
}
|
|
392
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Get the description for the command.
|
|
396
|
+
*
|
|
397
|
+
* @param {Command} cmd
|
|
398
|
+
* @returns {string}
|
|
399
|
+
*/
|
|
400
|
+
commandDescription(cmd) {
|
|
401
|
+
return cmd.description();
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
405
|
+
* (Fallback to description for backwards compatibility.)
|
|
406
|
+
*
|
|
407
|
+
* @param {Command} cmd
|
|
408
|
+
* @returns {string}
|
|
409
|
+
*/
|
|
410
|
+
subcommandDescription(cmd) {
|
|
411
|
+
return cmd.summary() || cmd.description();
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Get the option description to show in the list of options.
|
|
415
|
+
*
|
|
416
|
+
* @param {Option} option
|
|
417
|
+
* @return {string}
|
|
418
|
+
*/
|
|
419
|
+
optionDescription(option) {
|
|
420
|
+
const extraInfo = [];
|
|
421
|
+
if (option.argChoices) {
|
|
422
|
+
extraInfo.push(
|
|
423
|
+
// use stringify to match the display of the default value
|
|
424
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
if (option.defaultValue !== void 0) {
|
|
428
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
429
|
+
if (showDefault) {
|
|
430
|
+
extraInfo.push(
|
|
431
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
436
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
437
|
+
}
|
|
438
|
+
if (option.envVar !== void 0) {
|
|
439
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
440
|
+
}
|
|
441
|
+
if (extraInfo.length > 0) {
|
|
442
|
+
return `${option.description} (${extraInfo.join(", ")})`;
|
|
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 extraDescripton = `(${extraInfo.join(", ")})`;
|
|
467
|
+
if (argument.description) {
|
|
468
|
+
return `${argument.description} ${extraDescripton}`;
|
|
469
|
+
}
|
|
470
|
+
return extraDescripton;
|
|
471
|
+
}
|
|
472
|
+
return argument.description;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Generate the built-in help text.
|
|
476
|
+
*
|
|
477
|
+
* @param {Command} cmd
|
|
478
|
+
* @param {Help} helper
|
|
479
|
+
* @returns {string}
|
|
480
|
+
*/
|
|
481
|
+
formatHelp(cmd, helper) {
|
|
482
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
483
|
+
const helpWidth = helper.helpWidth || 80;
|
|
484
|
+
const itemIndentWidth = 2;
|
|
485
|
+
const itemSeparatorWidth = 2;
|
|
486
|
+
function formatItem(term, description) {
|
|
487
|
+
if (description) {
|
|
488
|
+
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
|
|
489
|
+
return helper.wrap(
|
|
490
|
+
fullText,
|
|
491
|
+
helpWidth - itemIndentWidth,
|
|
492
|
+
termWidth + itemSeparatorWidth
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
return term;
|
|
496
|
+
}
|
|
497
|
+
function formatList(textArray) {
|
|
498
|
+
return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
|
|
499
|
+
}
|
|
500
|
+
let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
|
|
501
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
502
|
+
if (commandDescription.length > 0) {
|
|
503
|
+
output = output.concat([
|
|
504
|
+
helper.wrap(commandDescription, helpWidth, 0),
|
|
505
|
+
""
|
|
506
|
+
]);
|
|
507
|
+
}
|
|
508
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
509
|
+
return formatItem(
|
|
510
|
+
helper.argumentTerm(argument),
|
|
511
|
+
helper.argumentDescription(argument)
|
|
512
|
+
);
|
|
513
|
+
});
|
|
514
|
+
if (argumentList.length > 0) {
|
|
515
|
+
output = output.concat(["Arguments:", formatList(argumentList), ""]);
|
|
516
|
+
}
|
|
517
|
+
const optionList = helper.visibleOptions(cmd).map((option) => {
|
|
518
|
+
return formatItem(
|
|
519
|
+
helper.optionTerm(option),
|
|
520
|
+
helper.optionDescription(option)
|
|
521
|
+
);
|
|
522
|
+
});
|
|
523
|
+
if (optionList.length > 0) {
|
|
524
|
+
output = output.concat(["Options:", formatList(optionList), ""]);
|
|
525
|
+
}
|
|
526
|
+
if (this.showGlobalOptions) {
|
|
527
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
528
|
+
return formatItem(
|
|
529
|
+
helper.optionTerm(option),
|
|
530
|
+
helper.optionDescription(option)
|
|
531
|
+
);
|
|
532
|
+
});
|
|
533
|
+
if (globalOptionList.length > 0) {
|
|
534
|
+
output = output.concat([
|
|
535
|
+
"Global Options:",
|
|
536
|
+
formatList(globalOptionList),
|
|
537
|
+
""
|
|
538
|
+
]);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
|
|
542
|
+
return formatItem(
|
|
543
|
+
helper.subcommandTerm(cmd2),
|
|
544
|
+
helper.subcommandDescription(cmd2)
|
|
545
|
+
);
|
|
546
|
+
});
|
|
547
|
+
if (commandList.length > 0) {
|
|
548
|
+
output = output.concat(["Commands:", formatList(commandList), ""]);
|
|
549
|
+
}
|
|
550
|
+
return output.join("\n");
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Calculate the pad width from the maximum term length.
|
|
554
|
+
*
|
|
555
|
+
* @param {Command} cmd
|
|
556
|
+
* @param {Help} helper
|
|
557
|
+
* @returns {number}
|
|
558
|
+
*/
|
|
559
|
+
padWidth(cmd, helper) {
|
|
560
|
+
return Math.max(
|
|
561
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
562
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
563
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
564
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Wrap the given string to width characters per line, with lines after the first indented.
|
|
569
|
+
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
|
|
570
|
+
*
|
|
571
|
+
* @param {string} str
|
|
572
|
+
* @param {number} width
|
|
573
|
+
* @param {number} indent
|
|
574
|
+
* @param {number} [minColumnWidth=40]
|
|
575
|
+
* @return {string}
|
|
576
|
+
*
|
|
577
|
+
*/
|
|
578
|
+
wrap(str, width, indent, minColumnWidth = 40) {
|
|
579
|
+
const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
|
|
580
|
+
const manualIndent = new RegExp(`[\\n][${indents}]+`);
|
|
581
|
+
if (str.match(manualIndent)) return str;
|
|
582
|
+
const columnWidth = width - indent;
|
|
583
|
+
if (columnWidth < minColumnWidth) return str;
|
|
584
|
+
const leadingStr = str.slice(0, indent);
|
|
585
|
+
const columnText = str.slice(indent).replace("\r\n", "\n");
|
|
586
|
+
const indentString = " ".repeat(indent);
|
|
587
|
+
const zeroWidthSpace = "\u200B";
|
|
588
|
+
const breaks = `\\s${zeroWidthSpace}`;
|
|
589
|
+
const regex = new RegExp(
|
|
590
|
+
`
|
|
591
|
+
|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
|
|
592
|
+
"g"
|
|
593
|
+
);
|
|
594
|
+
const lines = columnText.match(regex) || [];
|
|
595
|
+
return leadingStr + lines.map((line, i) => {
|
|
596
|
+
if (line === "\n") return "";
|
|
597
|
+
return (i > 0 ? indentString : "") + line.trimEnd();
|
|
598
|
+
}).join("\n");
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
exports2.Help = Help2;
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
// node_modules/commander/lib/option.js
|
|
606
|
+
var require_option = __commonJS({
|
|
607
|
+
"node_modules/commander/lib/option.js"(exports2) {
|
|
608
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
609
|
+
var Option2 = class {
|
|
610
|
+
/**
|
|
611
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
612
|
+
*
|
|
613
|
+
* @param {string} flags
|
|
614
|
+
* @param {string} [description]
|
|
615
|
+
*/
|
|
616
|
+
constructor(flags, description) {
|
|
617
|
+
this.flags = flags;
|
|
618
|
+
this.description = description || "";
|
|
619
|
+
this.required = flags.includes("<");
|
|
620
|
+
this.optional = flags.includes("[");
|
|
621
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
622
|
+
this.mandatory = false;
|
|
623
|
+
const optionFlags = splitOptionFlags(flags);
|
|
624
|
+
this.short = optionFlags.shortFlag;
|
|
625
|
+
this.long = optionFlags.longFlag;
|
|
626
|
+
this.negate = false;
|
|
627
|
+
if (this.long) {
|
|
628
|
+
this.negate = this.long.startsWith("--no-");
|
|
629
|
+
}
|
|
630
|
+
this.defaultValue = void 0;
|
|
631
|
+
this.defaultValueDescription = void 0;
|
|
632
|
+
this.presetArg = void 0;
|
|
633
|
+
this.envVar = void 0;
|
|
634
|
+
this.parseArg = void 0;
|
|
635
|
+
this.hidden = false;
|
|
636
|
+
this.argChoices = void 0;
|
|
637
|
+
this.conflictsWith = [];
|
|
638
|
+
this.implied = void 0;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
642
|
+
*
|
|
643
|
+
* @param {*} value
|
|
644
|
+
* @param {string} [description]
|
|
645
|
+
* @return {Option}
|
|
646
|
+
*/
|
|
647
|
+
default(value, description) {
|
|
648
|
+
this.defaultValue = value;
|
|
649
|
+
this.defaultValueDescription = description;
|
|
650
|
+
return this;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
654
|
+
* The custom processing (parseArg) is called.
|
|
655
|
+
*
|
|
656
|
+
* @example
|
|
657
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
658
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
659
|
+
*
|
|
660
|
+
* @param {*} arg
|
|
661
|
+
* @return {Option}
|
|
662
|
+
*/
|
|
663
|
+
preset(arg) {
|
|
664
|
+
this.presetArg = arg;
|
|
665
|
+
return this;
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Add option name(s) that conflict with this option.
|
|
669
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
670
|
+
*
|
|
671
|
+
* @example
|
|
672
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
673
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
674
|
+
*
|
|
675
|
+
* @param {(string | string[])} names
|
|
676
|
+
* @return {Option}
|
|
677
|
+
*/
|
|
678
|
+
conflicts(names) {
|
|
679
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
680
|
+
return this;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
684
|
+
*
|
|
685
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
686
|
+
*
|
|
687
|
+
* @example
|
|
688
|
+
* program
|
|
689
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
690
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
691
|
+
*
|
|
692
|
+
* @param {object} impliedOptionValues
|
|
693
|
+
* @return {Option}
|
|
694
|
+
*/
|
|
695
|
+
implies(impliedOptionValues) {
|
|
696
|
+
let newImplied = impliedOptionValues;
|
|
697
|
+
if (typeof impliedOptionValues === "string") {
|
|
698
|
+
newImplied = { [impliedOptionValues]: true };
|
|
699
|
+
}
|
|
700
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
701
|
+
return this;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Set environment variable to check for option value.
|
|
705
|
+
*
|
|
706
|
+
* An environment variable is only used if when processed the current option value is
|
|
707
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
708
|
+
*
|
|
709
|
+
* @param {string} name
|
|
710
|
+
* @return {Option}
|
|
711
|
+
*/
|
|
712
|
+
env(name) {
|
|
713
|
+
this.envVar = name;
|
|
714
|
+
return this;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
718
|
+
*
|
|
719
|
+
* @param {Function} [fn]
|
|
720
|
+
* @return {Option}
|
|
721
|
+
*/
|
|
722
|
+
argParser(fn) {
|
|
723
|
+
this.parseArg = fn;
|
|
724
|
+
return this;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
728
|
+
*
|
|
729
|
+
* @param {boolean} [mandatory=true]
|
|
730
|
+
* @return {Option}
|
|
731
|
+
*/
|
|
732
|
+
makeOptionMandatory(mandatory = true) {
|
|
733
|
+
this.mandatory = !!mandatory;
|
|
734
|
+
return this;
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Hide option in help.
|
|
738
|
+
*
|
|
739
|
+
* @param {boolean} [hide=true]
|
|
740
|
+
* @return {Option}
|
|
741
|
+
*/
|
|
742
|
+
hideHelp(hide = true) {
|
|
743
|
+
this.hidden = !!hide;
|
|
744
|
+
return this;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* @package
|
|
748
|
+
*/
|
|
749
|
+
_concatValue(value, previous) {
|
|
750
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
751
|
+
return [value];
|
|
752
|
+
}
|
|
753
|
+
return previous.concat(value);
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Only allow option value to be one of choices.
|
|
757
|
+
*
|
|
758
|
+
* @param {string[]} values
|
|
759
|
+
* @return {Option}
|
|
760
|
+
*/
|
|
761
|
+
choices(values) {
|
|
762
|
+
this.argChoices = values.slice();
|
|
763
|
+
this.parseArg = (arg, previous) => {
|
|
764
|
+
if (!this.argChoices.includes(arg)) {
|
|
765
|
+
throw new InvalidArgumentError2(
|
|
766
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
if (this.variadic) {
|
|
770
|
+
return this._concatValue(arg, previous);
|
|
771
|
+
}
|
|
772
|
+
return arg;
|
|
773
|
+
};
|
|
774
|
+
return this;
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Return option name.
|
|
778
|
+
*
|
|
779
|
+
* @return {string}
|
|
780
|
+
*/
|
|
781
|
+
name() {
|
|
782
|
+
if (this.long) {
|
|
783
|
+
return this.long.replace(/^--/, "");
|
|
784
|
+
}
|
|
785
|
+
return this.short.replace(/^-/, "");
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Return option name, in a camelcase format that can be used
|
|
789
|
+
* as a object attribute key.
|
|
790
|
+
*
|
|
791
|
+
* @return {string}
|
|
792
|
+
*/
|
|
793
|
+
attributeName() {
|
|
794
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Check if `arg` matches the short or long flag.
|
|
798
|
+
*
|
|
799
|
+
* @param {string} arg
|
|
800
|
+
* @return {boolean}
|
|
801
|
+
* @package
|
|
802
|
+
*/
|
|
803
|
+
is(arg) {
|
|
804
|
+
return this.short === arg || this.long === arg;
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Return whether a boolean option.
|
|
808
|
+
*
|
|
809
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
810
|
+
*
|
|
811
|
+
* @return {boolean}
|
|
812
|
+
* @package
|
|
813
|
+
*/
|
|
814
|
+
isBoolean() {
|
|
815
|
+
return !this.required && !this.optional && !this.negate;
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
var DualOptions = class {
|
|
819
|
+
/**
|
|
820
|
+
* @param {Option[]} options
|
|
821
|
+
*/
|
|
822
|
+
constructor(options) {
|
|
823
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
824
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
825
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
826
|
+
options.forEach((option) => {
|
|
827
|
+
if (option.negate) {
|
|
828
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
829
|
+
} else {
|
|
830
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
this.negativeOptions.forEach((value, key) => {
|
|
834
|
+
if (this.positiveOptions.has(key)) {
|
|
835
|
+
this.dualOptions.add(key);
|
|
836
|
+
}
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
841
|
+
*
|
|
842
|
+
* @param {*} value
|
|
843
|
+
* @param {Option} option
|
|
844
|
+
* @returns {boolean}
|
|
845
|
+
*/
|
|
846
|
+
valueFromOption(value, option) {
|
|
847
|
+
const optionKey = option.attributeName();
|
|
848
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
849
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
850
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
851
|
+
return option.negate === (negativeValue === value);
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
function camelcase(str) {
|
|
855
|
+
return str.split("-").reduce((str2, word) => {
|
|
856
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
function splitOptionFlags(flags) {
|
|
860
|
+
let shortFlag;
|
|
861
|
+
let longFlag;
|
|
862
|
+
const flagParts = flags.split(/[ |,]+/);
|
|
863
|
+
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
|
|
864
|
+
shortFlag = flagParts.shift();
|
|
865
|
+
longFlag = flagParts.shift();
|
|
866
|
+
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
|
|
867
|
+
shortFlag = longFlag;
|
|
868
|
+
longFlag = void 0;
|
|
869
|
+
}
|
|
870
|
+
return { shortFlag, longFlag };
|
|
871
|
+
}
|
|
872
|
+
exports2.Option = Option2;
|
|
873
|
+
exports2.DualOptions = DualOptions;
|
|
874
|
+
}
|
|
875
|
+
});
|
|
876
|
+
|
|
877
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
878
|
+
var require_suggestSimilar = __commonJS({
|
|
879
|
+
"node_modules/commander/lib/suggestSimilar.js"(exports2) {
|
|
880
|
+
var maxDistance = 3;
|
|
881
|
+
function editDistance(a, b) {
|
|
882
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
883
|
+
return Math.max(a.length, b.length);
|
|
884
|
+
const d = [];
|
|
885
|
+
for (let i = 0; i <= a.length; i++) {
|
|
886
|
+
d[i] = [i];
|
|
887
|
+
}
|
|
888
|
+
for (let j = 0; j <= b.length; j++) {
|
|
889
|
+
d[0][j] = j;
|
|
890
|
+
}
|
|
891
|
+
for (let j = 1; j <= b.length; j++) {
|
|
892
|
+
for (let i = 1; i <= a.length; i++) {
|
|
893
|
+
let cost = 1;
|
|
894
|
+
if (a[i - 1] === b[j - 1]) {
|
|
895
|
+
cost = 0;
|
|
896
|
+
} else {
|
|
897
|
+
cost = 1;
|
|
898
|
+
}
|
|
899
|
+
d[i][j] = Math.min(
|
|
900
|
+
d[i - 1][j] + 1,
|
|
901
|
+
// deletion
|
|
902
|
+
d[i][j - 1] + 1,
|
|
903
|
+
// insertion
|
|
904
|
+
d[i - 1][j - 1] + cost
|
|
905
|
+
// substitution
|
|
906
|
+
);
|
|
907
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
908
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
return d[a.length][b.length];
|
|
913
|
+
}
|
|
914
|
+
function suggestSimilar(word, candidates) {
|
|
915
|
+
if (!candidates || candidates.length === 0) return "";
|
|
916
|
+
candidates = Array.from(new Set(candidates));
|
|
917
|
+
const searchingOptions = word.startsWith("--");
|
|
918
|
+
if (searchingOptions) {
|
|
919
|
+
word = word.slice(2);
|
|
920
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
921
|
+
}
|
|
922
|
+
let similar = [];
|
|
923
|
+
let bestDistance = maxDistance;
|
|
924
|
+
const minSimilarity = 0.4;
|
|
925
|
+
candidates.forEach((candidate) => {
|
|
926
|
+
if (candidate.length <= 1) return;
|
|
927
|
+
const distance = editDistance(word, candidate);
|
|
928
|
+
const length = Math.max(word.length, candidate.length);
|
|
929
|
+
const similarity = (length - distance) / length;
|
|
930
|
+
if (similarity > minSimilarity) {
|
|
931
|
+
if (distance < bestDistance) {
|
|
932
|
+
bestDistance = distance;
|
|
933
|
+
similar = [candidate];
|
|
934
|
+
} else if (distance === bestDistance) {
|
|
935
|
+
similar.push(candidate);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
940
|
+
if (searchingOptions) {
|
|
941
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
942
|
+
}
|
|
943
|
+
if (similar.length > 1) {
|
|
944
|
+
return `
|
|
945
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
946
|
+
}
|
|
947
|
+
if (similar.length === 1) {
|
|
948
|
+
return `
|
|
949
|
+
(Did you mean ${similar[0]}?)`;
|
|
950
|
+
}
|
|
951
|
+
return "";
|
|
952
|
+
}
|
|
953
|
+
exports2.suggestSimilar = suggestSimilar;
|
|
954
|
+
}
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
// node_modules/commander/lib/command.js
|
|
958
|
+
var require_command = __commonJS({
|
|
959
|
+
"node_modules/commander/lib/command.js"(exports2) {
|
|
960
|
+
var EventEmitter = require("node:events").EventEmitter;
|
|
961
|
+
var childProcess = require("node:child_process");
|
|
962
|
+
var path = require("node:path");
|
|
963
|
+
var fs = require("node:fs");
|
|
964
|
+
var process2 = require("node:process");
|
|
965
|
+
var { Argument: Argument2, humanReadableArgName } = require_argument();
|
|
966
|
+
var { CommanderError: CommanderError2 } = require_error();
|
|
967
|
+
var { Help: Help2 } = require_help();
|
|
968
|
+
var { Option: Option2, DualOptions } = require_option();
|
|
969
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
970
|
+
var Command2 = class _Command extends EventEmitter {
|
|
971
|
+
/**
|
|
972
|
+
* Initialize a new `Command`.
|
|
973
|
+
*
|
|
974
|
+
* @param {string} [name]
|
|
975
|
+
*/
|
|
976
|
+
constructor(name) {
|
|
977
|
+
super();
|
|
978
|
+
this.commands = [];
|
|
979
|
+
this.options = [];
|
|
980
|
+
this.parent = null;
|
|
981
|
+
this._allowUnknownOption = false;
|
|
982
|
+
this._allowExcessArguments = true;
|
|
983
|
+
this.registeredArguments = [];
|
|
984
|
+
this._args = this.registeredArguments;
|
|
985
|
+
this.args = [];
|
|
986
|
+
this.rawArgs = [];
|
|
987
|
+
this.processedArgs = [];
|
|
988
|
+
this._scriptPath = null;
|
|
989
|
+
this._name = name || "";
|
|
990
|
+
this._optionValues = {};
|
|
991
|
+
this._optionValueSources = {};
|
|
992
|
+
this._storeOptionsAsProperties = false;
|
|
993
|
+
this._actionHandler = null;
|
|
994
|
+
this._executableHandler = false;
|
|
995
|
+
this._executableFile = null;
|
|
996
|
+
this._executableDir = null;
|
|
997
|
+
this._defaultCommandName = null;
|
|
998
|
+
this._exitCallback = null;
|
|
999
|
+
this._aliases = [];
|
|
1000
|
+
this._combineFlagAndOptionalValue = true;
|
|
1001
|
+
this._description = "";
|
|
1002
|
+
this._summary = "";
|
|
1003
|
+
this._argsDescription = void 0;
|
|
1004
|
+
this._enablePositionalOptions = false;
|
|
1005
|
+
this._passThroughOptions = false;
|
|
1006
|
+
this._lifeCycleHooks = {};
|
|
1007
|
+
this._showHelpAfterError = false;
|
|
1008
|
+
this._showSuggestionAfterError = true;
|
|
1009
|
+
this._outputConfiguration = {
|
|
1010
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1011
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1012
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1013
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1014
|
+
outputError: (str, write) => write(str)
|
|
1015
|
+
};
|
|
1016
|
+
this._hidden = false;
|
|
1017
|
+
this._helpOption = void 0;
|
|
1018
|
+
this._addImplicitHelpCommand = void 0;
|
|
1019
|
+
this._helpCommand = void 0;
|
|
1020
|
+
this._helpConfiguration = {};
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1024
|
+
*
|
|
1025
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1026
|
+
*
|
|
1027
|
+
* @param {Command} sourceCommand
|
|
1028
|
+
* @return {Command} `this` command for chaining
|
|
1029
|
+
*/
|
|
1030
|
+
copyInheritedSettings(sourceCommand) {
|
|
1031
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1032
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1033
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1034
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1035
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1036
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1037
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1038
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1039
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1040
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1041
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1042
|
+
return this;
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* @returns {Command[]}
|
|
1046
|
+
* @private
|
|
1047
|
+
*/
|
|
1048
|
+
_getCommandAndAncestors() {
|
|
1049
|
+
const result = [];
|
|
1050
|
+
for (let command = this; command; command = command.parent) {
|
|
1051
|
+
result.push(command);
|
|
1052
|
+
}
|
|
1053
|
+
return result;
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Define a command.
|
|
1057
|
+
*
|
|
1058
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1059
|
+
*
|
|
1060
|
+
* @example
|
|
1061
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1062
|
+
* program
|
|
1063
|
+
* .command('clone <source> [destination]')
|
|
1064
|
+
* .description('clone a repository into a newly created directory')
|
|
1065
|
+
* .action((source, destination) => {
|
|
1066
|
+
* console.log('clone command called');
|
|
1067
|
+
* });
|
|
1068
|
+
*
|
|
1069
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1070
|
+
* program
|
|
1071
|
+
* .command('start <service>', 'start named service')
|
|
1072
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1073
|
+
*
|
|
1074
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1075
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1076
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1077
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1078
|
+
*/
|
|
1079
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1080
|
+
let desc = actionOptsOrExecDesc;
|
|
1081
|
+
let opts = execOpts;
|
|
1082
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1083
|
+
opts = desc;
|
|
1084
|
+
desc = null;
|
|
1085
|
+
}
|
|
1086
|
+
opts = opts || {};
|
|
1087
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1088
|
+
const cmd = this.createCommand(name);
|
|
1089
|
+
if (desc) {
|
|
1090
|
+
cmd.description(desc);
|
|
1091
|
+
cmd._executableHandler = true;
|
|
1092
|
+
}
|
|
1093
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1094
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1095
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1096
|
+
if (args) cmd.arguments(args);
|
|
1097
|
+
this._registerCommand(cmd);
|
|
1098
|
+
cmd.parent = this;
|
|
1099
|
+
cmd.copyInheritedSettings(this);
|
|
1100
|
+
if (desc) return this;
|
|
1101
|
+
return cmd;
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Factory routine to create a new unattached command.
|
|
1105
|
+
*
|
|
1106
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1107
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1108
|
+
*
|
|
1109
|
+
* @param {string} [name]
|
|
1110
|
+
* @return {Command} new command
|
|
1111
|
+
*/
|
|
1112
|
+
createCommand(name) {
|
|
1113
|
+
return new _Command(name);
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1117
|
+
* or by overriding Help properties using configureHelp().
|
|
1118
|
+
*
|
|
1119
|
+
* @return {Help}
|
|
1120
|
+
*/
|
|
1121
|
+
createHelp() {
|
|
1122
|
+
return Object.assign(new Help2(), this.configureHelp());
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1126
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1127
|
+
*
|
|
1128
|
+
* @param {object} [configuration] - configuration options
|
|
1129
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1130
|
+
*/
|
|
1131
|
+
configureHelp(configuration) {
|
|
1132
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1133
|
+
this._helpConfiguration = configuration;
|
|
1134
|
+
return this;
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1138
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1139
|
+
*
|
|
1140
|
+
* The configuration properties are all functions:
|
|
1141
|
+
*
|
|
1142
|
+
* // functions to change where being written, stdout and stderr
|
|
1143
|
+
* writeOut(str)
|
|
1144
|
+
* writeErr(str)
|
|
1145
|
+
* // matching functions to specify width for wrapping help
|
|
1146
|
+
* getOutHelpWidth()
|
|
1147
|
+
* getErrHelpWidth()
|
|
1148
|
+
* // functions based on what is being written out
|
|
1149
|
+
* outputError(str, write) // used for displaying errors, and not used for displaying help
|
|
1150
|
+
*
|
|
1151
|
+
* @param {object} [configuration] - configuration options
|
|
1152
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1153
|
+
*/
|
|
1154
|
+
configureOutput(configuration) {
|
|
1155
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1156
|
+
Object.assign(this._outputConfiguration, configuration);
|
|
1157
|
+
return this;
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Display the help or a custom message after an error occurs.
|
|
1161
|
+
*
|
|
1162
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1163
|
+
* @return {Command} `this` command for chaining
|
|
1164
|
+
*/
|
|
1165
|
+
showHelpAfterError(displayHelp = true) {
|
|
1166
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1167
|
+
this._showHelpAfterError = displayHelp;
|
|
1168
|
+
return this;
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1172
|
+
*
|
|
1173
|
+
* @param {boolean} [displaySuggestion]
|
|
1174
|
+
* @return {Command} `this` command for chaining
|
|
1175
|
+
*/
|
|
1176
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1177
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1178
|
+
return this;
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* Add a prepared subcommand.
|
|
1182
|
+
*
|
|
1183
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1184
|
+
*
|
|
1185
|
+
* @param {Command} cmd - new subcommand
|
|
1186
|
+
* @param {object} [opts] - configuration options
|
|
1187
|
+
* @return {Command} `this` command for chaining
|
|
1188
|
+
*/
|
|
1189
|
+
addCommand(cmd, opts) {
|
|
1190
|
+
if (!cmd._name) {
|
|
1191
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1192
|
+
- specify the name in Command constructor or using .name()`);
|
|
1193
|
+
}
|
|
1194
|
+
opts = opts || {};
|
|
1195
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1196
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1197
|
+
this._registerCommand(cmd);
|
|
1198
|
+
cmd.parent = this;
|
|
1199
|
+
cmd._checkForBrokenPassThrough();
|
|
1200
|
+
return this;
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Factory routine to create a new unattached argument.
|
|
1204
|
+
*
|
|
1205
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1206
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1207
|
+
*
|
|
1208
|
+
* @param {string} name
|
|
1209
|
+
* @param {string} [description]
|
|
1210
|
+
* @return {Argument} new argument
|
|
1211
|
+
*/
|
|
1212
|
+
createArgument(name, description) {
|
|
1213
|
+
return new Argument2(name, description);
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Define argument syntax for command.
|
|
1217
|
+
*
|
|
1218
|
+
* The default is that the argument is required, and you can explicitly
|
|
1219
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1220
|
+
*
|
|
1221
|
+
* @example
|
|
1222
|
+
* program.argument('<input-file>');
|
|
1223
|
+
* program.argument('[output-file]');
|
|
1224
|
+
*
|
|
1225
|
+
* @param {string} name
|
|
1226
|
+
* @param {string} [description]
|
|
1227
|
+
* @param {(Function|*)} [fn] - custom argument processing function
|
|
1228
|
+
* @param {*} [defaultValue]
|
|
1229
|
+
* @return {Command} `this` command for chaining
|
|
1230
|
+
*/
|
|
1231
|
+
argument(name, description, fn, defaultValue) {
|
|
1232
|
+
const argument = this.createArgument(name, description);
|
|
1233
|
+
if (typeof fn === "function") {
|
|
1234
|
+
argument.default(defaultValue).argParser(fn);
|
|
1235
|
+
} else {
|
|
1236
|
+
argument.default(fn);
|
|
1237
|
+
}
|
|
1238
|
+
this.addArgument(argument);
|
|
1239
|
+
return this;
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1243
|
+
*
|
|
1244
|
+
* See also .argument().
|
|
1245
|
+
*
|
|
1246
|
+
* @example
|
|
1247
|
+
* program.arguments('<cmd> [env]');
|
|
1248
|
+
*
|
|
1249
|
+
* @param {string} names
|
|
1250
|
+
* @return {Command} `this` command for chaining
|
|
1251
|
+
*/
|
|
1252
|
+
arguments(names) {
|
|
1253
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1254
|
+
this.argument(detail);
|
|
1255
|
+
});
|
|
1256
|
+
return this;
|
|
1257
|
+
}
|
|
1258
|
+
/**
|
|
1259
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1260
|
+
*
|
|
1261
|
+
* @param {Argument} argument
|
|
1262
|
+
* @return {Command} `this` command for chaining
|
|
1263
|
+
*/
|
|
1264
|
+
addArgument(argument) {
|
|
1265
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1266
|
+
if (previousArgument && previousArgument.variadic) {
|
|
1267
|
+
throw new Error(
|
|
1268
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1269
|
+
);
|
|
1270
|
+
}
|
|
1271
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1272
|
+
throw new Error(
|
|
1273
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1274
|
+
);
|
|
1275
|
+
}
|
|
1276
|
+
this.registeredArguments.push(argument);
|
|
1277
|
+
return this;
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1281
|
+
*
|
|
1282
|
+
* @example
|
|
1283
|
+
* program.helpCommand('help [cmd]');
|
|
1284
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1285
|
+
* program.helpCommand(false); // suppress default help command
|
|
1286
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1287
|
+
*
|
|
1288
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1289
|
+
* @param {string} [description] - custom description
|
|
1290
|
+
* @return {Command} `this` command for chaining
|
|
1291
|
+
*/
|
|
1292
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1293
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1294
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1295
|
+
return this;
|
|
1296
|
+
}
|
|
1297
|
+
enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1298
|
+
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1299
|
+
const helpDescription = description ?? "display help for command";
|
|
1300
|
+
const helpCommand = this.createCommand(helpName);
|
|
1301
|
+
helpCommand.helpOption(false);
|
|
1302
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1303
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1304
|
+
this._addImplicitHelpCommand = true;
|
|
1305
|
+
this._helpCommand = helpCommand;
|
|
1306
|
+
return this;
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* Add prepared custom help command.
|
|
1310
|
+
*
|
|
1311
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1312
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1313
|
+
* @return {Command} `this` command for chaining
|
|
1314
|
+
*/
|
|
1315
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1316
|
+
if (typeof helpCommand !== "object") {
|
|
1317
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1318
|
+
return this;
|
|
1319
|
+
}
|
|
1320
|
+
this._addImplicitHelpCommand = true;
|
|
1321
|
+
this._helpCommand = helpCommand;
|
|
1322
|
+
return this;
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Lazy create help command.
|
|
1326
|
+
*
|
|
1327
|
+
* @return {(Command|null)}
|
|
1328
|
+
* @package
|
|
1329
|
+
*/
|
|
1330
|
+
_getHelpCommand() {
|
|
1331
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1332
|
+
if (hasImplicitHelpCommand) {
|
|
1333
|
+
if (this._helpCommand === void 0) {
|
|
1334
|
+
this.helpCommand(void 0, void 0);
|
|
1335
|
+
}
|
|
1336
|
+
return this._helpCommand;
|
|
1337
|
+
}
|
|
1338
|
+
return null;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Add hook for life cycle event.
|
|
1342
|
+
*
|
|
1343
|
+
* @param {string} event
|
|
1344
|
+
* @param {Function} listener
|
|
1345
|
+
* @return {Command} `this` command for chaining
|
|
1346
|
+
*/
|
|
1347
|
+
hook(event, listener) {
|
|
1348
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1349
|
+
if (!allowedValues.includes(event)) {
|
|
1350
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1351
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1352
|
+
}
|
|
1353
|
+
if (this._lifeCycleHooks[event]) {
|
|
1354
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1355
|
+
} else {
|
|
1356
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1357
|
+
}
|
|
1358
|
+
return this;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1362
|
+
*
|
|
1363
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1364
|
+
* @return {Command} `this` command for chaining
|
|
1365
|
+
*/
|
|
1366
|
+
exitOverride(fn) {
|
|
1367
|
+
if (fn) {
|
|
1368
|
+
this._exitCallback = fn;
|
|
1369
|
+
} else {
|
|
1370
|
+
this._exitCallback = (err) => {
|
|
1371
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1372
|
+
throw err;
|
|
1373
|
+
} else {
|
|
1374
|
+
}
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
return this;
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1381
|
+
*
|
|
1382
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1383
|
+
* @param {string} code an id string representing the error
|
|
1384
|
+
* @param {string} message human-readable description of the error
|
|
1385
|
+
* @return never
|
|
1386
|
+
* @private
|
|
1387
|
+
*/
|
|
1388
|
+
_exit(exitCode, code, message) {
|
|
1389
|
+
if (this._exitCallback) {
|
|
1390
|
+
this._exitCallback(new CommanderError2(exitCode, code, message));
|
|
1391
|
+
}
|
|
1392
|
+
process2.exit(exitCode);
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Register callback `fn` for the command.
|
|
1396
|
+
*
|
|
1397
|
+
* @example
|
|
1398
|
+
* program
|
|
1399
|
+
* .command('serve')
|
|
1400
|
+
* .description('start service')
|
|
1401
|
+
* .action(function() {
|
|
1402
|
+
* // do work here
|
|
1403
|
+
* });
|
|
1404
|
+
*
|
|
1405
|
+
* @param {Function} fn
|
|
1406
|
+
* @return {Command} `this` command for chaining
|
|
1407
|
+
*/
|
|
1408
|
+
action(fn) {
|
|
1409
|
+
const listener = (args) => {
|
|
1410
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1411
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1412
|
+
if (this._storeOptionsAsProperties) {
|
|
1413
|
+
actionArgs[expectedArgsCount] = this;
|
|
1414
|
+
} else {
|
|
1415
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1416
|
+
}
|
|
1417
|
+
actionArgs.push(this);
|
|
1418
|
+
return fn.apply(this, actionArgs);
|
|
1419
|
+
};
|
|
1420
|
+
this._actionHandler = listener;
|
|
1421
|
+
return this;
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* Factory routine to create a new unattached option.
|
|
1425
|
+
*
|
|
1426
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1427
|
+
* create the option. You can override createOption to return a custom option.
|
|
1428
|
+
*
|
|
1429
|
+
* @param {string} flags
|
|
1430
|
+
* @param {string} [description]
|
|
1431
|
+
* @return {Option} new option
|
|
1432
|
+
*/
|
|
1433
|
+
createOption(flags, description) {
|
|
1434
|
+
return new Option2(flags, description);
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1438
|
+
*
|
|
1439
|
+
* @param {(Option | Argument)} target
|
|
1440
|
+
* @param {string} value
|
|
1441
|
+
* @param {*} previous
|
|
1442
|
+
* @param {string} invalidArgumentMessage
|
|
1443
|
+
* @private
|
|
1444
|
+
*/
|
|
1445
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1446
|
+
try {
|
|
1447
|
+
return target.parseArg(value, previous);
|
|
1448
|
+
} catch (err) {
|
|
1449
|
+
if (err.code === "commander.invalidArgument") {
|
|
1450
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1451
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1452
|
+
}
|
|
1453
|
+
throw err;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Check for option flag conflicts.
|
|
1458
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1459
|
+
*
|
|
1460
|
+
* @param {Option} option
|
|
1461
|
+
* @private
|
|
1462
|
+
*/
|
|
1463
|
+
_registerOption(option) {
|
|
1464
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1465
|
+
if (matchingOption) {
|
|
1466
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1467
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1468
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1469
|
+
}
|
|
1470
|
+
this.options.push(option);
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1474
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1475
|
+
*
|
|
1476
|
+
* @param {Command} command
|
|
1477
|
+
* @private
|
|
1478
|
+
*/
|
|
1479
|
+
_registerCommand(command) {
|
|
1480
|
+
const knownBy = (cmd) => {
|
|
1481
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1482
|
+
};
|
|
1483
|
+
const alreadyUsed = knownBy(command).find(
|
|
1484
|
+
(name) => this._findCommand(name)
|
|
1485
|
+
);
|
|
1486
|
+
if (alreadyUsed) {
|
|
1487
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1488
|
+
const newCmd = knownBy(command).join("|");
|
|
1489
|
+
throw new Error(
|
|
1490
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1491
|
+
);
|
|
1492
|
+
}
|
|
1493
|
+
this.commands.push(command);
|
|
1494
|
+
}
|
|
1495
|
+
/**
|
|
1496
|
+
* Add an option.
|
|
1497
|
+
*
|
|
1498
|
+
* @param {Option} option
|
|
1499
|
+
* @return {Command} `this` command for chaining
|
|
1500
|
+
*/
|
|
1501
|
+
addOption(option) {
|
|
1502
|
+
this._registerOption(option);
|
|
1503
|
+
const oname = option.name();
|
|
1504
|
+
const name = option.attributeName();
|
|
1505
|
+
if (option.negate) {
|
|
1506
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1507
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1508
|
+
this.setOptionValueWithSource(
|
|
1509
|
+
name,
|
|
1510
|
+
option.defaultValue === void 0 ? true : option.defaultValue,
|
|
1511
|
+
"default"
|
|
1512
|
+
);
|
|
1513
|
+
}
|
|
1514
|
+
} else if (option.defaultValue !== void 0) {
|
|
1515
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1516
|
+
}
|
|
1517
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1518
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1519
|
+
val = option.presetArg;
|
|
1520
|
+
}
|
|
1521
|
+
const oldValue = this.getOptionValue(name);
|
|
1522
|
+
if (val !== null && option.parseArg) {
|
|
1523
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1524
|
+
} else if (val !== null && option.variadic) {
|
|
1525
|
+
val = option._concatValue(val, oldValue);
|
|
1526
|
+
}
|
|
1527
|
+
if (val == null) {
|
|
1528
|
+
if (option.negate) {
|
|
1529
|
+
val = false;
|
|
1530
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1531
|
+
val = true;
|
|
1532
|
+
} else {
|
|
1533
|
+
val = "";
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1537
|
+
};
|
|
1538
|
+
this.on("option:" + oname, (val) => {
|
|
1539
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1540
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1541
|
+
});
|
|
1542
|
+
if (option.envVar) {
|
|
1543
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1544
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1545
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
return this;
|
|
1549
|
+
}
|
|
1550
|
+
/**
|
|
1551
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1552
|
+
*
|
|
1553
|
+
* @return {Command} `this` command for chaining
|
|
1554
|
+
* @private
|
|
1555
|
+
*/
|
|
1556
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1557
|
+
if (typeof flags === "object" && flags instanceof Option2) {
|
|
1558
|
+
throw new Error(
|
|
1559
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1560
|
+
);
|
|
1561
|
+
}
|
|
1562
|
+
const option = this.createOption(flags, description);
|
|
1563
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1564
|
+
if (typeof fn === "function") {
|
|
1565
|
+
option.default(defaultValue).argParser(fn);
|
|
1566
|
+
} else if (fn instanceof RegExp) {
|
|
1567
|
+
const regex = fn;
|
|
1568
|
+
fn = (val, def) => {
|
|
1569
|
+
const m = regex.exec(val);
|
|
1570
|
+
return m ? m[0] : def;
|
|
1571
|
+
};
|
|
1572
|
+
option.default(defaultValue).argParser(fn);
|
|
1573
|
+
} else {
|
|
1574
|
+
option.default(fn);
|
|
1575
|
+
}
|
|
1576
|
+
return this.addOption(option);
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1580
|
+
*
|
|
1581
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1582
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1583
|
+
*
|
|
1584
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1585
|
+
*
|
|
1586
|
+
* @example
|
|
1587
|
+
* program
|
|
1588
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1589
|
+
* .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1590
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1591
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1592
|
+
*
|
|
1593
|
+
* @param {string} flags
|
|
1594
|
+
* @param {string} [description]
|
|
1595
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1596
|
+
* @param {*} [defaultValue]
|
|
1597
|
+
* @return {Command} `this` command for chaining
|
|
1598
|
+
*/
|
|
1599
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1600
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1601
|
+
}
|
|
1602
|
+
/**
|
|
1603
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1604
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1605
|
+
*
|
|
1606
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1607
|
+
*
|
|
1608
|
+
* @param {string} flags
|
|
1609
|
+
* @param {string} [description]
|
|
1610
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1611
|
+
* @param {*} [defaultValue]
|
|
1612
|
+
* @return {Command} `this` command for chaining
|
|
1613
|
+
*/
|
|
1614
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1615
|
+
return this._optionEx(
|
|
1616
|
+
{ mandatory: true },
|
|
1617
|
+
flags,
|
|
1618
|
+
description,
|
|
1619
|
+
parseArg,
|
|
1620
|
+
defaultValue
|
|
1621
|
+
);
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Alter parsing of short flags with optional values.
|
|
1625
|
+
*
|
|
1626
|
+
* @example
|
|
1627
|
+
* // for `.option('-f,--flag [value]'):
|
|
1628
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1629
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1630
|
+
*
|
|
1631
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1632
|
+
* @return {Command} `this` command for chaining
|
|
1633
|
+
*/
|
|
1634
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1635
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1636
|
+
return this;
|
|
1637
|
+
}
|
|
1638
|
+
/**
|
|
1639
|
+
* Allow unknown options on the command line.
|
|
1640
|
+
*
|
|
1641
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1642
|
+
* @return {Command} `this` command for chaining
|
|
1643
|
+
*/
|
|
1644
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1645
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1646
|
+
return this;
|
|
1647
|
+
}
|
|
1648
|
+
/**
|
|
1649
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1650
|
+
*
|
|
1651
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1652
|
+
* @return {Command} `this` command for chaining
|
|
1653
|
+
*/
|
|
1654
|
+
allowExcessArguments(allowExcess = true) {
|
|
1655
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1656
|
+
return this;
|
|
1657
|
+
}
|
|
1658
|
+
/**
|
|
1659
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1660
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1661
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1662
|
+
*
|
|
1663
|
+
* @param {boolean} [positional]
|
|
1664
|
+
* @return {Command} `this` command for chaining
|
|
1665
|
+
*/
|
|
1666
|
+
enablePositionalOptions(positional = true) {
|
|
1667
|
+
this._enablePositionalOptions = !!positional;
|
|
1668
|
+
return this;
|
|
1669
|
+
}
|
|
1670
|
+
/**
|
|
1671
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1672
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1673
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1674
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1675
|
+
*
|
|
1676
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1677
|
+
* @return {Command} `this` command for chaining
|
|
1678
|
+
*/
|
|
1679
|
+
passThroughOptions(passThrough = true) {
|
|
1680
|
+
this._passThroughOptions = !!passThrough;
|
|
1681
|
+
this._checkForBrokenPassThrough();
|
|
1682
|
+
return this;
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* @private
|
|
1686
|
+
*/
|
|
1687
|
+
_checkForBrokenPassThrough() {
|
|
1688
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1689
|
+
throw new Error(
|
|
1690
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1691
|
+
);
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
/**
|
|
1695
|
+
* Whether to store option values as properties on command object,
|
|
1696
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1697
|
+
*
|
|
1698
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1699
|
+
* @return {Command} `this` command for chaining
|
|
1700
|
+
*/
|
|
1701
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1702
|
+
if (this.options.length) {
|
|
1703
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1704
|
+
}
|
|
1705
|
+
if (Object.keys(this._optionValues).length) {
|
|
1706
|
+
throw new Error(
|
|
1707
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1708
|
+
);
|
|
1709
|
+
}
|
|
1710
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1711
|
+
return this;
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Retrieve option value.
|
|
1715
|
+
*
|
|
1716
|
+
* @param {string} key
|
|
1717
|
+
* @return {object} value
|
|
1718
|
+
*/
|
|
1719
|
+
getOptionValue(key) {
|
|
1720
|
+
if (this._storeOptionsAsProperties) {
|
|
1721
|
+
return this[key];
|
|
1722
|
+
}
|
|
1723
|
+
return this._optionValues[key];
|
|
1724
|
+
}
|
|
1725
|
+
/**
|
|
1726
|
+
* Store option value.
|
|
1727
|
+
*
|
|
1728
|
+
* @param {string} key
|
|
1729
|
+
* @param {object} value
|
|
1730
|
+
* @return {Command} `this` command for chaining
|
|
1731
|
+
*/
|
|
1732
|
+
setOptionValue(key, value) {
|
|
1733
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1734
|
+
}
|
|
1735
|
+
/**
|
|
1736
|
+
* Store option value and where the value came from.
|
|
1737
|
+
*
|
|
1738
|
+
* @param {string} key
|
|
1739
|
+
* @param {object} value
|
|
1740
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1741
|
+
* @return {Command} `this` command for chaining
|
|
1742
|
+
*/
|
|
1743
|
+
setOptionValueWithSource(key, value, source) {
|
|
1744
|
+
if (this._storeOptionsAsProperties) {
|
|
1745
|
+
this[key] = value;
|
|
1746
|
+
} else {
|
|
1747
|
+
this._optionValues[key] = value;
|
|
1748
|
+
}
|
|
1749
|
+
this._optionValueSources[key] = source;
|
|
1750
|
+
return this;
|
|
1751
|
+
}
|
|
1752
|
+
/**
|
|
1753
|
+
* Get source of option value.
|
|
1754
|
+
* Expected values are default | config | env | cli | implied
|
|
1755
|
+
*
|
|
1756
|
+
* @param {string} key
|
|
1757
|
+
* @return {string}
|
|
1758
|
+
*/
|
|
1759
|
+
getOptionValueSource(key) {
|
|
1760
|
+
return this._optionValueSources[key];
|
|
1761
|
+
}
|
|
1762
|
+
/**
|
|
1763
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1764
|
+
* Expected values are default | config | env | cli | implied
|
|
1765
|
+
*
|
|
1766
|
+
* @param {string} key
|
|
1767
|
+
* @return {string}
|
|
1768
|
+
*/
|
|
1769
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1770
|
+
let source;
|
|
1771
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1772
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
1773
|
+
source = cmd.getOptionValueSource(key);
|
|
1774
|
+
}
|
|
1775
|
+
});
|
|
1776
|
+
return source;
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* Get user arguments from implied or explicit arguments.
|
|
1780
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1781
|
+
*
|
|
1782
|
+
* @private
|
|
1783
|
+
*/
|
|
1784
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1785
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
1786
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1787
|
+
}
|
|
1788
|
+
parseOptions = parseOptions || {};
|
|
1789
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1790
|
+
if (process2.versions?.electron) {
|
|
1791
|
+
parseOptions.from = "electron";
|
|
1792
|
+
}
|
|
1793
|
+
const execArgv = process2.execArgv ?? [];
|
|
1794
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
1795
|
+
parseOptions.from = "eval";
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
if (argv === void 0) {
|
|
1799
|
+
argv = process2.argv;
|
|
1800
|
+
}
|
|
1801
|
+
this.rawArgs = argv.slice();
|
|
1802
|
+
let userArgs;
|
|
1803
|
+
switch (parseOptions.from) {
|
|
1804
|
+
case void 0:
|
|
1805
|
+
case "node":
|
|
1806
|
+
this._scriptPath = argv[1];
|
|
1807
|
+
userArgs = argv.slice(2);
|
|
1808
|
+
break;
|
|
1809
|
+
case "electron":
|
|
1810
|
+
if (process2.defaultApp) {
|
|
1811
|
+
this._scriptPath = argv[1];
|
|
1812
|
+
userArgs = argv.slice(2);
|
|
1813
|
+
} else {
|
|
1814
|
+
userArgs = argv.slice(1);
|
|
1815
|
+
}
|
|
1816
|
+
break;
|
|
1817
|
+
case "user":
|
|
1818
|
+
userArgs = argv.slice(0);
|
|
1819
|
+
break;
|
|
1820
|
+
case "eval":
|
|
1821
|
+
userArgs = argv.slice(1);
|
|
1822
|
+
break;
|
|
1823
|
+
default:
|
|
1824
|
+
throw new Error(
|
|
1825
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
if (!this._name && this._scriptPath)
|
|
1829
|
+
this.nameFromFilename(this._scriptPath);
|
|
1830
|
+
this._name = this._name || "program";
|
|
1831
|
+
return userArgs;
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1835
|
+
*
|
|
1836
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
1837
|
+
*
|
|
1838
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1839
|
+
*
|
|
1840
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1841
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1842
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1843
|
+
* - `'user'`: just user arguments
|
|
1844
|
+
*
|
|
1845
|
+
* @example
|
|
1846
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
1847
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1848
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1849
|
+
*
|
|
1850
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
1851
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
1852
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
1853
|
+
* @return {Command} `this` command for chaining
|
|
1854
|
+
*/
|
|
1855
|
+
parse(argv, parseOptions) {
|
|
1856
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1857
|
+
this._parseCommand([], userArgs);
|
|
1858
|
+
return this;
|
|
1859
|
+
}
|
|
1860
|
+
/**
|
|
1861
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1862
|
+
*
|
|
1863
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1864
|
+
*
|
|
1865
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1866
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1867
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1868
|
+
* - `'user'`: just user arguments
|
|
1869
|
+
*
|
|
1870
|
+
* @example
|
|
1871
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
1872
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1873
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1874
|
+
*
|
|
1875
|
+
* @param {string[]} [argv]
|
|
1876
|
+
* @param {object} [parseOptions]
|
|
1877
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
1878
|
+
* @return {Promise}
|
|
1879
|
+
*/
|
|
1880
|
+
async parseAsync(argv, parseOptions) {
|
|
1881
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1882
|
+
await this._parseCommand([], userArgs);
|
|
1883
|
+
return this;
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Execute a sub-command executable.
|
|
1887
|
+
*
|
|
1888
|
+
* @private
|
|
1889
|
+
*/
|
|
1890
|
+
_executeSubCommand(subcommand, args) {
|
|
1891
|
+
args = args.slice();
|
|
1892
|
+
let launchWithNode = false;
|
|
1893
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1894
|
+
function findFile(baseDir, baseName) {
|
|
1895
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1896
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
1897
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
1898
|
+
const foundExt = sourceExt.find(
|
|
1899
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
1900
|
+
);
|
|
1901
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
1902
|
+
return void 0;
|
|
1903
|
+
}
|
|
1904
|
+
this._checkForMissingMandatoryOptions();
|
|
1905
|
+
this._checkForConflictingOptions();
|
|
1906
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1907
|
+
let executableDir = this._executableDir || "";
|
|
1908
|
+
if (this._scriptPath) {
|
|
1909
|
+
let resolvedScriptPath;
|
|
1910
|
+
try {
|
|
1911
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1912
|
+
} catch (err) {
|
|
1913
|
+
resolvedScriptPath = this._scriptPath;
|
|
1914
|
+
}
|
|
1915
|
+
executableDir = path.resolve(
|
|
1916
|
+
path.dirname(resolvedScriptPath),
|
|
1917
|
+
executableDir
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
if (executableDir) {
|
|
1921
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1922
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1923
|
+
const legacyName = path.basename(
|
|
1924
|
+
this._scriptPath,
|
|
1925
|
+
path.extname(this._scriptPath)
|
|
1926
|
+
);
|
|
1927
|
+
if (legacyName !== this._name) {
|
|
1928
|
+
localFile = findFile(
|
|
1929
|
+
executableDir,
|
|
1930
|
+
`${legacyName}-${subcommand._name}`
|
|
1931
|
+
);
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
executableFile = localFile || executableFile;
|
|
1935
|
+
}
|
|
1936
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1937
|
+
let proc;
|
|
1938
|
+
if (process2.platform !== "win32") {
|
|
1939
|
+
if (launchWithNode) {
|
|
1940
|
+
args.unshift(executableFile);
|
|
1941
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1942
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
1943
|
+
} else {
|
|
1944
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1945
|
+
}
|
|
1946
|
+
} else {
|
|
1947
|
+
args.unshift(executableFile);
|
|
1948
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1949
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
1950
|
+
}
|
|
1951
|
+
if (!proc.killed) {
|
|
1952
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1953
|
+
signals.forEach((signal) => {
|
|
1954
|
+
process2.on(signal, () => {
|
|
1955
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1956
|
+
proc.kill(signal);
|
|
1957
|
+
}
|
|
1958
|
+
});
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
const exitCallback = this._exitCallback;
|
|
1962
|
+
proc.on("close", (code) => {
|
|
1963
|
+
code = code ?? 1;
|
|
1964
|
+
if (!exitCallback) {
|
|
1965
|
+
process2.exit(code);
|
|
1966
|
+
} else {
|
|
1967
|
+
exitCallback(
|
|
1968
|
+
new CommanderError2(
|
|
1969
|
+
code,
|
|
1970
|
+
"commander.executeSubCommandAsync",
|
|
1971
|
+
"(close)"
|
|
1972
|
+
)
|
|
1973
|
+
);
|
|
1974
|
+
}
|
|
1975
|
+
});
|
|
1976
|
+
proc.on("error", (err) => {
|
|
1977
|
+
if (err.code === "ENOENT") {
|
|
1978
|
+
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";
|
|
1979
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1980
|
+
- if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1981
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1982
|
+
- ${executableDirMessage}`;
|
|
1983
|
+
throw new Error(executableMissing);
|
|
1984
|
+
} else if (err.code === "EACCES") {
|
|
1985
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
1986
|
+
}
|
|
1987
|
+
if (!exitCallback) {
|
|
1988
|
+
process2.exit(1);
|
|
1989
|
+
} else {
|
|
1990
|
+
const wrappedError = new CommanderError2(
|
|
1991
|
+
1,
|
|
1992
|
+
"commander.executeSubCommandAsync",
|
|
1993
|
+
"(error)"
|
|
1994
|
+
);
|
|
1995
|
+
wrappedError.nestedError = err;
|
|
1996
|
+
exitCallback(wrappedError);
|
|
1997
|
+
}
|
|
1998
|
+
});
|
|
1999
|
+
this.runningCommand = proc;
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* @private
|
|
2003
|
+
*/
|
|
2004
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2005
|
+
const subCommand = this._findCommand(commandName);
|
|
2006
|
+
if (!subCommand) this.help({ error: true });
|
|
2007
|
+
let promiseChain;
|
|
2008
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2009
|
+
promiseChain,
|
|
2010
|
+
subCommand,
|
|
2011
|
+
"preSubcommand"
|
|
2012
|
+
);
|
|
2013
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2014
|
+
if (subCommand._executableHandler) {
|
|
2015
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2016
|
+
} else {
|
|
2017
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2018
|
+
}
|
|
2019
|
+
});
|
|
2020
|
+
return promiseChain;
|
|
2021
|
+
}
|
|
2022
|
+
/**
|
|
2023
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2024
|
+
* e.g. help foo
|
|
2025
|
+
*
|
|
2026
|
+
* @private
|
|
2027
|
+
*/
|
|
2028
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2029
|
+
if (!subcommandName) {
|
|
2030
|
+
this.help();
|
|
2031
|
+
}
|
|
2032
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2033
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2034
|
+
subCommand.help();
|
|
2035
|
+
}
|
|
2036
|
+
return this._dispatchSubcommand(
|
|
2037
|
+
subcommandName,
|
|
2038
|
+
[],
|
|
2039
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2040
|
+
);
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* Check this.args against expected this.registeredArguments.
|
|
2044
|
+
*
|
|
2045
|
+
* @private
|
|
2046
|
+
*/
|
|
2047
|
+
_checkNumberOfArguments() {
|
|
2048
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2049
|
+
if (arg.required && this.args[i] == null) {
|
|
2050
|
+
this.missingArgument(arg.name());
|
|
2051
|
+
}
|
|
2052
|
+
});
|
|
2053
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2054
|
+
return;
|
|
2055
|
+
}
|
|
2056
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2057
|
+
this._excessArguments(this.args);
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
/**
|
|
2061
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2062
|
+
*
|
|
2063
|
+
* @private
|
|
2064
|
+
*/
|
|
2065
|
+
_processArguments() {
|
|
2066
|
+
const myParseArg = (argument, value, previous) => {
|
|
2067
|
+
let parsedValue = value;
|
|
2068
|
+
if (value !== null && argument.parseArg) {
|
|
2069
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2070
|
+
parsedValue = this._callParseArg(
|
|
2071
|
+
argument,
|
|
2072
|
+
value,
|
|
2073
|
+
previous,
|
|
2074
|
+
invalidValueMessage
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
return parsedValue;
|
|
2078
|
+
};
|
|
2079
|
+
this._checkNumberOfArguments();
|
|
2080
|
+
const processedArgs = [];
|
|
2081
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2082
|
+
let value = declaredArg.defaultValue;
|
|
2083
|
+
if (declaredArg.variadic) {
|
|
2084
|
+
if (index < this.args.length) {
|
|
2085
|
+
value = this.args.slice(index);
|
|
2086
|
+
if (declaredArg.parseArg) {
|
|
2087
|
+
value = value.reduce((processed, v) => {
|
|
2088
|
+
return myParseArg(declaredArg, v, processed);
|
|
2089
|
+
}, declaredArg.defaultValue);
|
|
2090
|
+
}
|
|
2091
|
+
} else if (value === void 0) {
|
|
2092
|
+
value = [];
|
|
2093
|
+
}
|
|
2094
|
+
} else if (index < this.args.length) {
|
|
2095
|
+
value = this.args[index];
|
|
2096
|
+
if (declaredArg.parseArg) {
|
|
2097
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
processedArgs[index] = value;
|
|
2101
|
+
});
|
|
2102
|
+
this.processedArgs = processedArgs;
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2106
|
+
*
|
|
2107
|
+
* @param {(Promise|undefined)} promise
|
|
2108
|
+
* @param {Function} fn
|
|
2109
|
+
* @return {(Promise|undefined)}
|
|
2110
|
+
* @private
|
|
2111
|
+
*/
|
|
2112
|
+
_chainOrCall(promise, fn) {
|
|
2113
|
+
if (promise && promise.then && typeof promise.then === "function") {
|
|
2114
|
+
return promise.then(() => fn());
|
|
2115
|
+
}
|
|
2116
|
+
return fn();
|
|
2117
|
+
}
|
|
2118
|
+
/**
|
|
2119
|
+
*
|
|
2120
|
+
* @param {(Promise|undefined)} promise
|
|
2121
|
+
* @param {string} event
|
|
2122
|
+
* @return {(Promise|undefined)}
|
|
2123
|
+
* @private
|
|
2124
|
+
*/
|
|
2125
|
+
_chainOrCallHooks(promise, event) {
|
|
2126
|
+
let result = promise;
|
|
2127
|
+
const hooks = [];
|
|
2128
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2129
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2130
|
+
hooks.push({ hookedCommand, callback });
|
|
2131
|
+
});
|
|
2132
|
+
});
|
|
2133
|
+
if (event === "postAction") {
|
|
2134
|
+
hooks.reverse();
|
|
2135
|
+
}
|
|
2136
|
+
hooks.forEach((hookDetail) => {
|
|
2137
|
+
result = this._chainOrCall(result, () => {
|
|
2138
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2139
|
+
});
|
|
2140
|
+
});
|
|
2141
|
+
return result;
|
|
2142
|
+
}
|
|
2143
|
+
/**
|
|
2144
|
+
*
|
|
2145
|
+
* @param {(Promise|undefined)} promise
|
|
2146
|
+
* @param {Command} subCommand
|
|
2147
|
+
* @param {string} event
|
|
2148
|
+
* @return {(Promise|undefined)}
|
|
2149
|
+
* @private
|
|
2150
|
+
*/
|
|
2151
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2152
|
+
let result = promise;
|
|
2153
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2154
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2155
|
+
result = this._chainOrCall(result, () => {
|
|
2156
|
+
return hook(this, subCommand);
|
|
2157
|
+
});
|
|
2158
|
+
});
|
|
2159
|
+
}
|
|
2160
|
+
return result;
|
|
2161
|
+
}
|
|
2162
|
+
/**
|
|
2163
|
+
* Process arguments in context of this command.
|
|
2164
|
+
* Returns action result, in case it is a promise.
|
|
2165
|
+
*
|
|
2166
|
+
* @private
|
|
2167
|
+
*/
|
|
2168
|
+
_parseCommand(operands, unknown) {
|
|
2169
|
+
const parsed = this.parseOptions(unknown);
|
|
2170
|
+
this._parseOptionsEnv();
|
|
2171
|
+
this._parseOptionsImplied();
|
|
2172
|
+
operands = operands.concat(parsed.operands);
|
|
2173
|
+
unknown = parsed.unknown;
|
|
2174
|
+
this.args = operands.concat(unknown);
|
|
2175
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2176
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2177
|
+
}
|
|
2178
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2179
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2180
|
+
}
|
|
2181
|
+
if (this._defaultCommandName) {
|
|
2182
|
+
this._outputHelpIfRequested(unknown);
|
|
2183
|
+
return this._dispatchSubcommand(
|
|
2184
|
+
this._defaultCommandName,
|
|
2185
|
+
operands,
|
|
2186
|
+
unknown
|
|
2187
|
+
);
|
|
2188
|
+
}
|
|
2189
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2190
|
+
this.help({ error: true });
|
|
2191
|
+
}
|
|
2192
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2193
|
+
this._checkForMissingMandatoryOptions();
|
|
2194
|
+
this._checkForConflictingOptions();
|
|
2195
|
+
const checkForUnknownOptions = () => {
|
|
2196
|
+
if (parsed.unknown.length > 0) {
|
|
2197
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2198
|
+
}
|
|
2199
|
+
};
|
|
2200
|
+
const commandEvent = `command:${this.name()}`;
|
|
2201
|
+
if (this._actionHandler) {
|
|
2202
|
+
checkForUnknownOptions();
|
|
2203
|
+
this._processArguments();
|
|
2204
|
+
let promiseChain;
|
|
2205
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2206
|
+
promiseChain = this._chainOrCall(
|
|
2207
|
+
promiseChain,
|
|
2208
|
+
() => this._actionHandler(this.processedArgs)
|
|
2209
|
+
);
|
|
2210
|
+
if (this.parent) {
|
|
2211
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2212
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2213
|
+
});
|
|
2214
|
+
}
|
|
2215
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2216
|
+
return promiseChain;
|
|
2217
|
+
}
|
|
2218
|
+
if (this.parent && this.parent.listenerCount(commandEvent)) {
|
|
2219
|
+
checkForUnknownOptions();
|
|
2220
|
+
this._processArguments();
|
|
2221
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2222
|
+
} else if (operands.length) {
|
|
2223
|
+
if (this._findCommand("*")) {
|
|
2224
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2225
|
+
}
|
|
2226
|
+
if (this.listenerCount("command:*")) {
|
|
2227
|
+
this.emit("command:*", operands, unknown);
|
|
2228
|
+
} else if (this.commands.length) {
|
|
2229
|
+
this.unknownCommand();
|
|
2230
|
+
} else {
|
|
2231
|
+
checkForUnknownOptions();
|
|
2232
|
+
this._processArguments();
|
|
2233
|
+
}
|
|
2234
|
+
} else if (this.commands.length) {
|
|
2235
|
+
checkForUnknownOptions();
|
|
2236
|
+
this.help({ error: true });
|
|
2237
|
+
} else {
|
|
2238
|
+
checkForUnknownOptions();
|
|
2239
|
+
this._processArguments();
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
/**
|
|
2243
|
+
* Find matching command.
|
|
2244
|
+
*
|
|
2245
|
+
* @private
|
|
2246
|
+
* @return {Command | undefined}
|
|
2247
|
+
*/
|
|
2248
|
+
_findCommand(name) {
|
|
2249
|
+
if (!name) return void 0;
|
|
2250
|
+
return this.commands.find(
|
|
2251
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2252
|
+
);
|
|
2253
|
+
}
|
|
2254
|
+
/**
|
|
2255
|
+
* Return an option matching `arg` if any.
|
|
2256
|
+
*
|
|
2257
|
+
* @param {string} arg
|
|
2258
|
+
* @return {Option}
|
|
2259
|
+
* @package
|
|
2260
|
+
*/
|
|
2261
|
+
_findOption(arg) {
|
|
2262
|
+
return this.options.find((option) => option.is(arg));
|
|
2263
|
+
}
|
|
2264
|
+
/**
|
|
2265
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2266
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2267
|
+
*
|
|
2268
|
+
* @private
|
|
2269
|
+
*/
|
|
2270
|
+
_checkForMissingMandatoryOptions() {
|
|
2271
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2272
|
+
cmd.options.forEach((anOption) => {
|
|
2273
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2274
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2275
|
+
}
|
|
2276
|
+
});
|
|
2277
|
+
});
|
|
2278
|
+
}
|
|
2279
|
+
/**
|
|
2280
|
+
* Display an error message if conflicting options are used together in this.
|
|
2281
|
+
*
|
|
2282
|
+
* @private
|
|
2283
|
+
*/
|
|
2284
|
+
_checkForConflictingLocalOptions() {
|
|
2285
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2286
|
+
const optionKey = option.attributeName();
|
|
2287
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2288
|
+
return false;
|
|
2289
|
+
}
|
|
2290
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2291
|
+
});
|
|
2292
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2293
|
+
(option) => option.conflictsWith.length > 0
|
|
2294
|
+
);
|
|
2295
|
+
optionsWithConflicting.forEach((option) => {
|
|
2296
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2297
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2298
|
+
);
|
|
2299
|
+
if (conflictingAndDefined) {
|
|
2300
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2301
|
+
}
|
|
2302
|
+
});
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* Display an error message if conflicting options are used together.
|
|
2306
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2307
|
+
*
|
|
2308
|
+
* @private
|
|
2309
|
+
*/
|
|
2310
|
+
_checkForConflictingOptions() {
|
|
2311
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2312
|
+
cmd._checkForConflictingLocalOptions();
|
|
2313
|
+
});
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Parse options from `argv` removing known options,
|
|
2317
|
+
* and return argv split into operands and unknown arguments.
|
|
2318
|
+
*
|
|
2319
|
+
* Examples:
|
|
2320
|
+
*
|
|
2321
|
+
* argv => operands, unknown
|
|
2322
|
+
* --known kkk op => [op], []
|
|
2323
|
+
* op --known kkk => [op], []
|
|
2324
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2325
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2326
|
+
*
|
|
2327
|
+
* @param {string[]} argv
|
|
2328
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2329
|
+
*/
|
|
2330
|
+
parseOptions(argv) {
|
|
2331
|
+
const operands = [];
|
|
2332
|
+
const unknown = [];
|
|
2333
|
+
let dest = operands;
|
|
2334
|
+
const args = argv.slice();
|
|
2335
|
+
function maybeOption(arg) {
|
|
2336
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2337
|
+
}
|
|
2338
|
+
let activeVariadicOption = null;
|
|
2339
|
+
while (args.length) {
|
|
2340
|
+
const arg = args.shift();
|
|
2341
|
+
if (arg === "--") {
|
|
2342
|
+
if (dest === unknown) dest.push(arg);
|
|
2343
|
+
dest.push(...args);
|
|
2344
|
+
break;
|
|
2345
|
+
}
|
|
2346
|
+
if (activeVariadicOption && !maybeOption(arg)) {
|
|
2347
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2348
|
+
continue;
|
|
2349
|
+
}
|
|
2350
|
+
activeVariadicOption = null;
|
|
2351
|
+
if (maybeOption(arg)) {
|
|
2352
|
+
const option = this._findOption(arg);
|
|
2353
|
+
if (option) {
|
|
2354
|
+
if (option.required) {
|
|
2355
|
+
const value = args.shift();
|
|
2356
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2357
|
+
this.emit(`option:${option.name()}`, value);
|
|
2358
|
+
} else if (option.optional) {
|
|
2359
|
+
let value = null;
|
|
2360
|
+
if (args.length > 0 && !maybeOption(args[0])) {
|
|
2361
|
+
value = args.shift();
|
|
2362
|
+
}
|
|
2363
|
+
this.emit(`option:${option.name()}`, value);
|
|
2364
|
+
} else {
|
|
2365
|
+
this.emit(`option:${option.name()}`);
|
|
2366
|
+
}
|
|
2367
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2368
|
+
continue;
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2372
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2373
|
+
if (option) {
|
|
2374
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2375
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2376
|
+
} else {
|
|
2377
|
+
this.emit(`option:${option.name()}`);
|
|
2378
|
+
args.unshift(`-${arg.slice(2)}`);
|
|
2379
|
+
}
|
|
2380
|
+
continue;
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2384
|
+
const index = arg.indexOf("=");
|
|
2385
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2386
|
+
if (option && (option.required || option.optional)) {
|
|
2387
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2388
|
+
continue;
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
if (maybeOption(arg)) {
|
|
2392
|
+
dest = unknown;
|
|
2393
|
+
}
|
|
2394
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2395
|
+
if (this._findCommand(arg)) {
|
|
2396
|
+
operands.push(arg);
|
|
2397
|
+
if (args.length > 0) unknown.push(...args);
|
|
2398
|
+
break;
|
|
2399
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2400
|
+
operands.push(arg);
|
|
2401
|
+
if (args.length > 0) operands.push(...args);
|
|
2402
|
+
break;
|
|
2403
|
+
} else if (this._defaultCommandName) {
|
|
2404
|
+
unknown.push(arg);
|
|
2405
|
+
if (args.length > 0) unknown.push(...args);
|
|
2406
|
+
break;
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
if (this._passThroughOptions) {
|
|
2410
|
+
dest.push(arg);
|
|
2411
|
+
if (args.length > 0) dest.push(...args);
|
|
2412
|
+
break;
|
|
2413
|
+
}
|
|
2414
|
+
dest.push(arg);
|
|
2415
|
+
}
|
|
2416
|
+
return { operands, unknown };
|
|
2417
|
+
}
|
|
2418
|
+
/**
|
|
2419
|
+
* Return an object containing local option values as key-value pairs.
|
|
2420
|
+
*
|
|
2421
|
+
* @return {object}
|
|
2422
|
+
*/
|
|
2423
|
+
opts() {
|
|
2424
|
+
if (this._storeOptionsAsProperties) {
|
|
2425
|
+
const result = {};
|
|
2426
|
+
const len = this.options.length;
|
|
2427
|
+
for (let i = 0; i < len; i++) {
|
|
2428
|
+
const key = this.options[i].attributeName();
|
|
2429
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2430
|
+
}
|
|
2431
|
+
return result;
|
|
2432
|
+
}
|
|
2433
|
+
return this._optionValues;
|
|
2434
|
+
}
|
|
2435
|
+
/**
|
|
2436
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2437
|
+
*
|
|
2438
|
+
* @return {object}
|
|
2439
|
+
*/
|
|
2440
|
+
optsWithGlobals() {
|
|
2441
|
+
return this._getCommandAndAncestors().reduce(
|
|
2442
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2443
|
+
{}
|
|
2444
|
+
);
|
|
2445
|
+
}
|
|
2446
|
+
/**
|
|
2447
|
+
* Display error message and exit (or call exitOverride).
|
|
2448
|
+
*
|
|
2449
|
+
* @param {string} message
|
|
2450
|
+
* @param {object} [errorOptions]
|
|
2451
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2452
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2453
|
+
*/
|
|
2454
|
+
error(message, errorOptions) {
|
|
2455
|
+
this._outputConfiguration.outputError(
|
|
2456
|
+
`${message}
|
|
2457
|
+
`,
|
|
2458
|
+
this._outputConfiguration.writeErr
|
|
2459
|
+
);
|
|
2460
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2461
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2462
|
+
`);
|
|
2463
|
+
} else if (this._showHelpAfterError) {
|
|
2464
|
+
this._outputConfiguration.writeErr("\n");
|
|
2465
|
+
this.outputHelp({ error: true });
|
|
2466
|
+
}
|
|
2467
|
+
const config = errorOptions || {};
|
|
2468
|
+
const exitCode = config.exitCode || 1;
|
|
2469
|
+
const code = config.code || "commander.error";
|
|
2470
|
+
this._exit(exitCode, code, message);
|
|
2471
|
+
}
|
|
2472
|
+
/**
|
|
2473
|
+
* Apply any option related environment variables, if option does
|
|
2474
|
+
* not have a value from cli or client code.
|
|
2475
|
+
*
|
|
2476
|
+
* @private
|
|
2477
|
+
*/
|
|
2478
|
+
_parseOptionsEnv() {
|
|
2479
|
+
this.options.forEach((option) => {
|
|
2480
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2481
|
+
const optionKey = option.attributeName();
|
|
2482
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2483
|
+
this.getOptionValueSource(optionKey)
|
|
2484
|
+
)) {
|
|
2485
|
+
if (option.required || option.optional) {
|
|
2486
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2487
|
+
} else {
|
|
2488
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
});
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2496
|
+
*
|
|
2497
|
+
* @private
|
|
2498
|
+
*/
|
|
2499
|
+
_parseOptionsImplied() {
|
|
2500
|
+
const dualHelper = new DualOptions(this.options);
|
|
2501
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2502
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2503
|
+
};
|
|
2504
|
+
this.options.filter(
|
|
2505
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2506
|
+
this.getOptionValue(option.attributeName()),
|
|
2507
|
+
option
|
|
2508
|
+
)
|
|
2509
|
+
).forEach((option) => {
|
|
2510
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2511
|
+
this.setOptionValueWithSource(
|
|
2512
|
+
impliedKey,
|
|
2513
|
+
option.implied[impliedKey],
|
|
2514
|
+
"implied"
|
|
2515
|
+
);
|
|
2516
|
+
});
|
|
2517
|
+
});
|
|
2518
|
+
}
|
|
2519
|
+
/**
|
|
2520
|
+
* Argument `name` is missing.
|
|
2521
|
+
*
|
|
2522
|
+
* @param {string} name
|
|
2523
|
+
* @private
|
|
2524
|
+
*/
|
|
2525
|
+
missingArgument(name) {
|
|
2526
|
+
const message = `error: missing required argument '${name}'`;
|
|
2527
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2528
|
+
}
|
|
2529
|
+
/**
|
|
2530
|
+
* `Option` is missing an argument.
|
|
2531
|
+
*
|
|
2532
|
+
* @param {Option} option
|
|
2533
|
+
* @private
|
|
2534
|
+
*/
|
|
2535
|
+
optionMissingArgument(option) {
|
|
2536
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2537
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2538
|
+
}
|
|
2539
|
+
/**
|
|
2540
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2541
|
+
*
|
|
2542
|
+
* @param {Option} option
|
|
2543
|
+
* @private
|
|
2544
|
+
*/
|
|
2545
|
+
missingMandatoryOptionValue(option) {
|
|
2546
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2547
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* `Option` conflicts with another option.
|
|
2551
|
+
*
|
|
2552
|
+
* @param {Option} option
|
|
2553
|
+
* @param {Option} conflictingOption
|
|
2554
|
+
* @private
|
|
2555
|
+
*/
|
|
2556
|
+
_conflictingOption(option, conflictingOption) {
|
|
2557
|
+
const findBestOptionFromValue = (option2) => {
|
|
2558
|
+
const optionKey = option2.attributeName();
|
|
2559
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2560
|
+
const negativeOption = this.options.find(
|
|
2561
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2562
|
+
);
|
|
2563
|
+
const positiveOption = this.options.find(
|
|
2564
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2565
|
+
);
|
|
2566
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2567
|
+
return negativeOption;
|
|
2568
|
+
}
|
|
2569
|
+
return positiveOption || option2;
|
|
2570
|
+
};
|
|
2571
|
+
const getErrorMessage = (option2) => {
|
|
2572
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2573
|
+
const optionKey = bestOption.attributeName();
|
|
2574
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2575
|
+
if (source === "env") {
|
|
2576
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2577
|
+
}
|
|
2578
|
+
return `option '${bestOption.flags}'`;
|
|
2579
|
+
};
|
|
2580
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2581
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* Unknown option `flag`.
|
|
2585
|
+
*
|
|
2586
|
+
* @param {string} flag
|
|
2587
|
+
* @private
|
|
2588
|
+
*/
|
|
2589
|
+
unknownOption(flag) {
|
|
2590
|
+
if (this._allowUnknownOption) return;
|
|
2591
|
+
let suggestion = "";
|
|
2592
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2593
|
+
let candidateFlags = [];
|
|
2594
|
+
let command = this;
|
|
2595
|
+
do {
|
|
2596
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2597
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2598
|
+
command = command.parent;
|
|
2599
|
+
} while (command && !command._enablePositionalOptions);
|
|
2600
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2601
|
+
}
|
|
2602
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2603
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2604
|
+
}
|
|
2605
|
+
/**
|
|
2606
|
+
* Excess arguments, more than expected.
|
|
2607
|
+
*
|
|
2608
|
+
* @param {string[]} receivedArgs
|
|
2609
|
+
* @private
|
|
2610
|
+
*/
|
|
2611
|
+
_excessArguments(receivedArgs) {
|
|
2612
|
+
if (this._allowExcessArguments) return;
|
|
2613
|
+
const expected = this.registeredArguments.length;
|
|
2614
|
+
const s = expected === 1 ? "" : "s";
|
|
2615
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2616
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
2617
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2618
|
+
}
|
|
2619
|
+
/**
|
|
2620
|
+
* Unknown command.
|
|
2621
|
+
*
|
|
2622
|
+
* @private
|
|
2623
|
+
*/
|
|
2624
|
+
unknownCommand() {
|
|
2625
|
+
const unknownName = this.args[0];
|
|
2626
|
+
let suggestion = "";
|
|
2627
|
+
if (this._showSuggestionAfterError) {
|
|
2628
|
+
const candidateNames = [];
|
|
2629
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2630
|
+
candidateNames.push(command.name());
|
|
2631
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2632
|
+
});
|
|
2633
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2634
|
+
}
|
|
2635
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2636
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2637
|
+
}
|
|
2638
|
+
/**
|
|
2639
|
+
* Get or set the program version.
|
|
2640
|
+
*
|
|
2641
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2642
|
+
*
|
|
2643
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2644
|
+
*
|
|
2645
|
+
* @param {string} [str]
|
|
2646
|
+
* @param {string} [flags]
|
|
2647
|
+
* @param {string} [description]
|
|
2648
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2649
|
+
*/
|
|
2650
|
+
version(str, flags, description) {
|
|
2651
|
+
if (str === void 0) return this._version;
|
|
2652
|
+
this._version = str;
|
|
2653
|
+
flags = flags || "-V, --version";
|
|
2654
|
+
description = description || "output the version number";
|
|
2655
|
+
const versionOption = this.createOption(flags, description);
|
|
2656
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2657
|
+
this._registerOption(versionOption);
|
|
2658
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2659
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2660
|
+
`);
|
|
2661
|
+
this._exit(0, "commander.version", str);
|
|
2662
|
+
});
|
|
2663
|
+
return this;
|
|
2664
|
+
}
|
|
2665
|
+
/**
|
|
2666
|
+
* Set the description.
|
|
2667
|
+
*
|
|
2668
|
+
* @param {string} [str]
|
|
2669
|
+
* @param {object} [argsDescription]
|
|
2670
|
+
* @return {(string|Command)}
|
|
2671
|
+
*/
|
|
2672
|
+
description(str, argsDescription) {
|
|
2673
|
+
if (str === void 0 && argsDescription === void 0)
|
|
2674
|
+
return this._description;
|
|
2675
|
+
this._description = str;
|
|
2676
|
+
if (argsDescription) {
|
|
2677
|
+
this._argsDescription = argsDescription;
|
|
2678
|
+
}
|
|
2679
|
+
return this;
|
|
2680
|
+
}
|
|
2681
|
+
/**
|
|
2682
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2683
|
+
*
|
|
2684
|
+
* @param {string} [str]
|
|
2685
|
+
* @return {(string|Command)}
|
|
2686
|
+
*/
|
|
2687
|
+
summary(str) {
|
|
2688
|
+
if (str === void 0) return this._summary;
|
|
2689
|
+
this._summary = str;
|
|
2690
|
+
return this;
|
|
2691
|
+
}
|
|
2692
|
+
/**
|
|
2693
|
+
* Set an alias for the command.
|
|
2694
|
+
*
|
|
2695
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2696
|
+
*
|
|
2697
|
+
* @param {string} [alias]
|
|
2698
|
+
* @return {(string|Command)}
|
|
2699
|
+
*/
|
|
2700
|
+
alias(alias) {
|
|
2701
|
+
if (alias === void 0) return this._aliases[0];
|
|
2702
|
+
let command = this;
|
|
2703
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
2704
|
+
command = this.commands[this.commands.length - 1];
|
|
2705
|
+
}
|
|
2706
|
+
if (alias === command._name)
|
|
2707
|
+
throw new Error("Command alias can't be the same as its name");
|
|
2708
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2709
|
+
if (matchingCommand) {
|
|
2710
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2711
|
+
throw new Error(
|
|
2712
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
2713
|
+
);
|
|
2714
|
+
}
|
|
2715
|
+
command._aliases.push(alias);
|
|
2716
|
+
return this;
|
|
2717
|
+
}
|
|
2718
|
+
/**
|
|
2719
|
+
* Set aliases for the command.
|
|
2720
|
+
*
|
|
2721
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2722
|
+
*
|
|
2723
|
+
* @param {string[]} [aliases]
|
|
2724
|
+
* @return {(string[]|Command)}
|
|
2725
|
+
*/
|
|
2726
|
+
aliases(aliases) {
|
|
2727
|
+
if (aliases === void 0) return this._aliases;
|
|
2728
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2729
|
+
return this;
|
|
2730
|
+
}
|
|
2731
|
+
/**
|
|
2732
|
+
* Set / get the command usage `str`.
|
|
2733
|
+
*
|
|
2734
|
+
* @param {string} [str]
|
|
2735
|
+
* @return {(string|Command)}
|
|
2736
|
+
*/
|
|
2737
|
+
usage(str) {
|
|
2738
|
+
if (str === void 0) {
|
|
2739
|
+
if (this._usage) return this._usage;
|
|
2740
|
+
const args = this.registeredArguments.map((arg) => {
|
|
2741
|
+
return humanReadableArgName(arg);
|
|
2742
|
+
});
|
|
2743
|
+
return [].concat(
|
|
2744
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
2745
|
+
this.commands.length ? "[command]" : [],
|
|
2746
|
+
this.registeredArguments.length ? args : []
|
|
2747
|
+
).join(" ");
|
|
2748
|
+
}
|
|
2749
|
+
this._usage = str;
|
|
2750
|
+
return this;
|
|
2751
|
+
}
|
|
2752
|
+
/**
|
|
2753
|
+
* Get or set the name of the command.
|
|
2754
|
+
*
|
|
2755
|
+
* @param {string} [str]
|
|
2756
|
+
* @return {(string|Command)}
|
|
2757
|
+
*/
|
|
2758
|
+
name(str) {
|
|
2759
|
+
if (str === void 0) return this._name;
|
|
2760
|
+
this._name = str;
|
|
2761
|
+
return this;
|
|
2762
|
+
}
|
|
2763
|
+
/**
|
|
2764
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
2765
|
+
* or require.main.filename, or __filename.
|
|
2766
|
+
*
|
|
2767
|
+
* (Used internally and public although not documented in README.)
|
|
2768
|
+
*
|
|
2769
|
+
* @example
|
|
2770
|
+
* program.nameFromFilename(require.main.filename);
|
|
2771
|
+
*
|
|
2772
|
+
* @param {string} filename
|
|
2773
|
+
* @return {Command}
|
|
2774
|
+
*/
|
|
2775
|
+
nameFromFilename(filename) {
|
|
2776
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
2777
|
+
return this;
|
|
2778
|
+
}
|
|
2779
|
+
/**
|
|
2780
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
2781
|
+
*
|
|
2782
|
+
* @example
|
|
2783
|
+
* program.executableDir(__dirname);
|
|
2784
|
+
* // or
|
|
2785
|
+
* program.executableDir('subcommands');
|
|
2786
|
+
*
|
|
2787
|
+
* @param {string} [path]
|
|
2788
|
+
* @return {(string|null|Command)}
|
|
2789
|
+
*/
|
|
2790
|
+
executableDir(path2) {
|
|
2791
|
+
if (path2 === void 0) return this._executableDir;
|
|
2792
|
+
this._executableDir = path2;
|
|
2793
|
+
return this;
|
|
2794
|
+
}
|
|
2795
|
+
/**
|
|
2796
|
+
* Return program help documentation.
|
|
2797
|
+
*
|
|
2798
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
2799
|
+
* @return {string}
|
|
2800
|
+
*/
|
|
2801
|
+
helpInformation(contextOptions) {
|
|
2802
|
+
const helper = this.createHelp();
|
|
2803
|
+
if (helper.helpWidth === void 0) {
|
|
2804
|
+
helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
|
|
2805
|
+
}
|
|
2806
|
+
return helper.formatHelp(this, helper);
|
|
2807
|
+
}
|
|
2808
|
+
/**
|
|
2809
|
+
* @private
|
|
2810
|
+
*/
|
|
2811
|
+
_getHelpContext(contextOptions) {
|
|
2812
|
+
contextOptions = contextOptions || {};
|
|
2813
|
+
const context = { error: !!contextOptions.error };
|
|
2814
|
+
let write;
|
|
2815
|
+
if (context.error) {
|
|
2816
|
+
write = (arg) => this._outputConfiguration.writeErr(arg);
|
|
2817
|
+
} else {
|
|
2818
|
+
write = (arg) => this._outputConfiguration.writeOut(arg);
|
|
2819
|
+
}
|
|
2820
|
+
context.write = contextOptions.write || write;
|
|
2821
|
+
context.command = this;
|
|
2822
|
+
return context;
|
|
2823
|
+
}
|
|
2824
|
+
/**
|
|
2825
|
+
* Output help information for this command.
|
|
2826
|
+
*
|
|
2827
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2828
|
+
*
|
|
2829
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2830
|
+
*/
|
|
2831
|
+
outputHelp(contextOptions) {
|
|
2832
|
+
let deprecatedCallback;
|
|
2833
|
+
if (typeof contextOptions === "function") {
|
|
2834
|
+
deprecatedCallback = contextOptions;
|
|
2835
|
+
contextOptions = void 0;
|
|
2836
|
+
}
|
|
2837
|
+
const context = this._getHelpContext(contextOptions);
|
|
2838
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
|
|
2839
|
+
this.emit("beforeHelp", context);
|
|
2840
|
+
let helpInformation = this.helpInformation(context);
|
|
2841
|
+
if (deprecatedCallback) {
|
|
2842
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
2843
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
2844
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
context.write(helpInformation);
|
|
2848
|
+
if (this._getHelpOption()?.long) {
|
|
2849
|
+
this.emit(this._getHelpOption().long);
|
|
2850
|
+
}
|
|
2851
|
+
this.emit("afterHelp", context);
|
|
2852
|
+
this._getCommandAndAncestors().forEach(
|
|
2853
|
+
(command) => command.emit("afterAllHelp", context)
|
|
2854
|
+
);
|
|
2855
|
+
}
|
|
2856
|
+
/**
|
|
2857
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
2858
|
+
* Pass in false to disable the built-in help option.
|
|
2859
|
+
*
|
|
2860
|
+
* @example
|
|
2861
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
2862
|
+
* program.helpOption(false); // disable
|
|
2863
|
+
*
|
|
2864
|
+
* @param {(string | boolean)} flags
|
|
2865
|
+
* @param {string} [description]
|
|
2866
|
+
* @return {Command} `this` command for chaining
|
|
2867
|
+
*/
|
|
2868
|
+
helpOption(flags, description) {
|
|
2869
|
+
if (typeof flags === "boolean") {
|
|
2870
|
+
if (flags) {
|
|
2871
|
+
this._helpOption = this._helpOption ?? void 0;
|
|
2872
|
+
} else {
|
|
2873
|
+
this._helpOption = null;
|
|
2874
|
+
}
|
|
2875
|
+
return this;
|
|
2876
|
+
}
|
|
2877
|
+
flags = flags ?? "-h, --help";
|
|
2878
|
+
description = description ?? "display help for command";
|
|
2879
|
+
this._helpOption = this.createOption(flags, description);
|
|
2880
|
+
return this;
|
|
2881
|
+
}
|
|
2882
|
+
/**
|
|
2883
|
+
* Lazy create help option.
|
|
2884
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
2885
|
+
*
|
|
2886
|
+
* @returns {(Option | null)} the help option
|
|
2887
|
+
* @package
|
|
2888
|
+
*/
|
|
2889
|
+
_getHelpOption() {
|
|
2890
|
+
if (this._helpOption === void 0) {
|
|
2891
|
+
this.helpOption(void 0, void 0);
|
|
2892
|
+
}
|
|
2893
|
+
return this._helpOption;
|
|
2894
|
+
}
|
|
2895
|
+
/**
|
|
2896
|
+
* Supply your own option to use for the built-in help option.
|
|
2897
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
2898
|
+
*
|
|
2899
|
+
* @param {Option} option
|
|
2900
|
+
* @return {Command} `this` command for chaining
|
|
2901
|
+
*/
|
|
2902
|
+
addHelpOption(option) {
|
|
2903
|
+
this._helpOption = option;
|
|
2904
|
+
return this;
|
|
2905
|
+
}
|
|
2906
|
+
/**
|
|
2907
|
+
* Output help information and exit.
|
|
2908
|
+
*
|
|
2909
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2910
|
+
*
|
|
2911
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2912
|
+
*/
|
|
2913
|
+
help(contextOptions) {
|
|
2914
|
+
this.outputHelp(contextOptions);
|
|
2915
|
+
let exitCode = process2.exitCode || 0;
|
|
2916
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
2917
|
+
exitCode = 1;
|
|
2918
|
+
}
|
|
2919
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
2920
|
+
}
|
|
2921
|
+
/**
|
|
2922
|
+
* Add additional text to be displayed with the built-in help.
|
|
2923
|
+
*
|
|
2924
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
2925
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
2926
|
+
*
|
|
2927
|
+
* @param {string} position - before or after built-in help
|
|
2928
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
2929
|
+
* @return {Command} `this` command for chaining
|
|
2930
|
+
*/
|
|
2931
|
+
addHelpText(position, text) {
|
|
2932
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
2933
|
+
if (!allowedValues.includes(position)) {
|
|
2934
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
2935
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2936
|
+
}
|
|
2937
|
+
const helpEvent = `${position}Help`;
|
|
2938
|
+
this.on(helpEvent, (context) => {
|
|
2939
|
+
let helpStr;
|
|
2940
|
+
if (typeof text === "function") {
|
|
2941
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
2942
|
+
} else {
|
|
2943
|
+
helpStr = text;
|
|
2944
|
+
}
|
|
2945
|
+
if (helpStr) {
|
|
2946
|
+
context.write(`${helpStr}
|
|
2947
|
+
`);
|
|
2948
|
+
}
|
|
2949
|
+
});
|
|
2950
|
+
return this;
|
|
2951
|
+
}
|
|
2952
|
+
/**
|
|
2953
|
+
* Output help information if help flags specified
|
|
2954
|
+
*
|
|
2955
|
+
* @param {Array} args - array of options to search for help flags
|
|
2956
|
+
* @private
|
|
2957
|
+
*/
|
|
2958
|
+
_outputHelpIfRequested(args) {
|
|
2959
|
+
const helpOption = this._getHelpOption();
|
|
2960
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
2961
|
+
if (helpRequested) {
|
|
2962
|
+
this.outputHelp();
|
|
2963
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
};
|
|
2967
|
+
function incrementNodeInspectorPort(args) {
|
|
2968
|
+
return args.map((arg) => {
|
|
2969
|
+
if (!arg.startsWith("--inspect")) {
|
|
2970
|
+
return arg;
|
|
2971
|
+
}
|
|
2972
|
+
let debugOption;
|
|
2973
|
+
let debugHost = "127.0.0.1";
|
|
2974
|
+
let debugPort = "9229";
|
|
2975
|
+
let match;
|
|
2976
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
2977
|
+
debugOption = match[1];
|
|
2978
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2979
|
+
debugOption = match[1];
|
|
2980
|
+
if (/^\d+$/.test(match[3])) {
|
|
2981
|
+
debugPort = match[3];
|
|
2982
|
+
} else {
|
|
2983
|
+
debugHost = match[3];
|
|
2984
|
+
}
|
|
2985
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2986
|
+
debugOption = match[1];
|
|
2987
|
+
debugHost = match[3];
|
|
2988
|
+
debugPort = match[4];
|
|
2989
|
+
}
|
|
2990
|
+
if (debugOption && debugPort !== "0") {
|
|
2991
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2992
|
+
}
|
|
2993
|
+
return arg;
|
|
2994
|
+
});
|
|
2995
|
+
}
|
|
2996
|
+
exports2.Command = Command2;
|
|
2997
|
+
}
|
|
2998
|
+
});
|
|
2999
|
+
|
|
3000
|
+
// node_modules/commander/index.js
|
|
3001
|
+
var require_commander = __commonJS({
|
|
3002
|
+
"node_modules/commander/index.js"(exports2) {
|
|
3003
|
+
var { Argument: Argument2 } = require_argument();
|
|
3004
|
+
var { Command: Command2 } = require_command();
|
|
3005
|
+
var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
3006
|
+
var { Help: Help2 } = require_help();
|
|
3007
|
+
var { Option: Option2 } = require_option();
|
|
3008
|
+
exports2.program = new Command2();
|
|
3009
|
+
exports2.createCommand = (name) => new Command2(name);
|
|
3010
|
+
exports2.createOption = (flags, description) => new Option2(flags, description);
|
|
3011
|
+
exports2.createArgument = (name, description) => new Argument2(name, description);
|
|
3012
|
+
exports2.Command = Command2;
|
|
3013
|
+
exports2.Option = Option2;
|
|
3014
|
+
exports2.Argument = Argument2;
|
|
3015
|
+
exports2.Help = Help2;
|
|
3016
|
+
exports2.CommanderError = CommanderError2;
|
|
3017
|
+
exports2.InvalidArgumentError = InvalidArgumentError2;
|
|
3018
|
+
exports2.InvalidOptionArgumentError = InvalidArgumentError2;
|
|
3019
|
+
}
|
|
3020
|
+
});
|
|
3021
|
+
|
|
3022
|
+
// node_modules/commander/esm.mjs
|
|
3023
|
+
var import_index = __toESM(require_commander(), 1);
|
|
3024
|
+
var {
|
|
3025
|
+
program,
|
|
3026
|
+
createCommand,
|
|
3027
|
+
createArgument,
|
|
3028
|
+
createOption,
|
|
3029
|
+
CommanderError,
|
|
3030
|
+
InvalidArgumentError,
|
|
3031
|
+
InvalidOptionArgumentError,
|
|
3032
|
+
// deprecated old name
|
|
3033
|
+
Command,
|
|
3034
|
+
Argument,
|
|
3035
|
+
Option,
|
|
3036
|
+
Help
|
|
3037
|
+
} = import_index.default;
|
|
3038
|
+
|
|
3039
|
+
// src/index.ts
|
|
3040
|
+
var import_promises = require("node:fs/promises");
|
|
3041
|
+
var import_node_fs2 = require("node:fs");
|
|
3042
|
+
var import_node_crypto = require("node:crypto");
|
|
3043
|
+
|
|
3044
|
+
// src/rules-sync.ts
|
|
3045
|
+
function normalizeEol(s) {
|
|
3046
|
+
return s.replace(/\r\n/g, "\n");
|
|
3047
|
+
}
|
|
3048
|
+
function needsUpdate(source, current) {
|
|
3049
|
+
if (current === null) return true;
|
|
3050
|
+
return normalizeEol(source) !== normalizeEol(current);
|
|
3051
|
+
}
|
|
3052
|
+
function isRulesSource(orgRulesSource) {
|
|
3053
|
+
return orgRulesSource === "self";
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
// src/saga-capture.ts
|
|
3057
|
+
function parseHookInput(stdin) {
|
|
3058
|
+
try {
|
|
3059
|
+
const o = JSON.parse(stdin || "{}");
|
|
3060
|
+
return o && typeof o === "object" ? o : {};
|
|
3061
|
+
} catch {
|
|
3062
|
+
return {};
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
|
|
3066
|
+
// src/index.ts
|
|
3067
|
+
var import_node_child_process3 = require("node:child_process");
|
|
3068
|
+
var import_node_util2 = require("node:util");
|
|
3069
|
+
var import_node_path2 = require("node:path");
|
|
3070
|
+
|
|
3071
|
+
// src/saga-head-maintainer.ts
|
|
3072
|
+
var import_node_child_process = require("node:child_process");
|
|
3073
|
+
var import_node_fs = require("node:fs");
|
|
3074
|
+
var import_node_path = require("node:path");
|
|
3075
|
+
var HEAD_MIN_INTERVAL_MS = 5 * 60 * 1e3;
|
|
3076
|
+
var HEAD_ENGINE_TIMEOUT_MS = 15e3;
|
|
3077
|
+
function resolveEngine(platform, custom) {
|
|
3078
|
+
if (custom) return { cmd: custom, args: [], shell: true };
|
|
3079
|
+
return { cmd: "claude", args: ["-p"], shell: platform === "win32" };
|
|
3080
|
+
}
|
|
3081
|
+
function headTsPath(key) {
|
|
3082
|
+
const safe = (s) => s.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
3083
|
+
return `.mmi/head-ts/${safe(key.project)}/${safe(key.branch)}/${safe(key.sessionId)}`;
|
|
3084
|
+
}
|
|
3085
|
+
function headGateDue(path, now = Date.now()) {
|
|
3086
|
+
try {
|
|
3087
|
+
const last = Number((0, import_node_fs.readFileSync)(path, "utf8").trim()) || 0;
|
|
3088
|
+
return now - last >= HEAD_MIN_INTERVAL_MS;
|
|
3089
|
+
} catch {
|
|
3090
|
+
return true;
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
function markHeadRun(path, now = Date.now()) {
|
|
3094
|
+
try {
|
|
3095
|
+
(0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(path), { recursive: true });
|
|
3096
|
+
(0, import_node_fs.writeFileSync)(path, String(now), "utf8");
|
|
3097
|
+
} catch {
|
|
3098
|
+
}
|
|
3099
|
+
}
|
|
3100
|
+
function headPrompt(state) {
|
|
3101
|
+
return [
|
|
3102
|
+
"You maintain two durable slots of a work-session: GOAL (the current objective) and PINNED (things",
|
|
3103
|
+
"worth remembering). Given the CURRENT HEAD and the recent TRANSCRIPT + DECISIONS, return an updated",
|
|
3104
|
+
"GOAL and PINNED only. Keep them tight and concrete; keep anything the user pinned; never invent;",
|
|
3105
|
+
"preserve Turkish characters (\xE7 \u011F \u0131 \u0130 \xF6 \u015F \xFC) exactly. Do NOT manage next or the checklist \u2014 the note",
|
|
3106
|
+
"path owns those. Never restate an unverified artifact-claim (a named file, PR, flag, or board state)",
|
|
3107
|
+
"as settled fact \u2014 keep it as the belief it was recorded as.",
|
|
3108
|
+
'Output ONLY a JSON object: {"goal":string,"pinned":[string]}.',
|
|
3109
|
+
"",
|
|
3110
|
+
"CURRENT HEAD:",
|
|
3111
|
+
JSON.stringify(state.head ?? {}, null, 2),
|
|
3112
|
+
"",
|
|
3113
|
+
"RECENT TRANSCRIPT (oldest to newest):",
|
|
3114
|
+
JSON.stringify(state.actionLog ?? []),
|
|
3115
|
+
"",
|
|
3116
|
+
"DECISIONS:",
|
|
3117
|
+
(state.decisions ?? []).map((d) => `- ${d}`).join("\n") || "(none)"
|
|
3118
|
+
].join("\n");
|
|
3119
|
+
}
|
|
3120
|
+
function parseHeadUpdate(raw) {
|
|
3121
|
+
const m = raw.match(/\{[\s\S]*\}/);
|
|
3122
|
+
if (!m) return null;
|
|
3123
|
+
let obj;
|
|
3124
|
+
try {
|
|
3125
|
+
obj = JSON.parse(m[0]);
|
|
3126
|
+
} catch {
|
|
3127
|
+
return null;
|
|
3128
|
+
}
|
|
3129
|
+
if (!obj || typeof obj !== "object") return null;
|
|
3130
|
+
const u = {};
|
|
3131
|
+
if (typeof obj.goal === "string") u.goal = obj.goal;
|
|
3132
|
+
if (Array.isArray(obj.pinned)) u.pinned = obj.pinned.filter((x) => typeof x === "string");
|
|
3133
|
+
return Object.keys(u).length ? u : null;
|
|
3134
|
+
}
|
|
3135
|
+
async function runHeadEngine(prompt, timeoutMs = HEAD_ENGINE_TIMEOUT_MS) {
|
|
3136
|
+
const { cmd, args, shell } = resolveEngine(process.platform, process.env.SAGA_HEAD_ENGINE);
|
|
3137
|
+
return await new Promise((resolve) => {
|
|
3138
|
+
let child;
|
|
3139
|
+
try {
|
|
3140
|
+
child = (0, import_node_child_process.spawn)(cmd, args, { shell, windowsHide: true });
|
|
3141
|
+
} catch {
|
|
3142
|
+
return resolve("");
|
|
3143
|
+
}
|
|
3144
|
+
let out = "";
|
|
3145
|
+
let done = false;
|
|
3146
|
+
const finish = (v) => {
|
|
3147
|
+
if (done) return;
|
|
3148
|
+
done = true;
|
|
3149
|
+
clearTimeout(timer);
|
|
3150
|
+
resolve(v);
|
|
3151
|
+
};
|
|
3152
|
+
const timer = setTimeout(() => {
|
|
3153
|
+
try {
|
|
3154
|
+
child.kill();
|
|
3155
|
+
} catch {
|
|
3156
|
+
}
|
|
3157
|
+
finish("");
|
|
3158
|
+
}, timeoutMs);
|
|
3159
|
+
child.stdout?.on("data", (d) => out += d.toString());
|
|
3160
|
+
child.on("error", () => finish(""));
|
|
3161
|
+
child.on("close", () => finish(out));
|
|
3162
|
+
try {
|
|
3163
|
+
child.stdin?.write(prompt);
|
|
3164
|
+
child.stdin?.end();
|
|
3165
|
+
} catch {
|
|
3166
|
+
finish("");
|
|
3167
|
+
}
|
|
3168
|
+
});
|
|
3169
|
+
}
|
|
3170
|
+
|
|
3171
|
+
// src/gh-create.ts
|
|
3172
|
+
var ISSUE_TYPES = ["bug", "feature", "task"];
|
|
3173
|
+
var PRIORITIES = ["high", "medium", "low"];
|
|
3174
|
+
function parseCreatedUrl(stdout) {
|
|
3175
|
+
const re = /https:\/\/github\.com\/[^\s]+\/(?:issues|pull)\/(\d+)/g;
|
|
3176
|
+
let match;
|
|
3177
|
+
let last;
|
|
3178
|
+
while ((match = re.exec(stdout)) !== null) {
|
|
3179
|
+
last = { number: Number(match[1]), url: match[0] };
|
|
3180
|
+
}
|
|
3181
|
+
if (!last) throw new Error(`could not find a github issue/PR URL in gh output:
|
|
3182
|
+
${stdout.trim() || "(empty)"}`);
|
|
3183
|
+
return last;
|
|
3184
|
+
}
|
|
3185
|
+
function buildIssueArgs({ type, title, body, priority, repo }) {
|
|
3186
|
+
if (!ISSUE_TYPES.includes(type)) throw new Error(`unknown issue type "${type}" \u2014 expected one of: ${ISSUE_TYPES.join(", ")}`);
|
|
3187
|
+
if (!PRIORITIES.includes(priority)) {
|
|
3188
|
+
throw new Error(`unknown priority "${priority}" \u2014 expected one of: ${PRIORITIES.join(", ")}`);
|
|
3189
|
+
}
|
|
3190
|
+
const args = ["issue", "create"];
|
|
3191
|
+
if (repo) args.push("--repo", repo);
|
|
3192
|
+
args.push("--title", title, "--body", body, "--label", type);
|
|
3193
|
+
args.push("--label", `priority:${priority}`);
|
|
3194
|
+
return args;
|
|
3195
|
+
}
|
|
3196
|
+
function buildPrArgs({ title, body, base, head, repo }) {
|
|
3197
|
+
const args = ["pr", "create"];
|
|
3198
|
+
if (repo) args.push("--repo", repo);
|
|
3199
|
+
args.push("--title", title, "--body", body);
|
|
3200
|
+
if (base) args.push("--base", base);
|
|
3201
|
+
if (head) args.push("--head", head);
|
|
3202
|
+
return args;
|
|
3203
|
+
}
|
|
3204
|
+
|
|
3205
|
+
// src/saga-session.ts
|
|
3206
|
+
function resolveSession(d) {
|
|
3207
|
+
const harness = d.env.CLAUDE_SESSION_ID?.trim();
|
|
3208
|
+
if (harness) return { id: harness, source: "harness" };
|
|
3209
|
+
const override = d.env.MMI_SAGA_SESSION_ID?.trim();
|
|
3210
|
+
if (override) return { id: override, source: "env" };
|
|
3211
|
+
const persisted = d.readPersisted()?.trim();
|
|
3212
|
+
if (persisted) return { id: persisted, source: "persisted" };
|
|
3213
|
+
const id = `${d.now().toISOString().replace(/[:.]/g, "-")}-${d.rand()}`;
|
|
3214
|
+
d.writePersisted(id);
|
|
3215
|
+
return { id, source: "generated" };
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
// src/saga-health.ts
|
|
3219
|
+
function buildHealth(i) {
|
|
3220
|
+
const problems = [];
|
|
3221
|
+
if (!i.sagaApiUrl) problems.push("sagaApiUrl not configured in .mmi/config.json");
|
|
3222
|
+
if (!i.identity) problems.push("no GitHub identity (gh auth token / GH_TOKEN)");
|
|
3223
|
+
if (!i.reachable) problems.push("saga backend unreachable");
|
|
3224
|
+
if (!i.key.sessionId || i.key.sessionId === "-") problems.push("unsafe session id");
|
|
3225
|
+
const safeToWrite = problems.length === 0;
|
|
3226
|
+
return {
|
|
3227
|
+
ok: safeToWrite,
|
|
3228
|
+
safeToWrite,
|
|
3229
|
+
identity: i.identity,
|
|
3230
|
+
reachable: i.reachable,
|
|
3231
|
+
sagaApiUrl: i.sagaApiUrl,
|
|
3232
|
+
key: i.key,
|
|
3233
|
+
source: i.source,
|
|
3234
|
+
problems
|
|
3235
|
+
};
|
|
3236
|
+
}
|
|
3237
|
+
function healthBanner(report) {
|
|
3238
|
+
if (report.ok) return null;
|
|
3239
|
+
const summary = report.problems.slice(0, 2).join("; ") || "unknown saga health gap";
|
|
3240
|
+
const suffix = report.problems.length > 2 ? ` (+${report.problems.length - 2} more)` : "";
|
|
3241
|
+
return `saga health: CHECK - ${summary}${suffix}`;
|
|
3242
|
+
}
|
|
3243
|
+
|
|
3244
|
+
// src/saga-note.ts
|
|
3245
|
+
function buildNoteCapture(summary, o, id, evidence) {
|
|
3246
|
+
const queueOp = o.queueAdd ? { op: "add", text: o.queueAdd } : o.queueDone != null ? { op: "done", index: Number(o.queueDone) } : void 0;
|
|
3247
|
+
const state = o.diagnostic ? "diagnostic" : o.verified ? "verified" : "asserted";
|
|
3248
|
+
const source = o.diagnostic ? "probe" : "note";
|
|
3249
|
+
const anchor = {};
|
|
3250
|
+
if (evidence.sha) anchor.sha = evidence.sha;
|
|
3251
|
+
if (evidence.branch) anchor.branch = evidence.branch;
|
|
3252
|
+
if (evidence.pr) anchor.pr = evidence.pr;
|
|
3253
|
+
if (evidence.file) anchor.file = evidence.file;
|
|
3254
|
+
return {
|
|
3255
|
+
event: "note",
|
|
3256
|
+
id,
|
|
3257
|
+
summary,
|
|
3258
|
+
next: o.next,
|
|
3259
|
+
decision: o.decision,
|
|
3260
|
+
queueOp,
|
|
3261
|
+
state,
|
|
3262
|
+
source,
|
|
3263
|
+
evidence: Object.keys(anchor).length ? anchor : void 0,
|
|
3264
|
+
surface: process.env.MMI_AGENT_SURFACE || "claude"
|
|
3265
|
+
};
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
// src/version-lag.ts
|
|
3269
|
+
var VERSION_LABEL = "installed plugin/adapter cache freshness";
|
|
3270
|
+
var VERSION_FIX = "refresh/update the MMI plugin, or run the repo-local CLI: node cli/dist/index.cjs doctor --json";
|
|
3271
|
+
function parseVersion(v) {
|
|
3272
|
+
return v.replace(/^v/, "").split(/[.-]/).slice(0, 3).map((part) => {
|
|
3273
|
+
const n = Number.parseInt(part, 10);
|
|
3274
|
+
return Number.isFinite(n) ? n : 0;
|
|
3275
|
+
});
|
|
3276
|
+
}
|
|
3277
|
+
function compareVersions(a, b) {
|
|
3278
|
+
const left = parseVersion(a);
|
|
3279
|
+
const right = parseVersion(b);
|
|
3280
|
+
for (let i = 0; i < 3; i++) {
|
|
3281
|
+
const delta = (left[i] ?? 0) - (right[i] ?? 0);
|
|
3282
|
+
if (delta !== 0) return delta;
|
|
3283
|
+
}
|
|
3284
|
+
return 0;
|
|
3285
|
+
}
|
|
3286
|
+
function buildVersionLagReport(input) {
|
|
3287
|
+
if (input.releasedVersion && compareVersions(input.currentVersion, input.releasedVersion) < 0) {
|
|
3288
|
+
return {
|
|
3289
|
+
ok: false,
|
|
3290
|
+
label: VERSION_LABEL,
|
|
3291
|
+
fix: VERSION_FIX,
|
|
3292
|
+
currentVersion: input.currentVersion,
|
|
3293
|
+
repoVersion: input.repoVersion,
|
|
3294
|
+
releasedVersion: input.releasedVersion,
|
|
3295
|
+
staleAgainst: "released"
|
|
3296
|
+
};
|
|
3297
|
+
}
|
|
3298
|
+
if (input.repoVersion && compareVersions(input.currentVersion, input.repoVersion) < 0) {
|
|
3299
|
+
return {
|
|
3300
|
+
ok: false,
|
|
3301
|
+
label: VERSION_LABEL,
|
|
3302
|
+
fix: VERSION_FIX,
|
|
3303
|
+
currentVersion: input.currentVersion,
|
|
3304
|
+
repoVersion: input.repoVersion,
|
|
3305
|
+
releasedVersion: input.releasedVersion,
|
|
3306
|
+
staleAgainst: "repo"
|
|
3307
|
+
};
|
|
3308
|
+
}
|
|
3309
|
+
return {
|
|
3310
|
+
ok: true,
|
|
3311
|
+
label: VERSION_LABEL,
|
|
3312
|
+
fix: VERSION_FIX,
|
|
3313
|
+
currentVersion: input.currentVersion,
|
|
3314
|
+
repoVersion: input.repoVersion,
|
|
3315
|
+
releasedVersion: input.releasedVersion
|
|
3316
|
+
};
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
// src/issue-related.ts
|
|
3320
|
+
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
3321
|
+
"a",
|
|
3322
|
+
"an",
|
|
3323
|
+
"and",
|
|
3324
|
+
"are",
|
|
3325
|
+
"as",
|
|
3326
|
+
"be",
|
|
3327
|
+
"for",
|
|
3328
|
+
"from",
|
|
3329
|
+
"in",
|
|
3330
|
+
"is",
|
|
3331
|
+
"it",
|
|
3332
|
+
"of",
|
|
3333
|
+
"on",
|
|
3334
|
+
"or",
|
|
3335
|
+
"the",
|
|
3336
|
+
"to",
|
|
3337
|
+
"with"
|
|
3338
|
+
]);
|
|
3339
|
+
function tokens(text) {
|
|
3340
|
+
return new Set(
|
|
3341
|
+
text.toLowerCase().replace(/[^a-z0-9#]+/g, " ").split(/\s+/).filter((t) => t.length >= 3 && !STOPWORDS.has(t))
|
|
3342
|
+
);
|
|
3343
|
+
}
|
|
3344
|
+
function jaccard(a, b) {
|
|
3345
|
+
if (!a.size || !b.size) return 0;
|
|
3346
|
+
let intersection = 0;
|
|
3347
|
+
for (const t of a) if (b.has(t)) intersection++;
|
|
3348
|
+
return intersection / (a.size + b.size - intersection);
|
|
3349
|
+
}
|
|
3350
|
+
function scoreRelatedIssue(source, candidate) {
|
|
3351
|
+
const sourceTitle = tokens(source.title);
|
|
3352
|
+
const candidateTitle = tokens(candidate.title);
|
|
3353
|
+
const sourceAll = tokens(`${source.title}
|
|
3354
|
+
${source.body}`);
|
|
3355
|
+
const candidateAll = tokens(`${candidate.title}
|
|
3356
|
+
${candidate.body ?? ""}`);
|
|
3357
|
+
return Number((jaccard(sourceTitle, candidateTitle) * 0.65 + jaccard(sourceAll, candidateAll) * 0.35).toFixed(3));
|
|
3358
|
+
}
|
|
3359
|
+
function findRelatedIssues(source, issues, highConfidence = 0.35) {
|
|
3360
|
+
return issues.filter((issue2) => issue2.number !== source.number).map((issue2) => ({ ...issue2, score: scoreRelatedIssue(source, issue2) })).filter((issue2) => issue2.score >= highConfidence).sort((a, b) => b.score - a.score || a.number - b.number).slice(0, 5);
|
|
3361
|
+
}
|
|
3362
|
+
function relatedMarker(issueNumber) {
|
|
3363
|
+
return `<!-- mmi-related:${issueNumber} -->`;
|
|
3364
|
+
}
|
|
3365
|
+
function buildRelatedComment(issueNumber, candidates) {
|
|
3366
|
+
const lines = candidates.map((c) => `- #${c.number} (${c.score.toFixed(3)}) ${c.title}`);
|
|
3367
|
+
return `${relatedMarker(issueNumber)}
|
|
3368
|
+
Related work discovered by mmi-cli:
|
|
3369
|
+
|
|
3370
|
+
${lines.join("\n")}`;
|
|
3371
|
+
}
|
|
3372
|
+
|
|
3373
|
+
// src/board.ts
|
|
3374
|
+
var import_node_child_process2 = require("node:child_process");
|
|
3375
|
+
var import_node_util = require("node:util");
|
|
3376
|
+
var execFileP = (0, import_node_util.promisify)(import_node_child_process2.execFile);
|
|
3377
|
+
var BOARD_STATUSES = ["Todo", "In Progress", "In Review", "Done"];
|
|
3378
|
+
var ACTIVE_STATUSES = /* @__PURE__ */ new Set(["Todo", "In Progress", "In Review"]);
|
|
3379
|
+
var STATUS_ORDER = new Map(BOARD_STATUSES.map((s, i) => [s, i]));
|
|
3380
|
+
var TYPE_LABELS = ["bug", "feature", "task"];
|
|
3381
|
+
var defaultGh = async (args) => {
|
|
3382
|
+
const { stdout, stderr } = await execFileP("gh", args, { maxBuffer: 10 * 1024 * 1024 });
|
|
3383
|
+
return { stdout: String(stdout), stderr: String(stderr) };
|
|
3384
|
+
};
|
|
3385
|
+
var defaultGit = async (args) => {
|
|
3386
|
+
try {
|
|
3387
|
+
const { stdout } = await execFileP("git", args);
|
|
3388
|
+
return stdout.trim();
|
|
3389
|
+
} catch {
|
|
3390
|
+
return "";
|
|
3391
|
+
}
|
|
3392
|
+
};
|
|
3393
|
+
var PROJECT_ITEMS_QUERY = `
|
|
3394
|
+
query($owner: String!, $number: Int!, $statusField: String!, $after: String) {
|
|
3395
|
+
viewer { login }
|
|
3396
|
+
organization(login: $owner) {
|
|
3397
|
+
projectV2(number: $number) {
|
|
3398
|
+
id
|
|
3399
|
+
title
|
|
3400
|
+
items(first: 100, after: $after) {
|
|
3401
|
+
pageInfo { hasNextPage endCursor }
|
|
3402
|
+
nodes {
|
|
3403
|
+
id
|
|
3404
|
+
fieldValueByName(name: $statusField) {
|
|
3405
|
+
... on ProjectV2ItemFieldSingleSelectValue { name optionId }
|
|
3406
|
+
}
|
|
3407
|
+
content {
|
|
3408
|
+
__typename
|
|
3409
|
+
... on Issue {
|
|
3410
|
+
id
|
|
3411
|
+
number
|
|
3412
|
+
title
|
|
3413
|
+
url
|
|
3414
|
+
state
|
|
3415
|
+
repository { nameWithOwner }
|
|
3416
|
+
labels(first: 10) { nodes { name } }
|
|
3417
|
+
assignees(first: 10) { nodes { login } }
|
|
3418
|
+
}
|
|
3419
|
+
... on PullRequest {
|
|
3420
|
+
id
|
|
3421
|
+
number
|
|
3422
|
+
title
|
|
3423
|
+
url
|
|
3424
|
+
state
|
|
3425
|
+
repository { nameWithOwner }
|
|
3426
|
+
labels(first: 10) { nodes { name } }
|
|
3427
|
+
assignees(first: 10) { nodes { login } }
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
}
|
|
3431
|
+
}
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
}`;
|
|
3435
|
+
function resolveBoardConfig(cfg) {
|
|
3436
|
+
const missing = [];
|
|
3437
|
+
if (!cfg.projectOwner) missing.push("projectOwner");
|
|
3438
|
+
if (!cfg.projectNumber) missing.push("projectNumber");
|
|
3439
|
+
if (!cfg.projectId) missing.push("projectId");
|
|
3440
|
+
if (!cfg.statusFieldId) missing.push("statusFieldId");
|
|
3441
|
+
if (!cfg.statusOptions) missing.push("statusOptions");
|
|
3442
|
+
for (const status of BOARD_STATUSES) {
|
|
3443
|
+
if (!cfg.statusOptions?.[status]) missing.push(`statusOptions.${status}`);
|
|
3444
|
+
}
|
|
3445
|
+
if (missing.length) throw new Error(`repo board config missing ${missing.join(", ")} in .mmi/config.json`);
|
|
3446
|
+
return {
|
|
3447
|
+
projectOwner: cfg.projectOwner,
|
|
3448
|
+
projectNumber: cfg.projectNumber,
|
|
3449
|
+
projectId: cfg.projectId,
|
|
3450
|
+
statusFieldId: cfg.statusFieldId,
|
|
3451
|
+
statusOptions: cfg.statusOptions
|
|
3452
|
+
};
|
|
3453
|
+
}
|
|
3454
|
+
function repoFromGitRemote(remote) {
|
|
3455
|
+
const value = remote.trim().replace(/\.git$/, "");
|
|
3456
|
+
const https = value.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)$/i);
|
|
3457
|
+
if (https) return https[1];
|
|
3458
|
+
const ssh = value.match(/^git@github\.com:([^/]+\/[^/]+)$/i);
|
|
3459
|
+
if (ssh) return ssh[1];
|
|
3460
|
+
const sshUrl = value.match(/^ssh:\/\/git@github\.com\/([^/]+\/[^/]+)$/i);
|
|
3461
|
+
if (sshUrl) return sshUrl[1];
|
|
3462
|
+
return void 0;
|
|
3463
|
+
}
|
|
3464
|
+
function parseIssueSelector(selector, defaultRepo) {
|
|
3465
|
+
const trimmed = selector.trim();
|
|
3466
|
+
const url = trimmed.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)$/i);
|
|
3467
|
+
if (url) return { repo: url[1], number: Number(url[2]) };
|
|
3468
|
+
const qualified = trimmed.match(/^([^/\s#]+\/[^/\s#]+)#(\d+)$/);
|
|
3469
|
+
if (qualified) return { repo: qualified[1], number: Number(qualified[2]) };
|
|
3470
|
+
const local = trimmed.match(/^#?(\d+)$/);
|
|
3471
|
+
if (local) return { repo: defaultRepo, number: Number(local[1]) };
|
|
3472
|
+
throw new Error(`expected an issue selector like 123, #123, owner/repo#123, or a GitHub issue URL`);
|
|
3473
|
+
}
|
|
3474
|
+
function partitionBoardItems(items, viewer, currentRepo) {
|
|
3475
|
+
const empty = () => ({ userOwned: [], claimable: [], taken: [] });
|
|
3476
|
+
const groups = { primary: empty(), secondary: empty() };
|
|
3477
|
+
const viewerKey = viewer.toLowerCase();
|
|
3478
|
+
const repoKey = currentRepo.toLowerCase();
|
|
3479
|
+
for (const item of items) {
|
|
3480
|
+
if (!ACTIVE_STATUSES.has(item.status)) continue;
|
|
3481
|
+
const scope = item.repository.toLowerCase() === repoKey ? "primary" : "secondary";
|
|
3482
|
+
const assignees = item.assignees.map((a) => a.toLowerCase());
|
|
3483
|
+
const assignedToViewer = assignees.includes(viewerKey);
|
|
3484
|
+
if (assignedToViewer) {
|
|
3485
|
+
groups[scope].userOwned.push(item);
|
|
3486
|
+
} else if (item.status === "Todo" && item.assignees.length === 0) {
|
|
3487
|
+
groups[scope].claimable.push(item);
|
|
3488
|
+
} else if (item.assignees.length > 0) {
|
|
3489
|
+
groups[scope].taken.push(item);
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
sortBuckets(groups.primary);
|
|
3493
|
+
sortBuckets(groups.secondary);
|
|
3494
|
+
return groups;
|
|
3495
|
+
}
|
|
3496
|
+
function detailCandidates(report) {
|
|
3497
|
+
return [
|
|
3498
|
+
...report.primary.userOwned,
|
|
3499
|
+
...report.primary.claimable,
|
|
3500
|
+
...report.secondary.userOwned,
|
|
3501
|
+
...report.secondary.claimable
|
|
3502
|
+
].filter((item) => item.contentType === "Issue");
|
|
3503
|
+
}
|
|
3504
|
+
function findClaimableItem(report, selector) {
|
|
3505
|
+
const candidates = [...report.primary.claimable, ...report.secondary.claimable];
|
|
3506
|
+
const found = candidates.find((item) => item.repository.toLowerCase() === selector.repo.toLowerCase() && item.number === selector.number);
|
|
3507
|
+
if (found) return found;
|
|
3508
|
+
const all = [
|
|
3509
|
+
...report.primary.userOwned,
|
|
3510
|
+
...report.primary.claimable,
|
|
3511
|
+
...report.primary.taken,
|
|
3512
|
+
...report.secondary.userOwned,
|
|
3513
|
+
...report.secondary.claimable,
|
|
3514
|
+
...report.secondary.taken
|
|
3515
|
+
];
|
|
3516
|
+
const existing = all.find((item) => item.repository.toLowerCase() === selector.repo.toLowerCase() && item.number === selector.number);
|
|
3517
|
+
if (existing) {
|
|
3518
|
+
if (existing.status !== "Todo") throw new Error(`${existing.ref} is ${existing.status}, not Todo`);
|
|
3519
|
+
if (existing.assignees.length) throw new Error(`${existing.ref} is already assigned to @${existing.assignees.join(", @")}`);
|
|
3520
|
+
throw new Error(`${existing.ref} is not claimable`);
|
|
3521
|
+
}
|
|
3522
|
+
throw new Error(`${selector.repo}#${selector.number} is not on this project board`);
|
|
3523
|
+
}
|
|
3524
|
+
function renderBoardReport(report) {
|
|
3525
|
+
const lines = [`Board \xB7 ${report.project.title} \xB7 @${report.viewer}`];
|
|
3526
|
+
renderScope(lines, "PRIMARY", report.repo, report.primary);
|
|
3527
|
+
renderScope(lines, "SECONDARY", "Other repos on this project", report.secondary);
|
|
3528
|
+
if (report.warnings.length) {
|
|
3529
|
+
lines.push("", "Warnings");
|
|
3530
|
+
for (const warning of report.warnings) lines.push(` ${warning}`);
|
|
3531
|
+
}
|
|
3532
|
+
return lines.join("\n");
|
|
3533
|
+
}
|
|
3534
|
+
async function readBoard(options, deps = {}) {
|
|
3535
|
+
const cfg = resolveBoardConfig(options.config);
|
|
3536
|
+
const gh = deps.gh ?? defaultGh;
|
|
3537
|
+
const git = deps.git ?? defaultGit;
|
|
3538
|
+
const currentRepo = options.repo ?? repoFromGitRemote(await git(["remote", "get-url", "origin"])) ?? "";
|
|
3539
|
+
if (!currentRepo) throw new Error("could not resolve current GitHub repo; pass --repo owner/repo");
|
|
3540
|
+
const warnings = [];
|
|
3541
|
+
const nodes = [];
|
|
3542
|
+
let viewer = "";
|
|
3543
|
+
let projectTitle = "";
|
|
3544
|
+
let after;
|
|
3545
|
+
let projectId = cfg.projectId;
|
|
3546
|
+
let partial = false;
|
|
3547
|
+
do {
|
|
3548
|
+
try {
|
|
3549
|
+
const page = await fetchProjectPage(gh, cfg, after);
|
|
3550
|
+
viewer ||= page.viewer.login;
|
|
3551
|
+
const project = page.organization?.projectV2;
|
|
3552
|
+
if (!project) throw new Error(`project ${cfg.projectOwner}#${cfg.projectNumber} not found`);
|
|
3553
|
+
projectId = project.id;
|
|
3554
|
+
projectTitle ||= project.title;
|
|
3555
|
+
nodes.push(...project.items.nodes ?? []);
|
|
3556
|
+
after = project.items.pageInfo.hasNextPage ? project.items.pageInfo.endCursor ?? void 0 : void 0;
|
|
3557
|
+
} catch (e) {
|
|
3558
|
+
const message = `partial board read: ${e.message}`;
|
|
3559
|
+
if (!nodes.length || !options.allowPartial) throw new Error(message);
|
|
3560
|
+
warnings.push(message);
|
|
3561
|
+
partial = true;
|
|
3562
|
+
after = void 0;
|
|
3563
|
+
}
|
|
3564
|
+
} while (after);
|
|
3565
|
+
const items = nodesToItems(nodes, warnings);
|
|
3566
|
+
const groups = partitionBoardItems(items, viewer, currentRepo);
|
|
3567
|
+
const report = {
|
|
3568
|
+
project: { owner: cfg.projectOwner, number: cfg.projectNumber, id: projectId, title: projectTitle || String(cfg.projectNumber) },
|
|
3569
|
+
viewer,
|
|
3570
|
+
repo: currentRepo,
|
|
3571
|
+
...groups,
|
|
3572
|
+
warnings,
|
|
3573
|
+
partial
|
|
3574
|
+
};
|
|
3575
|
+
if (options.includeBundleDetails) {
|
|
3576
|
+
await attachBundleDetails(report, gh, options.allowPartial ?? false);
|
|
3577
|
+
}
|
|
3578
|
+
return report;
|
|
3579
|
+
}
|
|
3580
|
+
async function claimBoardIssue(options, deps = {}) {
|
|
3581
|
+
const cfg = resolveBoardConfig(options.config);
|
|
3582
|
+
const gh = deps.gh ?? defaultGh;
|
|
3583
|
+
const report = await readBoard({ config: cfg, repo: options.repo, allowPartial: options.allowPartial }, deps);
|
|
3584
|
+
const selector = parseIssueSelector(options.selector, report.repo);
|
|
3585
|
+
const item = findClaimableItem(report, selector);
|
|
3586
|
+
if (item.contentType !== "Issue") throw new Error(`${item.ref} is not an issue`);
|
|
3587
|
+
try {
|
|
3588
|
+
await gh(["issue", "edit", String(item.number), "--repo", item.repository, "--add-assignee", "@me"]);
|
|
3589
|
+
} catch (e) {
|
|
3590
|
+
throw new Error(`claim failed before board status changed: ${ghError(e)}`);
|
|
3591
|
+
}
|
|
3592
|
+
try {
|
|
3593
|
+
await gh([
|
|
3594
|
+
"project",
|
|
3595
|
+
"item-edit",
|
|
3596
|
+
"--id",
|
|
3597
|
+
item.itemId,
|
|
3598
|
+
"--project-id",
|
|
3599
|
+
cfg.projectId,
|
|
3600
|
+
"--field-id",
|
|
3601
|
+
cfg.statusFieldId,
|
|
3602
|
+
"--single-select-option-id",
|
|
3603
|
+
cfg.statusOptions["In Progress"]
|
|
3604
|
+
]);
|
|
3605
|
+
} catch (e) {
|
|
3606
|
+
const warning = `partial claim: ${item.ref} was assigned to @${report.viewer}, but Status was not moved to In Progress (${ghError(e)})`;
|
|
3607
|
+
if (!options.allowPartial) throw new Error(warning);
|
|
3608
|
+
return { item, viewer: report.viewer, repo: report.repo, status: "Todo", partial: true, warning };
|
|
3609
|
+
}
|
|
3610
|
+
return { item: { ...item, assignees: [...item.assignees, report.viewer], status: "In Progress" }, viewer: report.viewer, repo: report.repo, status: "In Progress", partial: false };
|
|
3611
|
+
}
|
|
3612
|
+
async function fetchProjectPage(gh, cfg, after) {
|
|
3613
|
+
const args = [
|
|
3614
|
+
"api",
|
|
3615
|
+
"graphql",
|
|
3616
|
+
"-f",
|
|
3617
|
+
`query=${PROJECT_ITEMS_QUERY}`,
|
|
3618
|
+
"-f",
|
|
3619
|
+
`owner=${cfg.projectOwner}`,
|
|
3620
|
+
"-F",
|
|
3621
|
+
`number=${cfg.projectNumber}`,
|
|
3622
|
+
"-f",
|
|
3623
|
+
"statusField=Status"
|
|
3624
|
+
];
|
|
3625
|
+
if (after) args.push("-f", `after=${after}`);
|
|
3626
|
+
const { stdout } = await gh(args);
|
|
3627
|
+
const parsed = JSON.parse(stdout);
|
|
3628
|
+
if (!parsed.data) throw new Error("gh GraphQL response did not include data");
|
|
3629
|
+
return parsed.data;
|
|
3630
|
+
}
|
|
3631
|
+
function nodesToItems(nodes, warnings) {
|
|
3632
|
+
const items = [];
|
|
3633
|
+
for (const node of nodes) {
|
|
3634
|
+
const item = nodeToItem(node);
|
|
3635
|
+
if (item) items.push(item);
|
|
3636
|
+
else if (node.content?.__typename) warnings.push(`skipped unsupported project item type ${node.content.__typename}`);
|
|
3637
|
+
}
|
|
3638
|
+
return items;
|
|
3639
|
+
}
|
|
3640
|
+
function nodeToItem(node) {
|
|
3641
|
+
const content = node.content;
|
|
3642
|
+
if (!node.id || !isSupportedContent(content)) return void 0;
|
|
3643
|
+
const status = asBoardStatus(node.fieldValueByName?.name);
|
|
3644
|
+
const repository = content.repository?.nameWithOwner;
|
|
3645
|
+
if (!status || !content.id || !content.number || !content.title || !content.url || !repository) return void 0;
|
|
3646
|
+
const labels = (content.labels?.nodes ?? []).map((l) => l.name).filter((name) => Boolean(name));
|
|
3647
|
+
const assignees = (content.assignees?.nodes ?? []).map((a) => a.login).filter((login) => Boolean(login));
|
|
3648
|
+
return {
|
|
3649
|
+
itemId: node.id,
|
|
3650
|
+
contentId: content.id,
|
|
3651
|
+
contentType: content.__typename,
|
|
3652
|
+
repository,
|
|
3653
|
+
number: content.number,
|
|
3654
|
+
ref: `${repository}#${content.number}`,
|
|
3655
|
+
url: content.url,
|
|
3656
|
+
title: content.title,
|
|
3657
|
+
state: content.state ?? "",
|
|
3658
|
+
status,
|
|
3659
|
+
statusOptionId: node.fieldValueByName?.optionId,
|
|
3660
|
+
assignees,
|
|
3661
|
+
labels,
|
|
3662
|
+
type: labels.find((label) => TYPE_LABELS.includes(label)) ?? labels[0]
|
|
3663
|
+
};
|
|
3664
|
+
}
|
|
3665
|
+
function isSupportedContent(content) {
|
|
3666
|
+
return Boolean(content && (content.__typename === "Issue" || content.__typename === "PullRequest"));
|
|
3667
|
+
}
|
|
3668
|
+
async function attachBundleDetails(report, gh, allowPartial) {
|
|
3669
|
+
const candidates = detailCandidates(report);
|
|
3670
|
+
if (candidates.length <= 1) return;
|
|
3671
|
+
for (const item of candidates) {
|
|
3672
|
+
try {
|
|
3673
|
+
const { stdout } = await gh(["issue", "view", String(item.number), "--repo", item.repository, "--json", "body,comments"]);
|
|
3674
|
+
const detail = JSON.parse(stdout);
|
|
3675
|
+
item.details = {
|
|
3676
|
+
body: detail.body ?? "",
|
|
3677
|
+
comments: (detail.comments ?? []).map((comment) => ({
|
|
3678
|
+
author: comment.author?.login ?? "",
|
|
3679
|
+
body: comment.body ?? ""
|
|
3680
|
+
}))
|
|
3681
|
+
};
|
|
3682
|
+
} catch (e) {
|
|
3683
|
+
const warning = `partial detail read: ${item.ref}: ${ghError(e)}`;
|
|
3684
|
+
if (!allowPartial) throw new Error(warning);
|
|
3685
|
+
report.warnings.push(warning);
|
|
3686
|
+
report.partial = true;
|
|
3687
|
+
}
|
|
3688
|
+
}
|
|
3689
|
+
}
|
|
3690
|
+
function renderScope(lines, label, title, buckets) {
|
|
3691
|
+
if (!hasItems(buckets)) return;
|
|
3692
|
+
lines.push("", `${label} \xB7 ${title}`);
|
|
3693
|
+
renderOwned(lines, buckets.userOwned);
|
|
3694
|
+
renderClaimable(lines, buckets.claimable);
|
|
3695
|
+
renderTaken(lines, buckets.taken);
|
|
3696
|
+
}
|
|
3697
|
+
function renderOwned(lines, items) {
|
|
3698
|
+
if (!items.length) return;
|
|
3699
|
+
lines.push("Yours");
|
|
3700
|
+
for (const status of ["Todo", "In Progress", "In Review"]) {
|
|
3701
|
+
const group = items.filter((item) => item.status === status);
|
|
3702
|
+
if (!group.length) continue;
|
|
3703
|
+
lines.push(` ${status}${status === "In Review" ? " (awaiting admin review & merge)" : ""}`);
|
|
3704
|
+
for (const item of group) lines.push(` ${renderTitledItem(item)}`);
|
|
3705
|
+
}
|
|
3706
|
+
}
|
|
3707
|
+
function renderClaimable(lines, items) {
|
|
3708
|
+
if (!items.length) return;
|
|
3709
|
+
lines.push("Free to claim");
|
|
3710
|
+
for (const item of items) lines.push(` ${renderTitledItem(item)}`);
|
|
3711
|
+
}
|
|
3712
|
+
function renderTaken(lines, items) {
|
|
3713
|
+
if (!items.length) return;
|
|
3714
|
+
lines.push("Taken");
|
|
3715
|
+
for (const item of items) lines.push(` ${item.ref} \xB7 ${item.status} \xB7 @${item.assignees.join(", @")}`);
|
|
3716
|
+
}
|
|
3717
|
+
function renderTitledItem(item) {
|
|
3718
|
+
return `${item.ref} - [${item.type ?? "item"}] ${item.title}`;
|
|
3719
|
+
}
|
|
3720
|
+
function hasItems(buckets) {
|
|
3721
|
+
return buckets.userOwned.length > 0 || buckets.claimable.length > 0 || buckets.taken.length > 0;
|
|
3722
|
+
}
|
|
3723
|
+
function sortBuckets(buckets) {
|
|
3724
|
+
buckets.userOwned.sort(compareItems);
|
|
3725
|
+
buckets.claimable.sort(compareItems);
|
|
3726
|
+
buckets.taken.sort(compareItems);
|
|
3727
|
+
}
|
|
3728
|
+
function compareItems(a, b) {
|
|
3729
|
+
return (STATUS_ORDER.get(a.status) ?? 99) - (STATUS_ORDER.get(b.status) ?? 99) || a.repository.localeCompare(b.repository) || a.number - b.number;
|
|
3730
|
+
}
|
|
3731
|
+
function asBoardStatus(value) {
|
|
3732
|
+
return BOARD_STATUSES.includes(value) ? value : void 0;
|
|
3733
|
+
}
|
|
3734
|
+
function ghError(e) {
|
|
3735
|
+
const err = e;
|
|
3736
|
+
return (err.stderr || err.message || String(e)).trim();
|
|
3737
|
+
}
|
|
3738
|
+
|
|
3739
|
+
// src/gc.ts
|
|
3740
|
+
var DEFAULT_PROTECTED = /* @__PURE__ */ new Set(["development", "main", "master", "rc"]);
|
|
3741
|
+
function groupedPrs(prs) {
|
|
3742
|
+
const out = /* @__PURE__ */ new Map();
|
|
3743
|
+
for (const pr2 of prs) {
|
|
3744
|
+
const branch = pr2.headRefName?.trim();
|
|
3745
|
+
if (!branch) continue;
|
|
3746
|
+
out.set(branch, [...out.get(branch) ?? [], pr2]);
|
|
3747
|
+
}
|
|
3748
|
+
return out;
|
|
3749
|
+
}
|
|
3750
|
+
function closedState(prs) {
|
|
3751
|
+
if (!prs?.length) return null;
|
|
3752
|
+
if (prs.some((pr2) => pr2.state === "OPEN")) return null;
|
|
3753
|
+
const closed = prs.filter((pr2) => pr2.state === "MERGED" || pr2.state === "CLOSED");
|
|
3754
|
+
if (!closed.length) return null;
|
|
3755
|
+
const state = closed.some((pr2) => pr2.state === "MERGED") ? "MERGED" : "CLOSED";
|
|
3756
|
+
return { state, numbers: closed.map((pr2) => pr2.number).filter((n) => typeof n === "number") };
|
|
3757
|
+
}
|
|
3758
|
+
function branchForTrackingRef(ref, remote) {
|
|
3759
|
+
const prefix = `${remote}/`;
|
|
3760
|
+
if (!ref.startsWith(prefix)) return null;
|
|
3761
|
+
const branch = ref.slice(prefix.length);
|
|
3762
|
+
return branch && branch !== "HEAD" ? branch : null;
|
|
3763
|
+
}
|
|
3764
|
+
function buildGcPlan(inputs) {
|
|
3765
|
+
const remote = inputs.remote ?? "origin";
|
|
3766
|
+
const protectedBranches = /* @__PURE__ */ new Set([...inputs.protectedBranches ?? [], ...DEFAULT_PROTECTED]);
|
|
3767
|
+
const prs = groupedPrs(inputs.pullRequests);
|
|
3768
|
+
const worktrees = new Map((inputs.worktrees ?? []).map((w) => [w.branch, w]));
|
|
3769
|
+
const dirtyWorktrees = new Set((inputs.worktrees ?? []).filter((w) => w.dirty).map((w) => w.branch));
|
|
3770
|
+
const skipped = [];
|
|
3771
|
+
const branches = [];
|
|
3772
|
+
for (const branch of [...new Set(inputs.localBranches.map((b) => b.trim()).filter(Boolean))]) {
|
|
3773
|
+
if (protectedBranches.has(branch)) {
|
|
3774
|
+
skipped.push({ branch, reason: "protected" });
|
|
3775
|
+
continue;
|
|
3776
|
+
}
|
|
3777
|
+
const prSet = prs.get(branch);
|
|
3778
|
+
if (prSet?.some((pr2) => pr2.state === "OPEN")) {
|
|
3779
|
+
skipped.push({ branch, reason: "open-pr" });
|
|
3780
|
+
continue;
|
|
3781
|
+
}
|
|
3782
|
+
const state = closedState(prSet);
|
|
3783
|
+
if (!state) continue;
|
|
3784
|
+
if (branch === inputs.currentBranch) {
|
|
3785
|
+
skipped.push({ branch, reason: "current-branch" });
|
|
3786
|
+
continue;
|
|
3787
|
+
}
|
|
3788
|
+
const worktree = worktrees.get(branch);
|
|
3789
|
+
if (worktree?.dirty) {
|
|
3790
|
+
skipped.push({ branch, reason: "dirty-worktree", detail: worktree.path });
|
|
3791
|
+
continue;
|
|
3792
|
+
}
|
|
3793
|
+
branches.push({ branch, prState: state.state, prNumbers: state.numbers, worktreePath: worktree?.path });
|
|
3794
|
+
}
|
|
3795
|
+
const trackingRefs = [...new Set(inputs.staleTrackingRefs ?? [])].map((ref) => {
|
|
3796
|
+
const branch = branchForTrackingRef(ref, remote);
|
|
3797
|
+
if (!branch || protectedBranches.has(branch)) return null;
|
|
3798
|
+
if (branch === inputs.currentBranch || dirtyWorktrees.has(branch)) return null;
|
|
3799
|
+
const prSet = prs.get(branch);
|
|
3800
|
+
if (prSet?.some((pr2) => pr2.state === "OPEN")) return null;
|
|
3801
|
+
const state = closedState(prSet);
|
|
3802
|
+
return state ? { ref, branch, prState: state.state, prNumbers: state.numbers } : null;
|
|
3803
|
+
}).filter((r) => Boolean(r));
|
|
3804
|
+
return { branches, trackingRefs, skipped };
|
|
3805
|
+
}
|
|
3806
|
+
function parseRemotePruneDryRun(stdout) {
|
|
3807
|
+
const refs = [];
|
|
3808
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
3809
|
+
const match = line.match(/\[would prune\]\s+(.+)$/);
|
|
3810
|
+
if (match?.[1]) refs.push(match[1].trim());
|
|
3811
|
+
}
|
|
3812
|
+
return refs;
|
|
3813
|
+
}
|
|
3814
|
+
function parseWorktreePorcelain(stdout) {
|
|
3815
|
+
const out = [];
|
|
3816
|
+
for (const block of stdout.split(/\r?\n(?=worktree )/)) {
|
|
3817
|
+
let path = "";
|
|
3818
|
+
let branch = "";
|
|
3819
|
+
for (const line of block.split(/\r?\n/)) {
|
|
3820
|
+
if (line.startsWith("worktree ")) path = line.slice("worktree ".length).trim();
|
|
3821
|
+
if (line.startsWith("branch refs/heads/")) branch = line.slice("branch refs/heads/".length).trim();
|
|
3822
|
+
}
|
|
3823
|
+
if (path && branch) out.push({ path, branch });
|
|
3824
|
+
}
|
|
3825
|
+
return out;
|
|
3826
|
+
}
|
|
3827
|
+
function formatGcPlan(plan, apply) {
|
|
3828
|
+
const lines = [`mmi-cli gc: ${apply ? "apply" : "dry-run"}`];
|
|
3829
|
+
if (!plan.branches.length && !plan.trackingRefs.length) lines.push("nothing to clean");
|
|
3830
|
+
if (plan.branches.length) {
|
|
3831
|
+
lines.push("local branches:");
|
|
3832
|
+
for (const b of plan.branches) {
|
|
3833
|
+
const prs = b.prNumbers.length ? ` #${b.prNumbers.join(",#")}` : "";
|
|
3834
|
+
const wt = b.worktreePath ? ` (worktree: ${b.worktreePath})` : "";
|
|
3835
|
+
lines.push(` - ${b.branch} (${b.prState}${prs})${wt}`);
|
|
3836
|
+
}
|
|
3837
|
+
}
|
|
3838
|
+
if (plan.trackingRefs.length) {
|
|
3839
|
+
lines.push("stale tracking refs:");
|
|
3840
|
+
for (const r of plan.trackingRefs) {
|
|
3841
|
+
const prs = r.prNumbers.length ? ` #${r.prNumbers.join(",#")}` : "";
|
|
3842
|
+
lines.push(` - ${r.ref} (${r.prState}${prs})`);
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
if (plan.skipped.length) {
|
|
3846
|
+
lines.push("skipped:");
|
|
3847
|
+
for (const s of plan.skipped) {
|
|
3848
|
+
lines.push(` - ${s.branch}: ${s.reason}${s.detail ? ` (${s.detail})` : ""}`);
|
|
3849
|
+
}
|
|
3850
|
+
}
|
|
3851
|
+
if (!apply && (plan.branches.length || plan.trackingRefs.length)) lines.push("rerun with --apply to delete only the listed items");
|
|
3852
|
+
return lines.join("\n");
|
|
3853
|
+
}
|
|
3854
|
+
|
|
3855
|
+
// src/command-plans.ts
|
|
3856
|
+
function stagePlan(stage = {}) {
|
|
3857
|
+
return [
|
|
3858
|
+
{ label: "force-kill previous local stage", command: "mmi-cli stage stop --apply" },
|
|
3859
|
+
{ label: "run local build", command: stage.build || "(no stage.build configured)" },
|
|
3860
|
+
{ label: "start local stage", command: stage.up || "(no stage.up configured)" },
|
|
3861
|
+
{ label: "check health", command: stage.healthUrl ? `curl --fail ${stage.healthUrl}` : "(no stage.healthUrl configured)" }
|
|
3862
|
+
];
|
|
3863
|
+
}
|
|
3864
|
+
function trainPlan(command) {
|
|
3865
|
+
if (command === "rc") {
|
|
3866
|
+
return [
|
|
3867
|
+
{ label: "verify current branch is development" },
|
|
3868
|
+
{ label: "merge development to rc", gated: true },
|
|
3869
|
+
{ label: "deploy rc", gated: true }
|
|
3870
|
+
];
|
|
3871
|
+
}
|
|
3872
|
+
if (command === "release") {
|
|
3873
|
+
return [
|
|
3874
|
+
{ label: "verify current branch is rc" },
|
|
3875
|
+
{ label: "merge rc to main", gated: true },
|
|
3876
|
+
{ label: "tag release and publish GitHub Release", gated: true },
|
|
3877
|
+
{ label: "deploy prod", gated: true },
|
|
3878
|
+
{ label: "roll development forward", gated: true }
|
|
3879
|
+
];
|
|
3880
|
+
}
|
|
3881
|
+
return [
|
|
3882
|
+
{ label: "branch hotfix from main", gated: true },
|
|
3883
|
+
{ label: "apply approved fix", gated: true },
|
|
3884
|
+
{ label: "deploy prod", gated: true },
|
|
3885
|
+
{ label: "back-merge to rc and development", gated: true }
|
|
3886
|
+
];
|
|
3887
|
+
}
|
|
3888
|
+
function bootstrapPlan(repo, repoClass) {
|
|
3889
|
+
const branches = repoClass === "content" ? "main" : "development, rc, main";
|
|
3890
|
+
return [
|
|
3891
|
+
{ label: `create or inspect ${repo}` },
|
|
3892
|
+
{ label: `provision branches: ${branches}`, gated: true },
|
|
3893
|
+
{ label: "apply branch protection / train allowlist", gated: true },
|
|
3894
|
+
{ label: "attach GitHub Project v2 and write .mmi/config.json", gated: true },
|
|
3895
|
+
{ label: "seed README.md and architecture.md", gated: true },
|
|
3896
|
+
{ label: "install plugin settings and register fanout", gated: true }
|
|
3897
|
+
];
|
|
3898
|
+
}
|
|
3899
|
+
|
|
3900
|
+
// src/index.ts
|
|
3901
|
+
var execFileP2 = (0, import_node_util2.promisify)(import_node_child_process3.execFile);
|
|
3902
|
+
var GIT_TIMEOUT_MS = 1e4;
|
|
3903
|
+
var GC_GH_TIMEOUT_MS = 2e4;
|
|
3904
|
+
async function githubToken() {
|
|
3905
|
+
if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
|
|
3906
|
+
if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
|
|
3907
|
+
try {
|
|
3908
|
+
const { stdout } = await execFileP2("gh", ["auth", "token"]);
|
|
3909
|
+
return stdout.trim() || void 0;
|
|
3910
|
+
} catch {
|
|
3911
|
+
return void 0;
|
|
3912
|
+
}
|
|
3913
|
+
}
|
|
3914
|
+
async function githubLogin() {
|
|
3915
|
+
try {
|
|
3916
|
+
const { stdout } = await execFileP2("gh", ["api", "user", "--jq", ".login"]);
|
|
3917
|
+
return stdout.trim() || void 0;
|
|
3918
|
+
} catch {
|
|
3919
|
+
return void 0;
|
|
3920
|
+
}
|
|
3921
|
+
}
|
|
3922
|
+
async function sagaHeaders(extra = {}) {
|
|
3923
|
+
const t = await githubToken();
|
|
3924
|
+
return t ? { ...extra, Authorization: `Bearer ${t}` } : extra;
|
|
3925
|
+
}
|
|
3926
|
+
async function loadConfig() {
|
|
3927
|
+
try {
|
|
3928
|
+
return JSON.parse(await (0, import_promises.readFile)(".mmi/config.json", "utf8"));
|
|
3929
|
+
} catch {
|
|
3930
|
+
return {};
|
|
3931
|
+
}
|
|
3932
|
+
}
|
|
3933
|
+
var DEFAULT_RULES_SOURCE = "https://raw.githubusercontent.com/mutmutco/MMI-Hub/development";
|
|
3934
|
+
var DEFAULT_KB_SOURCE = "https://raw.githubusercontent.com/mutmutco/MM-KB/main";
|
|
3935
|
+
var SESSION_FILE = ".mmi/.session";
|
|
3936
|
+
var gitOut = async (args) => {
|
|
3937
|
+
try {
|
|
3938
|
+
return (await execFileP2("git", [...args])).stdout.trim();
|
|
3939
|
+
} catch {
|
|
3940
|
+
return "";
|
|
3941
|
+
}
|
|
3942
|
+
};
|
|
3943
|
+
function sessionDeps() {
|
|
3944
|
+
return {
|
|
3945
|
+
env: process.env,
|
|
3946
|
+
readPersisted: () => {
|
|
3947
|
+
try {
|
|
3948
|
+
return (0, import_node_fs2.readFileSync)(SESSION_FILE, "utf8");
|
|
3949
|
+
} catch {
|
|
3950
|
+
return null;
|
|
3951
|
+
}
|
|
3952
|
+
},
|
|
3953
|
+
writePersisted: (id) => persistSession(id),
|
|
3954
|
+
now: () => /* @__PURE__ */ new Date(),
|
|
3955
|
+
rand: () => (0, import_node_crypto.randomBytes)(4).toString("hex")
|
|
3956
|
+
};
|
|
3957
|
+
}
|
|
3958
|
+
var resolveSessionId = () => resolveSession(sessionDeps());
|
|
3959
|
+
function persistSession(id) {
|
|
3960
|
+
try {
|
|
3961
|
+
(0, import_node_fs2.mkdirSync)(".mmi", { recursive: true });
|
|
3962
|
+
(0, import_node_fs2.writeFileSync)(SESSION_FILE, id, "utf8");
|
|
3963
|
+
} catch {
|
|
3964
|
+
}
|
|
3965
|
+
}
|
|
3966
|
+
async function sagaKey(cfg, session) {
|
|
3967
|
+
const remote = await gitOut(["remote", "get-url", "origin"]);
|
|
3968
|
+
const repo = remote.replace(/\.git$/, "").split("/").pop() || "-";
|
|
3969
|
+
return { project: cfg.project || repo, branch: await gitOut(["rev-parse", "--abbrev-ref", "HEAD"]) || "-", sessionId: (session ?? resolveSessionId()).id };
|
|
3970
|
+
}
|
|
3971
|
+
async function postCapture(capture, quiet = false) {
|
|
3972
|
+
try {
|
|
3973
|
+
const cfg = await loadConfig();
|
|
3974
|
+
if (!cfg.sagaApiUrl) {
|
|
3975
|
+
if (!quiet) console.error("mmi-cli saga: sagaApiUrl not configured in .mmi/config.json");
|
|
3976
|
+
return;
|
|
3977
|
+
}
|
|
3978
|
+
const res = await fetch(`${cfg.sagaApiUrl}/saga/capture`, {
|
|
3979
|
+
method: "POST",
|
|
3980
|
+
headers: await sagaHeaders({ "content-type": "application/json" }),
|
|
3981
|
+
body: JSON.stringify({ ...capture, ...await sagaKey(cfg) }),
|
|
3982
|
+
signal: AbortSignal.timeout(8e3)
|
|
3983
|
+
});
|
|
3984
|
+
if (!quiet) console.log(res.ok ? "noted" : `saga: HTTP ${res.status}`);
|
|
3985
|
+
} catch (e) {
|
|
3986
|
+
if (!quiet) console.error(`mmi-cli saga: ${e.message}`);
|
|
3987
|
+
}
|
|
3988
|
+
}
|
|
3989
|
+
async function readStdin() {
|
|
3990
|
+
if (process.stdin.isTTY) return "";
|
|
3991
|
+
const chunks = [];
|
|
3992
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
3993
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
3994
|
+
}
|
|
3995
|
+
async function ghPrs(limit) {
|
|
3996
|
+
const args = (state) => ["pr", "list", "--state", state, "--limit", String(limit), "--json", "number,headRefName,state"];
|
|
3997
|
+
const [open, closed] = await Promise.all([
|
|
3998
|
+
execFileP2("gh", args("open"), { timeout: GC_GH_TIMEOUT_MS }),
|
|
3999
|
+
execFileP2("gh", args("closed"), { timeout: GC_GH_TIMEOUT_MS })
|
|
4000
|
+
]);
|
|
4001
|
+
return [...JSON.parse(open.stdout || "[]"), ...JSON.parse(closed.stdout || "[]")];
|
|
4002
|
+
}
|
|
4003
|
+
async function worktreeBranches() {
|
|
4004
|
+
const { stdout } = await execFileP2("git", ["worktree", "list", "--porcelain"], { timeout: GIT_TIMEOUT_MS });
|
|
4005
|
+
const parsed = parseWorktreePorcelain(stdout);
|
|
4006
|
+
return await Promise.all(parsed.map(async (w) => {
|
|
4007
|
+
let dirty = true;
|
|
4008
|
+
try {
|
|
4009
|
+
const { stdout: status } = await execFileP2("git", ["-C", w.path, "status", "--porcelain"], { timeout: GIT_TIMEOUT_MS });
|
|
4010
|
+
dirty = status.trim().length > 0;
|
|
4011
|
+
} catch {
|
|
4012
|
+
dirty = true;
|
|
4013
|
+
}
|
|
4014
|
+
return { ...w, dirty };
|
|
4015
|
+
}));
|
|
4016
|
+
}
|
|
4017
|
+
async function gcPlan(remote, limit) {
|
|
4018
|
+
const [branches, current, stale, prs, worktrees] = await Promise.all([
|
|
4019
|
+
gitOut(["branch", "--format=%(refname:short)"]),
|
|
4020
|
+
gitOut(["rev-parse", "--abbrev-ref", "HEAD"]),
|
|
4021
|
+
execFileP2("git", ["remote", "prune", remote, "--dry-run"], { timeout: GIT_TIMEOUT_MS }).then((r) => parseRemotePruneDryRun(`${r.stdout}${r.stderr}`)).catch(() => []),
|
|
4022
|
+
ghPrs(limit),
|
|
4023
|
+
worktreeBranches()
|
|
4024
|
+
]);
|
|
4025
|
+
return buildGcPlan({
|
|
4026
|
+
localBranches: branches.split(/\r?\n/).map((b) => b.trim()).filter(Boolean),
|
|
4027
|
+
currentBranch: current,
|
|
4028
|
+
staleTrackingRefs: stale,
|
|
4029
|
+
pullRequests: prs,
|
|
4030
|
+
worktrees,
|
|
4031
|
+
remote
|
|
4032
|
+
});
|
|
4033
|
+
}
|
|
4034
|
+
async function applyGcPlan(plan, remote) {
|
|
4035
|
+
for (const branch of plan.branches) {
|
|
4036
|
+
if (branch.worktreePath) await execFileP2("git", ["worktree", "remove", branch.worktreePath], { timeout: GIT_TIMEOUT_MS });
|
|
4037
|
+
await execFileP2("git", ["branch", "-D", branch.branch], { timeout: GIT_TIMEOUT_MS });
|
|
4038
|
+
}
|
|
4039
|
+
for (const ref of plan.trackingRefs) {
|
|
4040
|
+
await execFileP2("git", ["update-ref", "-d", `refs/remotes/${remote}/${ref.branch}`], { timeout: GIT_TIMEOUT_MS });
|
|
4041
|
+
}
|
|
4042
|
+
if (plan.branches.some((b) => b.worktreePath)) {
|
|
4043
|
+
await execFileP2("git", ["worktree", "prune"], { timeout: GIT_TIMEOUT_MS });
|
|
4044
|
+
}
|
|
4045
|
+
}
|
|
4046
|
+
function resolveVersion() {
|
|
4047
|
+
try {
|
|
4048
|
+
const manifest = (0, import_node_path2.join)(__dirname, "..", "..", ".claude-plugin", "plugin.json");
|
|
4049
|
+
return JSON.parse((0, import_node_fs2.readFileSync)(manifest, "utf8")).version || "0.0.0";
|
|
4050
|
+
} catch {
|
|
4051
|
+
try {
|
|
4052
|
+
const pkg = (0, import_node_path2.join)(__dirname, "..", "package.json");
|
|
4053
|
+
return JSON.parse((0, import_node_fs2.readFileSync)(pkg, "utf8")).version || "0.0.0";
|
|
4054
|
+
} catch {
|
|
4055
|
+
return "0.0.0";
|
|
4056
|
+
}
|
|
4057
|
+
}
|
|
4058
|
+
}
|
|
4059
|
+
function readRepoVersion() {
|
|
4060
|
+
try {
|
|
4061
|
+
return JSON.parse((0, import_node_fs2.readFileSync)((0, import_node_path2.join)(process.cwd(), ".claude-plugin", "plugin.json"), "utf8")).version || void 0;
|
|
4062
|
+
} catch {
|
|
4063
|
+
return void 0;
|
|
4064
|
+
}
|
|
4065
|
+
}
|
|
4066
|
+
async function fetchReleasedVersion() {
|
|
4067
|
+
try {
|
|
4068
|
+
const res = await fetch("https://raw.githubusercontent.com/mutmutco/MMI-Hub/main/.claude-plugin/plugin.json", {
|
|
4069
|
+
signal: AbortSignal.timeout(5e3)
|
|
4070
|
+
});
|
|
4071
|
+
if (!res.ok) return void 0;
|
|
4072
|
+
return (await res.json()).version;
|
|
4073
|
+
} catch {
|
|
4074
|
+
return void 0;
|
|
4075
|
+
}
|
|
4076
|
+
}
|
|
4077
|
+
var program2 = new Command();
|
|
4078
|
+
program2.name("mmi-cli").description("MMI Future CLI \u2014 org rules delivery, saga, KB. The engine the plugin SessionStart hook drives.").version(resolveVersion());
|
|
4079
|
+
var rules = program2.command("rules").description("org rules delivery");
|
|
4080
|
+
rules.command("sync").option("--quiet", "stay silent unless something changed or errored").description("fetch AGENTS.md / CLAUDE.md / .claude/settings.json from MMI-Hub and write them verbatim (org-owned, whole-file)").action(async (opts) => {
|
|
4081
|
+
const cfg = await loadConfig();
|
|
4082
|
+
if (isRulesSource(cfg.orgRulesSource)) {
|
|
4083
|
+
if (!opts.quiet) console.log('mmi-cli rules: source repo (orgRulesSource: "self") \u2014 skipping self-sync');
|
|
4084
|
+
return;
|
|
4085
|
+
}
|
|
4086
|
+
const base = (cfg.orgRulesSource ?? DEFAULT_RULES_SOURCE).replace(/\/$/, "");
|
|
4087
|
+
let changed = 0;
|
|
4088
|
+
for (const file of ["AGENTS.md", "CLAUDE.md", ".claude/settings.json"]) {
|
|
4089
|
+
let source;
|
|
4090
|
+
try {
|
|
4091
|
+
const res = await fetch(`${base}/${file}`);
|
|
4092
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
4093
|
+
source = await res.text();
|
|
4094
|
+
} catch (e) {
|
|
4095
|
+
if (!opts.quiet) console.error(`mmi-cli rules: could not fetch ${file} (${e.message}); left it untouched`);
|
|
4096
|
+
continue;
|
|
4097
|
+
}
|
|
4098
|
+
const current = (0, import_node_fs2.existsSync)(file) ? await (0, import_promises.readFile)(file, "utf8") : null;
|
|
4099
|
+
if (needsUpdate(source, current)) {
|
|
4100
|
+
const slash = file.lastIndexOf("/");
|
|
4101
|
+
if (slash > 0) (0, import_node_fs2.mkdirSync)(file.slice(0, slash), { recursive: true });
|
|
4102
|
+
await (0, import_promises.writeFile)(file, normalizeEol(source), "utf8");
|
|
4103
|
+
changed++;
|
|
4104
|
+
if (!opts.quiet) console.log(`mmi-cli rules: updated ${file}`);
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
4107
|
+
if (!opts.quiet && changed === 0) console.log("mmi-cli rules: up to date");
|
|
4108
|
+
});
|
|
4109
|
+
var saga = program2.command("saga").description("per-session continuity");
|
|
4110
|
+
async function runNote(summary, o) {
|
|
4111
|
+
const [sha, key] = await Promise.all([gitOut(["rev-parse", "--short", "HEAD"]), sagaKey(await loadConfig())]);
|
|
4112
|
+
const capture = buildNoteCapture(summary, o, (0, import_node_crypto.randomUUID)(), { sha: sha || void 0, branch: key.branch });
|
|
4113
|
+
await postCapture(capture);
|
|
4114
|
+
}
|
|
4115
|
+
saga.command("note <summary>").description("record a one-line structured note into your saga (the per-turn capture)").option("--next <text>", 'set "where I left off" (NEXT)').option("--decision <text>", "append a verbatim decision").option("--queue-add <text>", "add a worklist item").option("--queue-done <n>", "mark worklist item N done").option("--verified", "mark this claim as checked against source (state: verified, else asserted)").option("--diagnostic", "isolate a probe write (state: diagnostic, source: probe) \u2014 never resume/LAST 5").action((summary, o) => runNote(summary, o));
|
|
4116
|
+
saga.command("probe <summary>").description("record a diagnostic probe note (alias for `saga note --diagnostic`)").option("--next <text>", 'set "where I left off" (NEXT)').option("--decision <text>", "append a verbatim decision").option("--queue-add <text>", "add a worklist item").option("--queue-done <n>", "mark worklist item N done").action((summary, o) => runNote(summary, { ...o, diagnostic: true }));
|
|
4117
|
+
saga.command("show").option("--quiet", "no-op silently when unconfigured/unreachable (SessionStart hook)").option("--latest-anywhere", "resume the newest saga across all repos (default: current repo)").description("print your resume block \u2014 current repo HEAD + project memory (where you left off)").action(async (opts) => {
|
|
4118
|
+
const cfg = await loadConfig();
|
|
4119
|
+
if (!cfg.sagaApiUrl) {
|
|
4120
|
+
if (opts.quiet) return;
|
|
4121
|
+
return fail("saga: sagaApiUrl not configured in .mmi/config.json");
|
|
4122
|
+
}
|
|
4123
|
+
try {
|
|
4124
|
+
const key = await sagaKey(cfg);
|
|
4125
|
+
const qs = opts.latestAnywhere ? "scope=anywhere" : new URLSearchParams({ project: key.project, branch: key.branch }).toString();
|
|
4126
|
+
const res = await fetch(`${cfg.sagaApiUrl}/saga/head?${qs}`, { headers: await sagaHeaders(), signal: AbortSignal.timeout(8e3) });
|
|
4127
|
+
if (res.ok) return console.log(await res.text());
|
|
4128
|
+
if (!opts.quiet) console.log(`saga show failed: HTTP ${res.status}`);
|
|
4129
|
+
} catch (e) {
|
|
4130
|
+
if (!opts.quiet) console.error(`saga show: ${e.message}`);
|
|
4131
|
+
}
|
|
4132
|
+
});
|
|
4133
|
+
saga.command("capture").option("--quiet", "capture silently (for the Stop hook)").description("per-turn deterministic capture (Stop hook): turn boundary + current sha").action(async (opts) => {
|
|
4134
|
+
const hook = parseHookInput(await readStdin());
|
|
4135
|
+
if (hook.session_id) persistSession(hook.session_id);
|
|
4136
|
+
await postCapture({ event: "stop", id: (0, import_node_crypto.randomUUID)(), source: "hook", sha: await gitOut(["rev-parse", "--short", "HEAD"]), surface: process.env.MMI_AGENT_SURFACE || "claude" }, opts.quiet ?? false);
|
|
4137
|
+
});
|
|
4138
|
+
saga.command("session").option("--quiet", "silent (for the SessionStart hook)").description("persist the harness session id for this repo (SessionStart hook)").action(async () => {
|
|
4139
|
+
const hook = parseHookInput(await readStdin());
|
|
4140
|
+
if (hook.session_id) persistSession(hook.session_id);
|
|
4141
|
+
});
|
|
4142
|
+
saga.command("head-update").option("--run", "detached worker: fetch state, run the engine, post the curated HEAD").option("--quiet", "silent (Stop hook)").description("curate the smart HEAD in the background (engine via SAGA_HEAD_ENGINE; default local claude)").action(async (o) => {
|
|
4143
|
+
if (!o.run) {
|
|
4144
|
+
const gateKey = await sagaKey(await loadConfig());
|
|
4145
|
+
const tsPath = headTsPath(gateKey);
|
|
4146
|
+
if (!headGateDue(tsPath)) return;
|
|
4147
|
+
markHeadRun(tsPath);
|
|
4148
|
+
try {
|
|
4149
|
+
(0, import_node_child_process3.spawn)(process.execPath, [process.argv[1], "saga", "head-update", "--run"], {
|
|
4150
|
+
detached: true,
|
|
4151
|
+
stdio: "ignore",
|
|
4152
|
+
windowsHide: true
|
|
4153
|
+
}).unref();
|
|
4154
|
+
} catch {
|
|
4155
|
+
}
|
|
4156
|
+
return;
|
|
4157
|
+
}
|
|
4158
|
+
try {
|
|
4159
|
+
const cfg = await loadConfig();
|
|
4160
|
+
if (!cfg.sagaApiUrl) return;
|
|
4161
|
+
const key = await sagaKey(cfg);
|
|
4162
|
+
const qs = new URLSearchParams(key).toString();
|
|
4163
|
+
const res = await fetch(`${cfg.sagaApiUrl}/saga/state?${qs}`, { headers: await sagaHeaders(), signal: AbortSignal.timeout(8e3) });
|
|
4164
|
+
if (!res.ok) return;
|
|
4165
|
+
const state = await res.json();
|
|
4166
|
+
if (!state.actionLog?.length) return;
|
|
4167
|
+
const update = parseHeadUpdate(await runHeadEngine(headPrompt(state)));
|
|
4168
|
+
if (!update) return;
|
|
4169
|
+
await fetch(`${cfg.sagaApiUrl}/saga/head`, {
|
|
4170
|
+
method: "POST",
|
|
4171
|
+
headers: await sagaHeaders({ "content-type": "application/json" }),
|
|
4172
|
+
body: JSON.stringify({ ...update, ...key }),
|
|
4173
|
+
signal: AbortSignal.timeout(2e4)
|
|
4174
|
+
});
|
|
4175
|
+
} catch {
|
|
4176
|
+
}
|
|
4177
|
+
});
|
|
4178
|
+
saga.command("key").option("--json", "machine-readable output").description("print the resolved saga key + session-id source (no write)").action(async (o) => {
|
|
4179
|
+
const cfg = await loadConfig();
|
|
4180
|
+
const session = resolveSessionId();
|
|
4181
|
+
const key = await sagaKey(cfg, session);
|
|
4182
|
+
const source = session.source;
|
|
4183
|
+
if (o.json) return console.log(JSON.stringify({ ...key, source }));
|
|
4184
|
+
console.log(`project=${key.project} branch=${key.branch} session=${key.sessionId} source=${source}`);
|
|
4185
|
+
});
|
|
4186
|
+
async function probeBackend(url) {
|
|
4187
|
+
try {
|
|
4188
|
+
const res = await fetch(`${url}/saga/head`, { headers: await sagaHeaders(), signal: AbortSignal.timeout(8e3) });
|
|
4189
|
+
return res.ok;
|
|
4190
|
+
} catch {
|
|
4191
|
+
return false;
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
saga.command("health").option("--json", "machine-readable output").option("--banner", "one-line SessionStart banner; silent when healthy").option("--quiet", "suppress detail output").description("zero-write health check: auth, backend reachability, resolved key").action(async (o) => {
|
|
4195
|
+
const cfg = await loadConfig();
|
|
4196
|
+
const session = resolveSessionId();
|
|
4197
|
+
const key = await sagaKey(cfg, session);
|
|
4198
|
+
const source = session.source;
|
|
4199
|
+
const identity = await githubLogin();
|
|
4200
|
+
const reachable = cfg.sagaApiUrl ? await probeBackend(cfg.sagaApiUrl) : false;
|
|
4201
|
+
const report = buildHealth({ key, source, identity, reachable, sagaApiUrl: cfg.sagaApiUrl });
|
|
4202
|
+
if (o.json) return console.log(JSON.stringify(report));
|
|
4203
|
+
if (o.banner) {
|
|
4204
|
+
const banner = healthBanner(report);
|
|
4205
|
+
if (banner) console.log(banner);
|
|
4206
|
+
return;
|
|
4207
|
+
}
|
|
4208
|
+
if (o.quiet) return;
|
|
4209
|
+
console.log(`saga health: ${report.ok ? "OK" : "NOT OK"}`);
|
|
4210
|
+
if (report.problems.length) console.log(report.problems.map((p) => ` - ${p}`).join("\n"));
|
|
4211
|
+
});
|
|
4212
|
+
program2.command("gc").description("dry-run cleanup for merged/closed PR branches and stale tracking refs").option("--dry-run", "show what would be deleted (default)").option("--apply", "delete only the listed clean merged/closed PR branches and stale tracking refs").option("--json", "machine-readable output").option("--remote <name>", "remote name", "origin").option("--limit <n>", "PRs to inspect per state", "200").action(async (o) => {
|
|
4213
|
+
if (o.apply && o.dryRun) return fail("gc: choose either --dry-run or --apply");
|
|
4214
|
+
const limit = Number.parseInt(o.limit, 10);
|
|
4215
|
+
if (!Number.isFinite(limit) || limit < 1) return fail("gc: --limit must be a positive integer");
|
|
4216
|
+
try {
|
|
4217
|
+
const plan = await gcPlan(o.remote, limit);
|
|
4218
|
+
if (o.apply) await applyGcPlan(plan, o.remote);
|
|
4219
|
+
if (o.json) return console.log(JSON.stringify({ dryRun: !o.apply, remote: o.remote, plan }, null, 2));
|
|
4220
|
+
console.log(formatGcPlan(plan, Boolean(o.apply)));
|
|
4221
|
+
} catch (e) {
|
|
4222
|
+
fail(`gc: ${e.message}`);
|
|
4223
|
+
}
|
|
4224
|
+
});
|
|
4225
|
+
program2.command("kb").description("org knowledgebase (read-only)").command("get <path>").description("print a KB document by path").action(async (path) => {
|
|
4226
|
+
const cfg = await loadConfig();
|
|
4227
|
+
const base = (cfg.kbSource ?? DEFAULT_KB_SOURCE).replace(/\/$/, "");
|
|
4228
|
+
const res = await fetch(`${base}/${path.replace(/^\//, "")}`);
|
|
4229
|
+
console.log(res.ok ? await res.text() : `kb get failed: HTTP ${res.status}`);
|
|
4230
|
+
});
|
|
4231
|
+
async function ghCreate(args) {
|
|
4232
|
+
try {
|
|
4233
|
+
const { stdout } = await execFileP2("gh", args);
|
|
4234
|
+
return parseCreatedUrl(stdout);
|
|
4235
|
+
} catch (e) {
|
|
4236
|
+
const err = e;
|
|
4237
|
+
fail(`gh ${args[0]} create failed: ${(err.stderr || err.message || String(e)).trim()}`);
|
|
4238
|
+
}
|
|
4239
|
+
}
|
|
4240
|
+
async function ghJson(args, timeout = 1e4) {
|
|
4241
|
+
const { stdout } = await execFileP2("gh", args, { timeout });
|
|
4242
|
+
return JSON.parse(stdout);
|
|
4243
|
+
}
|
|
4244
|
+
async function resolveRepo(repo) {
|
|
4245
|
+
if (repo) return repo;
|
|
4246
|
+
try {
|
|
4247
|
+
const { stdout } = await execFileP2("gh", ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"], { timeout: 5e3 });
|
|
4248
|
+
return stdout.trim() || void 0;
|
|
4249
|
+
} catch {
|
|
4250
|
+
return void 0;
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
function scheduleRelatedDiscovery(o) {
|
|
4254
|
+
try {
|
|
4255
|
+
const args = ["issue", "discover-related", "--number", String(o.number), "--title", o.title, "--body", o.body];
|
|
4256
|
+
if (o.repo) args.push("--repo", o.repo);
|
|
4257
|
+
(0, import_node_child_process3.spawn)(process.execPath, [process.argv[1], ...args], {
|
|
4258
|
+
detached: true,
|
|
4259
|
+
stdio: "ignore",
|
|
4260
|
+
windowsHide: true,
|
|
4261
|
+
cwd: process.cwd()
|
|
4262
|
+
}).unref();
|
|
4263
|
+
} catch {
|
|
4264
|
+
}
|
|
4265
|
+
}
|
|
4266
|
+
var issue = program2.command("issue").description("issues \u2014 reliable create with structured output");
|
|
4267
|
+
issue.command("create").description("create an issue (type \u2192 label) and print {number,url,label} JSON").requiredOption("--type <type>", "bug | feature | task (sets the matching label)").requiredOption("--title <title>", "issue title").requiredOption("--body <body>", "issue body (markdown)").requiredOption("--priority <priority>", "high | medium | low (adds a priority:<p> label)").option("--repo <owner/repo>", "target repo (defaults to the current repo)").action(async (o) => {
|
|
4268
|
+
let args;
|
|
4269
|
+
try {
|
|
4270
|
+
args = buildIssueArgs({ type: o.type, title: o.title, body: o.body, priority: o.priority, repo: o.repo });
|
|
4271
|
+
} catch (e) {
|
|
4272
|
+
return fail(`issue create: ${e.message}`);
|
|
4273
|
+
}
|
|
4274
|
+
const created = await ghCreate(args);
|
|
4275
|
+
scheduleRelatedDiscovery({ repo: o.repo, number: created.number, title: o.title, body: o.body });
|
|
4276
|
+
console.log(JSON.stringify({ ...created, label: o.type, priority: o.priority }));
|
|
4277
|
+
});
|
|
4278
|
+
issue.command("discover-related").description("find related issues for an existing issue and post only high-confidence links").requiredOption("--number <number>", "created issue number").requiredOption("--title <title>", "created issue title").requiredOption("--body <body>", "created issue body").option("--repo <owner/repo>", "target repo (defaults to the current repo)").option("--json", "print candidates instead of posting").action(async (o) => {
|
|
4279
|
+
const number = Number(o.number);
|
|
4280
|
+
if (!Number.isInteger(number) || number <= 0) return fail("issue discover-related: --number must be a positive integer");
|
|
4281
|
+
const repo = await resolveRepo(o.repo);
|
|
4282
|
+
if (!repo) return fail("issue discover-related: could not resolve repo");
|
|
4283
|
+
try {
|
|
4284
|
+
const issues = await ghJson([
|
|
4285
|
+
"issue",
|
|
4286
|
+
"list",
|
|
4287
|
+
"--repo",
|
|
4288
|
+
repo,
|
|
4289
|
+
"--state",
|
|
4290
|
+
"open",
|
|
4291
|
+
"--limit",
|
|
4292
|
+
"100",
|
|
4293
|
+
"--json",
|
|
4294
|
+
"number,title,body,url"
|
|
4295
|
+
]);
|
|
4296
|
+
const candidates = findRelatedIssues({ number, title: o.title, body: o.body }, issues);
|
|
4297
|
+
if (o.json) return console.log(JSON.stringify({ number, repo, candidates }, null, 2));
|
|
4298
|
+
if (!candidates.length) return;
|
|
4299
|
+
const viewed = await ghJson([
|
|
4300
|
+
"issue",
|
|
4301
|
+
"view",
|
|
4302
|
+
String(number),
|
|
4303
|
+
"--repo",
|
|
4304
|
+
repo,
|
|
4305
|
+
"--json",
|
|
4306
|
+
"comments"
|
|
4307
|
+
]);
|
|
4308
|
+
if (viewed.comments.some((comment) => comment.body.includes(relatedMarker(number)))) return;
|
|
4309
|
+
await execFileP2("gh", ["issue", "comment", String(number), "--repo", repo, "--body", buildRelatedComment(number, candidates)], { timeout: 1e4 });
|
|
4310
|
+
} catch {
|
|
4311
|
+
}
|
|
4312
|
+
});
|
|
4313
|
+
var pr = program2.command("pr").description("pull requests \u2014 reliable create with structured output");
|
|
4314
|
+
pr.command("create").description("create a PR and print {number,url} JSON").requiredOption("--title <title>", "PR title").requiredOption("--body <body>", "PR body (markdown)").option("--base <branch>", "base branch (defaults to the repo default)").option("--head <branch>", "head branch (defaults to the current branch)").option("--repo <owner/repo>", "target repo (defaults to the current repo)").action(async (o) => {
|
|
4315
|
+
const created = await ghCreate(buildPrArgs({ title: o.title, body: o.body, base: o.base, head: o.head, repo: o.repo }));
|
|
4316
|
+
console.log(JSON.stringify(created));
|
|
4317
|
+
});
|
|
4318
|
+
async function runBoardRead(o) {
|
|
4319
|
+
try {
|
|
4320
|
+
const report = await readBoard({
|
|
4321
|
+
config: await loadConfig(),
|
|
4322
|
+
repo: o.repo,
|
|
4323
|
+
includeBundleDetails: o.bundleDetails,
|
|
4324
|
+
allowPartial: o.allowPartial
|
|
4325
|
+
});
|
|
4326
|
+
console.log(o.json ? JSON.stringify(report) : renderBoardReport(report));
|
|
4327
|
+
} catch (e) {
|
|
4328
|
+
fail(`board read failed: ${e.message}`);
|
|
4329
|
+
}
|
|
4330
|
+
}
|
|
4331
|
+
var board = program2.command("board").description("read and claim Project v2 work items for the current repo");
|
|
4332
|
+
board.command("read", { isDefault: true }).description("read the board and print user-owned, claimable, and taken items").option("--json", "machine-readable output").option("--repo <owner/repo>", "current repo (defaults to git origin)").option("--bundle-details", "fetch body/comments only for user-owned and claimable issues").option("--allow-partial", "return partial board results when later page/detail reads fail").action((o) => runBoardRead(o));
|
|
4333
|
+
board.command("claim <issue>").description("assign a Todo issue to you and move its Project v2 Status to In Progress").option("--json", "machine-readable output").option("--repo <owner/repo>", "current repo for local issue numbers (defaults to git origin)").option("--allow-partial", "return success JSON if assignment succeeds but the status move fails").action(async (issueRef, o) => {
|
|
4334
|
+
try {
|
|
4335
|
+
const result = await claimBoardIssue({ config: await loadConfig(), selector: issueRef, repo: o.repo, allowPartial: o.allowPartial });
|
|
4336
|
+
if (o.json) return console.log(JSON.stringify(result));
|
|
4337
|
+
console.log(result.partial ? `Partially claimed ${result.item.ref}: ${result.warning}` : `Claimed ${result.item.ref} - In Progress`);
|
|
4338
|
+
} catch (e) {
|
|
4339
|
+
fail(`board claim failed: ${e.message}`);
|
|
4340
|
+
}
|
|
4341
|
+
});
|
|
4342
|
+
function renderSteps(title, steps) {
|
|
4343
|
+
return [
|
|
4344
|
+
title,
|
|
4345
|
+
...steps.map((step, i) => `${i + 1}. ${step.gated ? "[gated] " : ""}${step.label}${step.command ? ` - ${step.command}` : ""}`)
|
|
4346
|
+
].join("\n");
|
|
4347
|
+
}
|
|
4348
|
+
program2.command("stage").description("plan or run the repo local stage environment").option("--json", "machine-readable output").option("--apply", "reserved for future stage execution; requires repo stage config").action(async (o) => {
|
|
4349
|
+
if (o.apply) return fail("stage: execution is not implemented yet; use the dry-run plan and the existing /stage skill");
|
|
4350
|
+
const steps = stagePlan((await loadConfig()).stage);
|
|
4351
|
+
console.log(o.json ? JSON.stringify({ command: "stage", steps }, null, 2) : renderSteps("mmi-cli stage: dry-run plan", steps));
|
|
4352
|
+
});
|
|
4353
|
+
for (const commandName of ["rc", "release", "hotfix"]) {
|
|
4354
|
+
program2.command(commandName).description(`plan ${commandName} train operations; mutations require explicit approval`).option("--json", "machine-readable output").option("--apply", "reserved for future train execution after explicit admin approval").action((o) => {
|
|
4355
|
+
if (o.apply) return fail(`${commandName}: execution is not implemented yet; use the dry-run plan and the existing /${commandName} skill`);
|
|
4356
|
+
const steps = trainPlan(commandName);
|
|
4357
|
+
console.log(o.json ? JSON.stringify({ command: commandName, steps }, null, 2) : renderSteps(`mmi-cli ${commandName}: dry-run plan`, steps));
|
|
4358
|
+
});
|
|
4359
|
+
}
|
|
4360
|
+
program2.command("bootstrap").description("plan repo bootstrap operations; mutations require master-admin approval").requiredOption("--repo <owner/repo>", "target repo").option("--class <class>", "deployable | content", "deployable").option("--json", "machine-readable output").option("--apply", "reserved for future bootstrap execution after explicit master-admin approval").action((o) => {
|
|
4361
|
+
if (o.apply) return fail("bootstrap: execution is not implemented yet; use the dry-run plan and the existing /bootstrap skill");
|
|
4362
|
+
if (o.class !== "deployable" && o.class !== "content") return fail("bootstrap: --class must be deployable or content");
|
|
4363
|
+
const steps = bootstrapPlan(o.repo, o.class);
|
|
4364
|
+
console.log(o.json ? JSON.stringify({ command: "bootstrap", repo: o.repo, class: o.class, steps }, null, 2) : renderSteps(`mmi-cli bootstrap: dry-run plan for ${o.repo}`, steps));
|
|
4365
|
+
});
|
|
4366
|
+
var isWin = process.platform === "win32";
|
|
4367
|
+
program2.command("doctor").description("check onboarding gates (GitHub auth, mmi-cli on PATH, repo config, plugin git clone) and print fixes").option("--banner", "one-line resume summary; silent when all gates pass").option("--json", "machine-readable output").action(async (opts) => {
|
|
4368
|
+
const checks = [];
|
|
4369
|
+
const token = await githubToken();
|
|
4370
|
+
let ghFix = "run: gh auth login";
|
|
4371
|
+
if (!token) {
|
|
4372
|
+
try {
|
|
4373
|
+
await execFileP2("gh", ["--version"]);
|
|
4374
|
+
} catch {
|
|
4375
|
+
ghFix = "install GitHub CLI (https://cli.github.com), then: gh auth login";
|
|
4376
|
+
}
|
|
4377
|
+
}
|
|
4378
|
+
checks.push({ ok: Boolean(token), label: "GitHub auth (saga + gh ops)", fix: ghFix });
|
|
4379
|
+
let onPath = false;
|
|
4380
|
+
try {
|
|
4381
|
+
await execFileP2(isWin ? "where" : "which", ["mmi-cli"]);
|
|
4382
|
+
onPath = true;
|
|
4383
|
+
} catch {
|
|
4384
|
+
}
|
|
4385
|
+
if (!onPath) {
|
|
4386
|
+
const root = process.env.CLAUDE_PLUGIN_ROOT;
|
|
4387
|
+
if (root && (0, import_node_fs2.existsSync)(`${root}/bin/mmi-cli${isWin ? ".cmd" : ""}`)) onPath = true;
|
|
4388
|
+
}
|
|
4389
|
+
checks.push({ ok: onPath, label: "mmi-cli on PATH", fix: "auto-provisioned at session start \u2014 reopen the session, or install the MMI plugin" });
|
|
4390
|
+
checks.push(buildVersionLagReport({
|
|
4391
|
+
currentVersion: resolveVersion(),
|
|
4392
|
+
repoVersion: readRepoVersion(),
|
|
4393
|
+
releasedVersion: await fetchReleasedVersion()
|
|
4394
|
+
}));
|
|
4395
|
+
const cfg = await loadConfig();
|
|
4396
|
+
checks.push({ ok: Boolean(cfg.sagaApiUrl), label: "repo config (.mmi/config.json)", fix: "ask a master-admin to run /bootstrap on this repo" });
|
|
4397
|
+
const REWRITE_KEY = "url.https://github.com/.insteadOf";
|
|
4398
|
+
const CLONE_FIX = 'run: git config --global url."https://github.com/".insteadOf "git@github.com:"';
|
|
4399
|
+
let cloneOk = false;
|
|
4400
|
+
try {
|
|
4401
|
+
const { stdout } = await execFileP2("git", ["config", "--global", "--get-all", REWRITE_KEY]);
|
|
4402
|
+
cloneOk = stdout.split("\n").some((l) => l.trim() === "git@github.com:");
|
|
4403
|
+
} catch {
|
|
4404
|
+
}
|
|
4405
|
+
if (!cloneOk) {
|
|
4406
|
+
try {
|
|
4407
|
+
await execFileP2("git", ["config", "--global", "--add", REWRITE_KEY, "git@github.com:"]);
|
|
4408
|
+
cloneOk = true;
|
|
4409
|
+
if (!opts.banner && !opts.json) console.error(" \u21BB repaired: git insteadOf git@github.com \u2192 https (plugin clone over HTTPS)");
|
|
4410
|
+
} catch {
|
|
4411
|
+
}
|
|
4412
|
+
}
|
|
4413
|
+
checks.push({ ok: cloneOk, label: "plugin git clone (SSH\u2192HTTPS rewrite)", fix: CLONE_FIX });
|
|
4414
|
+
const gaps = checks.filter((c) => !c.ok);
|
|
4415
|
+
if (opts.json) {
|
|
4416
|
+
console.log(JSON.stringify({ ok: gaps.length === 0, checks }, null, 2));
|
|
4417
|
+
return;
|
|
4418
|
+
}
|
|
4419
|
+
if (opts.banner) {
|
|
4420
|
+
if (gaps.length) console.log(`\u26A0 MMI setup needed \u2014 ${gaps.map((g) => g.fix).join(" \xB7 ")}`);
|
|
4421
|
+
return;
|
|
4422
|
+
}
|
|
4423
|
+
for (const c of checks) console.log(c.ok ? `\u2713 ${c.label}` : `\u2717 ${c.label}
|
|
4424
|
+
\u2192 ${c.fix}`);
|
|
4425
|
+
console.log(gaps.length ? `
|
|
4426
|
+
${gaps.length} item(s) need attention.` : "\nAll set \u2014 you are ready.");
|
|
4427
|
+
});
|
|
4428
|
+
function fail(msg) {
|
|
4429
|
+
console.error(`mmi-cli ${msg}`);
|
|
4430
|
+
process.exit(1);
|
|
4431
|
+
}
|
|
4432
|
+
program2.parseAsync();
|