@mu-crew/mu 3.12.0 → 3.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-3BARPJLY.js +44 -0
- package/dist/{chunk-R2SVBZAB.js → chunk-45KQLMEL.js} +193 -93
- package/dist/chunk-45KQLMEL.js.map +1 -0
- package/dist/{chunk-XV7J56GD.js → chunk-G434JKV2.js} +4 -3
- package/dist/{chunk-XV7J56GD.js.map → chunk-G434JKV2.js.map} +1 -1
- package/dist/{chunk-IRPTNVJC.js → chunk-KUGUFBWH.js} +8622 -6026
- package/dist/chunk-KUGUFBWH.js.map +1 -0
- package/dist/{chunk-77GBZ2KR.js → chunk-QITLNZEM.js} +3 -1
- package/dist/{chunk-77GBZ2KR.js.map → chunk-QITLNZEM.js.map} +1 -1
- package/dist/{chunk-TEGZOXML.js → chunk-VIEYQMQA.js} +12 -10
- package/dist/chunk-VIEYQMQA.js.map +1 -0
- package/dist/{chunk-L2ABBTYG.js → chunk-WI6AWCMK.js} +3 -1
- package/dist/{chunk-L2ABBTYG.js.map → chunk-WI6AWCMK.js.map} +1 -1
- package/dist/{cli-MDCJEU74.js → cli-CKOMHBXV.js} +3581 -107
- package/dist/cli-CKOMHBXV.js.map +1 -0
- package/dist/cli.js +4 -3
- package/dist/cli.js.map +1 -1
- package/dist/devtools-LS4ZEPWM.js +3772 -0
- package/dist/devtools-LS4ZEPWM.js.map +1 -0
- package/dist/extension/mu-pi.js +206 -61
- package/dist/extension/mu-pi.js.map +1 -1
- package/dist/index.d.ts +309 -228
- package/dist/index.js +12 -5
- package/dist/tui-LFJ5P4Y2.js +40956 -0
- package/dist/tui-LFJ5P4Y2.js.map +1 -0
- package/dist/tui-sync-worker.js +4 -3
- package/dist/tui-sync-worker.js.map +1 -1
- package/dist/yank-XDOONQSL.js +13 -0
- package/docs/ARCHITECTURE.md +4 -1
- package/docs/ROADMAP.md +43 -38
- package/docs/VISION.md +8 -0
- package/docs/VOCABULARY.md +3 -1
- package/docs/architecture/dag.md +4 -0
- package/docs/architecture/sync.md +8 -0
- package/docs/architecture/tui.md +11 -2
- package/docs/guide/delegate.md +6 -4
- package/docs/guide/recovery.md +4 -0
- package/docs/reference/env.md +2 -2
- package/package.json +2 -1
- package/skills/mu/SKILL.md +12 -2
- package/skills/mu/recipes/adversarial-review.md +3 -0
- package/skills/mu/recipes/backlog-triage.md +2 -0
- package/skills/mu/recipes/findings.md +7 -0
- package/skills/mu/recipes/long-run.md +3 -1
- package/skills/mu/recipes/loop-until-done.md +3 -1
- package/skills/mu/recipes/orchestrator-loop.md +4 -0
- package/skills/mu/recipes/ultrathink.md +3 -1
- package/skills/mu/recipes/watcher.md +6 -1
- package/dist/chunk-IRPTNVJC.js.map +0 -1
- package/dist/chunk-PZ5AY32C.js +0 -10
- package/dist/chunk-R2SVBZAB.js.map +0 -1
- package/dist/chunk-TEGZOXML.js.map +0 -1
- package/dist/cli-MDCJEU74.js.map +0 -1
- package/dist/tui-LO75XA3O.js +0 -6452
- package/dist/tui-LO75XA3O.js.map +0 -1
- package/dist/yank-T3AYQTVR.js +0 -12
- /package/dist/{chunk-PZ5AY32C.js.map → chunk-3BARPJLY.js.map} +0 -0
- /package/dist/{yank-T3AYQTVR.js.map → yank-XDOONQSL.js.map} +0 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createRequire as __muCreateRequire } from "node:module"; const require = __muCreateRequire(import.meta.url);
|
|
1
2
|
import {
|
|
2
3
|
NothingToUndoError,
|
|
3
4
|
UndoGroupNotFoundError,
|
|
@@ -6,7 +7,7 @@ import {
|
|
|
6
7
|
planUndo,
|
|
7
8
|
resolveGroupId,
|
|
8
9
|
undoGroup
|
|
9
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-G434JKV2.js";
|
|
10
11
|
import {
|
|
11
12
|
IDLE_GLYPH,
|
|
12
13
|
TASK_SORT_KEYS,
|
|
@@ -28,19 +29,21 @@ import {
|
|
|
28
29
|
statusIcon,
|
|
29
30
|
truncate,
|
|
30
31
|
truncateFront
|
|
31
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-VIEYQMQA.js";
|
|
32
33
|
import {
|
|
33
34
|
AgentAbortNeedsCtlError,
|
|
34
35
|
AgentAbortTimeoutError,
|
|
35
36
|
AgentBusyError,
|
|
36
37
|
AgentCtlUnreachableError,
|
|
37
38
|
AgentDiedOnSpawnError,
|
|
39
|
+
AgentEmptySendError,
|
|
38
40
|
AgentExistsError,
|
|
39
41
|
AgentExtensionOutdatedError,
|
|
40
42
|
AgentFreshNeedsCtlError,
|
|
41
43
|
AgentNameExhaustedError,
|
|
42
44
|
AgentNotFoundError,
|
|
43
45
|
AgentNotInWorkstreamError,
|
|
46
|
+
AgentSendIndeterminateError,
|
|
44
47
|
AgentSlashCommandUnsupportedError,
|
|
45
48
|
AgentSpawnCliNotFoundError,
|
|
46
49
|
AgentSpawnStartupError,
|
|
@@ -63,6 +66,7 @@ import {
|
|
|
63
66
|
MAX_SOCK_PATH,
|
|
64
67
|
MuxError,
|
|
65
68
|
NoMultiplexerError,
|
|
69
|
+
OPS_ENTITIES_SQL,
|
|
66
70
|
PaneNotFoundError,
|
|
67
71
|
PaneNotInSessionError,
|
|
68
72
|
ReaperDetectedDuringWaitError,
|
|
@@ -85,6 +89,7 @@ import {
|
|
|
85
89
|
WorkspaceDirtyError,
|
|
86
90
|
WorkspaceExistsError,
|
|
87
91
|
WorkspaceNotFoundError,
|
|
92
|
+
WorkspaceOwnerBusyError,
|
|
88
93
|
WorkspacePathNotEmptyError,
|
|
89
94
|
WorkspacePreservedError,
|
|
90
95
|
WorkspaceVcsRequiredError,
|
|
@@ -103,6 +108,7 @@ import {
|
|
|
103
108
|
appendLog,
|
|
104
109
|
assertWorkstreamInitable,
|
|
105
110
|
backendByName,
|
|
111
|
+
blockedReason,
|
|
106
112
|
checkCheapDriftInvariant,
|
|
107
113
|
checkDrift,
|
|
108
114
|
checkFleetHazards,
|
|
@@ -123,6 +129,7 @@ import {
|
|
|
123
129
|
ensureWorkstream,
|
|
124
130
|
ensureWorkstreamSession,
|
|
125
131
|
expectsCtl,
|
|
132
|
+
findEdgeCycles,
|
|
126
133
|
findRemoteDispatch,
|
|
127
134
|
formatDriftRecord,
|
|
128
135
|
freeWorkspace,
|
|
@@ -206,7 +213,7 @@ import {
|
|
|
206
213
|
waitForAgents,
|
|
207
214
|
waitForTasks,
|
|
208
215
|
weakDecisionWarning
|
|
209
|
-
} from "./chunk-
|
|
216
|
+
} from "./chunk-KUGUFBWH.js";
|
|
210
217
|
import {
|
|
211
218
|
CURRENT_SCHEMA_VERSION,
|
|
212
219
|
EXPECTED_TABLES,
|
|
@@ -236,17 +243,3384 @@ import {
|
|
|
236
243
|
transportNextSteps,
|
|
237
244
|
tryResolveWorkstreamId,
|
|
238
245
|
withOpContext
|
|
239
|
-
} from "./chunk-
|
|
246
|
+
} from "./chunk-45KQLMEL.js";
|
|
240
247
|
import {
|
|
241
248
|
defaultStateDir
|
|
242
|
-
} from "./chunk-
|
|
243
|
-
import "./chunk-
|
|
249
|
+
} from "./chunk-WI6AWCMK.js";
|
|
250
|
+
import "./chunk-3BARPJLY.js";
|
|
244
251
|
|
|
245
252
|
// src/cli.ts
|
|
246
253
|
import { readFileSync } from "fs";
|
|
247
|
-
import { dirname as
|
|
254
|
+
import { dirname as dirname8, join as join2 } from "path";
|
|
248
255
|
import { fileURLToPath } from "url";
|
|
249
|
-
|
|
256
|
+
|
|
257
|
+
// node_modules/commander/lib/error.js
|
|
258
|
+
var CommanderError = class extends Error {
|
|
259
|
+
/**
|
|
260
|
+
* Constructs the CommanderError class
|
|
261
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
262
|
+
* @param {string} code an id string representing the error
|
|
263
|
+
* @param {string} message human-readable description of the error
|
|
264
|
+
*/
|
|
265
|
+
constructor(exitCode, code, message) {
|
|
266
|
+
super(message);
|
|
267
|
+
Error.captureStackTrace(this, this.constructor);
|
|
268
|
+
this.name = this.constructor.name;
|
|
269
|
+
this.code = code;
|
|
270
|
+
this.exitCode = exitCode;
|
|
271
|
+
this.nestedError = void 0;
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
275
|
+
/**
|
|
276
|
+
* Constructs the InvalidArgumentError class
|
|
277
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
278
|
+
*/
|
|
279
|
+
constructor(message) {
|
|
280
|
+
super(1, "commander.invalidArgument", message);
|
|
281
|
+
Error.captureStackTrace(this, this.constructor);
|
|
282
|
+
this.name = this.constructor.name;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// node_modules/commander/lib/argument.js
|
|
287
|
+
var Argument = class {
|
|
288
|
+
/**
|
|
289
|
+
* Initialize a new command argument with the given name and description.
|
|
290
|
+
* The default is that the argument is required, and you can explicitly
|
|
291
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
292
|
+
*
|
|
293
|
+
* @param {string} name
|
|
294
|
+
* @param {string} [description]
|
|
295
|
+
*/
|
|
296
|
+
constructor(name, description) {
|
|
297
|
+
this.description = description || "";
|
|
298
|
+
this.variadic = false;
|
|
299
|
+
this.parseArg = void 0;
|
|
300
|
+
this.defaultValue = void 0;
|
|
301
|
+
this.defaultValueDescription = void 0;
|
|
302
|
+
this.argChoices = void 0;
|
|
303
|
+
switch (name[0]) {
|
|
304
|
+
case "<":
|
|
305
|
+
this.required = true;
|
|
306
|
+
this._name = name.slice(1, -1);
|
|
307
|
+
break;
|
|
308
|
+
case "[":
|
|
309
|
+
this.required = false;
|
|
310
|
+
this._name = name.slice(1, -1);
|
|
311
|
+
break;
|
|
312
|
+
default:
|
|
313
|
+
this.required = true;
|
|
314
|
+
this._name = name;
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
if (this._name.endsWith("...")) {
|
|
318
|
+
this.variadic = true;
|
|
319
|
+
this._name = this._name.slice(0, -3);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Return argument name.
|
|
324
|
+
*
|
|
325
|
+
* @return {string}
|
|
326
|
+
*/
|
|
327
|
+
name() {
|
|
328
|
+
return this._name;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* @package
|
|
332
|
+
*/
|
|
333
|
+
_collectValue(value, previous) {
|
|
334
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
335
|
+
return [value];
|
|
336
|
+
}
|
|
337
|
+
previous.push(value);
|
|
338
|
+
return previous;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
342
|
+
*
|
|
343
|
+
* @param {*} value
|
|
344
|
+
* @param {string} [description]
|
|
345
|
+
* @return {Argument}
|
|
346
|
+
*/
|
|
347
|
+
default(value, description) {
|
|
348
|
+
this.defaultValue = value;
|
|
349
|
+
this.defaultValueDescription = description;
|
|
350
|
+
return this;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
354
|
+
*
|
|
355
|
+
* @param {Function} [fn]
|
|
356
|
+
* @return {Argument}
|
|
357
|
+
*/
|
|
358
|
+
argParser(fn) {
|
|
359
|
+
this.parseArg = fn;
|
|
360
|
+
return this;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Only allow argument value to be one of choices.
|
|
364
|
+
*
|
|
365
|
+
* @param {string[]} values
|
|
366
|
+
* @return {Argument}
|
|
367
|
+
*/
|
|
368
|
+
choices(values) {
|
|
369
|
+
this.argChoices = values.slice();
|
|
370
|
+
this.parseArg = (arg, previous) => {
|
|
371
|
+
if (!this.argChoices.includes(arg)) {
|
|
372
|
+
throw new InvalidArgumentError(
|
|
373
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
if (this.variadic) {
|
|
377
|
+
return this._collectValue(arg, previous);
|
|
378
|
+
}
|
|
379
|
+
return arg;
|
|
380
|
+
};
|
|
381
|
+
return this;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Make argument required.
|
|
385
|
+
*
|
|
386
|
+
* @returns {Argument}
|
|
387
|
+
*/
|
|
388
|
+
argRequired() {
|
|
389
|
+
this.required = true;
|
|
390
|
+
return this;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Make argument optional.
|
|
394
|
+
*
|
|
395
|
+
* @returns {Argument}
|
|
396
|
+
*/
|
|
397
|
+
argOptional() {
|
|
398
|
+
this.required = false;
|
|
399
|
+
return this;
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
function humanReadableArgName(arg) {
|
|
403
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
404
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// node_modules/commander/lib/command.js
|
|
408
|
+
import { EventEmitter } from "events";
|
|
409
|
+
import childProcess from "child_process";
|
|
410
|
+
import path from "path";
|
|
411
|
+
import fs from "fs";
|
|
412
|
+
import process2 from "process";
|
|
413
|
+
import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
|
|
414
|
+
|
|
415
|
+
// node_modules/commander/lib/help.js
|
|
416
|
+
import { stripVTControlCharacters } from "util";
|
|
417
|
+
var Help = class {
|
|
418
|
+
constructor() {
|
|
419
|
+
this.helpWidth = void 0;
|
|
420
|
+
this.minWidthToWrap = 40;
|
|
421
|
+
this.sortSubcommands = false;
|
|
422
|
+
this.sortOptions = false;
|
|
423
|
+
this.showGlobalOptions = false;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
427
|
+
* and just before calling `formatHelp()`.
|
|
428
|
+
*
|
|
429
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
430
|
+
*
|
|
431
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
432
|
+
*/
|
|
433
|
+
prepareContext(contextOptions) {
|
|
434
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
438
|
+
*
|
|
439
|
+
* @param {Command} cmd
|
|
440
|
+
* @returns {Command[]}
|
|
441
|
+
*/
|
|
442
|
+
visibleCommands(cmd) {
|
|
443
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
444
|
+
const helpCommand = cmd._getHelpCommand();
|
|
445
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
446
|
+
visibleCommands.push(helpCommand);
|
|
447
|
+
}
|
|
448
|
+
if (this.sortSubcommands) {
|
|
449
|
+
visibleCommands.sort((a, b) => {
|
|
450
|
+
return a.name().localeCompare(b.name());
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
return visibleCommands;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Compare options for sort.
|
|
457
|
+
*
|
|
458
|
+
* @param {Option} a
|
|
459
|
+
* @param {Option} b
|
|
460
|
+
* @returns {number}
|
|
461
|
+
*/
|
|
462
|
+
compareOptions(a, b) {
|
|
463
|
+
const getSortKey = (option) => {
|
|
464
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
465
|
+
};
|
|
466
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
470
|
+
*
|
|
471
|
+
* @param {Command} cmd
|
|
472
|
+
* @returns {Option[]}
|
|
473
|
+
*/
|
|
474
|
+
visibleOptions(cmd) {
|
|
475
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
476
|
+
const helpOption = cmd._getHelpOption();
|
|
477
|
+
if (helpOption && !helpOption.hidden) {
|
|
478
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
479
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
480
|
+
if (!removeShort && !removeLong) {
|
|
481
|
+
visibleOptions.push(helpOption);
|
|
482
|
+
} else if (helpOption.long && !removeLong) {
|
|
483
|
+
visibleOptions.push(
|
|
484
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
485
|
+
);
|
|
486
|
+
} else if (helpOption.short && !removeShort) {
|
|
487
|
+
visibleOptions.push(
|
|
488
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (this.sortOptions) {
|
|
493
|
+
visibleOptions.sort(this.compareOptions);
|
|
494
|
+
}
|
|
495
|
+
return visibleOptions;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Get an array of the visible global options. (Not including help.)
|
|
499
|
+
*
|
|
500
|
+
* @param {Command} cmd
|
|
501
|
+
* @returns {Option[]}
|
|
502
|
+
*/
|
|
503
|
+
visibleGlobalOptions(cmd) {
|
|
504
|
+
if (!this.showGlobalOptions) return [];
|
|
505
|
+
const globalOptions = [];
|
|
506
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
507
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
508
|
+
(option) => !option.hidden
|
|
509
|
+
);
|
|
510
|
+
globalOptions.push(...visibleOptions);
|
|
511
|
+
}
|
|
512
|
+
if (this.sortOptions) {
|
|
513
|
+
globalOptions.sort(this.compareOptions);
|
|
514
|
+
}
|
|
515
|
+
return globalOptions;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Get an array of the arguments if any have a description.
|
|
519
|
+
*
|
|
520
|
+
* @param {Command} cmd
|
|
521
|
+
* @returns {Argument[]}
|
|
522
|
+
*/
|
|
523
|
+
visibleArguments(cmd) {
|
|
524
|
+
if (cmd._argsDescription) {
|
|
525
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
526
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
530
|
+
return cmd.registeredArguments;
|
|
531
|
+
}
|
|
532
|
+
return [];
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Get the command term to show in the list of subcommands.
|
|
536
|
+
*
|
|
537
|
+
* @param {Command} cmd
|
|
538
|
+
* @returns {string}
|
|
539
|
+
*/
|
|
540
|
+
subcommandTerm(cmd) {
|
|
541
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
542
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
543
|
+
(args ? " " + args : "");
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Get the option term to show in the list of options.
|
|
547
|
+
*
|
|
548
|
+
* @param {Option} option
|
|
549
|
+
* @returns {string}
|
|
550
|
+
*/
|
|
551
|
+
optionTerm(option) {
|
|
552
|
+
return option.flags;
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Get the argument term to show in the list of arguments.
|
|
556
|
+
*
|
|
557
|
+
* @param {Argument} argument
|
|
558
|
+
* @returns {string}
|
|
559
|
+
*/
|
|
560
|
+
argumentTerm(argument) {
|
|
561
|
+
return argument.name();
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Get the longest command term length.
|
|
565
|
+
*
|
|
566
|
+
* @param {Command} cmd
|
|
567
|
+
* @param {Help} helper
|
|
568
|
+
* @returns {number}
|
|
569
|
+
*/
|
|
570
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
571
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
572
|
+
return Math.max(
|
|
573
|
+
max,
|
|
574
|
+
this.displayWidth(
|
|
575
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
576
|
+
)
|
|
577
|
+
);
|
|
578
|
+
}, 0);
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Get the longest option term length.
|
|
582
|
+
*
|
|
583
|
+
* @param {Command} cmd
|
|
584
|
+
* @param {Help} helper
|
|
585
|
+
* @returns {number}
|
|
586
|
+
*/
|
|
587
|
+
longestOptionTermLength(cmd, helper) {
|
|
588
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
589
|
+
return Math.max(
|
|
590
|
+
max,
|
|
591
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
592
|
+
);
|
|
593
|
+
}, 0);
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Get the longest global option term length.
|
|
597
|
+
*
|
|
598
|
+
* @param {Command} cmd
|
|
599
|
+
* @param {Help} helper
|
|
600
|
+
* @returns {number}
|
|
601
|
+
*/
|
|
602
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
603
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
604
|
+
return Math.max(
|
|
605
|
+
max,
|
|
606
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
607
|
+
);
|
|
608
|
+
}, 0);
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Get the longest argument term length.
|
|
612
|
+
*
|
|
613
|
+
* @param {Command} cmd
|
|
614
|
+
* @param {Help} helper
|
|
615
|
+
* @returns {number}
|
|
616
|
+
*/
|
|
617
|
+
longestArgumentTermLength(cmd, helper) {
|
|
618
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
619
|
+
return Math.max(
|
|
620
|
+
max,
|
|
621
|
+
this.displayWidth(
|
|
622
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
623
|
+
)
|
|
624
|
+
);
|
|
625
|
+
}, 0);
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
629
|
+
*
|
|
630
|
+
* @param {Command} cmd
|
|
631
|
+
* @returns {string}
|
|
632
|
+
*/
|
|
633
|
+
commandUsage(cmd) {
|
|
634
|
+
let cmdName = cmd._name;
|
|
635
|
+
if (cmd._aliases[0]) {
|
|
636
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
637
|
+
}
|
|
638
|
+
let ancestorCmdNames = "";
|
|
639
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
640
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
641
|
+
}
|
|
642
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Get the description for the command.
|
|
646
|
+
*
|
|
647
|
+
* @param {Command} cmd
|
|
648
|
+
* @returns {string}
|
|
649
|
+
*/
|
|
650
|
+
commandDescription(cmd) {
|
|
651
|
+
return cmd.description();
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
655
|
+
* (Fallback to description for backwards compatibility.)
|
|
656
|
+
*
|
|
657
|
+
* @param {Command} cmd
|
|
658
|
+
* @returns {string}
|
|
659
|
+
*/
|
|
660
|
+
subcommandDescription(cmd) {
|
|
661
|
+
return cmd.summary() || cmd.description();
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Get the option description to show in the list of options.
|
|
665
|
+
*
|
|
666
|
+
* @param {Option} option
|
|
667
|
+
* @return {string}
|
|
668
|
+
*/
|
|
669
|
+
optionDescription(option) {
|
|
670
|
+
const extraInfo = [];
|
|
671
|
+
if (option.argChoices) {
|
|
672
|
+
extraInfo.push(
|
|
673
|
+
// use stringify to match the display of the default value
|
|
674
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
675
|
+
);
|
|
676
|
+
}
|
|
677
|
+
if (option.defaultValue !== void 0) {
|
|
678
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
679
|
+
if (showDefault) {
|
|
680
|
+
extraInfo.push(
|
|
681
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
682
|
+
);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
686
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
687
|
+
}
|
|
688
|
+
if (option.envVar !== void 0) {
|
|
689
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
690
|
+
}
|
|
691
|
+
if (extraInfo.length > 0) {
|
|
692
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
693
|
+
if (option.description) {
|
|
694
|
+
return `${option.description} ${extraDescription}`;
|
|
695
|
+
}
|
|
696
|
+
return extraDescription;
|
|
697
|
+
}
|
|
698
|
+
return option.description;
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Get the argument description to show in the list of arguments.
|
|
702
|
+
*
|
|
703
|
+
* @param {Argument} argument
|
|
704
|
+
* @return {string}
|
|
705
|
+
*/
|
|
706
|
+
argumentDescription(argument) {
|
|
707
|
+
const extraInfo = [];
|
|
708
|
+
if (argument.argChoices) {
|
|
709
|
+
extraInfo.push(
|
|
710
|
+
// use stringify to match the display of the default value
|
|
711
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
if (argument.defaultValue !== void 0) {
|
|
715
|
+
extraInfo.push(
|
|
716
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
717
|
+
);
|
|
718
|
+
}
|
|
719
|
+
if (extraInfo.length > 0) {
|
|
720
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
721
|
+
if (argument.description) {
|
|
722
|
+
return `${argument.description} ${extraDescription}`;
|
|
723
|
+
}
|
|
724
|
+
return extraDescription;
|
|
725
|
+
}
|
|
726
|
+
return argument.description;
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
730
|
+
*
|
|
731
|
+
* @param {string} heading
|
|
732
|
+
* @param {string[]} items
|
|
733
|
+
* @param {Help} helper
|
|
734
|
+
* @returns string[]
|
|
735
|
+
*/
|
|
736
|
+
formatItemList(heading, items, helper) {
|
|
737
|
+
if (items.length === 0) return [];
|
|
738
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Group items by their help group heading.
|
|
742
|
+
*
|
|
743
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
744
|
+
* @param {Command[] | Option[]} visibleItems
|
|
745
|
+
* @param {Function} getGroup
|
|
746
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
747
|
+
*/
|
|
748
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
749
|
+
const result = /* @__PURE__ */ new Map();
|
|
750
|
+
unsortedItems.forEach((item) => {
|
|
751
|
+
const group = getGroup(item);
|
|
752
|
+
if (!result.has(group)) result.set(group, []);
|
|
753
|
+
});
|
|
754
|
+
visibleItems.forEach((item) => {
|
|
755
|
+
const group = getGroup(item);
|
|
756
|
+
if (!result.has(group)) {
|
|
757
|
+
result.set(group, []);
|
|
758
|
+
}
|
|
759
|
+
result.get(group).push(item);
|
|
760
|
+
});
|
|
761
|
+
return result;
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Generate the built-in help text.
|
|
765
|
+
*
|
|
766
|
+
* @param {Command} cmd
|
|
767
|
+
* @param {Help} helper
|
|
768
|
+
* @returns {string}
|
|
769
|
+
*/
|
|
770
|
+
formatHelp(cmd, helper) {
|
|
771
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
772
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
773
|
+
function callFormatItem(term, description) {
|
|
774
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
775
|
+
}
|
|
776
|
+
let output = [
|
|
777
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
778
|
+
""
|
|
779
|
+
];
|
|
780
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
781
|
+
if (commandDescription.length > 0) {
|
|
782
|
+
output = output.concat([
|
|
783
|
+
helper.boxWrap(
|
|
784
|
+
helper.styleCommandDescription(commandDescription),
|
|
785
|
+
helpWidth
|
|
786
|
+
),
|
|
787
|
+
""
|
|
788
|
+
]);
|
|
789
|
+
}
|
|
790
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
791
|
+
return callFormatItem(
|
|
792
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
793
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
794
|
+
);
|
|
795
|
+
});
|
|
796
|
+
output = output.concat(
|
|
797
|
+
this.formatItemList("Arguments:", argumentList, helper)
|
|
798
|
+
);
|
|
799
|
+
const optionGroups = this.groupItems(
|
|
800
|
+
cmd.options,
|
|
801
|
+
helper.visibleOptions(cmd),
|
|
802
|
+
(option) => option.helpGroupHeading ?? "Options:"
|
|
803
|
+
);
|
|
804
|
+
optionGroups.forEach((options, group) => {
|
|
805
|
+
const optionList = options.map((option) => {
|
|
806
|
+
return callFormatItem(
|
|
807
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
808
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
809
|
+
);
|
|
810
|
+
});
|
|
811
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
812
|
+
});
|
|
813
|
+
if (helper.showGlobalOptions) {
|
|
814
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
815
|
+
return callFormatItem(
|
|
816
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
817
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
818
|
+
);
|
|
819
|
+
});
|
|
820
|
+
output = output.concat(
|
|
821
|
+
this.formatItemList("Global Options:", globalOptionList, helper)
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
const commandGroups = this.groupItems(
|
|
825
|
+
cmd.commands,
|
|
826
|
+
helper.visibleCommands(cmd),
|
|
827
|
+
(sub) => sub.helpGroup() || "Commands:"
|
|
828
|
+
);
|
|
829
|
+
commandGroups.forEach((commands, group) => {
|
|
830
|
+
const commandList = commands.map((sub) => {
|
|
831
|
+
return callFormatItem(
|
|
832
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
|
|
833
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(sub))
|
|
834
|
+
);
|
|
835
|
+
});
|
|
836
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
837
|
+
});
|
|
838
|
+
return output.join("\n");
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
842
|
+
*
|
|
843
|
+
* @param {string} str
|
|
844
|
+
* @returns {number}
|
|
845
|
+
*/
|
|
846
|
+
displayWidth(str) {
|
|
847
|
+
return stripVTControlCharacters(str).length;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
851
|
+
*
|
|
852
|
+
* @param {string} str
|
|
853
|
+
* @returns {string}
|
|
854
|
+
*/
|
|
855
|
+
styleTitle(str) {
|
|
856
|
+
return str;
|
|
857
|
+
}
|
|
858
|
+
styleUsage(str) {
|
|
859
|
+
return str.split(" ").map((word2) => {
|
|
860
|
+
if (word2 === "[options]") return this.styleOptionText(word2);
|
|
861
|
+
if (word2 === "[command]") return this.styleSubcommandText(word2);
|
|
862
|
+
if (word2[0] === "[" || word2[0] === "<")
|
|
863
|
+
return this.styleArgumentText(word2);
|
|
864
|
+
return this.styleCommandText(word2);
|
|
865
|
+
}).join(" ");
|
|
866
|
+
}
|
|
867
|
+
styleCommandDescription(str) {
|
|
868
|
+
return this.styleDescriptionText(str);
|
|
869
|
+
}
|
|
870
|
+
styleOptionDescription(str) {
|
|
871
|
+
return this.styleDescriptionText(str);
|
|
872
|
+
}
|
|
873
|
+
styleSubcommandDescription(str) {
|
|
874
|
+
return this.styleDescriptionText(str);
|
|
875
|
+
}
|
|
876
|
+
styleArgumentDescription(str) {
|
|
877
|
+
return this.styleDescriptionText(str);
|
|
878
|
+
}
|
|
879
|
+
styleDescriptionText(str) {
|
|
880
|
+
return str;
|
|
881
|
+
}
|
|
882
|
+
styleOptionTerm(str) {
|
|
883
|
+
return this.styleOptionText(str);
|
|
884
|
+
}
|
|
885
|
+
styleSubcommandTerm(str) {
|
|
886
|
+
return str.split(" ").map((word2) => {
|
|
887
|
+
if (word2 === "[options]") return this.styleOptionText(word2);
|
|
888
|
+
if (word2[0] === "[" || word2[0] === "<")
|
|
889
|
+
return this.styleArgumentText(word2);
|
|
890
|
+
return this.styleSubcommandText(word2);
|
|
891
|
+
}).join(" ");
|
|
892
|
+
}
|
|
893
|
+
styleArgumentTerm(str) {
|
|
894
|
+
return this.styleArgumentText(str);
|
|
895
|
+
}
|
|
896
|
+
styleOptionText(str) {
|
|
897
|
+
return str;
|
|
898
|
+
}
|
|
899
|
+
styleArgumentText(str) {
|
|
900
|
+
return str;
|
|
901
|
+
}
|
|
902
|
+
styleSubcommandText(str) {
|
|
903
|
+
return str;
|
|
904
|
+
}
|
|
905
|
+
styleCommandText(str) {
|
|
906
|
+
return str;
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Calculate the pad width from the maximum term length.
|
|
910
|
+
*
|
|
911
|
+
* @param {Command} cmd
|
|
912
|
+
* @param {Help} helper
|
|
913
|
+
* @returns {number}
|
|
914
|
+
*/
|
|
915
|
+
padWidth(cmd, helper) {
|
|
916
|
+
return Math.max(
|
|
917
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
918
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
919
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
920
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
921
|
+
);
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
925
|
+
*
|
|
926
|
+
* @param {string} str
|
|
927
|
+
* @returns {boolean}
|
|
928
|
+
*/
|
|
929
|
+
preformatted(str) {
|
|
930
|
+
return /\n[^\S\r\n]/.test(str);
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
934
|
+
*
|
|
935
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
936
|
+
* TTT DDD DDDD
|
|
937
|
+
* DD DDD
|
|
938
|
+
*
|
|
939
|
+
* @param {string} term
|
|
940
|
+
* @param {number} termWidth
|
|
941
|
+
* @param {string} description
|
|
942
|
+
* @param {Help} helper
|
|
943
|
+
* @returns {string}
|
|
944
|
+
*/
|
|
945
|
+
formatItem(term, termWidth, description, helper) {
|
|
946
|
+
const itemIndent = 2;
|
|
947
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
948
|
+
if (!description) return itemIndentStr + term;
|
|
949
|
+
const paddedTerm = term.padEnd(
|
|
950
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
951
|
+
);
|
|
952
|
+
const spacerWidth = 2;
|
|
953
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
954
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
955
|
+
let formattedDescription;
|
|
956
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
957
|
+
formattedDescription = description;
|
|
958
|
+
} else {
|
|
959
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
960
|
+
formattedDescription = wrappedDescription.replace(
|
|
961
|
+
/\n/g,
|
|
962
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
963
|
+
);
|
|
964
|
+
}
|
|
965
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
966
|
+
${itemIndentStr}`);
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
970
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
971
|
+
*
|
|
972
|
+
* @param {string} str
|
|
973
|
+
* @param {number} width
|
|
974
|
+
* @returns {string}
|
|
975
|
+
*/
|
|
976
|
+
boxWrap(str, width) {
|
|
977
|
+
if (width < this.minWidthToWrap) return str;
|
|
978
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
979
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
980
|
+
const wrappedLines = [];
|
|
981
|
+
rawLines.forEach((line) => {
|
|
982
|
+
const chunks = line.match(chunkPattern);
|
|
983
|
+
if (chunks === null) {
|
|
984
|
+
wrappedLines.push("");
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
let sumChunks = [chunks.shift()];
|
|
988
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
989
|
+
chunks.forEach((chunk) => {
|
|
990
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
991
|
+
if (sumWidth + visibleWidth <= width) {
|
|
992
|
+
sumChunks.push(chunk);
|
|
993
|
+
sumWidth += visibleWidth;
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
wrappedLines.push(sumChunks.join(""));
|
|
997
|
+
const nextChunk = chunk.trimStart();
|
|
998
|
+
sumChunks = [nextChunk];
|
|
999
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
1000
|
+
});
|
|
1001
|
+
wrappedLines.push(sumChunks.join(""));
|
|
1002
|
+
});
|
|
1003
|
+
return wrappedLines.join("\n");
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
// node_modules/commander/lib/option.js
|
|
1008
|
+
var Option = class {
|
|
1009
|
+
/**
|
|
1010
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
1011
|
+
*
|
|
1012
|
+
* @param {string} flags
|
|
1013
|
+
* @param {string} [description]
|
|
1014
|
+
*/
|
|
1015
|
+
constructor(flags, description) {
|
|
1016
|
+
this.flags = flags;
|
|
1017
|
+
this.description = description || "";
|
|
1018
|
+
this.required = flags.includes("<");
|
|
1019
|
+
this.optional = flags.includes("[");
|
|
1020
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
1021
|
+
this.mandatory = false;
|
|
1022
|
+
const optionFlags = splitOptionFlags(flags);
|
|
1023
|
+
this.short = optionFlags.shortFlag;
|
|
1024
|
+
this.long = optionFlags.longFlag;
|
|
1025
|
+
this.negate = false;
|
|
1026
|
+
if (this.long) {
|
|
1027
|
+
this.negate = this.long.startsWith("--no-");
|
|
1028
|
+
}
|
|
1029
|
+
this.defaultValue = void 0;
|
|
1030
|
+
this.defaultValueDescription = void 0;
|
|
1031
|
+
this.presetArg = void 0;
|
|
1032
|
+
this.envVar = void 0;
|
|
1033
|
+
this.parseArg = void 0;
|
|
1034
|
+
this.hidden = false;
|
|
1035
|
+
this.argChoices = void 0;
|
|
1036
|
+
this.conflictsWith = [];
|
|
1037
|
+
this.implied = void 0;
|
|
1038
|
+
this.helpGroupHeading = void 0;
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
1042
|
+
*
|
|
1043
|
+
* @param {*} value
|
|
1044
|
+
* @param {string} [description]
|
|
1045
|
+
* @return {Option}
|
|
1046
|
+
*/
|
|
1047
|
+
default(value, description) {
|
|
1048
|
+
this.defaultValue = value;
|
|
1049
|
+
this.defaultValueDescription = description;
|
|
1050
|
+
return this;
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
1054
|
+
* The custom processing (parseArg) is called.
|
|
1055
|
+
*
|
|
1056
|
+
* @example
|
|
1057
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
1058
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
1059
|
+
*
|
|
1060
|
+
* @param {*} arg
|
|
1061
|
+
* @return {Option}
|
|
1062
|
+
*/
|
|
1063
|
+
preset(arg) {
|
|
1064
|
+
this.presetArg = arg;
|
|
1065
|
+
return this;
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Add option name(s) that conflict with this option.
|
|
1069
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
1070
|
+
*
|
|
1071
|
+
* @example
|
|
1072
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
1073
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
1074
|
+
*
|
|
1075
|
+
* @param {(string | string[])} names
|
|
1076
|
+
* @return {Option}
|
|
1077
|
+
*/
|
|
1078
|
+
conflicts(names) {
|
|
1079
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
1080
|
+
return this;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
1084
|
+
*
|
|
1085
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
1086
|
+
*
|
|
1087
|
+
* @example
|
|
1088
|
+
* program
|
|
1089
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
1090
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
1091
|
+
*
|
|
1092
|
+
* @param {object} impliedOptionValues
|
|
1093
|
+
* @return {Option}
|
|
1094
|
+
*/
|
|
1095
|
+
implies(impliedOptionValues) {
|
|
1096
|
+
let newImplied = impliedOptionValues;
|
|
1097
|
+
if (typeof impliedOptionValues === "string") {
|
|
1098
|
+
newImplied = { [impliedOptionValues]: true };
|
|
1099
|
+
}
|
|
1100
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
1101
|
+
return this;
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Set environment variable to check for option value.
|
|
1105
|
+
*
|
|
1106
|
+
* An environment variable is only used if when processed the current option value is
|
|
1107
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
1108
|
+
*
|
|
1109
|
+
* @param {string} name
|
|
1110
|
+
* @return {Option}
|
|
1111
|
+
*/
|
|
1112
|
+
env(name) {
|
|
1113
|
+
this.envVar = name;
|
|
1114
|
+
return this;
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
1118
|
+
*
|
|
1119
|
+
* @param {Function} [fn]
|
|
1120
|
+
* @return {Option}
|
|
1121
|
+
*/
|
|
1122
|
+
argParser(fn) {
|
|
1123
|
+
this.parseArg = fn;
|
|
1124
|
+
return this;
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
1128
|
+
*
|
|
1129
|
+
* @param {boolean} [mandatory=true]
|
|
1130
|
+
* @return {Option}
|
|
1131
|
+
*/
|
|
1132
|
+
makeOptionMandatory(mandatory = true) {
|
|
1133
|
+
this.mandatory = !!mandatory;
|
|
1134
|
+
return this;
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Hide option in help.
|
|
1138
|
+
*
|
|
1139
|
+
* @param {boolean} [hide=true]
|
|
1140
|
+
* @return {Option}
|
|
1141
|
+
*/
|
|
1142
|
+
hideHelp(hide = true) {
|
|
1143
|
+
this.hidden = !!hide;
|
|
1144
|
+
return this;
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* @package
|
|
1148
|
+
*/
|
|
1149
|
+
_collectValue(value, previous) {
|
|
1150
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
1151
|
+
return [value];
|
|
1152
|
+
}
|
|
1153
|
+
previous.push(value);
|
|
1154
|
+
return previous;
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* Only allow option value to be one of choices.
|
|
1158
|
+
*
|
|
1159
|
+
* @param {string[]} values
|
|
1160
|
+
* @return {Option}
|
|
1161
|
+
*/
|
|
1162
|
+
choices(values) {
|
|
1163
|
+
this.argChoices = values.slice();
|
|
1164
|
+
this.parseArg = (arg, previous) => {
|
|
1165
|
+
if (!this.argChoices.includes(arg)) {
|
|
1166
|
+
throw new InvalidArgumentError(
|
|
1167
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
1168
|
+
);
|
|
1169
|
+
}
|
|
1170
|
+
if (this.variadic) {
|
|
1171
|
+
return this._collectValue(arg, previous);
|
|
1172
|
+
}
|
|
1173
|
+
return arg;
|
|
1174
|
+
};
|
|
1175
|
+
return this;
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* Return option name.
|
|
1179
|
+
*
|
|
1180
|
+
* @return {string}
|
|
1181
|
+
*/
|
|
1182
|
+
name() {
|
|
1183
|
+
if (this.long) {
|
|
1184
|
+
return this.long.replace(/^--/, "");
|
|
1185
|
+
}
|
|
1186
|
+
return this.short.replace(/^-/, "");
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* Return option name, in a camelcase format that can be used
|
|
1190
|
+
* as an object attribute key.
|
|
1191
|
+
*
|
|
1192
|
+
* @return {string}
|
|
1193
|
+
*/
|
|
1194
|
+
attributeName() {
|
|
1195
|
+
if (this.negate) {
|
|
1196
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
1197
|
+
}
|
|
1198
|
+
return camelcase(this.name());
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Set the help group heading.
|
|
1202
|
+
*
|
|
1203
|
+
* @param {string} heading
|
|
1204
|
+
* @return {Option}
|
|
1205
|
+
*/
|
|
1206
|
+
helpGroup(heading) {
|
|
1207
|
+
this.helpGroupHeading = heading;
|
|
1208
|
+
return this;
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Check if `arg` matches the short or long flag.
|
|
1212
|
+
*
|
|
1213
|
+
* @param {string} arg
|
|
1214
|
+
* @return {boolean}
|
|
1215
|
+
* @package
|
|
1216
|
+
*/
|
|
1217
|
+
is(arg) {
|
|
1218
|
+
return this.short === arg || this.long === arg;
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Return whether a boolean option.
|
|
1222
|
+
*
|
|
1223
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
1224
|
+
*
|
|
1225
|
+
* @return {boolean}
|
|
1226
|
+
* @package
|
|
1227
|
+
*/
|
|
1228
|
+
isBoolean() {
|
|
1229
|
+
return !this.required && !this.optional && !this.negate;
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
var DualOptions = class {
|
|
1233
|
+
/**
|
|
1234
|
+
* @param {Option[]} options
|
|
1235
|
+
*/
|
|
1236
|
+
constructor(options) {
|
|
1237
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
1238
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
1239
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
1240
|
+
options.forEach((option) => {
|
|
1241
|
+
if (option.negate) {
|
|
1242
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
1243
|
+
} else {
|
|
1244
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
1245
|
+
}
|
|
1246
|
+
});
|
|
1247
|
+
this.negativeOptions.forEach((value, key) => {
|
|
1248
|
+
if (this.positiveOptions.has(key)) {
|
|
1249
|
+
this.dualOptions.add(key);
|
|
1250
|
+
}
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1255
|
+
*
|
|
1256
|
+
* @param {*} value
|
|
1257
|
+
* @param {Option} option
|
|
1258
|
+
* @returns {boolean}
|
|
1259
|
+
*/
|
|
1260
|
+
valueFromOption(value, option) {
|
|
1261
|
+
const optionKey = option.attributeName();
|
|
1262
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1263
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1264
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1265
|
+
return option.negate === (negativeValue === value);
|
|
1266
|
+
}
|
|
1267
|
+
};
|
|
1268
|
+
function camelcase(str) {
|
|
1269
|
+
return str.split("-").reduce((str2, word2) => {
|
|
1270
|
+
return str2 + word2[0].toUpperCase() + word2.slice(1);
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
function splitOptionFlags(flags) {
|
|
1274
|
+
let shortFlag;
|
|
1275
|
+
let longFlag;
|
|
1276
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1277
|
+
const longFlagExp = /^--[^-]/;
|
|
1278
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1279
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1280
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1281
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1282
|
+
shortFlag = flagParts.shift();
|
|
1283
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1284
|
+
shortFlag = longFlag;
|
|
1285
|
+
longFlag = flagParts.shift();
|
|
1286
|
+
}
|
|
1287
|
+
if (flagParts[0].startsWith("-")) {
|
|
1288
|
+
const unsupportedFlag = flagParts[0];
|
|
1289
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1290
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1291
|
+
throw new Error(
|
|
1292
|
+
`${baseError}
|
|
1293
|
+
- a short flag is a single dash and a single character
|
|
1294
|
+
- either use a single dash and a single character (for a short flag)
|
|
1295
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1296
|
+
);
|
|
1297
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1298
|
+
throw new Error(`${baseError}
|
|
1299
|
+
- too many short flags`);
|
|
1300
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1301
|
+
throw new Error(`${baseError}
|
|
1302
|
+
- too many long flags`);
|
|
1303
|
+
throw new Error(`${baseError}
|
|
1304
|
+
- unrecognised flag format`);
|
|
1305
|
+
}
|
|
1306
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1307
|
+
throw new Error(
|
|
1308
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1309
|
+
);
|
|
1310
|
+
return { shortFlag, longFlag };
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1314
|
+
var maxDistance = 3;
|
|
1315
|
+
function editDistance(a, b) {
|
|
1316
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1317
|
+
return Math.max(a.length, b.length);
|
|
1318
|
+
const d = [];
|
|
1319
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1320
|
+
d[i] = [i];
|
|
1321
|
+
}
|
|
1322
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1323
|
+
d[0][j] = j;
|
|
1324
|
+
}
|
|
1325
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1326
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1327
|
+
let cost;
|
|
1328
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1329
|
+
cost = 0;
|
|
1330
|
+
} else {
|
|
1331
|
+
cost = 1;
|
|
1332
|
+
}
|
|
1333
|
+
d[i][j] = Math.min(
|
|
1334
|
+
d[i - 1][j] + 1,
|
|
1335
|
+
// deletion
|
|
1336
|
+
d[i][j - 1] + 1,
|
|
1337
|
+
// insertion
|
|
1338
|
+
d[i - 1][j - 1] + cost
|
|
1339
|
+
// substitution
|
|
1340
|
+
);
|
|
1341
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1342
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
return d[a.length][b.length];
|
|
1347
|
+
}
|
|
1348
|
+
function suggestSimilar(word2, candidates) {
|
|
1349
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1350
|
+
candidates = Array.from(new Set(candidates));
|
|
1351
|
+
const searchingOptions = word2.startsWith("--");
|
|
1352
|
+
if (searchingOptions) {
|
|
1353
|
+
word2 = word2.slice(2);
|
|
1354
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1355
|
+
}
|
|
1356
|
+
let similar = [];
|
|
1357
|
+
let bestDistance = maxDistance;
|
|
1358
|
+
const minSimilarity = 0.4;
|
|
1359
|
+
candidates.forEach((candidate) => {
|
|
1360
|
+
if (candidate.length <= 1) return;
|
|
1361
|
+
const distance = editDistance(word2, candidate);
|
|
1362
|
+
const length = Math.max(word2.length, candidate.length);
|
|
1363
|
+
const similarity = (length - distance) / length;
|
|
1364
|
+
if (similarity > minSimilarity) {
|
|
1365
|
+
if (distance < bestDistance) {
|
|
1366
|
+
bestDistance = distance;
|
|
1367
|
+
similar = [candidate];
|
|
1368
|
+
} else if (distance === bestDistance) {
|
|
1369
|
+
similar.push(candidate);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
});
|
|
1373
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1374
|
+
if (searchingOptions) {
|
|
1375
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1376
|
+
}
|
|
1377
|
+
if (similar.length > 1) {
|
|
1378
|
+
return `
|
|
1379
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1380
|
+
}
|
|
1381
|
+
if (similar.length === 1) {
|
|
1382
|
+
return `
|
|
1383
|
+
(Did you mean ${similar[0]}?)`;
|
|
1384
|
+
}
|
|
1385
|
+
return "";
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// node_modules/commander/lib/command.js
|
|
1389
|
+
var Command = class _Command extends EventEmitter {
|
|
1390
|
+
/**
|
|
1391
|
+
* Initialize a new `Command`.
|
|
1392
|
+
*
|
|
1393
|
+
* @param {string} [name]
|
|
1394
|
+
*/
|
|
1395
|
+
constructor(name) {
|
|
1396
|
+
super();
|
|
1397
|
+
this.commands = [];
|
|
1398
|
+
this.options = [];
|
|
1399
|
+
this.parent = null;
|
|
1400
|
+
this._allowUnknownOption = false;
|
|
1401
|
+
this._allowExcessArguments = false;
|
|
1402
|
+
this.registeredArguments = [];
|
|
1403
|
+
this._args = this.registeredArguments;
|
|
1404
|
+
this.args = [];
|
|
1405
|
+
this.rawArgs = [];
|
|
1406
|
+
this.processedArgs = [];
|
|
1407
|
+
this._scriptPath = null;
|
|
1408
|
+
this._name = name || "";
|
|
1409
|
+
this._optionValues = {};
|
|
1410
|
+
this._optionValueSources = {};
|
|
1411
|
+
this._storeOptionsAsProperties = false;
|
|
1412
|
+
this._actionHandler = null;
|
|
1413
|
+
this._executableHandler = false;
|
|
1414
|
+
this._executableFile = null;
|
|
1415
|
+
this._executableDir = null;
|
|
1416
|
+
this._defaultCommandName = null;
|
|
1417
|
+
this._exitCallback = null;
|
|
1418
|
+
this._aliases = [];
|
|
1419
|
+
this._combineFlagAndOptionalValue = true;
|
|
1420
|
+
this._description = "";
|
|
1421
|
+
this._summary = "";
|
|
1422
|
+
this._argsDescription = void 0;
|
|
1423
|
+
this._enablePositionalOptions = false;
|
|
1424
|
+
this._passThroughOptions = false;
|
|
1425
|
+
this._lifeCycleHooks = {};
|
|
1426
|
+
this._showHelpAfterError = false;
|
|
1427
|
+
this._showSuggestionAfterError = true;
|
|
1428
|
+
this._savedState = null;
|
|
1429
|
+
this._outputConfiguration = {
|
|
1430
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1431
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1432
|
+
outputError: (str, write) => write(str),
|
|
1433
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1434
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1435
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1436
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1437
|
+
stripColor: (str) => stripVTControlCharacters2(str)
|
|
1438
|
+
};
|
|
1439
|
+
this._hidden = false;
|
|
1440
|
+
this._helpOption = void 0;
|
|
1441
|
+
this._addImplicitHelpCommand = void 0;
|
|
1442
|
+
this._helpCommand = void 0;
|
|
1443
|
+
this._helpConfiguration = {};
|
|
1444
|
+
this._helpGroupHeading = void 0;
|
|
1445
|
+
this._defaultCommandGroup = void 0;
|
|
1446
|
+
this._defaultOptionGroup = void 0;
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1450
|
+
*
|
|
1451
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1452
|
+
*
|
|
1453
|
+
* @param {Command} sourceCommand
|
|
1454
|
+
* @return {Command} `this` command for chaining
|
|
1455
|
+
*/
|
|
1456
|
+
copyInheritedSettings(sourceCommand) {
|
|
1457
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1458
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1459
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1460
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1461
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1462
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1463
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1464
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1465
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1466
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1467
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1468
|
+
return this;
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* @returns {Command[]}
|
|
1472
|
+
* @private
|
|
1473
|
+
*/
|
|
1474
|
+
_getCommandAndAncestors() {
|
|
1475
|
+
const result = [];
|
|
1476
|
+
for (let command = this; command; command = command.parent) {
|
|
1477
|
+
result.push(command);
|
|
1478
|
+
}
|
|
1479
|
+
return result;
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* Define a command.
|
|
1483
|
+
*
|
|
1484
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1485
|
+
*
|
|
1486
|
+
* @example
|
|
1487
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1488
|
+
* program
|
|
1489
|
+
* .command('clone <source> [destination]')
|
|
1490
|
+
* .description('clone a repository into a newly created directory')
|
|
1491
|
+
* .action((source, destination) => {
|
|
1492
|
+
* console.log('clone command called');
|
|
1493
|
+
* });
|
|
1494
|
+
*
|
|
1495
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1496
|
+
* program
|
|
1497
|
+
* .command('start <service>', 'start named service')
|
|
1498
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1499
|
+
*
|
|
1500
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1501
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1502
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1503
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1504
|
+
*/
|
|
1505
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1506
|
+
let desc = actionOptsOrExecDesc;
|
|
1507
|
+
let opts = execOpts;
|
|
1508
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1509
|
+
opts = desc;
|
|
1510
|
+
desc = null;
|
|
1511
|
+
}
|
|
1512
|
+
opts = opts || {};
|
|
1513
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1514
|
+
const cmd = this.createCommand(name);
|
|
1515
|
+
if (desc) {
|
|
1516
|
+
cmd.description(desc);
|
|
1517
|
+
cmd._executableHandler = true;
|
|
1518
|
+
}
|
|
1519
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1520
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1521
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1522
|
+
if (args) cmd.arguments(args);
|
|
1523
|
+
this._registerCommand(cmd);
|
|
1524
|
+
cmd.parent = this;
|
|
1525
|
+
cmd.copyInheritedSettings(this);
|
|
1526
|
+
if (desc) return this;
|
|
1527
|
+
return cmd;
|
|
1528
|
+
}
|
|
1529
|
+
/**
|
|
1530
|
+
* Factory routine to create a new unattached command.
|
|
1531
|
+
*
|
|
1532
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1533
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1534
|
+
*
|
|
1535
|
+
* @param {string} [name]
|
|
1536
|
+
* @return {Command} new command
|
|
1537
|
+
*/
|
|
1538
|
+
createCommand(name) {
|
|
1539
|
+
return new _Command(name);
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1543
|
+
* or by overriding Help properties using configureHelp().
|
|
1544
|
+
*
|
|
1545
|
+
* @return {Help}
|
|
1546
|
+
*/
|
|
1547
|
+
createHelp() {
|
|
1548
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1549
|
+
}
|
|
1550
|
+
/**
|
|
1551
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1552
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1553
|
+
*
|
|
1554
|
+
* @param {object} [configuration] - configuration options
|
|
1555
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1556
|
+
*/
|
|
1557
|
+
configureHelp(configuration) {
|
|
1558
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1559
|
+
this._helpConfiguration = configuration;
|
|
1560
|
+
return this;
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1564
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1565
|
+
*
|
|
1566
|
+
* The configuration properties are all functions:
|
|
1567
|
+
*
|
|
1568
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1569
|
+
* writeOut(str)
|
|
1570
|
+
* writeErr(str)
|
|
1571
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1572
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1573
|
+
* // specify width for wrapping help
|
|
1574
|
+
* getOutHelpWidth()
|
|
1575
|
+
* getErrHelpWidth()
|
|
1576
|
+
* // color support, currently only used with Help
|
|
1577
|
+
* getOutHasColors()
|
|
1578
|
+
* getErrHasColors()
|
|
1579
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1580
|
+
*
|
|
1581
|
+
* @param {object} [configuration] - configuration options
|
|
1582
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1583
|
+
*/
|
|
1584
|
+
configureOutput(configuration) {
|
|
1585
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1586
|
+
this._outputConfiguration = {
|
|
1587
|
+
...this._outputConfiguration,
|
|
1588
|
+
...configuration
|
|
1589
|
+
};
|
|
1590
|
+
return this;
|
|
1591
|
+
}
|
|
1592
|
+
/**
|
|
1593
|
+
* Display the help or a custom message after an error occurs.
|
|
1594
|
+
*
|
|
1595
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1596
|
+
* @return {Command} `this` command for chaining
|
|
1597
|
+
*/
|
|
1598
|
+
showHelpAfterError(displayHelp = true) {
|
|
1599
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1600
|
+
this._showHelpAfterError = displayHelp;
|
|
1601
|
+
return this;
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1605
|
+
*
|
|
1606
|
+
* @param {boolean} [displaySuggestion]
|
|
1607
|
+
* @return {Command} `this` command for chaining
|
|
1608
|
+
*/
|
|
1609
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1610
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1611
|
+
return this;
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* Add a prepared subcommand.
|
|
1615
|
+
*
|
|
1616
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1617
|
+
*
|
|
1618
|
+
* @param {Command} cmd - new subcommand
|
|
1619
|
+
* @param {object} [opts] - configuration options
|
|
1620
|
+
* @return {Command} `this` command for chaining
|
|
1621
|
+
*/
|
|
1622
|
+
addCommand(cmd, opts) {
|
|
1623
|
+
if (!cmd._name) {
|
|
1624
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1625
|
+
- specify the name in Command constructor or using .name()`);
|
|
1626
|
+
}
|
|
1627
|
+
opts = opts || {};
|
|
1628
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1629
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1630
|
+
this._registerCommand(cmd);
|
|
1631
|
+
cmd.parent = this;
|
|
1632
|
+
cmd._checkForBrokenPassThrough();
|
|
1633
|
+
return this;
|
|
1634
|
+
}
|
|
1635
|
+
/**
|
|
1636
|
+
* Factory routine to create a new unattached argument.
|
|
1637
|
+
*
|
|
1638
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1639
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1640
|
+
*
|
|
1641
|
+
* @param {string} name
|
|
1642
|
+
* @param {string} [description]
|
|
1643
|
+
* @return {Argument} new argument
|
|
1644
|
+
*/
|
|
1645
|
+
createArgument(name, description) {
|
|
1646
|
+
return new Argument(name, description);
|
|
1647
|
+
}
|
|
1648
|
+
/**
|
|
1649
|
+
* Define argument syntax for command.
|
|
1650
|
+
*
|
|
1651
|
+
* The default is that the argument is required, and you can explicitly
|
|
1652
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1653
|
+
*
|
|
1654
|
+
* @example
|
|
1655
|
+
* program.argument('<input-file>');
|
|
1656
|
+
* program.argument('[output-file]');
|
|
1657
|
+
*
|
|
1658
|
+
* @param {string} name
|
|
1659
|
+
* @param {string} [description]
|
|
1660
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1661
|
+
* @param {*} [defaultValue]
|
|
1662
|
+
* @return {Command} `this` command for chaining
|
|
1663
|
+
*/
|
|
1664
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1665
|
+
const argument = this.createArgument(name, description);
|
|
1666
|
+
if (typeof parseArg === "function") {
|
|
1667
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
1668
|
+
} else {
|
|
1669
|
+
argument.default(parseArg);
|
|
1670
|
+
}
|
|
1671
|
+
this.addArgument(argument);
|
|
1672
|
+
return this;
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1676
|
+
*
|
|
1677
|
+
* See also .argument().
|
|
1678
|
+
*
|
|
1679
|
+
* @example
|
|
1680
|
+
* program.arguments('<cmd> [env]');
|
|
1681
|
+
*
|
|
1682
|
+
* @param {string} names
|
|
1683
|
+
* @return {Command} `this` command for chaining
|
|
1684
|
+
*/
|
|
1685
|
+
arguments(names) {
|
|
1686
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1687
|
+
this.argument(detail);
|
|
1688
|
+
});
|
|
1689
|
+
return this;
|
|
1690
|
+
}
|
|
1691
|
+
/**
|
|
1692
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1693
|
+
*
|
|
1694
|
+
* @param {Argument} argument
|
|
1695
|
+
* @return {Command} `this` command for chaining
|
|
1696
|
+
*/
|
|
1697
|
+
addArgument(argument) {
|
|
1698
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1699
|
+
if (previousArgument?.variadic) {
|
|
1700
|
+
throw new Error(
|
|
1701
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1705
|
+
throw new Error(
|
|
1706
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1707
|
+
);
|
|
1708
|
+
}
|
|
1709
|
+
this.registeredArguments.push(argument);
|
|
1710
|
+
return this;
|
|
1711
|
+
}
|
|
1712
|
+
/**
|
|
1713
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1714
|
+
*
|
|
1715
|
+
* @example
|
|
1716
|
+
* program.helpCommand('help [cmd]');
|
|
1717
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1718
|
+
* program.helpCommand(false); // suppress default help command
|
|
1719
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1720
|
+
*
|
|
1721
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1722
|
+
* @param {string} [description] - custom description
|
|
1723
|
+
* @return {Command} `this` command for chaining
|
|
1724
|
+
*/
|
|
1725
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1726
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1727
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1728
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
1729
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
1730
|
+
}
|
|
1731
|
+
return this;
|
|
1732
|
+
}
|
|
1733
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1734
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1735
|
+
const helpDescription = description ?? "display help for command";
|
|
1736
|
+
const helpCommand = this.createCommand(helpName);
|
|
1737
|
+
helpCommand.helpOption(false);
|
|
1738
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1739
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1740
|
+
this._addImplicitHelpCommand = true;
|
|
1741
|
+
this._helpCommand = helpCommand;
|
|
1742
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1743
|
+
return this;
|
|
1744
|
+
}
|
|
1745
|
+
/**
|
|
1746
|
+
* Add prepared custom help command.
|
|
1747
|
+
*
|
|
1748
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1749
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1750
|
+
* @return {Command} `this` command for chaining
|
|
1751
|
+
*/
|
|
1752
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1753
|
+
if (typeof helpCommand !== "object") {
|
|
1754
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1755
|
+
return this;
|
|
1756
|
+
}
|
|
1757
|
+
this._addImplicitHelpCommand = true;
|
|
1758
|
+
this._helpCommand = helpCommand;
|
|
1759
|
+
this._initCommandGroup(helpCommand);
|
|
1760
|
+
return this;
|
|
1761
|
+
}
|
|
1762
|
+
/**
|
|
1763
|
+
* Lazy create help command.
|
|
1764
|
+
*
|
|
1765
|
+
* @return {(Command|null)}
|
|
1766
|
+
* @package
|
|
1767
|
+
*/
|
|
1768
|
+
_getHelpCommand() {
|
|
1769
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1770
|
+
if (hasImplicitHelpCommand) {
|
|
1771
|
+
if (this._helpCommand === void 0) {
|
|
1772
|
+
this.helpCommand(void 0, void 0);
|
|
1773
|
+
}
|
|
1774
|
+
return this._helpCommand;
|
|
1775
|
+
}
|
|
1776
|
+
return null;
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* Add hook for life cycle event.
|
|
1780
|
+
*
|
|
1781
|
+
* @param {string} event
|
|
1782
|
+
* @param {Function} listener
|
|
1783
|
+
* @return {Command} `this` command for chaining
|
|
1784
|
+
*/
|
|
1785
|
+
hook(event, listener) {
|
|
1786
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1787
|
+
if (!allowedValues.includes(event)) {
|
|
1788
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1789
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1790
|
+
}
|
|
1791
|
+
if (this._lifeCycleHooks[event]) {
|
|
1792
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1793
|
+
} else {
|
|
1794
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1795
|
+
}
|
|
1796
|
+
return this;
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1800
|
+
*
|
|
1801
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1802
|
+
* @return {Command} `this` command for chaining
|
|
1803
|
+
*/
|
|
1804
|
+
exitOverride(fn) {
|
|
1805
|
+
if (fn) {
|
|
1806
|
+
this._exitCallback = fn;
|
|
1807
|
+
} else {
|
|
1808
|
+
this._exitCallback = (err) => {
|
|
1809
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1810
|
+
throw err;
|
|
1811
|
+
} else {
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
return this;
|
|
1816
|
+
}
|
|
1817
|
+
/**
|
|
1818
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1819
|
+
*
|
|
1820
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1821
|
+
* @param {string} code an id string representing the error
|
|
1822
|
+
* @param {string} message human-readable description of the error
|
|
1823
|
+
* @return never
|
|
1824
|
+
* @private
|
|
1825
|
+
*/
|
|
1826
|
+
_exit(exitCode, code, message) {
|
|
1827
|
+
if (this._exitCallback) {
|
|
1828
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1829
|
+
}
|
|
1830
|
+
process2.exit(exitCode);
|
|
1831
|
+
}
|
|
1832
|
+
/**
|
|
1833
|
+
* Register callback `fn` for the command.
|
|
1834
|
+
*
|
|
1835
|
+
* @example
|
|
1836
|
+
* program
|
|
1837
|
+
* .command('serve')
|
|
1838
|
+
* .description('start service')
|
|
1839
|
+
* .action(function() {
|
|
1840
|
+
* // do work here
|
|
1841
|
+
* });
|
|
1842
|
+
*
|
|
1843
|
+
* @param {Function} fn
|
|
1844
|
+
* @return {Command} `this` command for chaining
|
|
1845
|
+
*/
|
|
1846
|
+
action(fn) {
|
|
1847
|
+
const listener = (args) => {
|
|
1848
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1849
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1850
|
+
if (this._storeOptionsAsProperties) {
|
|
1851
|
+
actionArgs[expectedArgsCount] = this;
|
|
1852
|
+
} else {
|
|
1853
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1854
|
+
}
|
|
1855
|
+
actionArgs.push(this);
|
|
1856
|
+
return fn.apply(this, actionArgs);
|
|
1857
|
+
};
|
|
1858
|
+
this._actionHandler = listener;
|
|
1859
|
+
return this;
|
|
1860
|
+
}
|
|
1861
|
+
/**
|
|
1862
|
+
* Factory routine to create a new unattached option.
|
|
1863
|
+
*
|
|
1864
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1865
|
+
* create the option. You can override createOption to return a custom option.
|
|
1866
|
+
*
|
|
1867
|
+
* @param {string} flags
|
|
1868
|
+
* @param {string} [description]
|
|
1869
|
+
* @return {Option} new option
|
|
1870
|
+
*/
|
|
1871
|
+
createOption(flags, description) {
|
|
1872
|
+
return new Option(flags, description);
|
|
1873
|
+
}
|
|
1874
|
+
/**
|
|
1875
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1876
|
+
*
|
|
1877
|
+
* @param {(Option | Argument)} target
|
|
1878
|
+
* @param {string} value
|
|
1879
|
+
* @param {*} previous
|
|
1880
|
+
* @param {string} invalidArgumentMessage
|
|
1881
|
+
* @private
|
|
1882
|
+
*/
|
|
1883
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1884
|
+
try {
|
|
1885
|
+
return target.parseArg(value, previous);
|
|
1886
|
+
} catch (err) {
|
|
1887
|
+
if (err.code === "commander.invalidArgument") {
|
|
1888
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1889
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1890
|
+
}
|
|
1891
|
+
throw err;
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
/**
|
|
1895
|
+
* Check for option flag conflicts.
|
|
1896
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1897
|
+
*
|
|
1898
|
+
* @param {Option} option
|
|
1899
|
+
* @private
|
|
1900
|
+
*/
|
|
1901
|
+
_registerOption(option) {
|
|
1902
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1903
|
+
if (matchingOption) {
|
|
1904
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1905
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1906
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1907
|
+
}
|
|
1908
|
+
this._initOptionGroup(option);
|
|
1909
|
+
this.options.push(option);
|
|
1910
|
+
}
|
|
1911
|
+
/**
|
|
1912
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1913
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1914
|
+
*
|
|
1915
|
+
* @param {Command} command
|
|
1916
|
+
* @private
|
|
1917
|
+
*/
|
|
1918
|
+
_registerCommand(command) {
|
|
1919
|
+
const knownBy = (cmd) => {
|
|
1920
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1921
|
+
};
|
|
1922
|
+
const alreadyUsed = knownBy(command).find(
|
|
1923
|
+
(name) => this._findCommand(name)
|
|
1924
|
+
);
|
|
1925
|
+
if (alreadyUsed) {
|
|
1926
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1927
|
+
const newCmd = knownBy(command).join("|");
|
|
1928
|
+
throw new Error(
|
|
1929
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1930
|
+
);
|
|
1931
|
+
}
|
|
1932
|
+
this._initCommandGroup(command);
|
|
1933
|
+
this.commands.push(command);
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* Add an option.
|
|
1937
|
+
*
|
|
1938
|
+
* @param {Option} option
|
|
1939
|
+
* @return {Command} `this` command for chaining
|
|
1940
|
+
*/
|
|
1941
|
+
addOption(option) {
|
|
1942
|
+
this._registerOption(option);
|
|
1943
|
+
const oname = option.name();
|
|
1944
|
+
const name = option.attributeName();
|
|
1945
|
+
if (option.defaultValue !== void 0) {
|
|
1946
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1947
|
+
}
|
|
1948
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1949
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1950
|
+
val = option.presetArg;
|
|
1951
|
+
}
|
|
1952
|
+
const oldValue = this.getOptionValue(name);
|
|
1953
|
+
if (val !== null && option.parseArg) {
|
|
1954
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1955
|
+
} else if (val !== null && option.variadic) {
|
|
1956
|
+
val = option._collectValue(val, oldValue);
|
|
1957
|
+
}
|
|
1958
|
+
if (val == null) {
|
|
1959
|
+
if (option.negate) {
|
|
1960
|
+
val = false;
|
|
1961
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1962
|
+
val = true;
|
|
1963
|
+
} else {
|
|
1964
|
+
val = "";
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1968
|
+
};
|
|
1969
|
+
this.on("option:" + oname, (val) => {
|
|
1970
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1971
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1972
|
+
});
|
|
1973
|
+
if (option.envVar) {
|
|
1974
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1975
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1976
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
return this;
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1983
|
+
*
|
|
1984
|
+
* @return {Command} `this` command for chaining
|
|
1985
|
+
* @private
|
|
1986
|
+
*/
|
|
1987
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1988
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
1989
|
+
throw new Error(
|
|
1990
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1991
|
+
);
|
|
1992
|
+
}
|
|
1993
|
+
const option = this.createOption(flags, description);
|
|
1994
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1995
|
+
if (typeof fn === "function") {
|
|
1996
|
+
option.default(defaultValue).argParser(fn);
|
|
1997
|
+
} else if (fn instanceof RegExp) {
|
|
1998
|
+
const regex = fn;
|
|
1999
|
+
fn = (val, def) => {
|
|
2000
|
+
const m = regex.exec(val);
|
|
2001
|
+
return m ? m[0] : def;
|
|
2002
|
+
};
|
|
2003
|
+
option.default(defaultValue).argParser(fn);
|
|
2004
|
+
} else {
|
|
2005
|
+
option.default(fn);
|
|
2006
|
+
}
|
|
2007
|
+
return this.addOption(option);
|
|
2008
|
+
}
|
|
2009
|
+
/**
|
|
2010
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
2011
|
+
*
|
|
2012
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
2013
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
2014
|
+
*
|
|
2015
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
2016
|
+
*
|
|
2017
|
+
* @example
|
|
2018
|
+
* program
|
|
2019
|
+
* .option('-p, --pepper', 'add pepper')
|
|
2020
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
2021
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
2022
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
2023
|
+
*
|
|
2024
|
+
* @param {string} flags
|
|
2025
|
+
* @param {string} [description]
|
|
2026
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
2027
|
+
* @param {*} [defaultValue]
|
|
2028
|
+
* @return {Command} `this` command for chaining
|
|
2029
|
+
*/
|
|
2030
|
+
option(flags, description, parseArg, defaultValue) {
|
|
2031
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
2032
|
+
}
|
|
2033
|
+
/**
|
|
2034
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
2035
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
2036
|
+
*
|
|
2037
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
2038
|
+
*
|
|
2039
|
+
* @param {string} flags
|
|
2040
|
+
* @param {string} [description]
|
|
2041
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
2042
|
+
* @param {*} [defaultValue]
|
|
2043
|
+
* @return {Command} `this` command for chaining
|
|
2044
|
+
*/
|
|
2045
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
2046
|
+
return this._optionEx(
|
|
2047
|
+
{ mandatory: true },
|
|
2048
|
+
flags,
|
|
2049
|
+
description,
|
|
2050
|
+
parseArg,
|
|
2051
|
+
defaultValue
|
|
2052
|
+
);
|
|
2053
|
+
}
|
|
2054
|
+
/**
|
|
2055
|
+
* Alter parsing of short flags with optional values.
|
|
2056
|
+
*
|
|
2057
|
+
* @example
|
|
2058
|
+
* // for `.option('-f,--flag [value]'):
|
|
2059
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
2060
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
2061
|
+
*
|
|
2062
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
2063
|
+
* @return {Command} `this` command for chaining
|
|
2064
|
+
*/
|
|
2065
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
2066
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
2067
|
+
return this;
|
|
2068
|
+
}
|
|
2069
|
+
/**
|
|
2070
|
+
* Allow unknown options on the command line.
|
|
2071
|
+
*
|
|
2072
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
2073
|
+
* @return {Command} `this` command for chaining
|
|
2074
|
+
*/
|
|
2075
|
+
allowUnknownOption(allowUnknown = true) {
|
|
2076
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
2077
|
+
return this;
|
|
2078
|
+
}
|
|
2079
|
+
/**
|
|
2080
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
2081
|
+
*
|
|
2082
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
2083
|
+
* @return {Command} `this` command for chaining
|
|
2084
|
+
*/
|
|
2085
|
+
allowExcessArguments(allowExcess = true) {
|
|
2086
|
+
this._allowExcessArguments = !!allowExcess;
|
|
2087
|
+
return this;
|
|
2088
|
+
}
|
|
2089
|
+
/**
|
|
2090
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
2091
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
2092
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
2093
|
+
*
|
|
2094
|
+
* @param {boolean} [positional]
|
|
2095
|
+
* @return {Command} `this` command for chaining
|
|
2096
|
+
*/
|
|
2097
|
+
enablePositionalOptions(positional = true) {
|
|
2098
|
+
this._enablePositionalOptions = !!positional;
|
|
2099
|
+
return this;
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
2103
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
2104
|
+
* positional options to have been enabled on the program (parent commands).
|
|
2105
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
2106
|
+
*
|
|
2107
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
2108
|
+
* @return {Command} `this` command for chaining
|
|
2109
|
+
*/
|
|
2110
|
+
passThroughOptions(passThrough = true) {
|
|
2111
|
+
this._passThroughOptions = !!passThrough;
|
|
2112
|
+
this._checkForBrokenPassThrough();
|
|
2113
|
+
return this;
|
|
2114
|
+
}
|
|
2115
|
+
/**
|
|
2116
|
+
* @private
|
|
2117
|
+
*/
|
|
2118
|
+
_checkForBrokenPassThrough() {
|
|
2119
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
2120
|
+
throw new Error(
|
|
2121
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
2122
|
+
);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
/**
|
|
2126
|
+
* Whether to store option values as properties on command object,
|
|
2127
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
2128
|
+
*
|
|
2129
|
+
* @param {boolean} [storeAsProperties=true]
|
|
2130
|
+
* @return {Command} `this` command for chaining
|
|
2131
|
+
*/
|
|
2132
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
2133
|
+
if (this.options.length) {
|
|
2134
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
2135
|
+
}
|
|
2136
|
+
if (Object.keys(this._optionValues).length) {
|
|
2137
|
+
throw new Error(
|
|
2138
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
2139
|
+
);
|
|
2140
|
+
}
|
|
2141
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
2142
|
+
return this;
|
|
2143
|
+
}
|
|
2144
|
+
/**
|
|
2145
|
+
* Retrieve option value.
|
|
2146
|
+
*
|
|
2147
|
+
* @param {string} key
|
|
2148
|
+
* @return {object} value
|
|
2149
|
+
*/
|
|
2150
|
+
getOptionValue(key) {
|
|
2151
|
+
if (this._storeOptionsAsProperties) {
|
|
2152
|
+
return this[key];
|
|
2153
|
+
}
|
|
2154
|
+
return this._optionValues[key];
|
|
2155
|
+
}
|
|
2156
|
+
/**
|
|
2157
|
+
* Store option value.
|
|
2158
|
+
*
|
|
2159
|
+
* @param {string} key
|
|
2160
|
+
* @param {object} value
|
|
2161
|
+
* @return {Command} `this` command for chaining
|
|
2162
|
+
*/
|
|
2163
|
+
setOptionValue(key, value) {
|
|
2164
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
2165
|
+
}
|
|
2166
|
+
/**
|
|
2167
|
+
* Store option value and where the value came from.
|
|
2168
|
+
*
|
|
2169
|
+
* @param {string} key
|
|
2170
|
+
* @param {object} value
|
|
2171
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
2172
|
+
* @return {Command} `this` command for chaining
|
|
2173
|
+
*/
|
|
2174
|
+
setOptionValueWithSource(key, value, source) {
|
|
2175
|
+
if (this._storeOptionsAsProperties) {
|
|
2176
|
+
this[key] = value;
|
|
2177
|
+
} else {
|
|
2178
|
+
this._optionValues[key] = value;
|
|
2179
|
+
}
|
|
2180
|
+
this._optionValueSources[key] = source;
|
|
2181
|
+
return this;
|
|
2182
|
+
}
|
|
2183
|
+
/**
|
|
2184
|
+
* Get source of option value.
|
|
2185
|
+
* Expected values are default | config | env | cli | implied
|
|
2186
|
+
*
|
|
2187
|
+
* @param {string} key
|
|
2188
|
+
* @return {string}
|
|
2189
|
+
*/
|
|
2190
|
+
getOptionValueSource(key) {
|
|
2191
|
+
return this._optionValueSources[key];
|
|
2192
|
+
}
|
|
2193
|
+
/**
|
|
2194
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
2195
|
+
* Expected values are default | config | env | cli | implied
|
|
2196
|
+
*
|
|
2197
|
+
* @param {string} key
|
|
2198
|
+
* @return {string}
|
|
2199
|
+
*/
|
|
2200
|
+
getOptionValueSourceWithGlobals(key) {
|
|
2201
|
+
let source;
|
|
2202
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2203
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
2204
|
+
source = cmd.getOptionValueSource(key);
|
|
2205
|
+
}
|
|
2206
|
+
});
|
|
2207
|
+
return source;
|
|
2208
|
+
}
|
|
2209
|
+
/**
|
|
2210
|
+
* Get user arguments from implied or explicit arguments.
|
|
2211
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
2212
|
+
*
|
|
2213
|
+
* @private
|
|
2214
|
+
*/
|
|
2215
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
2216
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
2217
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
2218
|
+
}
|
|
2219
|
+
parseOptions = parseOptions || {};
|
|
2220
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
2221
|
+
if (process2.versions?.electron) {
|
|
2222
|
+
parseOptions.from = "electron";
|
|
2223
|
+
}
|
|
2224
|
+
const execArgv = process2.execArgv ?? [];
|
|
2225
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
2226
|
+
parseOptions.from = "eval";
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
if (argv === void 0) {
|
|
2230
|
+
argv = process2.argv;
|
|
2231
|
+
}
|
|
2232
|
+
this.rawArgs = argv.slice();
|
|
2233
|
+
let userArgs;
|
|
2234
|
+
switch (parseOptions.from) {
|
|
2235
|
+
case void 0:
|
|
2236
|
+
case "node":
|
|
2237
|
+
this._scriptPath = argv[1];
|
|
2238
|
+
userArgs = argv.slice(2);
|
|
2239
|
+
break;
|
|
2240
|
+
case "electron":
|
|
2241
|
+
if (process2.defaultApp) {
|
|
2242
|
+
this._scriptPath = argv[1];
|
|
2243
|
+
userArgs = argv.slice(2);
|
|
2244
|
+
} else {
|
|
2245
|
+
userArgs = argv.slice(1);
|
|
2246
|
+
}
|
|
2247
|
+
break;
|
|
2248
|
+
case "user":
|
|
2249
|
+
userArgs = argv.slice(0);
|
|
2250
|
+
break;
|
|
2251
|
+
case "eval":
|
|
2252
|
+
userArgs = argv.slice(1);
|
|
2253
|
+
break;
|
|
2254
|
+
default:
|
|
2255
|
+
throw new Error(
|
|
2256
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2257
|
+
);
|
|
2258
|
+
}
|
|
2259
|
+
if (!this._name && this._scriptPath)
|
|
2260
|
+
this.nameFromFilename(this._scriptPath);
|
|
2261
|
+
this._name = this._name || "program";
|
|
2262
|
+
return userArgs;
|
|
2263
|
+
}
|
|
2264
|
+
/**
|
|
2265
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2266
|
+
*
|
|
2267
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2268
|
+
*
|
|
2269
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2270
|
+
*
|
|
2271
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2272
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2273
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2274
|
+
* - `'user'`: just user arguments
|
|
2275
|
+
*
|
|
2276
|
+
* @example
|
|
2277
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2278
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2279
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2280
|
+
*
|
|
2281
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2282
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2283
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2284
|
+
* @return {Command} `this` command for chaining
|
|
2285
|
+
*/
|
|
2286
|
+
parse(argv, parseOptions) {
|
|
2287
|
+
this._prepareForParse();
|
|
2288
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2289
|
+
this._parseCommand([], userArgs);
|
|
2290
|
+
return this;
|
|
2291
|
+
}
|
|
2292
|
+
/**
|
|
2293
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2294
|
+
*
|
|
2295
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2296
|
+
*
|
|
2297
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2298
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2299
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2300
|
+
* - `'user'`: just user arguments
|
|
2301
|
+
*
|
|
2302
|
+
* @example
|
|
2303
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2304
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2305
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2306
|
+
*
|
|
2307
|
+
* @param {string[]} [argv]
|
|
2308
|
+
* @param {object} [parseOptions]
|
|
2309
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2310
|
+
* @return {Promise}
|
|
2311
|
+
*/
|
|
2312
|
+
async parseAsync(argv, parseOptions) {
|
|
2313
|
+
this._prepareForParse();
|
|
2314
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2315
|
+
await this._parseCommand([], userArgs);
|
|
2316
|
+
return this;
|
|
2317
|
+
}
|
|
2318
|
+
_prepareForParse() {
|
|
2319
|
+
if (this._savedState === null) {
|
|
2320
|
+
this.options.filter(
|
|
2321
|
+
(option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
|
|
2322
|
+
).forEach((option) => {
|
|
2323
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
2324
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
2325
|
+
this.setOptionValueWithSource(
|
|
2326
|
+
option.attributeName(),
|
|
2327
|
+
true,
|
|
2328
|
+
"default"
|
|
2329
|
+
);
|
|
2330
|
+
}
|
|
2331
|
+
});
|
|
2332
|
+
this.saveStateBeforeParse();
|
|
2333
|
+
} else {
|
|
2334
|
+
this.restoreStateBeforeParse();
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
/**
|
|
2338
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2339
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2340
|
+
*
|
|
2341
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2342
|
+
*/
|
|
2343
|
+
saveStateBeforeParse() {
|
|
2344
|
+
this._savedState = {
|
|
2345
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2346
|
+
_name: this._name,
|
|
2347
|
+
// option values before parse have default values (including false for negated options)
|
|
2348
|
+
// shallow clones
|
|
2349
|
+
_optionValues: { ...this._optionValues },
|
|
2350
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2351
|
+
};
|
|
2352
|
+
}
|
|
2353
|
+
/**
|
|
2354
|
+
* Restore state before parse for calls after the first.
|
|
2355
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2356
|
+
*
|
|
2357
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2358
|
+
*/
|
|
2359
|
+
restoreStateBeforeParse() {
|
|
2360
|
+
if (this._storeOptionsAsProperties)
|
|
2361
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2362
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2363
|
+
this._name = this._savedState._name;
|
|
2364
|
+
this._scriptPath = null;
|
|
2365
|
+
this.rawArgs = [];
|
|
2366
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2367
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2368
|
+
this.args = [];
|
|
2369
|
+
this.processedArgs = [];
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2373
|
+
*
|
|
2374
|
+
* @param {string} executableFile
|
|
2375
|
+
* @param {string} executableDir
|
|
2376
|
+
* @param {string} subcommandName
|
|
2377
|
+
*/
|
|
2378
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2379
|
+
if (fs.existsSync(executableFile)) return;
|
|
2380
|
+
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";
|
|
2381
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2382
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2383
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2384
|
+
- ${executableDirMessage}`;
|
|
2385
|
+
throw new Error(executableMissing);
|
|
2386
|
+
}
|
|
2387
|
+
/**
|
|
2388
|
+
* Execute a sub-command executable.
|
|
2389
|
+
*
|
|
2390
|
+
* @private
|
|
2391
|
+
*/
|
|
2392
|
+
_executeSubCommand(subcommand, args) {
|
|
2393
|
+
args = args.slice();
|
|
2394
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2395
|
+
function findFile(baseDir, baseName) {
|
|
2396
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2397
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2398
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2399
|
+
const foundExt = sourceExt.find(
|
|
2400
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2401
|
+
);
|
|
2402
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2403
|
+
return void 0;
|
|
2404
|
+
}
|
|
2405
|
+
this._checkForMissingMandatoryOptions();
|
|
2406
|
+
this._checkForConflictingOptions();
|
|
2407
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2408
|
+
let executableDir = this._executableDir || "";
|
|
2409
|
+
if (this._scriptPath) {
|
|
2410
|
+
let resolvedScriptPath;
|
|
2411
|
+
try {
|
|
2412
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2413
|
+
} catch {
|
|
2414
|
+
resolvedScriptPath = this._scriptPath;
|
|
2415
|
+
}
|
|
2416
|
+
executableDir = path.resolve(
|
|
2417
|
+
path.dirname(resolvedScriptPath),
|
|
2418
|
+
executableDir
|
|
2419
|
+
);
|
|
2420
|
+
}
|
|
2421
|
+
if (executableDir) {
|
|
2422
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2423
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2424
|
+
const legacyName = path.basename(
|
|
2425
|
+
this._scriptPath,
|
|
2426
|
+
path.extname(this._scriptPath)
|
|
2427
|
+
);
|
|
2428
|
+
if (legacyName !== this._name) {
|
|
2429
|
+
localFile = findFile(
|
|
2430
|
+
executableDir,
|
|
2431
|
+
`${legacyName}-${subcommand._name}`
|
|
2432
|
+
);
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
executableFile = localFile || executableFile;
|
|
2436
|
+
}
|
|
2437
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2438
|
+
let proc;
|
|
2439
|
+
if (process2.platform !== "win32") {
|
|
2440
|
+
if (launchWithNode) {
|
|
2441
|
+
args.unshift(executableFile);
|
|
2442
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2443
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2444
|
+
} else {
|
|
2445
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2446
|
+
}
|
|
2447
|
+
} else {
|
|
2448
|
+
this._checkForMissingExecutable(
|
|
2449
|
+
executableFile,
|
|
2450
|
+
executableDir,
|
|
2451
|
+
subcommand._name
|
|
2452
|
+
);
|
|
2453
|
+
args.unshift(executableFile);
|
|
2454
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2455
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2456
|
+
}
|
|
2457
|
+
if (!proc.killed) {
|
|
2458
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2459
|
+
signals.forEach((signal) => {
|
|
2460
|
+
process2.on(signal, () => {
|
|
2461
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2462
|
+
proc.kill(signal);
|
|
2463
|
+
}
|
|
2464
|
+
});
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
const exitCallback = this._exitCallback;
|
|
2468
|
+
proc.on("close", (code) => {
|
|
2469
|
+
code = code ?? 1;
|
|
2470
|
+
if (!exitCallback) {
|
|
2471
|
+
process2.exit(code);
|
|
2472
|
+
} else {
|
|
2473
|
+
exitCallback(
|
|
2474
|
+
new CommanderError(
|
|
2475
|
+
code,
|
|
2476
|
+
"commander.executeSubCommandAsync",
|
|
2477
|
+
"(close)"
|
|
2478
|
+
)
|
|
2479
|
+
);
|
|
2480
|
+
}
|
|
2481
|
+
});
|
|
2482
|
+
proc.on("error", (err) => {
|
|
2483
|
+
if (err.code === "ENOENT") {
|
|
2484
|
+
this._checkForMissingExecutable(
|
|
2485
|
+
executableFile,
|
|
2486
|
+
executableDir,
|
|
2487
|
+
subcommand._name
|
|
2488
|
+
);
|
|
2489
|
+
} else if (err.code === "EACCES") {
|
|
2490
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2491
|
+
}
|
|
2492
|
+
if (!exitCallback) {
|
|
2493
|
+
process2.exit(1);
|
|
2494
|
+
} else {
|
|
2495
|
+
const wrappedError = new CommanderError(
|
|
2496
|
+
1,
|
|
2497
|
+
"commander.executeSubCommandAsync",
|
|
2498
|
+
"(error)"
|
|
2499
|
+
);
|
|
2500
|
+
wrappedError.nestedError = err;
|
|
2501
|
+
exitCallback(wrappedError);
|
|
2502
|
+
}
|
|
2503
|
+
});
|
|
2504
|
+
this.runningCommand = proc;
|
|
2505
|
+
}
|
|
2506
|
+
/**
|
|
2507
|
+
* @private
|
|
2508
|
+
*/
|
|
2509
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2510
|
+
const subCommand = this._findCommand(commandName);
|
|
2511
|
+
if (!subCommand) this.help({ error: true });
|
|
2512
|
+
subCommand._prepareForParse();
|
|
2513
|
+
let promiseChain;
|
|
2514
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2515
|
+
promiseChain,
|
|
2516
|
+
subCommand,
|
|
2517
|
+
"preSubcommand"
|
|
2518
|
+
);
|
|
2519
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2520
|
+
if (subCommand._executableHandler) {
|
|
2521
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2522
|
+
} else {
|
|
2523
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2524
|
+
}
|
|
2525
|
+
});
|
|
2526
|
+
return promiseChain;
|
|
2527
|
+
}
|
|
2528
|
+
/**
|
|
2529
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2530
|
+
* e.g. help foo
|
|
2531
|
+
*
|
|
2532
|
+
* @private
|
|
2533
|
+
*/
|
|
2534
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2535
|
+
if (!subcommandName) {
|
|
2536
|
+
this.help();
|
|
2537
|
+
}
|
|
2538
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2539
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2540
|
+
subCommand.help();
|
|
2541
|
+
}
|
|
2542
|
+
return this._dispatchSubcommand(
|
|
2543
|
+
subcommandName,
|
|
2544
|
+
[],
|
|
2545
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2546
|
+
);
|
|
2547
|
+
}
|
|
2548
|
+
/**
|
|
2549
|
+
* Check this.args against expected this.registeredArguments.
|
|
2550
|
+
*
|
|
2551
|
+
* @private
|
|
2552
|
+
*/
|
|
2553
|
+
_checkNumberOfArguments() {
|
|
2554
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2555
|
+
if (arg.required && this.args[i] == null) {
|
|
2556
|
+
this.missingArgument(arg.name());
|
|
2557
|
+
}
|
|
2558
|
+
});
|
|
2559
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2560
|
+
return;
|
|
2561
|
+
}
|
|
2562
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2563
|
+
this._excessArguments(this.args);
|
|
2564
|
+
}
|
|
2565
|
+
}
|
|
2566
|
+
/**
|
|
2567
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2568
|
+
*
|
|
2569
|
+
* @private
|
|
2570
|
+
*/
|
|
2571
|
+
_processArguments() {
|
|
2572
|
+
const myParseArg = (argument, value, previous) => {
|
|
2573
|
+
let parsedValue = value;
|
|
2574
|
+
if (value !== null && argument.parseArg) {
|
|
2575
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2576
|
+
parsedValue = this._callParseArg(
|
|
2577
|
+
argument,
|
|
2578
|
+
value,
|
|
2579
|
+
previous,
|
|
2580
|
+
invalidValueMessage
|
|
2581
|
+
);
|
|
2582
|
+
}
|
|
2583
|
+
return parsedValue;
|
|
2584
|
+
};
|
|
2585
|
+
this._checkNumberOfArguments();
|
|
2586
|
+
const processedArgs = [];
|
|
2587
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2588
|
+
let value = declaredArg.defaultValue;
|
|
2589
|
+
if (declaredArg.variadic) {
|
|
2590
|
+
if (index < this.args.length) {
|
|
2591
|
+
value = this.args.slice(index);
|
|
2592
|
+
if (declaredArg.parseArg) {
|
|
2593
|
+
value = value.reduce((processed, v) => {
|
|
2594
|
+
return myParseArg(declaredArg, v, processed);
|
|
2595
|
+
}, declaredArg.defaultValue);
|
|
2596
|
+
}
|
|
2597
|
+
} else if (value === void 0) {
|
|
2598
|
+
value = [];
|
|
2599
|
+
}
|
|
2600
|
+
} else if (index < this.args.length) {
|
|
2601
|
+
value = this.args[index];
|
|
2602
|
+
if (declaredArg.parseArg) {
|
|
2603
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
processedArgs[index] = value;
|
|
2607
|
+
});
|
|
2608
|
+
this.processedArgs = processedArgs;
|
|
2609
|
+
}
|
|
2610
|
+
/**
|
|
2611
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2612
|
+
*
|
|
2613
|
+
* @param {(Promise|undefined)} promise
|
|
2614
|
+
* @param {Function} fn
|
|
2615
|
+
* @return {(Promise|undefined)}
|
|
2616
|
+
* @private
|
|
2617
|
+
*/
|
|
2618
|
+
_chainOrCall(promise, fn) {
|
|
2619
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
2620
|
+
return promise.then(() => fn());
|
|
2621
|
+
}
|
|
2622
|
+
return fn();
|
|
2623
|
+
}
|
|
2624
|
+
/**
|
|
2625
|
+
*
|
|
2626
|
+
* @param {(Promise|undefined)} promise
|
|
2627
|
+
* @param {string} event
|
|
2628
|
+
* @return {(Promise|undefined)}
|
|
2629
|
+
* @private
|
|
2630
|
+
*/
|
|
2631
|
+
_chainOrCallHooks(promise, event) {
|
|
2632
|
+
let result = promise;
|
|
2633
|
+
const hooks = [];
|
|
2634
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2635
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2636
|
+
hooks.push({ hookedCommand, callback });
|
|
2637
|
+
});
|
|
2638
|
+
});
|
|
2639
|
+
if (event === "postAction") {
|
|
2640
|
+
hooks.reverse();
|
|
2641
|
+
}
|
|
2642
|
+
hooks.forEach((hookDetail) => {
|
|
2643
|
+
result = this._chainOrCall(result, () => {
|
|
2644
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2645
|
+
});
|
|
2646
|
+
});
|
|
2647
|
+
return result;
|
|
2648
|
+
}
|
|
2649
|
+
/**
|
|
2650
|
+
*
|
|
2651
|
+
* @param {(Promise|undefined)} promise
|
|
2652
|
+
* @param {Command} subCommand
|
|
2653
|
+
* @param {string} event
|
|
2654
|
+
* @return {(Promise|undefined)}
|
|
2655
|
+
* @private
|
|
2656
|
+
*/
|
|
2657
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2658
|
+
let result = promise;
|
|
2659
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2660
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2661
|
+
result = this._chainOrCall(result, () => {
|
|
2662
|
+
return hook(this, subCommand);
|
|
2663
|
+
});
|
|
2664
|
+
});
|
|
2665
|
+
}
|
|
2666
|
+
return result;
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* Process arguments in context of this command.
|
|
2670
|
+
* Returns action result, in case it is a promise.
|
|
2671
|
+
*
|
|
2672
|
+
* @private
|
|
2673
|
+
*/
|
|
2674
|
+
_parseCommand(operands, unknown) {
|
|
2675
|
+
const parsed = this.parseOptions(unknown);
|
|
2676
|
+
this._parseOptionsEnv();
|
|
2677
|
+
this._parseOptionsImplied();
|
|
2678
|
+
operands = operands.concat(parsed.operands);
|
|
2679
|
+
unknown = parsed.unknown;
|
|
2680
|
+
this.args = operands.concat(unknown);
|
|
2681
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2682
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2683
|
+
}
|
|
2684
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2685
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2686
|
+
}
|
|
2687
|
+
if (this._defaultCommandName) {
|
|
2688
|
+
this._outputHelpIfRequested(unknown);
|
|
2689
|
+
return this._dispatchSubcommand(
|
|
2690
|
+
this._defaultCommandName,
|
|
2691
|
+
operands,
|
|
2692
|
+
unknown
|
|
2693
|
+
);
|
|
2694
|
+
}
|
|
2695
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2696
|
+
this.help({ error: true });
|
|
2697
|
+
}
|
|
2698
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2699
|
+
this._checkForMissingMandatoryOptions();
|
|
2700
|
+
this._checkForConflictingOptions();
|
|
2701
|
+
const checkForUnknownOptions = () => {
|
|
2702
|
+
if (parsed.unknown.length > 0) {
|
|
2703
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2704
|
+
}
|
|
2705
|
+
};
|
|
2706
|
+
const commandEvent = `command:${this.name()}`;
|
|
2707
|
+
if (this._actionHandler) {
|
|
2708
|
+
checkForUnknownOptions();
|
|
2709
|
+
this._processArguments();
|
|
2710
|
+
let promiseChain;
|
|
2711
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2712
|
+
promiseChain = this._chainOrCall(
|
|
2713
|
+
promiseChain,
|
|
2714
|
+
() => this._actionHandler(this.processedArgs)
|
|
2715
|
+
);
|
|
2716
|
+
if (this.parent) {
|
|
2717
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2718
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2719
|
+
});
|
|
2720
|
+
}
|
|
2721
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2722
|
+
return promiseChain;
|
|
2723
|
+
}
|
|
2724
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2725
|
+
checkForUnknownOptions();
|
|
2726
|
+
this._processArguments();
|
|
2727
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2728
|
+
} else if (operands.length) {
|
|
2729
|
+
if (this._findCommand("*")) {
|
|
2730
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2731
|
+
}
|
|
2732
|
+
if (this.listenerCount("command:*")) {
|
|
2733
|
+
this.emit("command:*", operands, unknown);
|
|
2734
|
+
} else if (this.commands.length) {
|
|
2735
|
+
this.unknownCommand();
|
|
2736
|
+
} else {
|
|
2737
|
+
checkForUnknownOptions();
|
|
2738
|
+
this._processArguments();
|
|
2739
|
+
}
|
|
2740
|
+
} else if (this.commands.length) {
|
|
2741
|
+
checkForUnknownOptions();
|
|
2742
|
+
this.help({ error: true });
|
|
2743
|
+
} else {
|
|
2744
|
+
checkForUnknownOptions();
|
|
2745
|
+
this._processArguments();
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
/**
|
|
2749
|
+
* Find matching command.
|
|
2750
|
+
*
|
|
2751
|
+
* @private
|
|
2752
|
+
* @return {Command | undefined}
|
|
2753
|
+
*/
|
|
2754
|
+
_findCommand(name) {
|
|
2755
|
+
if (!name) return void 0;
|
|
2756
|
+
return this.commands.find(
|
|
2757
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2758
|
+
);
|
|
2759
|
+
}
|
|
2760
|
+
/**
|
|
2761
|
+
* Return an option matching `arg` if any.
|
|
2762
|
+
*
|
|
2763
|
+
* @param {string} arg
|
|
2764
|
+
* @return {Option}
|
|
2765
|
+
* @package
|
|
2766
|
+
*/
|
|
2767
|
+
_findOption(arg) {
|
|
2768
|
+
return this.options.find((option) => option.is(arg));
|
|
2769
|
+
}
|
|
2770
|
+
/**
|
|
2771
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2772
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2773
|
+
*
|
|
2774
|
+
* @private
|
|
2775
|
+
*/
|
|
2776
|
+
_checkForMissingMandatoryOptions() {
|
|
2777
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2778
|
+
cmd.options.forEach((anOption) => {
|
|
2779
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2780
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2781
|
+
}
|
|
2782
|
+
});
|
|
2783
|
+
});
|
|
2784
|
+
}
|
|
2785
|
+
/**
|
|
2786
|
+
* Display an error message if conflicting options are used together in this.
|
|
2787
|
+
*
|
|
2788
|
+
* @private
|
|
2789
|
+
*/
|
|
2790
|
+
_checkForConflictingLocalOptions() {
|
|
2791
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2792
|
+
const optionKey = option.attributeName();
|
|
2793
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2794
|
+
return false;
|
|
2795
|
+
}
|
|
2796
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2797
|
+
});
|
|
2798
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2799
|
+
(option) => option.conflictsWith.length > 0
|
|
2800
|
+
);
|
|
2801
|
+
optionsWithConflicting.forEach((option) => {
|
|
2802
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2803
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2804
|
+
);
|
|
2805
|
+
if (conflictingAndDefined) {
|
|
2806
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2807
|
+
}
|
|
2808
|
+
});
|
|
2809
|
+
}
|
|
2810
|
+
/**
|
|
2811
|
+
* Display an error message if conflicting options are used together.
|
|
2812
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2813
|
+
*
|
|
2814
|
+
* @private
|
|
2815
|
+
*/
|
|
2816
|
+
_checkForConflictingOptions() {
|
|
2817
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2818
|
+
cmd._checkForConflictingLocalOptions();
|
|
2819
|
+
});
|
|
2820
|
+
}
|
|
2821
|
+
/**
|
|
2822
|
+
* Parse options from `argv` removing known options,
|
|
2823
|
+
* and return argv split into operands and unknown arguments.
|
|
2824
|
+
*
|
|
2825
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2826
|
+
*
|
|
2827
|
+
* Examples:
|
|
2828
|
+
*
|
|
2829
|
+
* argv => operands, unknown
|
|
2830
|
+
* --known kkk op => [op], []
|
|
2831
|
+
* op --known kkk => [op], []
|
|
2832
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2833
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2834
|
+
*
|
|
2835
|
+
* @param {string[]} args
|
|
2836
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2837
|
+
*/
|
|
2838
|
+
parseOptions(args) {
|
|
2839
|
+
const operands = [];
|
|
2840
|
+
const unknown = [];
|
|
2841
|
+
let dest = operands;
|
|
2842
|
+
function maybeOption(arg) {
|
|
2843
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2844
|
+
}
|
|
2845
|
+
const negativeNumberArg = (arg) => {
|
|
2846
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2847
|
+
return !this._getCommandAndAncestors().some(
|
|
2848
|
+
(cmd) => cmd.options.map((opt) => opt.short).some((short2) => /^-\d$/.test(short2))
|
|
2849
|
+
);
|
|
2850
|
+
};
|
|
2851
|
+
let activeVariadicOption = null;
|
|
2852
|
+
let activeGroup = null;
|
|
2853
|
+
let i = 0;
|
|
2854
|
+
while (i < args.length || activeGroup) {
|
|
2855
|
+
const arg = activeGroup ?? args[i++];
|
|
2856
|
+
activeGroup = null;
|
|
2857
|
+
if (arg === "--") {
|
|
2858
|
+
if (dest === unknown) dest.push(arg);
|
|
2859
|
+
dest.push(...args.slice(i));
|
|
2860
|
+
break;
|
|
2861
|
+
}
|
|
2862
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2863
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2864
|
+
continue;
|
|
2865
|
+
}
|
|
2866
|
+
activeVariadicOption = null;
|
|
2867
|
+
if (maybeOption(arg)) {
|
|
2868
|
+
const option = this._findOption(arg);
|
|
2869
|
+
if (option) {
|
|
2870
|
+
if (option.required) {
|
|
2871
|
+
const value = args[i++];
|
|
2872
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2873
|
+
this.emit(`option:${option.name()}`, value);
|
|
2874
|
+
} else if (option.optional) {
|
|
2875
|
+
let value = null;
|
|
2876
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
2877
|
+
value = args[i++];
|
|
2878
|
+
}
|
|
2879
|
+
this.emit(`option:${option.name()}`, value);
|
|
2880
|
+
} else {
|
|
2881
|
+
this.emit(`option:${option.name()}`);
|
|
2882
|
+
}
|
|
2883
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2884
|
+
continue;
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2888
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2889
|
+
if (option) {
|
|
2890
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2891
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2892
|
+
} else {
|
|
2893
|
+
this.emit(`option:${option.name()}`);
|
|
2894
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2895
|
+
}
|
|
2896
|
+
continue;
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2900
|
+
const index = arg.indexOf("=");
|
|
2901
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2902
|
+
if (option && (option.required || option.optional)) {
|
|
2903
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2904
|
+
continue;
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
2908
|
+
dest = unknown;
|
|
2909
|
+
}
|
|
2910
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2911
|
+
if (this._findCommand(arg)) {
|
|
2912
|
+
operands.push(arg);
|
|
2913
|
+
unknown.push(...args.slice(i));
|
|
2914
|
+
break;
|
|
2915
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2916
|
+
operands.push(arg, ...args.slice(i));
|
|
2917
|
+
break;
|
|
2918
|
+
} else if (this._defaultCommandName) {
|
|
2919
|
+
unknown.push(arg, ...args.slice(i));
|
|
2920
|
+
break;
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
if (this._passThroughOptions) {
|
|
2924
|
+
dest.push(arg, ...args.slice(i));
|
|
2925
|
+
break;
|
|
2926
|
+
}
|
|
2927
|
+
dest.push(arg);
|
|
2928
|
+
}
|
|
2929
|
+
return { operands, unknown };
|
|
2930
|
+
}
|
|
2931
|
+
/**
|
|
2932
|
+
* Return an object containing local option values as key-value pairs.
|
|
2933
|
+
*
|
|
2934
|
+
* @return {object}
|
|
2935
|
+
*/
|
|
2936
|
+
opts() {
|
|
2937
|
+
if (this._storeOptionsAsProperties) {
|
|
2938
|
+
const result = {};
|
|
2939
|
+
const len = this.options.length;
|
|
2940
|
+
for (let i = 0; i < len; i++) {
|
|
2941
|
+
const key = this.options[i].attributeName();
|
|
2942
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2943
|
+
}
|
|
2944
|
+
return result;
|
|
2945
|
+
}
|
|
2946
|
+
return this._optionValues;
|
|
2947
|
+
}
|
|
2948
|
+
/**
|
|
2949
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2950
|
+
*
|
|
2951
|
+
* @return {object}
|
|
2952
|
+
*/
|
|
2953
|
+
optsWithGlobals() {
|
|
2954
|
+
return this._getCommandAndAncestors().reduce(
|
|
2955
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2956
|
+
{}
|
|
2957
|
+
);
|
|
2958
|
+
}
|
|
2959
|
+
/**
|
|
2960
|
+
* Display error message and exit (or call exitOverride).
|
|
2961
|
+
*
|
|
2962
|
+
* @param {string} message
|
|
2963
|
+
* @param {object} [errorOptions]
|
|
2964
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2965
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2966
|
+
*/
|
|
2967
|
+
error(message, errorOptions) {
|
|
2968
|
+
this._outputConfiguration.outputError(
|
|
2969
|
+
`${message}
|
|
2970
|
+
`,
|
|
2971
|
+
this._outputConfiguration.writeErr
|
|
2972
|
+
);
|
|
2973
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2974
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2975
|
+
`);
|
|
2976
|
+
} else if (this._showHelpAfterError) {
|
|
2977
|
+
this._outputConfiguration.writeErr("\n");
|
|
2978
|
+
this.outputHelp({ error: true });
|
|
2979
|
+
}
|
|
2980
|
+
const config = errorOptions || {};
|
|
2981
|
+
const exitCode = config.exitCode || 1;
|
|
2982
|
+
const code = config.code || "commander.error";
|
|
2983
|
+
this._exit(exitCode, code, message);
|
|
2984
|
+
}
|
|
2985
|
+
/**
|
|
2986
|
+
* Apply any option related environment variables, if option does
|
|
2987
|
+
* not have a value from cli or client code.
|
|
2988
|
+
*
|
|
2989
|
+
* @private
|
|
2990
|
+
*/
|
|
2991
|
+
_parseOptionsEnv() {
|
|
2992
|
+
this.options.forEach((option) => {
|
|
2993
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2994
|
+
const optionKey = option.attributeName();
|
|
2995
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2996
|
+
this.getOptionValueSource(optionKey)
|
|
2997
|
+
)) {
|
|
2998
|
+
if (option.required || option.optional) {
|
|
2999
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
3000
|
+
} else {
|
|
3001
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
}
|
|
3005
|
+
});
|
|
3006
|
+
}
|
|
3007
|
+
/**
|
|
3008
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
3009
|
+
*
|
|
3010
|
+
* @private
|
|
3011
|
+
*/
|
|
3012
|
+
_parseOptionsImplied() {
|
|
3013
|
+
const dualHelper = new DualOptions(this.options);
|
|
3014
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
3015
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
3016
|
+
};
|
|
3017
|
+
this.options.filter(
|
|
3018
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
3019
|
+
this.getOptionValue(option.attributeName()),
|
|
3020
|
+
option
|
|
3021
|
+
)
|
|
3022
|
+
).forEach((option) => {
|
|
3023
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
3024
|
+
this.setOptionValueWithSource(
|
|
3025
|
+
impliedKey,
|
|
3026
|
+
option.implied[impliedKey],
|
|
3027
|
+
"implied"
|
|
3028
|
+
);
|
|
3029
|
+
});
|
|
3030
|
+
});
|
|
3031
|
+
}
|
|
3032
|
+
/**
|
|
3033
|
+
* Argument `name` is missing.
|
|
3034
|
+
*
|
|
3035
|
+
* @param {string} name
|
|
3036
|
+
* @private
|
|
3037
|
+
*/
|
|
3038
|
+
missingArgument(name) {
|
|
3039
|
+
const message = `error: missing required argument '${name}'`;
|
|
3040
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
3041
|
+
}
|
|
3042
|
+
/**
|
|
3043
|
+
* `Option` is missing an argument.
|
|
3044
|
+
*
|
|
3045
|
+
* @param {Option} option
|
|
3046
|
+
* @private
|
|
3047
|
+
*/
|
|
3048
|
+
optionMissingArgument(option) {
|
|
3049
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
3050
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
3051
|
+
}
|
|
3052
|
+
/**
|
|
3053
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
3054
|
+
*
|
|
3055
|
+
* @param {Option} option
|
|
3056
|
+
* @private
|
|
3057
|
+
*/
|
|
3058
|
+
missingMandatoryOptionValue(option) {
|
|
3059
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
3060
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
3061
|
+
}
|
|
3062
|
+
/**
|
|
3063
|
+
* `Option` conflicts with another option.
|
|
3064
|
+
*
|
|
3065
|
+
* @param {Option} option
|
|
3066
|
+
* @param {Option} conflictingOption
|
|
3067
|
+
* @private
|
|
3068
|
+
*/
|
|
3069
|
+
_conflictingOption(option, conflictingOption) {
|
|
3070
|
+
const findBestOptionFromValue = (option2) => {
|
|
3071
|
+
const optionKey = option2.attributeName();
|
|
3072
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
3073
|
+
const negativeOption = this.options.find(
|
|
3074
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
3075
|
+
);
|
|
3076
|
+
const positiveOption = this.options.find(
|
|
3077
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
3078
|
+
);
|
|
3079
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
3080
|
+
return negativeOption;
|
|
3081
|
+
}
|
|
3082
|
+
return positiveOption || option2;
|
|
3083
|
+
};
|
|
3084
|
+
const getErrorMessage = (option2) => {
|
|
3085
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
3086
|
+
const optionKey = bestOption.attributeName();
|
|
3087
|
+
const source = this.getOptionValueSource(optionKey);
|
|
3088
|
+
if (source === "env") {
|
|
3089
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
3090
|
+
}
|
|
3091
|
+
return `option '${bestOption.flags}'`;
|
|
3092
|
+
};
|
|
3093
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
3094
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
3095
|
+
}
|
|
3096
|
+
/**
|
|
3097
|
+
* Unknown option `flag`.
|
|
3098
|
+
*
|
|
3099
|
+
* @param {string} flag
|
|
3100
|
+
* @private
|
|
3101
|
+
*/
|
|
3102
|
+
unknownOption(flag) {
|
|
3103
|
+
if (this._allowUnknownOption) return;
|
|
3104
|
+
let suggestion = "";
|
|
3105
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
3106
|
+
let candidateFlags = [];
|
|
3107
|
+
let command = this;
|
|
3108
|
+
do {
|
|
3109
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
3110
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
3111
|
+
command = command.parent;
|
|
3112
|
+
} while (command && !command._enablePositionalOptions);
|
|
3113
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
3114
|
+
}
|
|
3115
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
3116
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
3117
|
+
}
|
|
3118
|
+
/**
|
|
3119
|
+
* Excess arguments, more than expected.
|
|
3120
|
+
*
|
|
3121
|
+
* @param {string[]} receivedArgs
|
|
3122
|
+
* @private
|
|
3123
|
+
*/
|
|
3124
|
+
_excessArguments(receivedArgs) {
|
|
3125
|
+
if (this._allowExcessArguments) return;
|
|
3126
|
+
const expected = this.registeredArguments.length;
|
|
3127
|
+
const s = expected === 1 ? "" : "s";
|
|
3128
|
+
const received = receivedArgs.length;
|
|
3129
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
3130
|
+
const details = receivedArgs.join(", ");
|
|
3131
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
|
|
3132
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
3133
|
+
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Unknown command.
|
|
3136
|
+
*
|
|
3137
|
+
* @private
|
|
3138
|
+
*/
|
|
3139
|
+
unknownCommand() {
|
|
3140
|
+
const unknownName = this.args[0];
|
|
3141
|
+
let suggestion = "";
|
|
3142
|
+
if (this._showSuggestionAfterError) {
|
|
3143
|
+
const candidateNames = [];
|
|
3144
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
3145
|
+
candidateNames.push(command.name());
|
|
3146
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
3147
|
+
});
|
|
3148
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
3149
|
+
}
|
|
3150
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
3151
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
3152
|
+
}
|
|
3153
|
+
/**
|
|
3154
|
+
* Get or set the program version.
|
|
3155
|
+
*
|
|
3156
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
3157
|
+
*
|
|
3158
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
3159
|
+
*
|
|
3160
|
+
* @param {string} [str]
|
|
3161
|
+
* @param {string} [flags]
|
|
3162
|
+
* @param {string} [description]
|
|
3163
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
3164
|
+
*/
|
|
3165
|
+
version(str, flags, description) {
|
|
3166
|
+
if (str === void 0) return this._version;
|
|
3167
|
+
this._version = str;
|
|
3168
|
+
flags = flags || "-V, --version";
|
|
3169
|
+
description = description || "output the version number";
|
|
3170
|
+
const versionOption = this.createOption(flags, description);
|
|
3171
|
+
this._versionOptionName = versionOption.attributeName();
|
|
3172
|
+
this._registerOption(versionOption);
|
|
3173
|
+
this.on("option:" + versionOption.name(), () => {
|
|
3174
|
+
this._outputConfiguration.writeOut(`${str}
|
|
3175
|
+
`);
|
|
3176
|
+
this._exit(0, "commander.version", str);
|
|
3177
|
+
});
|
|
3178
|
+
return this;
|
|
3179
|
+
}
|
|
3180
|
+
/**
|
|
3181
|
+
* Set the description.
|
|
3182
|
+
*
|
|
3183
|
+
* @param {string} [str]
|
|
3184
|
+
* @param {object} [argsDescription]
|
|
3185
|
+
* @return {(string|Command)}
|
|
3186
|
+
*/
|
|
3187
|
+
description(str, argsDescription) {
|
|
3188
|
+
if (str === void 0 && argsDescription === void 0)
|
|
3189
|
+
return this._description;
|
|
3190
|
+
this._description = str;
|
|
3191
|
+
if (argsDescription) {
|
|
3192
|
+
this._argsDescription = argsDescription;
|
|
3193
|
+
}
|
|
3194
|
+
return this;
|
|
3195
|
+
}
|
|
3196
|
+
/**
|
|
3197
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
3198
|
+
*
|
|
3199
|
+
* @param {string} [str]
|
|
3200
|
+
* @return {(string|Command)}
|
|
3201
|
+
*/
|
|
3202
|
+
summary(str) {
|
|
3203
|
+
if (str === void 0) return this._summary;
|
|
3204
|
+
this._summary = str;
|
|
3205
|
+
return this;
|
|
3206
|
+
}
|
|
3207
|
+
/**
|
|
3208
|
+
* Set an alias for the command.
|
|
3209
|
+
*
|
|
3210
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
3211
|
+
*
|
|
3212
|
+
* @param {string} [alias]
|
|
3213
|
+
* @return {(string|Command)}
|
|
3214
|
+
*/
|
|
3215
|
+
alias(alias) {
|
|
3216
|
+
if (alias === void 0) return this._aliases[0];
|
|
3217
|
+
let command = this;
|
|
3218
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
3219
|
+
command = this.commands[this.commands.length - 1];
|
|
3220
|
+
}
|
|
3221
|
+
if (alias === command._name)
|
|
3222
|
+
throw new Error("Command alias can't be the same as its name");
|
|
3223
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
3224
|
+
if (matchingCommand) {
|
|
3225
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
3226
|
+
throw new Error(
|
|
3227
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
3228
|
+
);
|
|
3229
|
+
}
|
|
3230
|
+
command._aliases.push(alias);
|
|
3231
|
+
return this;
|
|
3232
|
+
}
|
|
3233
|
+
/**
|
|
3234
|
+
* Set aliases for the command.
|
|
3235
|
+
*
|
|
3236
|
+
* Only the first alias is shown in the auto-generated help.
|
|
3237
|
+
*
|
|
3238
|
+
* @param {string[]} [aliases]
|
|
3239
|
+
* @return {(string[]|Command)}
|
|
3240
|
+
*/
|
|
3241
|
+
aliases(aliases) {
|
|
3242
|
+
if (aliases === void 0) return this._aliases;
|
|
3243
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
3244
|
+
return this;
|
|
3245
|
+
}
|
|
3246
|
+
/**
|
|
3247
|
+
* Set / get the command usage `str`.
|
|
3248
|
+
*
|
|
3249
|
+
* @param {string} [str]
|
|
3250
|
+
* @return {(string|Command)}
|
|
3251
|
+
*/
|
|
3252
|
+
usage(str) {
|
|
3253
|
+
if (str === void 0) {
|
|
3254
|
+
if (this._usage) return this._usage;
|
|
3255
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3256
|
+
return humanReadableArgName(arg);
|
|
3257
|
+
});
|
|
3258
|
+
return [].concat(
|
|
3259
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3260
|
+
this.commands.length ? "[command]" : [],
|
|
3261
|
+
this.registeredArguments.length ? args : []
|
|
3262
|
+
).join(" ");
|
|
3263
|
+
}
|
|
3264
|
+
this._usage = str;
|
|
3265
|
+
return this;
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* Get or set the name of the command.
|
|
3269
|
+
*
|
|
3270
|
+
* @param {string} [str]
|
|
3271
|
+
* @return {(string|Command)}
|
|
3272
|
+
*/
|
|
3273
|
+
name(str) {
|
|
3274
|
+
if (str === void 0) return this._name;
|
|
3275
|
+
this._name = str;
|
|
3276
|
+
return this;
|
|
3277
|
+
}
|
|
3278
|
+
/**
|
|
3279
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
3280
|
+
*
|
|
3281
|
+
* @param {string} [heading]
|
|
3282
|
+
* @return {Command | string}
|
|
3283
|
+
*/
|
|
3284
|
+
helpGroup(heading) {
|
|
3285
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
3286
|
+
this._helpGroupHeading = heading;
|
|
3287
|
+
return this;
|
|
3288
|
+
}
|
|
3289
|
+
/**
|
|
3290
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
3291
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
3292
|
+
*
|
|
3293
|
+
* @example
|
|
3294
|
+
* program.commandsGroup('Development Commands:);
|
|
3295
|
+
* program.command('watch')...
|
|
3296
|
+
* program.command('lint')...
|
|
3297
|
+
* ...
|
|
3298
|
+
*
|
|
3299
|
+
* @param {string} [heading]
|
|
3300
|
+
* @returns {Command | string}
|
|
3301
|
+
*/
|
|
3302
|
+
commandsGroup(heading) {
|
|
3303
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
3304
|
+
this._defaultCommandGroup = heading;
|
|
3305
|
+
return this;
|
|
3306
|
+
}
|
|
3307
|
+
/**
|
|
3308
|
+
* Set/get the default help group heading for options added to this command.
|
|
3309
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
3310
|
+
*
|
|
3311
|
+
* @example
|
|
3312
|
+
* program
|
|
3313
|
+
* .optionsGroup('Development Options:')
|
|
3314
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
3315
|
+
* .option('-p, --profile', 'output profiling information')
|
|
3316
|
+
*
|
|
3317
|
+
* @param {string} [heading]
|
|
3318
|
+
* @returns {Command | string}
|
|
3319
|
+
*/
|
|
3320
|
+
optionsGroup(heading) {
|
|
3321
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
3322
|
+
this._defaultOptionGroup = heading;
|
|
3323
|
+
return this;
|
|
3324
|
+
}
|
|
3325
|
+
/**
|
|
3326
|
+
* @param {Option} option
|
|
3327
|
+
* @private
|
|
3328
|
+
*/
|
|
3329
|
+
_initOptionGroup(option) {
|
|
3330
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
3331
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
3332
|
+
}
|
|
3333
|
+
/**
|
|
3334
|
+
* @param {Command} cmd
|
|
3335
|
+
* @private
|
|
3336
|
+
*/
|
|
3337
|
+
_initCommandGroup(cmd) {
|
|
3338
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
3339
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
3340
|
+
}
|
|
3341
|
+
/**
|
|
3342
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3343
|
+
* or import.meta.filename.
|
|
3344
|
+
*
|
|
3345
|
+
* (Used internally and public although not documented in README.)
|
|
3346
|
+
*
|
|
3347
|
+
* @example
|
|
3348
|
+
* program.nameFromFilename(import.meta.filename);
|
|
3349
|
+
*
|
|
3350
|
+
* @param {string} filename
|
|
3351
|
+
* @return {Command}
|
|
3352
|
+
*/
|
|
3353
|
+
nameFromFilename(filename) {
|
|
3354
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3355
|
+
return this;
|
|
3356
|
+
}
|
|
3357
|
+
/**
|
|
3358
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3359
|
+
*
|
|
3360
|
+
* @example
|
|
3361
|
+
* program.executableDir(import.meta.dirname);
|
|
3362
|
+
* // or
|
|
3363
|
+
* program.executableDir('subcommands');
|
|
3364
|
+
*
|
|
3365
|
+
* @param {string} [path]
|
|
3366
|
+
* @return {(string|null|Command)}
|
|
3367
|
+
*/
|
|
3368
|
+
executableDir(path3) {
|
|
3369
|
+
if (path3 === void 0) return this._executableDir;
|
|
3370
|
+
this._executableDir = path3;
|
|
3371
|
+
return this;
|
|
3372
|
+
}
|
|
3373
|
+
/**
|
|
3374
|
+
* Return program help documentation.
|
|
3375
|
+
*
|
|
3376
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3377
|
+
* @return {string}
|
|
3378
|
+
*/
|
|
3379
|
+
helpInformation(contextOptions) {
|
|
3380
|
+
const helper = this.createHelp();
|
|
3381
|
+
const context = this._getOutputContext(contextOptions);
|
|
3382
|
+
helper.prepareContext({
|
|
3383
|
+
error: context.error,
|
|
3384
|
+
helpWidth: context.helpWidth,
|
|
3385
|
+
outputHasColors: context.hasColors
|
|
3386
|
+
});
|
|
3387
|
+
const text = helper.formatHelp(this, helper);
|
|
3388
|
+
if (context.hasColors) return text;
|
|
3389
|
+
return this._outputConfiguration.stripColor(text);
|
|
3390
|
+
}
|
|
3391
|
+
/**
|
|
3392
|
+
* @typedef HelpContext
|
|
3393
|
+
* @type {object}
|
|
3394
|
+
* @property {boolean} error
|
|
3395
|
+
* @property {number} helpWidth
|
|
3396
|
+
* @property {boolean} hasColors
|
|
3397
|
+
* @property {function} write - includes stripColor if needed
|
|
3398
|
+
*
|
|
3399
|
+
* @returns {HelpContext}
|
|
3400
|
+
* @private
|
|
3401
|
+
*/
|
|
3402
|
+
_getOutputContext(contextOptions) {
|
|
3403
|
+
contextOptions = contextOptions || {};
|
|
3404
|
+
const error = !!contextOptions.error;
|
|
3405
|
+
let baseWrite;
|
|
3406
|
+
let hasColors;
|
|
3407
|
+
let helpWidth;
|
|
3408
|
+
if (error) {
|
|
3409
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3410
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3411
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3412
|
+
} else {
|
|
3413
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3414
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3415
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3416
|
+
}
|
|
3417
|
+
const write = (str) => {
|
|
3418
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3419
|
+
return baseWrite(str);
|
|
3420
|
+
};
|
|
3421
|
+
return { error, write, hasColors, helpWidth };
|
|
3422
|
+
}
|
|
3423
|
+
/**
|
|
3424
|
+
* Output help information for this command.
|
|
3425
|
+
*
|
|
3426
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3427
|
+
*
|
|
3428
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3429
|
+
*/
|
|
3430
|
+
outputHelp(contextOptions) {
|
|
3431
|
+
let deprecatedCallback;
|
|
3432
|
+
if (typeof contextOptions === "function") {
|
|
3433
|
+
deprecatedCallback = contextOptions;
|
|
3434
|
+
contextOptions = void 0;
|
|
3435
|
+
}
|
|
3436
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3437
|
+
const eventContext = {
|
|
3438
|
+
error: outputContext.error,
|
|
3439
|
+
write: outputContext.write,
|
|
3440
|
+
command: this
|
|
3441
|
+
};
|
|
3442
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3443
|
+
this.emit("beforeHelp", eventContext);
|
|
3444
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3445
|
+
if (deprecatedCallback) {
|
|
3446
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3447
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3448
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
outputContext.write(helpInformation);
|
|
3452
|
+
if (this._getHelpOption()?.long) {
|
|
3453
|
+
this.emit(this._getHelpOption().long);
|
|
3454
|
+
}
|
|
3455
|
+
this.emit("afterHelp", eventContext);
|
|
3456
|
+
this._getCommandAndAncestors().forEach(
|
|
3457
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3458
|
+
);
|
|
3459
|
+
}
|
|
3460
|
+
/**
|
|
3461
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3462
|
+
* Pass in false to disable the built-in help option.
|
|
3463
|
+
*
|
|
3464
|
+
* @example
|
|
3465
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3466
|
+
* program.helpOption(false); // disable
|
|
3467
|
+
*
|
|
3468
|
+
* @param {(string | boolean)} flags
|
|
3469
|
+
* @param {string} [description]
|
|
3470
|
+
* @return {Command} `this` command for chaining
|
|
3471
|
+
*/
|
|
3472
|
+
helpOption(flags, description) {
|
|
3473
|
+
if (typeof flags === "boolean") {
|
|
3474
|
+
if (flags) {
|
|
3475
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
3476
|
+
if (this._defaultOptionGroup) {
|
|
3477
|
+
this._initOptionGroup(this._getHelpOption());
|
|
3478
|
+
}
|
|
3479
|
+
} else {
|
|
3480
|
+
this._helpOption = null;
|
|
3481
|
+
}
|
|
3482
|
+
return this;
|
|
3483
|
+
}
|
|
3484
|
+
this._helpOption = this.createOption(
|
|
3485
|
+
flags ?? "-h, --help",
|
|
3486
|
+
description ?? "display help for command"
|
|
3487
|
+
);
|
|
3488
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
3489
|
+
return this;
|
|
3490
|
+
}
|
|
3491
|
+
/**
|
|
3492
|
+
* Lazy create help option.
|
|
3493
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3494
|
+
*
|
|
3495
|
+
* @returns {(Option | null)} the help option
|
|
3496
|
+
* @package
|
|
3497
|
+
*/
|
|
3498
|
+
_getHelpOption() {
|
|
3499
|
+
if (this._helpOption === void 0) {
|
|
3500
|
+
this.helpOption(void 0, void 0);
|
|
3501
|
+
}
|
|
3502
|
+
return this._helpOption;
|
|
3503
|
+
}
|
|
3504
|
+
/**
|
|
3505
|
+
* Supply your own option to use for the built-in help option.
|
|
3506
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3507
|
+
*
|
|
3508
|
+
* @param {Option} option
|
|
3509
|
+
* @return {Command} `this` command for chaining
|
|
3510
|
+
*/
|
|
3511
|
+
addHelpOption(option) {
|
|
3512
|
+
this._helpOption = option;
|
|
3513
|
+
this._initOptionGroup(option);
|
|
3514
|
+
return this;
|
|
3515
|
+
}
|
|
3516
|
+
/**
|
|
3517
|
+
* Output help information and exit.
|
|
3518
|
+
*
|
|
3519
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3520
|
+
*
|
|
3521
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3522
|
+
*/
|
|
3523
|
+
help(contextOptions) {
|
|
3524
|
+
this.outputHelp(contextOptions);
|
|
3525
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3526
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3527
|
+
exitCode = 1;
|
|
3528
|
+
}
|
|
3529
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3530
|
+
}
|
|
3531
|
+
/**
|
|
3532
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3533
|
+
* @typedef HelpTextEventContext
|
|
3534
|
+
* @type {object}
|
|
3535
|
+
* @property {boolean} error
|
|
3536
|
+
* @property {Command} command
|
|
3537
|
+
* @property {function} write
|
|
3538
|
+
*/
|
|
3539
|
+
/**
|
|
3540
|
+
* Add additional text to be displayed with the built-in help.
|
|
3541
|
+
*
|
|
3542
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3543
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3544
|
+
*
|
|
3545
|
+
* @param {string} position - before or after built-in help
|
|
3546
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3547
|
+
* @return {Command} `this` command for chaining
|
|
3548
|
+
*/
|
|
3549
|
+
addHelpText(position, text) {
|
|
3550
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3551
|
+
if (!allowedValues.includes(position)) {
|
|
3552
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3553
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3554
|
+
}
|
|
3555
|
+
const helpEvent = `${position}Help`;
|
|
3556
|
+
this.on(helpEvent, (context) => {
|
|
3557
|
+
let helpStr;
|
|
3558
|
+
if (typeof text === "function") {
|
|
3559
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3560
|
+
} else {
|
|
3561
|
+
helpStr = text;
|
|
3562
|
+
}
|
|
3563
|
+
if (helpStr) {
|
|
3564
|
+
context.write(`${helpStr}
|
|
3565
|
+
`);
|
|
3566
|
+
}
|
|
3567
|
+
});
|
|
3568
|
+
return this;
|
|
3569
|
+
}
|
|
3570
|
+
/**
|
|
3571
|
+
* Output help information if help flags specified
|
|
3572
|
+
*
|
|
3573
|
+
* @param {Array} args - array of options to search for help flags
|
|
3574
|
+
* @private
|
|
3575
|
+
*/
|
|
3576
|
+
_outputHelpIfRequested(args) {
|
|
3577
|
+
const helpOption = this._getHelpOption();
|
|
3578
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3579
|
+
if (helpRequested) {
|
|
3580
|
+
this.outputHelp();
|
|
3581
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3582
|
+
}
|
|
3583
|
+
}
|
|
3584
|
+
};
|
|
3585
|
+
function incrementNodeInspectorPort(args) {
|
|
3586
|
+
return args.map((arg) => {
|
|
3587
|
+
if (!arg.startsWith("--inspect")) {
|
|
3588
|
+
return arg;
|
|
3589
|
+
}
|
|
3590
|
+
let debugOption;
|
|
3591
|
+
let debugHost = "127.0.0.1";
|
|
3592
|
+
let debugPort = "9229";
|
|
3593
|
+
let match;
|
|
3594
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3595
|
+
debugOption = match[1];
|
|
3596
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3597
|
+
debugOption = match[1];
|
|
3598
|
+
if (/^\d+$/.test(match[3])) {
|
|
3599
|
+
debugPort = match[3];
|
|
3600
|
+
} else {
|
|
3601
|
+
debugHost = match[3];
|
|
3602
|
+
}
|
|
3603
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3604
|
+
debugOption = match[1];
|
|
3605
|
+
debugHost = match[3];
|
|
3606
|
+
debugPort = match[4];
|
|
3607
|
+
}
|
|
3608
|
+
if (debugOption && debugPort !== "0") {
|
|
3609
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3610
|
+
}
|
|
3611
|
+
return arg;
|
|
3612
|
+
});
|
|
3613
|
+
}
|
|
3614
|
+
function useColor() {
|
|
3615
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3616
|
+
return false;
|
|
3617
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3618
|
+
return true;
|
|
3619
|
+
return void 0;
|
|
3620
|
+
}
|
|
3621
|
+
|
|
3622
|
+
// node_modules/commander/index.js
|
|
3623
|
+
var program = new Command();
|
|
250
3624
|
|
|
251
3625
|
// src/cli/agents.ts
|
|
252
3626
|
import { dirname as dirname3 } from "path";
|
|
@@ -334,7 +3708,6 @@ function formatStaleWorkspaceWarning(staleness) {
|
|
|
334
3708
|
}
|
|
335
3709
|
|
|
336
3710
|
// src/cli/handle.ts
|
|
337
|
-
import { CommanderError } from "commander";
|
|
338
3711
|
var UsageError = class extends Error {
|
|
339
3712
|
name = "UsageError";
|
|
340
3713
|
};
|
|
@@ -385,8 +3758,8 @@ function classifyError(err) {
|
|
|
385
3758
|
if (err instanceof UsageError || // `mu log --kind task|note|...`: a tag naming a projectable entity.
|
|
386
3759
|
err instanceof LogKindReservedError || // abort on a non-pi agent: the operator picked the wrong verb (kick).
|
|
387
3760
|
err instanceof AgentAbortNeedsCtlError || // send --fresh on an agent with no control socket: wrong recipe.
|
|
388
|
-
err instanceof AgentFreshNeedsCtlError || // an unsupported slash command to a pi agent: --via mux is the recipe.
|
|
389
|
-
err instanceof AgentSlashCommandUnsupportedError || err instanceof WorkstreamNameInvalidError || err instanceof WorkstreamNameReservedError || // Same typed-*Invalid* class: a task id or a title the operator
|
|
3761
|
+
err instanceof AgentFreshNeedsCtlError || // an empty send or unsupported slash command to a pi agent: --via mux is the recipe.
|
|
3762
|
+
err instanceof AgentEmptySendError || err instanceof AgentSlashCommandUnsupportedError || err instanceof WorkstreamNameInvalidError || err instanceof WorkstreamNameReservedError || // Same typed-*Invalid* class: a task id or a title the operator
|
|
390
3763
|
// typed that cannot become an id. isUsageClassError prints --help.
|
|
391
3764
|
err instanceof TaskIdInvalidError || err instanceof TaskTitleSlugEmptyError || // The operator asked the ACTIVE backend for something it cannot do:
|
|
392
3765
|
// a `--cli` the mux does not recognise as an agent kind, or a
|
|
@@ -405,7 +3778,7 @@ function classifyError(err) {
|
|
|
405
3778
|
}
|
|
406
3779
|
if (err instanceof NameAmbiguousError || err instanceof AgentExistsError || err instanceof AgentNameExhaustedError || err instanceof TaskExistsError || err instanceof TaskAlreadyOwnedError || // Substate refusals (ts_4): a missing --why, a park from the wrong
|
|
407
3780
|
// phase, a claim on a parked task, a pair outside TASK_SUBSTATES.
|
|
408
|
-
err instanceof SubstateReasonRequiredError || err instanceof TaskParkStateError || err instanceof TaskParkedError || err instanceof TaskInTriageError || err instanceof InvalidSubstateError || err instanceof TaskClaimStaleWorkspaceError || err instanceof TaskNotInWorkstreamError || err instanceof AgentNotInWorkstreamError || err instanceof PaneNotInSessionError || err instanceof CycleError || err instanceof CrossWorkstreamEdgeError || err instanceof WorkspaceExistsError || err instanceof WorkspacePathNotEmptyError || err instanceof WorkspacePreservedError || err instanceof HomeDirAsProjectRootError || err instanceof WorkspaceVcsRequiredError || err instanceof WorkspaceDirtyError || err instanceof ClaimerNotRegisteredError || err instanceof SchemaTooOldError || err instanceof SchemaTooNewError || err instanceof WorkstreamExistsError || // Rebuild refuses to overwrite an existing target or to write onto
|
|
3781
|
+
err instanceof SubstateReasonRequiredError || err instanceof TaskParkStateError || err instanceof TaskParkedError || err instanceof TaskInTriageError || err instanceof InvalidSubstateError || err instanceof TaskClaimStaleWorkspaceError || err instanceof TaskNotInWorkstreamError || err instanceof AgentNotInWorkstreamError || err instanceof WorkspaceOwnerBusyError || err instanceof PaneNotInSessionError || err instanceof CycleError || err instanceof CrossWorkstreamEdgeError || err instanceof WorkspaceExistsError || err instanceof WorkspacePathNotEmptyError || err instanceof WorkspacePreservedError || err instanceof HomeDirAsProjectRootError || err instanceof WorkspaceVcsRequiredError || err instanceof WorkspaceDirtyError || err instanceof ClaimerNotRegisteredError || err instanceof SchemaTooOldError || err instanceof SchemaTooNewError || err instanceof WorkstreamExistsError || // Rebuild refuses to overwrite an existing target or to write onto
|
|
409
3782
|
// the source DB: both are name/state collisions, not usage errors.
|
|
410
3783
|
err instanceof RebuildTargetExistsError || err instanceof RebuildTargetIsSourceError || // An abbreviated group id matching several groups: the operator must
|
|
411
3784
|
// disambiguate. Guessing would be catastrophic for `mu undo`.
|
|
@@ -435,6 +3808,9 @@ function classifyError(err) {
|
|
|
435
3808
|
if (err instanceof AgentSpawnCliNotFoundError) {
|
|
436
3809
|
return { label: "spawn cli not found", exitCode: 1 };
|
|
437
3810
|
}
|
|
3811
|
+
if (err instanceof AgentSendIndeterminateError) {
|
|
3812
|
+
return { label: "send delivery unknown", exitCode: 1 };
|
|
3813
|
+
}
|
|
438
3814
|
if (err instanceof AgentCtlUnreachableError) {
|
|
439
3815
|
return { label: "ctl unreachable", exitCode: 1 };
|
|
440
3816
|
}
|
|
@@ -1922,8 +5298,8 @@ function buildJsonTree(db, workstream, taskId, down, seen) {
|
|
|
1922
5298
|
}
|
|
1923
5299
|
|
|
1924
5300
|
// src/cli/tasks/wire.ts
|
|
1925
|
-
function wireTaskCommands(
|
|
1926
|
-
const task =
|
|
5301
|
+
function wireTaskCommands(program2) {
|
|
5302
|
+
const task = program2.command("task").description("Task graph commands");
|
|
1927
5303
|
task.command("add [id]").description(
|
|
1928
5304
|
"Add a task to the graph. The id positional is optional \u2014 if omitted, derived from --title via slugify (collisions get _2, _3, \u2026 suffixes). Auto-derived ids are capped at ~40 chars with a word-boundary cut, so long titles drop trailing clauses; pass the <id> positional explicitly to override."
|
|
1929
5305
|
).requiredOption("-t, --title <title>", "task title").requiredOption("-i, --impact <n>", "impact 1..100", parseImpact).requiredOption("-e, --effort-days <days>", "effort in days (>0)", parsePositiveNumber).option(
|
|
@@ -2186,12 +5562,32 @@ async function cmdSpawn(db, rawName, opts) {
|
|
|
2186
5562
|
console.error(pc.yellow(`warning: ${warn.message}`));
|
|
2187
5563
|
printNextStepsTo(warn.errorNextSteps(), "stderr");
|
|
2188
5564
|
}
|
|
2189
|
-
const
|
|
5565
|
+
const trustSkip = agent.trustDialog === true && sendText !== void 0;
|
|
5566
|
+
if (agent.trustDialog === true) {
|
|
5567
|
+
console.error(
|
|
5568
|
+
pc.yellow(
|
|
5569
|
+
`warning: ${name} is showing Claude's folder-trust dialog (default "No, exit")${trustSkip ? "; --send skipped" : ""}`
|
|
5570
|
+
)
|
|
5571
|
+
);
|
|
5572
|
+
}
|
|
5573
|
+
const trustNext = agent.trustDialog === true ? [
|
|
5574
|
+
{
|
|
5575
|
+
intent: "Answer the trust dialog by hand (attach the pane), then send",
|
|
5576
|
+
command: `mu agent send ${name} <text> -w ${workstream}`
|
|
5577
|
+
}
|
|
5578
|
+
] : [];
|
|
5579
|
+
const sent = trustSkip ? {
|
|
5580
|
+
ok: false,
|
|
5581
|
+
error: "TrustDialogPending",
|
|
5582
|
+
message: "send skipped: Claude's folder-trust dialog is waiting in the pane",
|
|
5583
|
+
exitCode: 0
|
|
5584
|
+
} : sendText === void 0 ? void 0 : await spawnSend(db, agent, sendText);
|
|
2190
5585
|
const workspace = opts.workspace ? getWorkspaceForAgent(db, name, workstream) : void 0;
|
|
2191
5586
|
const resolvedCommand = opts.command ?? resolveCliCommand(agent.cli);
|
|
2192
5587
|
const commandOverridden = resolvedCommand !== agent.cli;
|
|
2193
5588
|
const envSourced = opts.command === void 0 ? resolveCliCommandWithSource(agent.cli) : void 0;
|
|
2194
5589
|
const nextSteps3 = [
|
|
5590
|
+
...trustNext,
|
|
2195
5591
|
// After --send the next step is the wait (or the pane read below).
|
|
2196
5592
|
...!sent?.ok ? [dispatchHint(agent)] : sent.runs !== void 0 ? [
|
|
2197
5593
|
{
|
|
@@ -2233,7 +5629,8 @@ async function cmdSpawn(db, rawName, opts) {
|
|
|
2233
5629
|
...sent !== void 0 ? { send: sent } : {},
|
|
2234
5630
|
nextSteps: nextSteps3
|
|
2235
5631
|
});
|
|
2236
|
-
if (sent !== void 0 && !sent.ok
|
|
5632
|
+
if (sent !== void 0 && !sent.ok && sent.exitCode !== 0)
|
|
5633
|
+
throw new CliExitError(sent.exitCode);
|
|
2237
5634
|
return;
|
|
2238
5635
|
}
|
|
2239
5636
|
const wsBit = opts.workspace ? pc.dim(" with auto-workspace") : "";
|
|
@@ -2247,10 +5644,12 @@ async function cmdSpawn(db, rawName, opts) {
|
|
|
2247
5644
|
const runs = sent.runs !== void 0 ? `, runs ${sent.runs}` : "";
|
|
2248
5645
|
console.log(pc.dim(` sent ${sent.sentBytes} bytes (via ${sent.transport}${runs})`));
|
|
2249
5646
|
} else if (sent !== void 0) {
|
|
2250
|
-
console.error(
|
|
5647
|
+
console.error(
|
|
5648
|
+
sent.exitCode === 0 ? pc.yellow(`warning: ${sent.message}`) : pc.red(`error: --send failed: ${sent.message}`)
|
|
5649
|
+
);
|
|
2251
5650
|
}
|
|
2252
5651
|
printNextSteps(nextSteps3);
|
|
2253
|
-
if (sent !== void 0 && !sent.ok) throw new CliExitError(sent.exitCode);
|
|
5652
|
+
if (sent !== void 0 && !sent.ok && sent.exitCode !== 0) throw new CliExitError(sent.exitCode);
|
|
2254
5653
|
}
|
|
2255
5654
|
async function spawnSend(db, agent, text) {
|
|
2256
5655
|
const fail = (err) => ({
|
|
@@ -2303,6 +5702,7 @@ async function cmdSend(db, rawName, rawText, opts = {}) {
|
|
|
2303
5702
|
if (isSlashCommand(text)) {
|
|
2304
5703
|
throw new UsageError("--interrupt sends a prompt, not a slash command");
|
|
2305
5704
|
}
|
|
5705
|
+
if (text === "") throw new UsageError("--interrupt needs a non-empty prompt");
|
|
2306
5706
|
} else if (opts.timeout !== void 0) {
|
|
2307
5707
|
throw new UsageError("--timeout only applies with --interrupt");
|
|
2308
5708
|
}
|
|
@@ -2766,7 +6166,8 @@ async function cmdAgentWait(db, rawNames, opts) {
|
|
|
2766
6166
|
const reading = agent === void 0 ? void 0 : readings.get(agentKey(agent));
|
|
2767
6167
|
snapshots.set(agentKey(ref), {
|
|
2768
6168
|
status: reading?.alive === false ? null : reading?.state ?? "unknown",
|
|
2769
|
-
...reading?.reason !== void 0 ? { unknownReason: reading.reason } : {}
|
|
6169
|
+
...reading?.reason !== void 0 ? { unknownReason: reading.reason } : {},
|
|
6170
|
+
...reading?.blocked !== void 0 ? { blocked: reading.blocked } : {}
|
|
2770
6171
|
});
|
|
2771
6172
|
}
|
|
2772
6173
|
return snapshots;
|
|
@@ -2782,10 +6183,11 @@ async function cmdAgentWait(db, rawNames, opts) {
|
|
|
2782
6183
|
const probe = await ctlProbe(sock);
|
|
2783
6184
|
if (probe.kind !== "ok") return void 0;
|
|
2784
6185
|
afterRuns = probe.status.runs;
|
|
2785
|
-
initial = { status: ctlRuntimeState(probe.status.state) };
|
|
6186
|
+
initial = { status: ctlRuntimeState(probe.status.state, probe.status.blocked) };
|
|
2786
6187
|
}
|
|
2787
|
-
const
|
|
2788
|
-
|
|
6188
|
+
const req = { op: "wait", afterRuns, returnOnBlocked: true };
|
|
6189
|
+
const settled = ctlRequest(sock, req, { signal }).then(
|
|
6190
|
+
(reply) => reply.ok && reply.ended === "blocked" && reply.blocked !== void 0 ? { status: "needs_permission", blocked: reply.blocked } : reply.ok && reply.state !== void 0 ? {
|
|
2789
6191
|
status: ctlRuntimeState(reply.state),
|
|
2790
6192
|
...reply.lastText !== void 0 ? { lastText: reply.lastText } : {},
|
|
2791
6193
|
...reply.lastError !== void 0 ? { lastError: reply.lastError } : {},
|
|
@@ -2800,7 +6202,7 @@ async function cmdAgentWait(db, rawNames, opts) {
|
|
|
2800
6202
|
return again.kind === "ok" ? { status: "unknown", unknownReason: "ctl wait interrupted" } : { status: null };
|
|
2801
6203
|
}
|
|
2802
6204
|
);
|
|
2803
|
-
return { initial, settled };
|
|
6205
|
+
return { initial, settled, afterRuns };
|
|
2804
6206
|
};
|
|
2805
6207
|
const timeoutMs = (opts.timeout ?? 600) * 1e3;
|
|
2806
6208
|
const result = await waitForAgents(db, refs, {
|
|
@@ -2820,6 +6222,7 @@ async function cmdAgentWait(db, rawNames, opts) {
|
|
|
2820
6222
|
}
|
|
2821
6223
|
});
|
|
2822
6224
|
const dead = result.agents.filter((a) => a.dead);
|
|
6225
|
+
const blocked = result.agents.filter((a) => a.blocked !== void 0);
|
|
2823
6226
|
const fired = result.agents.filter((a) => a.fired);
|
|
2824
6227
|
const firing = wantFirstShape && fired.length > 0 ? fired[0] : null;
|
|
2825
6228
|
const qualified = (a) => `${a.workstreamName}/${a.name}`;
|
|
@@ -2829,6 +6232,18 @@ async function cmdAgentWait(db, rawNames, opts) {
|
|
|
2829
6232
|
command: `mu agent read ${firing.name} -w ${firing.workstreamName}`
|
|
2830
6233
|
}
|
|
2831
6234
|
] : [];
|
|
6235
|
+
for (const a of blocked) {
|
|
6236
|
+
readHint.push(
|
|
6237
|
+
{
|
|
6238
|
+
intent: "Read the dialog pi is waiting on",
|
|
6239
|
+
command: `mu agent read ${a.name} -w ${a.workstreamName}`
|
|
6240
|
+
},
|
|
6241
|
+
{
|
|
6242
|
+
intent: "Wait again once it is answered",
|
|
6243
|
+
command: `mu agent wait ${a.name} -w ${a.workstreamName}${a.afterRuns !== void 0 ? ` --after-runs ${a.afterRuns}` : ""}`
|
|
6244
|
+
}
|
|
6245
|
+
);
|
|
6246
|
+
}
|
|
2832
6247
|
if (opts.json) {
|
|
2833
6248
|
emitJson({
|
|
2834
6249
|
agents: result.agents.map((a) => ({
|
|
@@ -2844,7 +6259,13 @@ async function cmdAgentWait(db, rawNames, opts) {
|
|
|
2844
6259
|
if (dead.length > 0) {
|
|
2845
6260
|
console.log(pc.red(`Agent pane(s) died: ${dead.map(qualified).join(", ")}`));
|
|
2846
6261
|
}
|
|
2847
|
-
|
|
6262
|
+
for (const a of blocked) {
|
|
6263
|
+
const why = a.blocked ? blockedReason(a.blocked) : "dialog";
|
|
6264
|
+
console.log(pc.magenta(`${qualified(a)} is waiting on a ${why}; its run is not finished`));
|
|
6265
|
+
}
|
|
6266
|
+
if (blocked.length > 0) {
|
|
6267
|
+
printNextSteps(readHint);
|
|
6268
|
+
} else if (result.timedOut) {
|
|
2848
6269
|
console.log(
|
|
2849
6270
|
pc.yellow(
|
|
2850
6271
|
`Timed out after ${opts.timeout ?? 600}s; ${fired.length}/${result.agents.length} finished`
|
|
@@ -2863,12 +6284,14 @@ async function cmdAgentWait(db, rawNames, opts) {
|
|
|
2863
6284
|
}
|
|
2864
6285
|
if (dead.length > 0) {
|
|
2865
6286
|
process.exitCode = 6;
|
|
6287
|
+
} else if (blocked.length > 0) {
|
|
6288
|
+
process.exitCode = 7;
|
|
2866
6289
|
} else if (result.timedOut) {
|
|
2867
6290
|
process.exitCode = 5;
|
|
2868
6291
|
}
|
|
2869
6292
|
}
|
|
2870
|
-
function wireAgentCommands(
|
|
2871
|
-
const agent =
|
|
6293
|
+
function wireAgentCommands(program2) {
|
|
6294
|
+
const agent = program2.command("agent").description("Agent-level commands");
|
|
2872
6295
|
agent.command("spawn <name>").description("Spawn a new agent in a mux pane").option(
|
|
2873
6296
|
"--cli <cli>",
|
|
2874
6297
|
"agent CLI key (default: pi); also used as the lookup key for $MU_<UPPER_CLI>_COMMAND, e.g. --cli pi_big resolves $MU_PI_BIG_COMMAND",
|
|
@@ -2963,7 +6386,7 @@ function wireAgentCommands(program) {
|
|
|
2963
6386
|
});
|
|
2964
6387
|
wireRemoteEnvCommand(agent);
|
|
2965
6388
|
agent.command("wait <names...>").description(
|
|
2966
|
-
"Block until agents finish working (busy \u2192 any other state). Keys on AGENTS, so it fires on needs_input too \u2014 a worker that stopped to ask a question satisfies it. For task-driven work prefer `mu task wait`, which keys on the task reaching CLOSED and has `--stuck-after` / `--on-stall` for the needs_input case; reach for this verb when the agent owns no task to wait on."
|
|
6389
|
+
"Block until agents finish working (busy \u2192 any other state). Keys on AGENTS, so it fires on needs_input too \u2014 a worker that stopped to ask a question satisfies it. For task-driven work prefer `mu task wait`, which keys on the task reaching CLOSED and has `--stuck-after` / `--on-stall` for the needs_input case; reach for this verb when the agent owns no task to wait on. A pi agent that opens an extension dialog (a confirm or question) ends the wait early with outcome `blocked`: its run is not finished. Exit 0 = met; 5 = timeout; 6 = a pane died; 7 = a pi agent is waiting on a dialog."
|
|
2967
6390
|
).option("--any", "succeed as soon as ONE listed agent finishes (default: all)").option("--first", "alias for --any that also prints the firing agent's ref").option(
|
|
2968
6391
|
"--timeout <seconds>",
|
|
2969
6392
|
"max seconds to wait, fractions allowed (0 = forever, default 600)",
|
|
@@ -2995,8 +6418,8 @@ function wireAgentCommands(program) {
|
|
|
2995
6418
|
)();
|
|
2996
6419
|
});
|
|
2997
6420
|
}
|
|
2998
|
-
function wireSelfCommands(
|
|
2999
|
-
const me =
|
|
6421
|
+
function wireSelfCommands(program2) {
|
|
6422
|
+
const me = program2.command("me").description(
|
|
3000
6423
|
"Identify the agent running this process (via $TMUX_PANE) plus its currently-owned tasks (excludes CLOSED by default). Subcommands: `mu me tasks` for just the owned-tasks table; `mu me next [-n K]` for the top-K ready tasks in this agent's workstream."
|
|
3001
6424
|
).option("--include-closed", "include CLOSED tasks in the owned-tasks list").option(...JSON_OPT).action(function() {
|
|
3002
6425
|
const opts = this.opts();
|
|
@@ -3046,7 +6469,8 @@ function compact(db) {
|
|
|
3046
6469
|
}).immediate();
|
|
3047
6470
|
return plan;
|
|
3048
6471
|
}
|
|
3049
|
-
var WORKSTREAM_OPS_WHERE = `(
|
|
6472
|
+
var WORKSTREAM_OPS_WHERE = `(entity IN (${OPS_ENTITIES_SQL}) AND key >= @ws AND key < @ws || '0'
|
|
6473
|
+
AND (key = @ws OR substr(key, 1, length(@ws) + 1) = @ws || '/'))`;
|
|
3050
6474
|
function listForgetCandidates(db) {
|
|
3051
6475
|
const spellings = intentSpellings("workstream.teardown");
|
|
3052
6476
|
const names = db.prepare(
|
|
@@ -3097,24 +6521,24 @@ function formatBytes(bytes) {
|
|
|
3097
6521
|
if (bytes < 1024 * 1024 * 1024) return `${Math.round(bytes / 1024 / 1024)}M`;
|
|
3098
6522
|
return `${(bytes / 1024 / 1024 / 1024).toFixed(1)}G`;
|
|
3099
6523
|
}
|
|
3100
|
-
function dirNames(
|
|
6524
|
+
function dirNames(path3) {
|
|
3101
6525
|
try {
|
|
3102
|
-
return readdirSync(
|
|
6526
|
+
return readdirSync(path3, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
3103
6527
|
} catch {
|
|
3104
6528
|
return [];
|
|
3105
6529
|
}
|
|
3106
6530
|
}
|
|
3107
|
-
function exists(
|
|
6531
|
+
function exists(path3) {
|
|
3108
6532
|
try {
|
|
3109
|
-
statSync(
|
|
6533
|
+
statSync(path3);
|
|
3110
6534
|
return true;
|
|
3111
6535
|
} catch {
|
|
3112
6536
|
return false;
|
|
3113
6537
|
}
|
|
3114
6538
|
}
|
|
3115
|
-
function sizeOf(
|
|
6539
|
+
function sizeOf(path3) {
|
|
3116
6540
|
try {
|
|
3117
|
-
return statSync(
|
|
6541
|
+
return statSync(path3).size;
|
|
3118
6542
|
} catch {
|
|
3119
6543
|
return 0;
|
|
3120
6544
|
}
|
|
@@ -3278,16 +6702,16 @@ function checkStaleLocks(now = Date.now()) {
|
|
|
3278
6702
|
]
|
|
3279
6703
|
};
|
|
3280
6704
|
}
|
|
3281
|
-
function walkBytes(
|
|
6705
|
+
function walkBytes(path3) {
|
|
3282
6706
|
let total = 0;
|
|
3283
6707
|
let entries;
|
|
3284
6708
|
try {
|
|
3285
|
-
entries = readdirSync(
|
|
6709
|
+
entries = readdirSync(path3, { withFileTypes: true });
|
|
3286
6710
|
} catch {
|
|
3287
6711
|
return 0;
|
|
3288
6712
|
}
|
|
3289
6713
|
for (const entry of entries) {
|
|
3290
|
-
const child = join(
|
|
6714
|
+
const child = join(path3, entry.name);
|
|
3291
6715
|
if (entry.isDirectory()) total += walkBytes(child);
|
|
3292
6716
|
else if (entry.isFile()) total += sizeOf(child);
|
|
3293
6717
|
}
|
|
@@ -3300,13 +6724,13 @@ function measureWorkspaceUsage(db) {
|
|
|
3300
6724
|
for (const wsName of dirNames(root)) {
|
|
3301
6725
|
const wsRoot = join(root, wsName);
|
|
3302
6726
|
for (const agentName of dirNames(wsRoot)) {
|
|
3303
|
-
const
|
|
6727
|
+
const path3 = join(wsRoot, agentName);
|
|
3304
6728
|
usage.push({
|
|
3305
6729
|
workstreamName: wsName,
|
|
3306
6730
|
agentName,
|
|
3307
|
-
path:
|
|
3308
|
-
bytes: walkBytes(
|
|
3309
|
-
orphan: !registered.has(
|
|
6731
|
+
path: path3,
|
|
6732
|
+
bytes: walkBytes(path3),
|
|
6733
|
+
orphan: !registered.has(path3)
|
|
3310
6734
|
});
|
|
3311
6735
|
}
|
|
3312
6736
|
}
|
|
@@ -3459,8 +6883,8 @@ function forgetHint(db) {
|
|
|
3459
6883
|
};
|
|
3460
6884
|
}
|
|
3461
6885
|
var FORGET_HINT_MIN_BYTES = 5 * 1024 * 1024;
|
|
3462
|
-
function wireDbCommands(
|
|
3463
|
-
const dbCmd =
|
|
6886
|
+
function wireDbCommands(program2) {
|
|
6887
|
+
const dbCmd = program2.command("db").description("Whole-DB file commands");
|
|
3464
6888
|
dbCmd.command("backup <file>").description(
|
|
3465
6889
|
"VACUUM INTO copy of the whole DB \u2014 the 'one file I can scp' convenience. Never overwrites. Real disaster recovery is `mu rebuild`."
|
|
3466
6890
|
).option(...JSON_OPT).action(function(file) {
|
|
@@ -3587,6 +7011,9 @@ function agentStateCheck(health, muExt) {
|
|
|
3587
7011
|
muExtOk: muExt.status === "ok"
|
|
3588
7012
|
});
|
|
3589
7013
|
}
|
|
7014
|
+
function cycleFix(c) {
|
|
7015
|
+
return `mu task unblock ${c.blocked} --by ${c.blocker} -w ${c.workstream}`;
|
|
7016
|
+
}
|
|
3590
7017
|
function printCheck(label, check) {
|
|
3591
7018
|
const colour = check.status === "ok" ? pc.green : check.status === "warn" ? pc.yellow : pc.red;
|
|
3592
7019
|
const word2 = check.status === "ok" ? "ok" : check.status.toUpperCase();
|
|
@@ -3736,6 +7163,20 @@ state (workstream=${ws})`));
|
|
|
3736
7163
|
console.log(pc.bold("\nfleet"));
|
|
3737
7164
|
const fleet = checkFleetHazards(db, { dbPath: defaultDbPath() });
|
|
3738
7165
|
let sawHazard = printHazards(fleet);
|
|
7166
|
+
console.log(pc.bold("\ndag"));
|
|
7167
|
+
const cycles = findEdgeCycles(db);
|
|
7168
|
+
if (cycles.length === 0) {
|
|
7169
|
+
console.log(` ${"cycles".padEnd(16)} : ${pc.green("ok")} ${pc.dim("no dependency cycles")}`);
|
|
7170
|
+
} else {
|
|
7171
|
+
sawHazard = true;
|
|
7172
|
+
console.log(
|
|
7173
|
+
` ${"cycles".padEnd(16)} : ${pc.yellow("WARN")} ${pc.dim(`${cycles.length} dependency cycle(s); members block each other until one closes. Applying every fix below breaks them all`)}`
|
|
7174
|
+
);
|
|
7175
|
+
for (const c of cycles) {
|
|
7176
|
+
console.log(` ${c.workstream}: ${[...c.path, c.path[0]].join(" -> ")}`);
|
|
7177
|
+
console.log(pc.dim(` break it: ${cycleFix(c)}`));
|
|
7178
|
+
}
|
|
7179
|
+
}
|
|
3739
7180
|
console.log(pc.bold("\nhousekeeping"));
|
|
3740
7181
|
const dormant = checkDormantWorkstreams(db, { currentWorkstream });
|
|
3741
7182
|
console.log(
|
|
@@ -3930,6 +7371,7 @@ async function cmdDoctorJson(db, opts = {}) {
|
|
|
3930
7371
|
severity: h.severity,
|
|
3931
7372
|
detail: h.detail
|
|
3932
7373
|
}));
|
|
7374
|
+
const dagCycles = findEdgeCycles(db).map((c) => ({ ...c, fix: cycleFix(c) }));
|
|
3933
7375
|
const disk = checkDiskRecon(db).map((h) => ({
|
|
3934
7376
|
name: h.name,
|
|
3935
7377
|
severity: h.severity,
|
|
@@ -3980,6 +7422,7 @@ async function cmdDoctorJson(db, opts = {}) {
|
|
|
3980
7422
|
state: workstreamStats,
|
|
3981
7423
|
fleet: hazards,
|
|
3982
7424
|
housekeeping,
|
|
7425
|
+
dagCycles,
|
|
3983
7426
|
disk,
|
|
3984
7427
|
workspaceUsage,
|
|
3985
7428
|
drift,
|
|
@@ -4021,8 +7464,8 @@ function countBlocked(db, workstream) {
|
|
|
4021
7464
|
WHERE ws.name = ?`
|
|
4022
7465
|
).get(workstream).n;
|
|
4023
7466
|
}
|
|
4024
|
-
function wireDoctorCommand(
|
|
4025
|
-
|
|
7467
|
+
function wireDoctorCommand(program2) {
|
|
7468
|
+
program2.command("doctor").description("Environment + state health check").option(...JSON_OPT).option(
|
|
4026
7469
|
"--deep",
|
|
4027
7470
|
"also rebuild the ops log into a temp DB and diff it against the live tables (slower: ~0.6ms per op)"
|
|
4028
7471
|
).option(
|
|
@@ -4071,8 +7514,8 @@ function cmdLink(target, opts) {
|
|
|
4071
7514
|
console.log(pc.dim("Restart pi agents (or /reload) to load the extension."));
|
|
4072
7515
|
printNextSteps(steps);
|
|
4073
7516
|
}
|
|
4074
|
-
function wireLinkCommand(
|
|
4075
|
-
|
|
7517
|
+
function wireLinkCommand(program2) {
|
|
7518
|
+
program2.command("link <target>").description("Install the mu pi extension (shim) and the mu skill; <target> must be 'pi'").option(...JSON_OPT).option("--copy", "inline the extension instead of a shim (pinned; relink after upgrades)").option("--force", "replace an existing extension or skill symlink that points elsewhere").option("--extension-only", "install only the pi extension").option("--skill-only", "install only the mu skill symlink").action(function(target) {
|
|
4076
7519
|
const cmd = this;
|
|
4077
7520
|
try {
|
|
4078
7521
|
cmdLink(target, cmd.opts());
|
|
@@ -4190,8 +7633,8 @@ function defaultLogTailIntervalMs() {
|
|
|
4190
7633
|
if (Number.isNaN(parsed)) return LOG_TAIL_INTERVAL_DEFAULT_MS;
|
|
4191
7634
|
return Math.max(LOG_TAIL_INTERVAL_FLOOR_MS, parsed);
|
|
4192
7635
|
}
|
|
4193
|
-
function wireLogCommand(
|
|
4194
|
-
|
|
7636
|
+
function wireLogCommand(program2) {
|
|
7637
|
+
program2.command("log [text]").description(
|
|
4195
7638
|
"Write a log entry (with text) or read the log (without). --tail blocks and prints new entries as they land."
|
|
4196
7639
|
).option("--as <name>", "override the source name (default: agent via $TMUX_PANE, else 'user')").option(
|
|
4197
7640
|
"--kind <kind>",
|
|
@@ -4295,8 +7738,8 @@ async function cmdRebuild(db, targetPath, opts = {}) {
|
|
|
4295
7738
|
}
|
|
4296
7739
|
printNextSteps(nextSteps(report));
|
|
4297
7740
|
}
|
|
4298
|
-
function wireRebuildCommand(
|
|
4299
|
-
|
|
7741
|
+
function wireRebuildCommand(program2) {
|
|
7742
|
+
program2.command("rebuild <file>").description(
|
|
4300
7743
|
"Replay the ops log into a NEW DB file (disaster recovery); prints the swap command"
|
|
4301
7744
|
).option(...JSON_OPT).option("--force", "replace <file> if it already exists (deleted first, never merged into)").action(function(file) {
|
|
4302
7745
|
const opts = this.opts();
|
|
@@ -4512,8 +7955,8 @@ function formatCell(v) {
|
|
|
4512
7955
|
if (typeof v === "string") return v;
|
|
4513
7956
|
return String(v);
|
|
4514
7957
|
}
|
|
4515
|
-
function wireSqlCommand(
|
|
4516
|
-
|
|
7958
|
+
function wireSqlCommand(program2) {
|
|
7959
|
+
program2.command("sql <query>").description("Run a SQL query against the live mu DB (SELECT / UPDATE / DELETE all allowed)").allowUnknownOption(true).option(...JSON_OPT).option(
|
|
4517
7960
|
"--confirm-rows <n>",
|
|
4518
7961
|
"abort if the affected-row count (ON DELETE CASCADE rows included) differs from N (rollback)",
|
|
4519
7962
|
parseLines
|
|
@@ -4525,7 +7968,7 @@ function wireSqlCommand(program) {
|
|
|
4525
7968
|
|
|
4526
7969
|
// src/cli/tui-launch-focus.ts
|
|
4527
7970
|
import { realpathSync } from "fs";
|
|
4528
|
-
import
|
|
7971
|
+
import path2 from "path";
|
|
4529
7972
|
|
|
4530
7973
|
// src/project-root.ts
|
|
4531
7974
|
import { execFile } from "child_process";
|
|
@@ -4537,11 +7980,11 @@ async function run(bin, args, cwd) {
|
|
|
4537
7980
|
const { stdout } = await exec(bin, [...args], { cwd, maxBuffer: 1024 * 1024 });
|
|
4538
7981
|
return stdout.trim();
|
|
4539
7982
|
}
|
|
4540
|
-
async function realpathOrResolve(
|
|
7983
|
+
async function realpathOrResolve(path3) {
|
|
4541
7984
|
try {
|
|
4542
|
-
return await realpath(
|
|
7985
|
+
return await realpath(path3);
|
|
4543
7986
|
} catch {
|
|
4544
|
-
return resolve2(
|
|
7987
|
+
return resolve2(path3);
|
|
4545
7988
|
}
|
|
4546
7989
|
}
|
|
4547
7990
|
async function gitProjectRoot(workspacePath) {
|
|
@@ -4589,13 +8032,13 @@ function normalizeExistingPath(candidatePath) {
|
|
|
4589
8032
|
try {
|
|
4590
8033
|
return realpathSync(candidatePath);
|
|
4591
8034
|
} catch {
|
|
4592
|
-
return
|
|
8035
|
+
return path2.resolve(candidatePath);
|
|
4593
8036
|
}
|
|
4594
8037
|
}
|
|
4595
8038
|
function isInsidePath(cwd, candidatePath) {
|
|
4596
8039
|
const normalizedCandidate = normalizeExistingPath(candidatePath);
|
|
4597
8040
|
if (cwd === normalizedCandidate) return true;
|
|
4598
|
-
return cwd.startsWith(`${normalizedCandidate}${
|
|
8041
|
+
return cwd.startsWith(`${normalizedCandidate}${path2.sep}`);
|
|
4599
8042
|
}
|
|
4600
8043
|
function latestActiveWorkstream(db, candidates) {
|
|
4601
8044
|
let best = null;
|
|
@@ -4661,7 +8104,7 @@ async function resolveInitialTab(names, db) {
|
|
|
4661
8104
|
}
|
|
4662
8105
|
|
|
4663
8106
|
// src/cli/tui-load.ts
|
|
4664
|
-
async function importTui(load = () => import("./tui-
|
|
8107
|
+
async function importTui(load = () => import("./tui-LFJ5P4Y2.js")) {
|
|
4665
8108
|
const key = "NODE_ENV";
|
|
4666
8109
|
if (process.env[key] !== void 0) return load();
|
|
4667
8110
|
process.env[key] = "production";
|
|
@@ -4891,8 +8334,8 @@ function printBareNoWorkstreamsHint() {
|
|
|
4891
8334
|
console.log("Next:");
|
|
4892
8335
|
console.log(" Get started: mu workstream init <name>");
|
|
4893
8336
|
}
|
|
4894
|
-
function wireStateCommands(
|
|
4895
|
-
|
|
8337
|
+
function wireStateCommands(program2) {
|
|
8338
|
+
program2.command("state").description(
|
|
4896
8339
|
"Canonical state card: agents + orphans + tracks + ready/in-progress/blocked/recent-closed tasks + workspaces + remote workers + recent events. The agent/API-facing static state surface. Default prints the static card; pass --tui to enter the interactive ink-based dashboard. -w accepts repeat or comma-separate (or both); --all is sugar for every workstream on this machine. N\u22652 stacks per-workstream cards."
|
|
4897
8340
|
).option(
|
|
4898
8341
|
"-w, --workstream <names...>",
|
|
@@ -5061,8 +8504,8 @@ function emitFrom(db, result, flushed, dir, opts) {
|
|
|
5061
8504
|
}
|
|
5062
8505
|
printNextSteps([{ intent: "See what landed", command: "mu log -n 20" }]);
|
|
5063
8506
|
}
|
|
5064
|
-
function wireSyncCommand(
|
|
5065
|
-
|
|
8507
|
+
function wireSyncCommand(program2) {
|
|
8508
|
+
program2.command("sync").description("Report peer status (flush + ingest happen on every mu invocation anyway)").option(...JSON_OPT).option("--from <path>", "ingest from a peer's mu.db directly (sshfs mount or copied file)").option("--repair <peer>", "reset that peer's watermark and re-read its segment from zero").action(function() {
|
|
5066
8509
|
const opts = this.opts();
|
|
5067
8510
|
return handle((db) => cmdSync(db, opts), this, { ambientSync: false })();
|
|
5068
8511
|
});
|
|
@@ -5235,8 +8678,8 @@ async function cmdUndo(db, groupRef, opts = {}) {
|
|
|
5235
8678
|
console.log(pc.dim(` This undo is itself undoable: mu undo ${short(result.undoGroupId)} --yes`));
|
|
5236
8679
|
printNextSteps(nextStepsForPlan(result.plan, true, result.undoGroupId));
|
|
5237
8680
|
}
|
|
5238
|
-
function wireUndoCommand(
|
|
5239
|
-
|
|
8681
|
+
function wireUndoCommand(program2) {
|
|
8682
|
+
program2.command("undo [group]").description(
|
|
5240
8683
|
"Revert one action by emitting inverse ops (dry-run by default; --yes applies). With no group, lists recent undoable actions."
|
|
5241
8684
|
).option(...JSON_OPT).option("--yes", "actually apply the inverse (default is a dry run)").option("--force", "apply even when the group was superseded by later work (discards it)").option("-n, --limit <n>", "how many recent groups to list", parsePositiveInt).action(function(group) {
|
|
5242
8685
|
const opts = this.opts();
|
|
@@ -5245,6 +8688,7 @@ function wireUndoCommand(program) {
|
|
|
5245
8688
|
}
|
|
5246
8689
|
|
|
5247
8690
|
// src/cli/workspace.ts
|
|
8691
|
+
import { dirname as dirname7 } from "path";
|
|
5248
8692
|
async function cmdWorkspaceList(db, opts) {
|
|
5249
8693
|
const workstream = opts.all ? void 0 : await resolveWorkstream(opts.workstream);
|
|
5250
8694
|
const rows = listWorkspaces(db, workstream);
|
|
@@ -5259,13 +8703,40 @@ async function cmdWorkspaceList(db, opts) {
|
|
|
5259
8703
|
}
|
|
5260
8704
|
console.log(formatWorkspacesTable(decorated));
|
|
5261
8705
|
}
|
|
8706
|
+
async function guardOwnerState(db, agent, workstream) {
|
|
8707
|
+
const row = getAgent(db, agent, workstream);
|
|
8708
|
+
if (!row?.paneId) return void 0;
|
|
8709
|
+
const reading = (await readAgentStates([row], { stateDir: dirname7(db.name) })).get(agentKey(row));
|
|
8710
|
+
const state = reading?.state ?? "unknown";
|
|
8711
|
+
if (state === "needs_input") return state;
|
|
8712
|
+
if (state === "unknown") {
|
|
8713
|
+
let live;
|
|
8714
|
+
try {
|
|
8715
|
+
live = await (await activeMux()).paneExists(row.paneId);
|
|
8716
|
+
} catch {
|
|
8717
|
+
throw new WorkspaceOwnerBusyError(
|
|
8718
|
+
agent,
|
|
8719
|
+
workstream,
|
|
8720
|
+
state,
|
|
8721
|
+
"pane liveness probe failed; state unknown"
|
|
8722
|
+
);
|
|
8723
|
+
}
|
|
8724
|
+
if (!live) return state;
|
|
8725
|
+
}
|
|
8726
|
+
throw new WorkspaceOwnerBusyError(agent, workstream, state);
|
|
8727
|
+
}
|
|
5262
8728
|
async function cmdWorkspaceFree(db, rawAgent, opts) {
|
|
5263
8729
|
const { name: agent } = await resolveEntityRef(db, rawAgent, opts, "workspace");
|
|
5264
8730
|
assertAgentInWorkstream(db, agent, opts.workstream);
|
|
5265
8731
|
const ws = await resolveWorkstream(opts.workstream);
|
|
8732
|
+
const checkedState = opts.force ? void 0 : await guardOwnerState(db, agent, ws);
|
|
5266
8733
|
const r = await freeWorkspace(db, agent, { commit: opts.commit ?? false, workstream: ws });
|
|
5267
8734
|
if (opts.json) {
|
|
5268
|
-
emitJson({
|
|
8735
|
+
emitJson({
|
|
8736
|
+
agentName: agent,
|
|
8737
|
+
...r,
|
|
8738
|
+
...checkedState !== void 0 ? { ownerState: checkedState } : {}
|
|
8739
|
+
});
|
|
5269
8740
|
return;
|
|
5270
8741
|
}
|
|
5271
8742
|
if (!r.removed && !r.rowDeleted) {
|
|
@@ -5412,8 +8883,8 @@ async function cmdWorkspaceOrphans(db, opts = {}) {
|
|
|
5412
8883
|
}
|
|
5413
8884
|
printNextSteps(nextSteps3);
|
|
5414
8885
|
}
|
|
5415
|
-
function wireWorkspaceCommands(
|
|
5416
|
-
const workspace =
|
|
8886
|
+
function wireWorkspaceCommands(program2) {
|
|
8887
|
+
const workspace = program2.command("workspace").description("VCS workspace commands (per-agent isolated working copies)");
|
|
5417
8888
|
workspace.command("list").description("List workspaces in the current workstream (--all spans every workstream)").option("--all", "list workspaces across every workstream").option(...WORKSTREAM_OPT).option(...JSON_OPT).action(function() {
|
|
5418
8889
|
const opts = this.opts();
|
|
5419
8890
|
return handle((db) => cmdWorkspaceList(db, opts), this)();
|
|
@@ -5425,8 +8896,8 @@ function wireWorkspaceCommands(program) {
|
|
|
5425
8896
|
return handle((db) => cmdWorkspaceRefresh(db, agent, opts), this)();
|
|
5426
8897
|
});
|
|
5427
8898
|
workspace.command("free <agent>").description(
|
|
5428
|
-
"Tear down an agent's workspace. With --commit, attempt to auto-commit pending changes first; without it, pending changes are lost. For git, --commit also creates a branch mu/<workstream>/<agent>-<sha> when the worktree's commits are on no branch, so they survive removal."
|
|
5429
|
-
).option("--commit", "auto-commit pending changes before removing the workspace").option(...WORKSTREAM_OPT).option(...JSON_OPT).action(function(agent) {
|
|
8899
|
+
"Tear down an agent's workspace. With --commit, attempt to auto-commit pending changes first; without it, pending changes are lost. Refuses (exit 4) while the owning agent is busy, awaiting permission, or unreadable with a live pane; --force skips only that check. For git, --commit also creates a branch mu/<workstream>/<agent>-<sha> when the worktree's commits are on no branch, so they survive removal."
|
|
8900
|
+
).option("--commit", "auto-commit pending changes before removing the workspace").option("--force", "skip the owner-agent state check (does not make removal any safer)").option(...WORKSTREAM_OPT).option(...JSON_OPT).action(function(agent) {
|
|
5430
8901
|
const opts = this.opts();
|
|
5431
8902
|
return handle((db) => cmdWorkspaceFree(db, agent, opts), this)();
|
|
5432
8903
|
});
|
|
@@ -5780,8 +9251,8 @@ function withPositionalWorkstream(opts, name) {
|
|
|
5780
9251
|
}
|
|
5781
9252
|
return { ...opts, workstream: name };
|
|
5782
9253
|
}
|
|
5783
|
-
function wireWorkstreamCommands(
|
|
5784
|
-
const workstream =
|
|
9254
|
+
function wireWorkstreamCommands(program2) {
|
|
9255
|
+
const workstream = program2.command("workstream").description(
|
|
5785
9256
|
"Workstream-level commands. Name them <project>-<purpose> (hail-auth), one per effort; tear down when it ships. Reviews nobody will track belong in scratch delegates, not a workstream."
|
|
5786
9257
|
);
|
|
5787
9258
|
workstream.command("init <name>").description(
|
|
@@ -5820,6 +9291,9 @@ async function resolveWorkstream(explicit) {
|
|
|
5820
9291
|
}
|
|
5821
9292
|
if (explicit) return explicit;
|
|
5822
9293
|
if (process.env.MU_SESSION) return process.env.MU_SESSION;
|
|
9294
|
+
if (process.env.MU_MANAGED_AGENT === "1" && process.env.MU_WORKSTREAM) {
|
|
9295
|
+
return process.env.MU_WORKSTREAM;
|
|
9296
|
+
}
|
|
5823
9297
|
const tmuxWorkstream = await resolveMuxSessionWorkstreamName();
|
|
5824
9298
|
if (tmuxWorkstream !== null) return tmuxWorkstream;
|
|
5825
9299
|
throw new UsageError(
|
|
@@ -6077,11 +9551,11 @@ function emitJson(value) {
|
|
|
6077
9551
|
function emitJsonCollection(items) {
|
|
6078
9552
|
emitJson({ items, count: items.length });
|
|
6079
9553
|
}
|
|
6080
|
-
async function cmdBareTui(db,
|
|
9554
|
+
async function cmdBareTui(db, program2, requestedWorkstreams) {
|
|
6081
9555
|
const workstreams = await listWorkstreams(db);
|
|
6082
9556
|
const requested = parseCsvFlag(requestedWorkstreams, "-w/--workstream");
|
|
6083
9557
|
if (workstreams.length === 0 && requested.length === 0) {
|
|
6084
|
-
|
|
9558
|
+
program2.outputHelp();
|
|
6085
9559
|
printBareNoWorkstreamsHint();
|
|
6086
9560
|
return;
|
|
6087
9561
|
}
|
|
@@ -6096,7 +9570,7 @@ async function cmdBareTui(db, program, requestedWorkstreams) {
|
|
|
6096
9570
|
await runTui(db, { workstreams: names, initialActive });
|
|
6097
9571
|
} catch (err) {
|
|
6098
9572
|
if (process.stdin.isTTY !== true) {
|
|
6099
|
-
|
|
9573
|
+
program2.outputHelp();
|
|
6100
9574
|
return;
|
|
6101
9575
|
}
|
|
6102
9576
|
throw err;
|
|
@@ -6104,7 +9578,7 @@ async function cmdBareTui(db, program, requestedWorkstreams) {
|
|
|
6104
9578
|
}
|
|
6105
9579
|
function readPackageVersion() {
|
|
6106
9580
|
try {
|
|
6107
|
-
const here =
|
|
9581
|
+
const here = dirname8(fileURLToPath(import.meta.url));
|
|
6108
9582
|
const pkgPath = join2(here, "..", "package.json");
|
|
6109
9583
|
const raw = readFileSync(pkgPath, "utf8");
|
|
6110
9584
|
const parsed = JSON.parse(raw);
|
|
@@ -6114,8 +9588,8 @@ function readPackageVersion() {
|
|
|
6114
9588
|
}
|
|
6115
9589
|
}
|
|
6116
9590
|
function buildProgram() {
|
|
6117
|
-
const
|
|
6118
|
-
|
|
9591
|
+
const program2 = new Command();
|
|
9592
|
+
program2.name("mu").description(
|
|
6119
9593
|
"Persistent crew of AI agents in tmux or herdr panes coordinated through a built-in task DAG."
|
|
6120
9594
|
).version(readPackageVersion()).helpOption("-h, --help").configureHelp({ sortSubcommands: true }).enablePositionalOptions().option(
|
|
6121
9595
|
"-w, --workstream <names>",
|
|
@@ -6125,28 +9599,28 @@ function buildProgram() {
|
|
|
6125
9599
|
const command = this;
|
|
6126
9600
|
const opts = command.opts();
|
|
6127
9601
|
if (process.stdout.isTTY !== true || process.env.MU_NO_TUI === "1" || opts.json === true) {
|
|
6128
|
-
|
|
9602
|
+
program2.outputHelp();
|
|
6129
9603
|
return;
|
|
6130
9604
|
}
|
|
6131
|
-
return handle((db) => cmdBareTui(db,
|
|
9605
|
+
return handle((db) => cmdBareTui(db, program2, opts.workstream), command, TUI_HANDLE_OPTS)();
|
|
6132
9606
|
});
|
|
6133
|
-
wireWorkstreamCommands(
|
|
6134
|
-
wireAgentCommands(
|
|
6135
|
-
wireSelfCommands(
|
|
6136
|
-
wireWorkspaceCommands(
|
|
6137
|
-
wireTaskCommands(
|
|
6138
|
-
wireLogCommand(
|
|
6139
|
-
wireStateCommands(
|
|
6140
|
-
wireSqlCommand(
|
|
6141
|
-
wireSyncCommand(
|
|
6142
|
-
wireRebuildCommand(
|
|
6143
|
-
wireDbCommands(
|
|
6144
|
-
wireUndoCommand(
|
|
6145
|
-
wireDoctorCommand(
|
|
6146
|
-
wireLinkCommand(
|
|
6147
|
-
applyAlphabeticalHelpSort(
|
|
6148
|
-
applyExitOverride(
|
|
6149
|
-
return
|
|
9607
|
+
wireWorkstreamCommands(program2);
|
|
9608
|
+
wireAgentCommands(program2);
|
|
9609
|
+
wireSelfCommands(program2);
|
|
9610
|
+
wireWorkspaceCommands(program2);
|
|
9611
|
+
wireTaskCommands(program2);
|
|
9612
|
+
wireLogCommand(program2);
|
|
9613
|
+
wireStateCommands(program2);
|
|
9614
|
+
wireSqlCommand(program2);
|
|
9615
|
+
wireSyncCommand(program2);
|
|
9616
|
+
wireRebuildCommand(program2);
|
|
9617
|
+
wireDbCommands(program2);
|
|
9618
|
+
wireUndoCommand(program2);
|
|
9619
|
+
wireDoctorCommand(program2);
|
|
9620
|
+
wireLinkCommand(program2);
|
|
9621
|
+
applyAlphabeticalHelpSort(program2);
|
|
9622
|
+
applyExitOverride(program2);
|
|
9623
|
+
return program2;
|
|
6150
9624
|
}
|
|
6151
9625
|
function forwardRootWorkstream(root, leaf) {
|
|
6152
9626
|
if (leaf === root) return;
|
|
@@ -6192,22 +9666,22 @@ function applyExitOverride(cmd) {
|
|
|
6192
9666
|
applyExitOverride(sub);
|
|
6193
9667
|
}
|
|
6194
9668
|
}
|
|
6195
|
-
function injectBareNamespaceHelp(
|
|
9669
|
+
function injectBareNamespaceHelp(program2, argv) {
|
|
6196
9670
|
if (argv.length !== 3) return argv;
|
|
6197
9671
|
const token = argv[2];
|
|
6198
9672
|
if (token === void 0 || token.startsWith("-")) return argv;
|
|
6199
|
-
const sub =
|
|
9673
|
+
const sub = program2.commands.find((c) => c.name() === token || c.aliases().includes(token));
|
|
6200
9674
|
if (!sub) return argv;
|
|
6201
9675
|
if (sub.commands.length === 0) return argv;
|
|
6202
9676
|
return [...argv, "--help"];
|
|
6203
9677
|
}
|
|
6204
9678
|
async function runCli(rawArgv) {
|
|
6205
|
-
const
|
|
6206
|
-
const argv = injectBareNamespaceHelp(
|
|
9679
|
+
const program2 = buildProgram();
|
|
9680
|
+
const argv = injectBareNamespaceHelp(program2, rawArgv);
|
|
6207
9681
|
try {
|
|
6208
|
-
await
|
|
9682
|
+
await program2.parseAsync(argv);
|
|
6209
9683
|
} catch (err) {
|
|
6210
|
-
const failingCmd = findCommandForArgv(
|
|
9684
|
+
const failingCmd = findCommandForArgv(program2, argv.slice(2));
|
|
6211
9685
|
const exitCode = emitParseError(err, failingCmd);
|
|
6212
9686
|
process.exit(exitCode);
|
|
6213
9687
|
}
|
|
@@ -6270,4 +9744,4 @@ export {
|
|
|
6270
9744
|
truncateFront,
|
|
6271
9745
|
withRoiAll
|
|
6272
9746
|
};
|
|
6273
|
-
//# sourceMappingURL=cli-
|
|
9747
|
+
//# sourceMappingURL=cli-CKOMHBXV.js.map
|