@difflab/pi 0.2.0 → 0.3.0-rc.202609201609.21ba1d2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -4
- package/agents/diffpi-orchestrator.md +17 -5
- package/agents/diffpi-planner.md +30 -0
- package/agents/diffpi-reviewer.md +36 -0
- package/agents/diffpi-worker.md +9 -1
- package/dist/assets.d.ts +2 -0
- package/dist/assets.d.ts.map +1 -1
- package/dist/cli/plan.d.ts +7 -0
- package/dist/cli/plan.d.ts.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +2855 -0
- package/dist/commands/background.d.ts +39 -0
- package/dist/commands/background.d.ts.map +1 -0
- package/dist/commands/index.d.ts +9 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/mode.d.ts +5 -0
- package/dist/commands/mode.d.ts.map +1 -0
- package/dist/commands/plan-parser.d.ts +18 -0
- package/dist/commands/plan-parser.d.ts.map +1 -0
- package/dist/commands/plan.d.ts +21 -0
- package/dist/commands/plan.d.ts.map +1 -0
- package/dist/commands/reload.d.ts +4 -0
- package/dist/commands/reload.d.ts.map +1 -0
- package/dist/commands/review.d.ts +5 -0
- package/dist/commands/review.d.ts.map +1 -0
- package/dist/environment.d.ts +41 -0
- package/dist/environment.d.ts.map +1 -0
- package/dist/extensions/ghx.d.ts +5 -0
- package/dist/extensions/ghx.d.ts.map +1 -0
- package/dist/extensions/gitx.d.ts +10 -0
- package/dist/extensions/gitx.d.ts.map +1 -0
- package/dist/extensions/glabx.d.ts +5 -0
- package/dist/extensions/glabx.d.ts.map +1 -0
- package/dist/extensions/index.js +4788 -301
- package/dist/{mise.d.ts → extensions/misex.d.ts} +3 -1
- package/dist/extensions/misex.d.ts.map +1 -0
- package/dist/{process.d.ts → extensions/processx.d.ts} +3 -1
- package/dist/extensions/processx.d.ts.map +1 -0
- package/dist/extensions/tuicrx.d.ts +66 -0
- package/dist/extensions/tuicrx.d.ts.map +1 -0
- package/dist/extensions/zedx.d.ts +18 -0
- package/dist/extensions/zedx.d.ts.map +1 -0
- package/dist/gates.d.ts +12 -0
- package/dist/gates.d.ts.map +1 -0
- package/dist/index.d.ts +27 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2817 -142
- package/dist/modes.d.ts +1 -0
- package/dist/modes.d.ts.map +1 -1
- package/dist/plan/annotations.d.ts +25 -0
- package/dist/plan/annotations.d.ts.map +1 -0
- package/dist/plan/escalation.d.ts +4 -0
- package/dist/plan/escalation.d.ts.map +1 -0
- package/dist/plan/execution.d.ts +19 -0
- package/dist/plan/execution.d.ts.map +1 -0
- package/dist/plan/index.d.ts +15 -0
- package/dist/plan/index.d.ts.map +1 -0
- package/dist/plan/lock.d.ts +7 -0
- package/dist/plan/lock.d.ts.map +1 -0
- package/dist/plan/log.d.ts +5 -0
- package/dist/plan/log.d.ts.map +1 -0
- package/dist/plan/markdown.d.ts +6 -0
- package/dist/plan/markdown.d.ts.map +1 -0
- package/dist/plan/store.d.ts +34 -0
- package/dist/plan/store.d.ts.map +1 -0
- package/dist/plan/transitions.d.ts +9 -0
- package/dist/plan/transitions.d.ts.map +1 -0
- package/dist/plan/types.d.ts +146 -0
- package/dist/plan/types.d.ts.map +1 -0
- package/dist/review/github-review-backend.d.ts +5 -0
- package/dist/review/github-review-backend.d.ts.map +1 -0
- package/dist/review/gitlab-review-backend.d.ts +12 -0
- package/dist/review/gitlab-review-backend.d.ts.map +1 -0
- package/dist/review/index.d.ts +8 -0
- package/dist/review/index.d.ts.map +1 -0
- package/dist/review/local-review-backend.d.ts +3 -0
- package/dist/review/local-review-backend.d.ts.map +1 -0
- package/dist/review/review-backend.d.ts +8 -0
- package/dist/review/review-backend.d.ts.map +1 -0
- package/dist/review/review-markdown.d.ts +6 -0
- package/dist/review/review-markdown.d.ts.map +1 -0
- package/dist/review/review-state.d.ts +19 -0
- package/dist/review/review-state.d.ts.map +1 -0
- package/dist/review/types.d.ts +107 -0
- package/dist/review/types.d.ts.map +1 -0
- package/dist/setup.d.ts +7 -0
- package/dist/setup.d.ts.map +1 -1
- package/dist/store.d.ts +16 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/templates.d.ts +14 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +4459 -299
- package/dist/tools/plan.d.ts +6 -0
- package/dist/tools/plan.d.ts.map +1 -0
- package/dist/tools/review.d.ts +7 -0
- package/dist/tools/review.d.ts.map +1 -0
- package/dist/tools/setup.d.ts.map +1 -1
- package/dist/tools/templates.d.ts +3 -0
- package/dist/tools/templates.d.ts.map +1 -0
- package/dist/vcs/forge-backend.d.ts +7 -0
- package/dist/vcs/forge-backend.d.ts.map +1 -0
- package/dist/vcs/github.d.ts +5 -0
- package/dist/vcs/github.d.ts.map +1 -0
- package/dist/vcs/gitlab.d.ts +4 -0
- package/dist/vcs/gitlab.d.ts.map +1 -0
- package/dist/vcs/helpers.d.ts +7 -0
- package/dist/vcs/helpers.d.ts.map +1 -0
- package/dist/vcs/index.d.ts +6 -0
- package/dist/vcs/index.d.ts.map +1 -0
- package/dist/vcs/types.d.ts +32 -0
- package/dist/vcs/types.d.ts.map +1 -0
- package/package.json +7 -2
- package/skills/diffpi-setup/SKILL.md +3 -1
- package/skills/plan/SKILL.md +13 -0
- package/skills/plan/references/workflows/annotate.md +6 -0
- package/skills/plan/references/workflows/finalize.md +7 -0
- package/skills/plan/references/workflows/go.md +7 -0
- package/skills/plan/references/workflows/help.md +13 -0
- package/skills/plan/references/workflows/init.md +6 -0
- package/skills/plan/references/workflows/new.md +7 -0
- package/skills/plan/references/workflows/update.md +7 -0
- package/skills/review/SKILL.md +17 -0
- package/skills/review/references/workflows/address.md +11 -0
- package/skills/review/references/workflows/auto.md +18 -0
- package/skills/review/references/workflows/complete.md +7 -0
- package/skills/review/references/workflows/edit.md +7 -0
- package/skills/review/references/workflows/help.md +30 -0
- package/skills/review/references/workflows/merge.md +6 -0
- package/skills/review/references/workflows/new.md +19 -0
- package/skills/review/references/workflows/open.md +3 -0
- package/skills/review/references/workflows/publish.md +8 -0
- package/templates/plan/PLAN.md +38 -0
- package/templates/review/draft-pr.md +25 -0
- package/dist/mise.d.ts.map +0 -1
- package/dist/process.d.ts.map +0 -1
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2855 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
5
|
+
var __exportCjs = (target, getters, setters) => {
|
|
6
|
+
for (var name in getters)
|
|
7
|
+
__defProp(target, name, {
|
|
8
|
+
get: getters[name],
|
|
9
|
+
set: setters[name],
|
|
10
|
+
enumerable: true,
|
|
11
|
+
configurable: true
|
|
12
|
+
});
|
|
13
|
+
};
|
|
14
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
15
|
+
|
|
16
|
+
// ../../node_modules/commander/lib/error.js
|
|
17
|
+
var require_error = __commonJS(function(exports) {
|
|
18
|
+
class CommanderError extends Error {
|
|
19
|
+
constructor(exitCode, code, message) {
|
|
20
|
+
super(message);
|
|
21
|
+
Error.captureStackTrace(this, this.constructor);
|
|
22
|
+
this.name = this.constructor.name;
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.exitCode = exitCode;
|
|
25
|
+
this.nestedError = undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
class InvalidArgumentError extends CommanderError {
|
|
30
|
+
constructor(message) {
|
|
31
|
+
super(1, "commander.invalidArgument", message);
|
|
32
|
+
Error.captureStackTrace(this, this.constructor);
|
|
33
|
+
this.name = this.constructor.name;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
exports.CommanderError = CommanderError;
|
|
37
|
+
exports.InvalidArgumentError = InvalidArgumentError;
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// ../../node_modules/commander/lib/argument.js
|
|
41
|
+
var require_argument = __commonJS(function(exports) {
|
|
42
|
+
var { InvalidArgumentError } = require_error();
|
|
43
|
+
|
|
44
|
+
class Argument {
|
|
45
|
+
constructor(name, description) {
|
|
46
|
+
this.description = description || "";
|
|
47
|
+
this.variadic = false;
|
|
48
|
+
this.parseArg = undefined;
|
|
49
|
+
this.defaultValue = undefined;
|
|
50
|
+
this.defaultValueDescription = undefined;
|
|
51
|
+
this.argChoices = undefined;
|
|
52
|
+
switch (name[0]) {
|
|
53
|
+
case "<":
|
|
54
|
+
this.required = true;
|
|
55
|
+
this._name = name.slice(1, -1);
|
|
56
|
+
break;
|
|
57
|
+
case "[":
|
|
58
|
+
this.required = false;
|
|
59
|
+
this._name = name.slice(1, -1);
|
|
60
|
+
break;
|
|
61
|
+
default:
|
|
62
|
+
this.required = true;
|
|
63
|
+
this._name = name;
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
if (this._name.endsWith("...")) {
|
|
67
|
+
this.variadic = true;
|
|
68
|
+
this._name = this._name.slice(0, -3);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
name() {
|
|
72
|
+
return this._name;
|
|
73
|
+
}
|
|
74
|
+
_collectValue(value, previous) {
|
|
75
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
76
|
+
return [value];
|
|
77
|
+
}
|
|
78
|
+
previous.push(value);
|
|
79
|
+
return previous;
|
|
80
|
+
}
|
|
81
|
+
default(value, description) {
|
|
82
|
+
this.defaultValue = value;
|
|
83
|
+
this.defaultValueDescription = description;
|
|
84
|
+
return this;
|
|
85
|
+
}
|
|
86
|
+
argParser(fn) {
|
|
87
|
+
this.parseArg = fn;
|
|
88
|
+
return this;
|
|
89
|
+
}
|
|
90
|
+
choices(values) {
|
|
91
|
+
this.argChoices = values.slice();
|
|
92
|
+
this.parseArg = (arg, previous) => {
|
|
93
|
+
if (!this.argChoices.includes(arg)) {
|
|
94
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
95
|
+
}
|
|
96
|
+
if (this.variadic) {
|
|
97
|
+
return this._collectValue(arg, previous);
|
|
98
|
+
}
|
|
99
|
+
return arg;
|
|
100
|
+
};
|
|
101
|
+
return this;
|
|
102
|
+
}
|
|
103
|
+
argRequired() {
|
|
104
|
+
this.required = true;
|
|
105
|
+
return this;
|
|
106
|
+
}
|
|
107
|
+
argOptional() {
|
|
108
|
+
this.required = false;
|
|
109
|
+
return this;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function humanReadableArgName(arg) {
|
|
113
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
114
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
115
|
+
}
|
|
116
|
+
exports.Argument = Argument;
|
|
117
|
+
exports.humanReadableArgName = humanReadableArgName;
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// ../../node_modules/commander/lib/help.js
|
|
121
|
+
var require_help = __commonJS(function(exports) {
|
|
122
|
+
var { humanReadableArgName } = require_argument();
|
|
123
|
+
|
|
124
|
+
class Help {
|
|
125
|
+
constructor() {
|
|
126
|
+
this.helpWidth = undefined;
|
|
127
|
+
this.minWidthToWrap = 40;
|
|
128
|
+
this.sortSubcommands = false;
|
|
129
|
+
this.sortOptions = false;
|
|
130
|
+
this.showGlobalOptions = false;
|
|
131
|
+
}
|
|
132
|
+
prepareContext(contextOptions) {
|
|
133
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
134
|
+
}
|
|
135
|
+
visibleCommands(cmd) {
|
|
136
|
+
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
|
|
137
|
+
const helpCommand = cmd._getHelpCommand();
|
|
138
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
139
|
+
visibleCommands.push(helpCommand);
|
|
140
|
+
}
|
|
141
|
+
if (this.sortSubcommands) {
|
|
142
|
+
visibleCommands.sort((a, b) => {
|
|
143
|
+
return a.name().localeCompare(b.name());
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return visibleCommands;
|
|
147
|
+
}
|
|
148
|
+
compareOptions(a, b) {
|
|
149
|
+
const getSortKey = (option) => {
|
|
150
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
151
|
+
};
|
|
152
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
153
|
+
}
|
|
154
|
+
visibleOptions(cmd) {
|
|
155
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
156
|
+
const helpOption = cmd._getHelpOption();
|
|
157
|
+
if (helpOption && !helpOption.hidden) {
|
|
158
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
159
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
160
|
+
if (!removeShort && !removeLong) {
|
|
161
|
+
visibleOptions.push(helpOption);
|
|
162
|
+
} else if (helpOption.long && !removeLong) {
|
|
163
|
+
visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
164
|
+
} else if (helpOption.short && !removeShort) {
|
|
165
|
+
visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (this.sortOptions) {
|
|
169
|
+
visibleOptions.sort(this.compareOptions);
|
|
170
|
+
}
|
|
171
|
+
return visibleOptions;
|
|
172
|
+
}
|
|
173
|
+
visibleGlobalOptions(cmd) {
|
|
174
|
+
if (!this.showGlobalOptions)
|
|
175
|
+
return [];
|
|
176
|
+
const globalOptions = [];
|
|
177
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
178
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
179
|
+
globalOptions.push(...visibleOptions);
|
|
180
|
+
}
|
|
181
|
+
if (this.sortOptions) {
|
|
182
|
+
globalOptions.sort(this.compareOptions);
|
|
183
|
+
}
|
|
184
|
+
return globalOptions;
|
|
185
|
+
}
|
|
186
|
+
visibleArguments(cmd) {
|
|
187
|
+
if (cmd._argsDescription) {
|
|
188
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
189
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
193
|
+
return cmd.registeredArguments;
|
|
194
|
+
}
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
subcommandTerm(cmd) {
|
|
198
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
199
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
200
|
+
}
|
|
201
|
+
optionTerm(option) {
|
|
202
|
+
return option.flags;
|
|
203
|
+
}
|
|
204
|
+
argumentTerm(argument) {
|
|
205
|
+
return argument.name();
|
|
206
|
+
}
|
|
207
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
208
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
209
|
+
return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
|
|
210
|
+
}, 0);
|
|
211
|
+
}
|
|
212
|
+
longestOptionTermLength(cmd, helper) {
|
|
213
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
214
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
215
|
+
}, 0);
|
|
216
|
+
}
|
|
217
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
218
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
219
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
220
|
+
}, 0);
|
|
221
|
+
}
|
|
222
|
+
longestArgumentTermLength(cmd, helper) {
|
|
223
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
224
|
+
return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
|
|
225
|
+
}, 0);
|
|
226
|
+
}
|
|
227
|
+
commandUsage(cmd) {
|
|
228
|
+
let cmdName = cmd._name;
|
|
229
|
+
if (cmd._aliases[0]) {
|
|
230
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
231
|
+
}
|
|
232
|
+
let ancestorCmdNames = "";
|
|
233
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
234
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
235
|
+
}
|
|
236
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
237
|
+
}
|
|
238
|
+
commandDescription(cmd) {
|
|
239
|
+
return cmd.description();
|
|
240
|
+
}
|
|
241
|
+
subcommandDescription(cmd) {
|
|
242
|
+
return cmd.summary() || cmd.description();
|
|
243
|
+
}
|
|
244
|
+
optionDescription(option) {
|
|
245
|
+
const extraInfo = [];
|
|
246
|
+
if (option.argChoices) {
|
|
247
|
+
extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
248
|
+
}
|
|
249
|
+
if (option.defaultValue !== undefined) {
|
|
250
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
251
|
+
if (showDefault) {
|
|
252
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (option.presetArg !== undefined && option.optional) {
|
|
256
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
257
|
+
}
|
|
258
|
+
if (option.envVar !== undefined) {
|
|
259
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
260
|
+
}
|
|
261
|
+
if (extraInfo.length > 0) {
|
|
262
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
263
|
+
if (option.description) {
|
|
264
|
+
return `${option.description} ${extraDescription}`;
|
|
265
|
+
}
|
|
266
|
+
return extraDescription;
|
|
267
|
+
}
|
|
268
|
+
return option.description;
|
|
269
|
+
}
|
|
270
|
+
argumentDescription(argument) {
|
|
271
|
+
const extraInfo = [];
|
|
272
|
+
if (argument.argChoices) {
|
|
273
|
+
extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
274
|
+
}
|
|
275
|
+
if (argument.defaultValue !== undefined) {
|
|
276
|
+
extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
277
|
+
}
|
|
278
|
+
if (extraInfo.length > 0) {
|
|
279
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
280
|
+
if (argument.description) {
|
|
281
|
+
return `${argument.description} ${extraDescription}`;
|
|
282
|
+
}
|
|
283
|
+
return extraDescription;
|
|
284
|
+
}
|
|
285
|
+
return argument.description;
|
|
286
|
+
}
|
|
287
|
+
formatItemList(heading, items, helper) {
|
|
288
|
+
if (items.length === 0)
|
|
289
|
+
return [];
|
|
290
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
291
|
+
}
|
|
292
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
293
|
+
const result = new Map;
|
|
294
|
+
unsortedItems.forEach((item) => {
|
|
295
|
+
const group = getGroup(item);
|
|
296
|
+
if (!result.has(group))
|
|
297
|
+
result.set(group, []);
|
|
298
|
+
});
|
|
299
|
+
visibleItems.forEach((item) => {
|
|
300
|
+
const group = getGroup(item);
|
|
301
|
+
if (!result.has(group)) {
|
|
302
|
+
result.set(group, []);
|
|
303
|
+
}
|
|
304
|
+
result.get(group).push(item);
|
|
305
|
+
});
|
|
306
|
+
return result;
|
|
307
|
+
}
|
|
308
|
+
formatHelp(cmd, helper) {
|
|
309
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
310
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
311
|
+
function callFormatItem(term, description) {
|
|
312
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
313
|
+
}
|
|
314
|
+
let output = [
|
|
315
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
316
|
+
""
|
|
317
|
+
];
|
|
318
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
319
|
+
if (commandDescription.length > 0) {
|
|
320
|
+
output = output.concat([
|
|
321
|
+
helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
|
|
322
|
+
""
|
|
323
|
+
]);
|
|
324
|
+
}
|
|
325
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
326
|
+
return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
|
|
327
|
+
});
|
|
328
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
|
|
329
|
+
const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
|
|
330
|
+
optionGroups.forEach((options, group) => {
|
|
331
|
+
const optionList = options.map((option) => {
|
|
332
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
333
|
+
});
|
|
334
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
335
|
+
});
|
|
336
|
+
if (helper.showGlobalOptions) {
|
|
337
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
338
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
339
|
+
});
|
|
340
|
+
output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
|
|
341
|
+
}
|
|
342
|
+
const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
|
|
343
|
+
commandGroups.forEach((commands, group) => {
|
|
344
|
+
const commandList = commands.map((sub) => {
|
|
345
|
+
return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
|
|
346
|
+
});
|
|
347
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
348
|
+
});
|
|
349
|
+
return output.join(`
|
|
350
|
+
`);
|
|
351
|
+
}
|
|
352
|
+
displayWidth(str) {
|
|
353
|
+
return stripColor(str).length;
|
|
354
|
+
}
|
|
355
|
+
styleTitle(str) {
|
|
356
|
+
return str;
|
|
357
|
+
}
|
|
358
|
+
styleUsage(str) {
|
|
359
|
+
return str.split(" ").map((word) => {
|
|
360
|
+
if (word === "[options]")
|
|
361
|
+
return this.styleOptionText(word);
|
|
362
|
+
if (word === "[command]")
|
|
363
|
+
return this.styleSubcommandText(word);
|
|
364
|
+
if (word[0] === "[" || word[0] === "<")
|
|
365
|
+
return this.styleArgumentText(word);
|
|
366
|
+
return this.styleCommandText(word);
|
|
367
|
+
}).join(" ");
|
|
368
|
+
}
|
|
369
|
+
styleCommandDescription(str) {
|
|
370
|
+
return this.styleDescriptionText(str);
|
|
371
|
+
}
|
|
372
|
+
styleOptionDescription(str) {
|
|
373
|
+
return this.styleDescriptionText(str);
|
|
374
|
+
}
|
|
375
|
+
styleSubcommandDescription(str) {
|
|
376
|
+
return this.styleDescriptionText(str);
|
|
377
|
+
}
|
|
378
|
+
styleArgumentDescription(str) {
|
|
379
|
+
return this.styleDescriptionText(str);
|
|
380
|
+
}
|
|
381
|
+
styleDescriptionText(str) {
|
|
382
|
+
return str;
|
|
383
|
+
}
|
|
384
|
+
styleOptionTerm(str) {
|
|
385
|
+
return this.styleOptionText(str);
|
|
386
|
+
}
|
|
387
|
+
styleSubcommandTerm(str) {
|
|
388
|
+
return str.split(" ").map((word) => {
|
|
389
|
+
if (word === "[options]")
|
|
390
|
+
return this.styleOptionText(word);
|
|
391
|
+
if (word[0] === "[" || word[0] === "<")
|
|
392
|
+
return this.styleArgumentText(word);
|
|
393
|
+
return this.styleSubcommandText(word);
|
|
394
|
+
}).join(" ");
|
|
395
|
+
}
|
|
396
|
+
styleArgumentTerm(str) {
|
|
397
|
+
return this.styleArgumentText(str);
|
|
398
|
+
}
|
|
399
|
+
styleOptionText(str) {
|
|
400
|
+
return str;
|
|
401
|
+
}
|
|
402
|
+
styleArgumentText(str) {
|
|
403
|
+
return str;
|
|
404
|
+
}
|
|
405
|
+
styleSubcommandText(str) {
|
|
406
|
+
return str;
|
|
407
|
+
}
|
|
408
|
+
styleCommandText(str) {
|
|
409
|
+
return str;
|
|
410
|
+
}
|
|
411
|
+
padWidth(cmd, helper) {
|
|
412
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
413
|
+
}
|
|
414
|
+
preformatted(str) {
|
|
415
|
+
return /\n[^\S\r\n]/.test(str);
|
|
416
|
+
}
|
|
417
|
+
formatItem(term, termWidth, description, helper) {
|
|
418
|
+
const itemIndent = 2;
|
|
419
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
420
|
+
if (!description)
|
|
421
|
+
return itemIndentStr + term;
|
|
422
|
+
const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
|
|
423
|
+
const spacerWidth = 2;
|
|
424
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
425
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
426
|
+
let formattedDescription;
|
|
427
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
428
|
+
formattedDescription = description;
|
|
429
|
+
} else {
|
|
430
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
431
|
+
formattedDescription = wrappedDescription.replace(/\n/g, `
|
|
432
|
+
` + " ".repeat(termWidth + spacerWidth));
|
|
433
|
+
}
|
|
434
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
435
|
+
${itemIndentStr}`);
|
|
436
|
+
}
|
|
437
|
+
boxWrap(str, width) {
|
|
438
|
+
if (width < this.minWidthToWrap)
|
|
439
|
+
return str;
|
|
440
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
441
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
442
|
+
const wrappedLines = [];
|
|
443
|
+
rawLines.forEach((line) => {
|
|
444
|
+
const chunks = line.match(chunkPattern);
|
|
445
|
+
if (chunks === null) {
|
|
446
|
+
wrappedLines.push("");
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
let sumChunks = [chunks.shift()];
|
|
450
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
451
|
+
chunks.forEach((chunk) => {
|
|
452
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
453
|
+
if (sumWidth + visibleWidth <= width) {
|
|
454
|
+
sumChunks.push(chunk);
|
|
455
|
+
sumWidth += visibleWidth;
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
wrappedLines.push(sumChunks.join(""));
|
|
459
|
+
const nextChunk = chunk.trimStart();
|
|
460
|
+
sumChunks = [nextChunk];
|
|
461
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
462
|
+
});
|
|
463
|
+
wrappedLines.push(sumChunks.join(""));
|
|
464
|
+
});
|
|
465
|
+
return wrappedLines.join(`
|
|
466
|
+
`);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
function stripColor(str) {
|
|
470
|
+
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
|
|
471
|
+
return str.replace(sgrPattern, "");
|
|
472
|
+
}
|
|
473
|
+
exports.Help = Help;
|
|
474
|
+
exports.stripColor = stripColor;
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
// ../../node_modules/commander/lib/option.js
|
|
478
|
+
var require_option = __commonJS(function(exports) {
|
|
479
|
+
var { InvalidArgumentError } = require_error();
|
|
480
|
+
|
|
481
|
+
class Option {
|
|
482
|
+
constructor(flags, description) {
|
|
483
|
+
this.flags = flags;
|
|
484
|
+
this.description = description || "";
|
|
485
|
+
this.required = flags.includes("<");
|
|
486
|
+
this.optional = flags.includes("[");
|
|
487
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
488
|
+
this.mandatory = false;
|
|
489
|
+
const optionFlags = splitOptionFlags(flags);
|
|
490
|
+
this.short = optionFlags.shortFlag;
|
|
491
|
+
this.long = optionFlags.longFlag;
|
|
492
|
+
this.negate = false;
|
|
493
|
+
if (this.long) {
|
|
494
|
+
this.negate = this.long.startsWith("--no-");
|
|
495
|
+
}
|
|
496
|
+
this.defaultValue = undefined;
|
|
497
|
+
this.defaultValueDescription = undefined;
|
|
498
|
+
this.presetArg = undefined;
|
|
499
|
+
this.envVar = undefined;
|
|
500
|
+
this.parseArg = undefined;
|
|
501
|
+
this.hidden = false;
|
|
502
|
+
this.argChoices = undefined;
|
|
503
|
+
this.conflictsWith = [];
|
|
504
|
+
this.implied = undefined;
|
|
505
|
+
this.helpGroupHeading = undefined;
|
|
506
|
+
}
|
|
507
|
+
default(value, description) {
|
|
508
|
+
this.defaultValue = value;
|
|
509
|
+
this.defaultValueDescription = description;
|
|
510
|
+
return this;
|
|
511
|
+
}
|
|
512
|
+
preset(arg) {
|
|
513
|
+
this.presetArg = arg;
|
|
514
|
+
return this;
|
|
515
|
+
}
|
|
516
|
+
conflicts(names) {
|
|
517
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
518
|
+
return this;
|
|
519
|
+
}
|
|
520
|
+
implies(impliedOptionValues) {
|
|
521
|
+
let newImplied = impliedOptionValues;
|
|
522
|
+
if (typeof impliedOptionValues === "string") {
|
|
523
|
+
newImplied = { [impliedOptionValues]: true };
|
|
524
|
+
}
|
|
525
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
526
|
+
return this;
|
|
527
|
+
}
|
|
528
|
+
env(name) {
|
|
529
|
+
this.envVar = name;
|
|
530
|
+
return this;
|
|
531
|
+
}
|
|
532
|
+
argParser(fn) {
|
|
533
|
+
this.parseArg = fn;
|
|
534
|
+
return this;
|
|
535
|
+
}
|
|
536
|
+
makeOptionMandatory(mandatory = true) {
|
|
537
|
+
this.mandatory = !!mandatory;
|
|
538
|
+
return this;
|
|
539
|
+
}
|
|
540
|
+
hideHelp(hide = true) {
|
|
541
|
+
this.hidden = !!hide;
|
|
542
|
+
return this;
|
|
543
|
+
}
|
|
544
|
+
_collectValue(value, previous) {
|
|
545
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
546
|
+
return [value];
|
|
547
|
+
}
|
|
548
|
+
previous.push(value);
|
|
549
|
+
return previous;
|
|
550
|
+
}
|
|
551
|
+
choices(values) {
|
|
552
|
+
this.argChoices = values.slice();
|
|
553
|
+
this.parseArg = (arg, previous) => {
|
|
554
|
+
if (!this.argChoices.includes(arg)) {
|
|
555
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
556
|
+
}
|
|
557
|
+
if (this.variadic) {
|
|
558
|
+
return this._collectValue(arg, previous);
|
|
559
|
+
}
|
|
560
|
+
return arg;
|
|
561
|
+
};
|
|
562
|
+
return this;
|
|
563
|
+
}
|
|
564
|
+
name() {
|
|
565
|
+
if (this.long) {
|
|
566
|
+
return this.long.replace(/^--/, "");
|
|
567
|
+
}
|
|
568
|
+
return this.short.replace(/^-/, "");
|
|
569
|
+
}
|
|
570
|
+
attributeName() {
|
|
571
|
+
if (this.negate) {
|
|
572
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
573
|
+
}
|
|
574
|
+
return camelcase(this.name());
|
|
575
|
+
}
|
|
576
|
+
helpGroup(heading) {
|
|
577
|
+
this.helpGroupHeading = heading;
|
|
578
|
+
return this;
|
|
579
|
+
}
|
|
580
|
+
is(arg) {
|
|
581
|
+
return this.short === arg || this.long === arg;
|
|
582
|
+
}
|
|
583
|
+
isBoolean() {
|
|
584
|
+
return !this.required && !this.optional && !this.negate;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
class DualOptions {
|
|
589
|
+
constructor(options) {
|
|
590
|
+
this.positiveOptions = new Map;
|
|
591
|
+
this.negativeOptions = new Map;
|
|
592
|
+
this.dualOptions = new Set;
|
|
593
|
+
options.forEach((option) => {
|
|
594
|
+
if (option.negate) {
|
|
595
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
596
|
+
} else {
|
|
597
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
this.negativeOptions.forEach((value, key) => {
|
|
601
|
+
if (this.positiveOptions.has(key)) {
|
|
602
|
+
this.dualOptions.add(key);
|
|
603
|
+
}
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
valueFromOption(value, option) {
|
|
607
|
+
const optionKey = option.attributeName();
|
|
608
|
+
if (!this.dualOptions.has(optionKey))
|
|
609
|
+
return true;
|
|
610
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
611
|
+
const negativeValue = preset !== undefined ? preset : false;
|
|
612
|
+
return option.negate === (negativeValue === value);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
function camelcase(str) {
|
|
616
|
+
return str.split("-").reduce((str, word) => {
|
|
617
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
function splitOptionFlags(flags) {
|
|
621
|
+
let shortFlag;
|
|
622
|
+
let longFlag;
|
|
623
|
+
const shortFlagExp = /^-[^-]$/;
|
|
624
|
+
const longFlagExp = /^--[^-]/;
|
|
625
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
626
|
+
if (shortFlagExp.test(flagParts[0]))
|
|
627
|
+
shortFlag = flagParts.shift();
|
|
628
|
+
if (longFlagExp.test(flagParts[0]))
|
|
629
|
+
longFlag = flagParts.shift();
|
|
630
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
631
|
+
shortFlag = flagParts.shift();
|
|
632
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
633
|
+
shortFlag = longFlag;
|
|
634
|
+
longFlag = flagParts.shift();
|
|
635
|
+
}
|
|
636
|
+
if (flagParts[0].startsWith("-")) {
|
|
637
|
+
const unsupportedFlag = flagParts[0];
|
|
638
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
639
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
640
|
+
throw new Error(`${baseError}
|
|
641
|
+
- a short flag is a single dash and a single character
|
|
642
|
+
- either use a single dash and a single character (for a short flag)
|
|
643
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
|
|
644
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
645
|
+
throw new Error(`${baseError}
|
|
646
|
+
- too many short flags`);
|
|
647
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
648
|
+
throw new Error(`${baseError}
|
|
649
|
+
- too many long flags`);
|
|
650
|
+
throw new Error(`${baseError}
|
|
651
|
+
- unrecognised flag format`);
|
|
652
|
+
}
|
|
653
|
+
if (shortFlag === undefined && longFlag === undefined)
|
|
654
|
+
throw new Error(`option creation failed due to no flags found in '${flags}'.`);
|
|
655
|
+
return { shortFlag, longFlag };
|
|
656
|
+
}
|
|
657
|
+
exports.Option = Option;
|
|
658
|
+
exports.DualOptions = DualOptions;
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
// ../../node_modules/commander/lib/suggestSimilar.js
|
|
662
|
+
var require_suggestSimilar = __commonJS(function(exports) {
|
|
663
|
+
var maxDistance = 3;
|
|
664
|
+
function editDistance(a, b) {
|
|
665
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
666
|
+
return Math.max(a.length, b.length);
|
|
667
|
+
const d = [];
|
|
668
|
+
for (let i = 0;i <= a.length; i++) {
|
|
669
|
+
d[i] = [i];
|
|
670
|
+
}
|
|
671
|
+
for (let j = 0;j <= b.length; j++) {
|
|
672
|
+
d[0][j] = j;
|
|
673
|
+
}
|
|
674
|
+
for (let j = 1;j <= b.length; j++) {
|
|
675
|
+
for (let i = 1;i <= a.length; i++) {
|
|
676
|
+
let cost = 1;
|
|
677
|
+
if (a[i - 1] === b[j - 1]) {
|
|
678
|
+
cost = 0;
|
|
679
|
+
} else {
|
|
680
|
+
cost = 1;
|
|
681
|
+
}
|
|
682
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
683
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
684
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return d[a.length][b.length];
|
|
689
|
+
}
|
|
690
|
+
function suggestSimilar(word, candidates) {
|
|
691
|
+
if (!candidates || candidates.length === 0)
|
|
692
|
+
return "";
|
|
693
|
+
candidates = Array.from(new Set(candidates));
|
|
694
|
+
const searchingOptions = word.startsWith("--");
|
|
695
|
+
if (searchingOptions) {
|
|
696
|
+
word = word.slice(2);
|
|
697
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
698
|
+
}
|
|
699
|
+
let similar = [];
|
|
700
|
+
let bestDistance = maxDistance;
|
|
701
|
+
const minSimilarity = 0.4;
|
|
702
|
+
candidates.forEach((candidate) => {
|
|
703
|
+
if (candidate.length <= 1)
|
|
704
|
+
return;
|
|
705
|
+
const distance = editDistance(word, candidate);
|
|
706
|
+
const length = Math.max(word.length, candidate.length);
|
|
707
|
+
const similarity = (length - distance) / length;
|
|
708
|
+
if (similarity > minSimilarity) {
|
|
709
|
+
if (distance < bestDistance) {
|
|
710
|
+
bestDistance = distance;
|
|
711
|
+
similar = [candidate];
|
|
712
|
+
} else if (distance === bestDistance) {
|
|
713
|
+
similar.push(candidate);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
});
|
|
717
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
718
|
+
if (searchingOptions) {
|
|
719
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
720
|
+
}
|
|
721
|
+
if (similar.length > 1) {
|
|
722
|
+
return `
|
|
723
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
724
|
+
}
|
|
725
|
+
if (similar.length === 1) {
|
|
726
|
+
return `
|
|
727
|
+
(Did you mean ${similar[0]}?)`;
|
|
728
|
+
}
|
|
729
|
+
return "";
|
|
730
|
+
}
|
|
731
|
+
exports.suggestSimilar = suggestSimilar;
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
// ../../node_modules/commander/lib/command.js
|
|
735
|
+
var require_command = __commonJS(function(exports) {
|
|
736
|
+
var EventEmitter = __require("node:events").EventEmitter;
|
|
737
|
+
var childProcess = __require("node:child_process");
|
|
738
|
+
var path = __require("node:path");
|
|
739
|
+
var fs = __require("node:fs");
|
|
740
|
+
var process2 = __require("node:process");
|
|
741
|
+
var { Argument, humanReadableArgName } = require_argument();
|
|
742
|
+
var { CommanderError } = require_error();
|
|
743
|
+
var { Help, stripColor } = require_help();
|
|
744
|
+
var { Option, DualOptions } = require_option();
|
|
745
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
746
|
+
|
|
747
|
+
class Command extends EventEmitter {
|
|
748
|
+
constructor(name) {
|
|
749
|
+
super();
|
|
750
|
+
this.commands = [];
|
|
751
|
+
this.options = [];
|
|
752
|
+
this.parent = null;
|
|
753
|
+
this._allowUnknownOption = false;
|
|
754
|
+
this._allowExcessArguments = false;
|
|
755
|
+
this.registeredArguments = [];
|
|
756
|
+
this._args = this.registeredArguments;
|
|
757
|
+
this.args = [];
|
|
758
|
+
this.rawArgs = [];
|
|
759
|
+
this.processedArgs = [];
|
|
760
|
+
this._scriptPath = null;
|
|
761
|
+
this._name = name || "";
|
|
762
|
+
this._optionValues = {};
|
|
763
|
+
this._optionValueSources = {};
|
|
764
|
+
this._storeOptionsAsProperties = false;
|
|
765
|
+
this._actionHandler = null;
|
|
766
|
+
this._executableHandler = false;
|
|
767
|
+
this._executableFile = null;
|
|
768
|
+
this._executableDir = null;
|
|
769
|
+
this._defaultCommandName = null;
|
|
770
|
+
this._exitCallback = null;
|
|
771
|
+
this._aliases = [];
|
|
772
|
+
this._combineFlagAndOptionalValue = true;
|
|
773
|
+
this._description = "";
|
|
774
|
+
this._summary = "";
|
|
775
|
+
this._argsDescription = undefined;
|
|
776
|
+
this._enablePositionalOptions = false;
|
|
777
|
+
this._passThroughOptions = false;
|
|
778
|
+
this._lifeCycleHooks = {};
|
|
779
|
+
this._showHelpAfterError = false;
|
|
780
|
+
this._showSuggestionAfterError = true;
|
|
781
|
+
this._savedState = null;
|
|
782
|
+
this._outputConfiguration = {
|
|
783
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
784
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
785
|
+
outputError: (str, write) => write(str),
|
|
786
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
|
|
787
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
|
|
788
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
789
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
790
|
+
stripColor: (str) => stripColor(str)
|
|
791
|
+
};
|
|
792
|
+
this._hidden = false;
|
|
793
|
+
this._helpOption = undefined;
|
|
794
|
+
this._addImplicitHelpCommand = undefined;
|
|
795
|
+
this._helpCommand = undefined;
|
|
796
|
+
this._helpConfiguration = {};
|
|
797
|
+
this._helpGroupHeading = undefined;
|
|
798
|
+
this._defaultCommandGroup = undefined;
|
|
799
|
+
this._defaultOptionGroup = undefined;
|
|
800
|
+
}
|
|
801
|
+
copyInheritedSettings(sourceCommand) {
|
|
802
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
803
|
+
this._helpOption = sourceCommand._helpOption;
|
|
804
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
805
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
806
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
807
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
808
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
809
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
810
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
811
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
812
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
813
|
+
return this;
|
|
814
|
+
}
|
|
815
|
+
_getCommandAndAncestors() {
|
|
816
|
+
const result = [];
|
|
817
|
+
for (let command = this;command; command = command.parent) {
|
|
818
|
+
result.push(command);
|
|
819
|
+
}
|
|
820
|
+
return result;
|
|
821
|
+
}
|
|
822
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
823
|
+
let desc = actionOptsOrExecDesc;
|
|
824
|
+
let opts = execOpts;
|
|
825
|
+
if (typeof desc === "object" && desc !== null) {
|
|
826
|
+
opts = desc;
|
|
827
|
+
desc = null;
|
|
828
|
+
}
|
|
829
|
+
opts = opts || {};
|
|
830
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
831
|
+
const cmd = this.createCommand(name);
|
|
832
|
+
if (desc) {
|
|
833
|
+
cmd.description(desc);
|
|
834
|
+
cmd._executableHandler = true;
|
|
835
|
+
}
|
|
836
|
+
if (opts.isDefault)
|
|
837
|
+
this._defaultCommandName = cmd._name;
|
|
838
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
839
|
+
cmd._executableFile = opts.executableFile || null;
|
|
840
|
+
if (args)
|
|
841
|
+
cmd.arguments(args);
|
|
842
|
+
this._registerCommand(cmd);
|
|
843
|
+
cmd.parent = this;
|
|
844
|
+
cmd.copyInheritedSettings(this);
|
|
845
|
+
if (desc)
|
|
846
|
+
return this;
|
|
847
|
+
return cmd;
|
|
848
|
+
}
|
|
849
|
+
createCommand(name) {
|
|
850
|
+
return new Command(name);
|
|
851
|
+
}
|
|
852
|
+
createHelp() {
|
|
853
|
+
return Object.assign(new Help, this.configureHelp());
|
|
854
|
+
}
|
|
855
|
+
configureHelp(configuration) {
|
|
856
|
+
if (configuration === undefined)
|
|
857
|
+
return this._helpConfiguration;
|
|
858
|
+
this._helpConfiguration = configuration;
|
|
859
|
+
return this;
|
|
860
|
+
}
|
|
861
|
+
configureOutput(configuration) {
|
|
862
|
+
if (configuration === undefined)
|
|
863
|
+
return this._outputConfiguration;
|
|
864
|
+
this._outputConfiguration = {
|
|
865
|
+
...this._outputConfiguration,
|
|
866
|
+
...configuration
|
|
867
|
+
};
|
|
868
|
+
return this;
|
|
869
|
+
}
|
|
870
|
+
showHelpAfterError(displayHelp = true) {
|
|
871
|
+
if (typeof displayHelp !== "string")
|
|
872
|
+
displayHelp = !!displayHelp;
|
|
873
|
+
this._showHelpAfterError = displayHelp;
|
|
874
|
+
return this;
|
|
875
|
+
}
|
|
876
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
877
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
878
|
+
return this;
|
|
879
|
+
}
|
|
880
|
+
addCommand(cmd, opts) {
|
|
881
|
+
if (!cmd._name) {
|
|
882
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
883
|
+
- specify the name in Command constructor or using .name()`);
|
|
884
|
+
}
|
|
885
|
+
opts = opts || {};
|
|
886
|
+
if (opts.isDefault)
|
|
887
|
+
this._defaultCommandName = cmd._name;
|
|
888
|
+
if (opts.noHelp || opts.hidden)
|
|
889
|
+
cmd._hidden = true;
|
|
890
|
+
this._registerCommand(cmd);
|
|
891
|
+
cmd.parent = this;
|
|
892
|
+
cmd._checkForBrokenPassThrough();
|
|
893
|
+
return this;
|
|
894
|
+
}
|
|
895
|
+
createArgument(name, description) {
|
|
896
|
+
return new Argument(name, description);
|
|
897
|
+
}
|
|
898
|
+
argument(name, description, parseArg, defaultValue) {
|
|
899
|
+
const argument = this.createArgument(name, description);
|
|
900
|
+
if (typeof parseArg === "function") {
|
|
901
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
902
|
+
} else {
|
|
903
|
+
argument.default(parseArg);
|
|
904
|
+
}
|
|
905
|
+
this.addArgument(argument);
|
|
906
|
+
return this;
|
|
907
|
+
}
|
|
908
|
+
arguments(names) {
|
|
909
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
910
|
+
this.argument(detail);
|
|
911
|
+
});
|
|
912
|
+
return this;
|
|
913
|
+
}
|
|
914
|
+
addArgument(argument) {
|
|
915
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
916
|
+
if (previousArgument?.variadic) {
|
|
917
|
+
throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
918
|
+
}
|
|
919
|
+
if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
|
|
920
|
+
throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
921
|
+
}
|
|
922
|
+
this.registeredArguments.push(argument);
|
|
923
|
+
return this;
|
|
924
|
+
}
|
|
925
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
926
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
927
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
928
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
929
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
930
|
+
}
|
|
931
|
+
return this;
|
|
932
|
+
}
|
|
933
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
934
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
935
|
+
const helpDescription = description ?? "display help for command";
|
|
936
|
+
const helpCommand = this.createCommand(helpName);
|
|
937
|
+
helpCommand.helpOption(false);
|
|
938
|
+
if (helpArgs)
|
|
939
|
+
helpCommand.arguments(helpArgs);
|
|
940
|
+
if (helpDescription)
|
|
941
|
+
helpCommand.description(helpDescription);
|
|
942
|
+
this._addImplicitHelpCommand = true;
|
|
943
|
+
this._helpCommand = helpCommand;
|
|
944
|
+
if (enableOrNameAndArgs || description)
|
|
945
|
+
this._initCommandGroup(helpCommand);
|
|
946
|
+
return this;
|
|
947
|
+
}
|
|
948
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
949
|
+
if (typeof helpCommand !== "object") {
|
|
950
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
951
|
+
return this;
|
|
952
|
+
}
|
|
953
|
+
this._addImplicitHelpCommand = true;
|
|
954
|
+
this._helpCommand = helpCommand;
|
|
955
|
+
this._initCommandGroup(helpCommand);
|
|
956
|
+
return this;
|
|
957
|
+
}
|
|
958
|
+
_getHelpCommand() {
|
|
959
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
960
|
+
if (hasImplicitHelpCommand) {
|
|
961
|
+
if (this._helpCommand === undefined) {
|
|
962
|
+
this.helpCommand(undefined, undefined);
|
|
963
|
+
}
|
|
964
|
+
return this._helpCommand;
|
|
965
|
+
}
|
|
966
|
+
return null;
|
|
967
|
+
}
|
|
968
|
+
hook(event, listener) {
|
|
969
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
970
|
+
if (!allowedValues.includes(event)) {
|
|
971
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
972
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
973
|
+
}
|
|
974
|
+
if (this._lifeCycleHooks[event]) {
|
|
975
|
+
this._lifeCycleHooks[event].push(listener);
|
|
976
|
+
} else {
|
|
977
|
+
this._lifeCycleHooks[event] = [listener];
|
|
978
|
+
}
|
|
979
|
+
return this;
|
|
980
|
+
}
|
|
981
|
+
exitOverride(fn) {
|
|
982
|
+
if (fn) {
|
|
983
|
+
this._exitCallback = fn;
|
|
984
|
+
} else {
|
|
985
|
+
this._exitCallback = (err) => {
|
|
986
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
987
|
+
throw err;
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
return this;
|
|
992
|
+
}
|
|
993
|
+
_exit(exitCode, code, message) {
|
|
994
|
+
if (this._exitCallback) {
|
|
995
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
996
|
+
}
|
|
997
|
+
process2.exit(exitCode);
|
|
998
|
+
}
|
|
999
|
+
action(fn) {
|
|
1000
|
+
const listener = (args) => {
|
|
1001
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1002
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1003
|
+
if (this._storeOptionsAsProperties) {
|
|
1004
|
+
actionArgs[expectedArgsCount] = this;
|
|
1005
|
+
} else {
|
|
1006
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1007
|
+
}
|
|
1008
|
+
actionArgs.push(this);
|
|
1009
|
+
return fn.apply(this, actionArgs);
|
|
1010
|
+
};
|
|
1011
|
+
this._actionHandler = listener;
|
|
1012
|
+
return this;
|
|
1013
|
+
}
|
|
1014
|
+
createOption(flags, description) {
|
|
1015
|
+
return new Option(flags, description);
|
|
1016
|
+
}
|
|
1017
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1018
|
+
try {
|
|
1019
|
+
return target.parseArg(value, previous);
|
|
1020
|
+
} catch (err) {
|
|
1021
|
+
if (err.code === "commander.invalidArgument") {
|
|
1022
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1023
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1024
|
+
}
|
|
1025
|
+
throw err;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
_registerOption(option) {
|
|
1029
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1030
|
+
if (matchingOption) {
|
|
1031
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1032
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1033
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1034
|
+
}
|
|
1035
|
+
this._initOptionGroup(option);
|
|
1036
|
+
this.options.push(option);
|
|
1037
|
+
}
|
|
1038
|
+
_registerCommand(command) {
|
|
1039
|
+
const knownBy = (cmd) => {
|
|
1040
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1041
|
+
};
|
|
1042
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
1043
|
+
if (alreadyUsed) {
|
|
1044
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1045
|
+
const newCmd = knownBy(command).join("|");
|
|
1046
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1047
|
+
}
|
|
1048
|
+
this._initCommandGroup(command);
|
|
1049
|
+
this.commands.push(command);
|
|
1050
|
+
}
|
|
1051
|
+
addOption(option) {
|
|
1052
|
+
this._registerOption(option);
|
|
1053
|
+
const oname = option.name();
|
|
1054
|
+
const name = option.attributeName();
|
|
1055
|
+
if (option.negate) {
|
|
1056
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1057
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1058
|
+
this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
|
|
1059
|
+
}
|
|
1060
|
+
} else if (option.defaultValue !== undefined) {
|
|
1061
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1062
|
+
}
|
|
1063
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1064
|
+
if (val == null && option.presetArg !== undefined) {
|
|
1065
|
+
val = option.presetArg;
|
|
1066
|
+
}
|
|
1067
|
+
const oldValue = this.getOptionValue(name);
|
|
1068
|
+
if (val !== null && option.parseArg) {
|
|
1069
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1070
|
+
} else if (val !== null && option.variadic) {
|
|
1071
|
+
val = option._collectValue(val, oldValue);
|
|
1072
|
+
}
|
|
1073
|
+
if (val == null) {
|
|
1074
|
+
if (option.negate) {
|
|
1075
|
+
val = false;
|
|
1076
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1077
|
+
val = true;
|
|
1078
|
+
} else {
|
|
1079
|
+
val = "";
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1083
|
+
};
|
|
1084
|
+
this.on("option:" + oname, (val) => {
|
|
1085
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1086
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1087
|
+
});
|
|
1088
|
+
if (option.envVar) {
|
|
1089
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1090
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1091
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
return this;
|
|
1095
|
+
}
|
|
1096
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1097
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
1098
|
+
throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1099
|
+
}
|
|
1100
|
+
const option = this.createOption(flags, description);
|
|
1101
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1102
|
+
if (typeof fn === "function") {
|
|
1103
|
+
option.default(defaultValue).argParser(fn);
|
|
1104
|
+
} else if (fn instanceof RegExp) {
|
|
1105
|
+
const regex = fn;
|
|
1106
|
+
fn = (val, def) => {
|
|
1107
|
+
const m = regex.exec(val);
|
|
1108
|
+
return m ? m[0] : def;
|
|
1109
|
+
};
|
|
1110
|
+
option.default(defaultValue).argParser(fn);
|
|
1111
|
+
} else {
|
|
1112
|
+
option.default(fn);
|
|
1113
|
+
}
|
|
1114
|
+
return this.addOption(option);
|
|
1115
|
+
}
|
|
1116
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1117
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1118
|
+
}
|
|
1119
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1120
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1121
|
+
}
|
|
1122
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1123
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1124
|
+
return this;
|
|
1125
|
+
}
|
|
1126
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1127
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1128
|
+
return this;
|
|
1129
|
+
}
|
|
1130
|
+
allowExcessArguments(allowExcess = true) {
|
|
1131
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1132
|
+
return this;
|
|
1133
|
+
}
|
|
1134
|
+
enablePositionalOptions(positional = true) {
|
|
1135
|
+
this._enablePositionalOptions = !!positional;
|
|
1136
|
+
return this;
|
|
1137
|
+
}
|
|
1138
|
+
passThroughOptions(passThrough = true) {
|
|
1139
|
+
this._passThroughOptions = !!passThrough;
|
|
1140
|
+
this._checkForBrokenPassThrough();
|
|
1141
|
+
return this;
|
|
1142
|
+
}
|
|
1143
|
+
_checkForBrokenPassThrough() {
|
|
1144
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1145
|
+
throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1149
|
+
if (this.options.length) {
|
|
1150
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1151
|
+
}
|
|
1152
|
+
if (Object.keys(this._optionValues).length) {
|
|
1153
|
+
throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1154
|
+
}
|
|
1155
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1156
|
+
return this;
|
|
1157
|
+
}
|
|
1158
|
+
getOptionValue(key) {
|
|
1159
|
+
if (this._storeOptionsAsProperties) {
|
|
1160
|
+
return this[key];
|
|
1161
|
+
}
|
|
1162
|
+
return this._optionValues[key];
|
|
1163
|
+
}
|
|
1164
|
+
setOptionValue(key, value) {
|
|
1165
|
+
return this.setOptionValueWithSource(key, value, undefined);
|
|
1166
|
+
}
|
|
1167
|
+
setOptionValueWithSource(key, value, source) {
|
|
1168
|
+
if (this._storeOptionsAsProperties) {
|
|
1169
|
+
this[key] = value;
|
|
1170
|
+
} else {
|
|
1171
|
+
this._optionValues[key] = value;
|
|
1172
|
+
}
|
|
1173
|
+
this._optionValueSources[key] = source;
|
|
1174
|
+
return this;
|
|
1175
|
+
}
|
|
1176
|
+
getOptionValueSource(key) {
|
|
1177
|
+
return this._optionValueSources[key];
|
|
1178
|
+
}
|
|
1179
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1180
|
+
let source;
|
|
1181
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1182
|
+
if (cmd.getOptionValueSource(key) !== undefined) {
|
|
1183
|
+
source = cmd.getOptionValueSource(key);
|
|
1184
|
+
}
|
|
1185
|
+
});
|
|
1186
|
+
return source;
|
|
1187
|
+
}
|
|
1188
|
+
_prepareUserArgs(argv2, parseOptions) {
|
|
1189
|
+
if (argv2 !== undefined && !Array.isArray(argv2)) {
|
|
1190
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1191
|
+
}
|
|
1192
|
+
parseOptions = parseOptions || {};
|
|
1193
|
+
if (argv2 === undefined && parseOptions.from === undefined) {
|
|
1194
|
+
if (process2.versions?.electron) {
|
|
1195
|
+
parseOptions.from = "electron";
|
|
1196
|
+
}
|
|
1197
|
+
const execArgv2 = process2.execArgv ?? [];
|
|
1198
|
+
if (execArgv2.includes("-e") || execArgv2.includes("--eval") || execArgv2.includes("-p") || execArgv2.includes("--print")) {
|
|
1199
|
+
parseOptions.from = "eval";
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
if (argv2 === undefined) {
|
|
1203
|
+
argv2 = process2.argv;
|
|
1204
|
+
}
|
|
1205
|
+
this.rawArgs = argv2.slice();
|
|
1206
|
+
let userArgs;
|
|
1207
|
+
switch (parseOptions.from) {
|
|
1208
|
+
case undefined:
|
|
1209
|
+
case "node":
|
|
1210
|
+
this._scriptPath = argv2[1];
|
|
1211
|
+
userArgs = argv2.slice(2);
|
|
1212
|
+
break;
|
|
1213
|
+
case "electron":
|
|
1214
|
+
if (process2.defaultApp) {
|
|
1215
|
+
this._scriptPath = argv2[1];
|
|
1216
|
+
userArgs = argv2.slice(2);
|
|
1217
|
+
} else {
|
|
1218
|
+
userArgs = argv2.slice(1);
|
|
1219
|
+
}
|
|
1220
|
+
break;
|
|
1221
|
+
case "user":
|
|
1222
|
+
userArgs = argv2.slice(0);
|
|
1223
|
+
break;
|
|
1224
|
+
case "eval":
|
|
1225
|
+
userArgs = argv2.slice(1);
|
|
1226
|
+
break;
|
|
1227
|
+
default:
|
|
1228
|
+
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1229
|
+
}
|
|
1230
|
+
if (!this._name && this._scriptPath)
|
|
1231
|
+
this.nameFromFilename(this._scriptPath);
|
|
1232
|
+
this._name = this._name || "program";
|
|
1233
|
+
return userArgs;
|
|
1234
|
+
}
|
|
1235
|
+
parse(argv, parseOptions) {
|
|
1236
|
+
this._prepareForParse();
|
|
1237
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1238
|
+
this._parseCommand([], userArgs);
|
|
1239
|
+
return this;
|
|
1240
|
+
}
|
|
1241
|
+
async parseAsync(argv, parseOptions) {
|
|
1242
|
+
this._prepareForParse();
|
|
1243
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1244
|
+
await this._parseCommand([], userArgs);
|
|
1245
|
+
return this;
|
|
1246
|
+
}
|
|
1247
|
+
_prepareForParse() {
|
|
1248
|
+
if (this._savedState === null) {
|
|
1249
|
+
this.saveStateBeforeParse();
|
|
1250
|
+
} else {
|
|
1251
|
+
this.restoreStateBeforeParse();
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
saveStateBeforeParse() {
|
|
1255
|
+
this._savedState = {
|
|
1256
|
+
_name: this._name,
|
|
1257
|
+
_optionValues: { ...this._optionValues },
|
|
1258
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
1259
|
+
};
|
|
1260
|
+
}
|
|
1261
|
+
restoreStateBeforeParse() {
|
|
1262
|
+
if (this._storeOptionsAsProperties)
|
|
1263
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
1264
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
1265
|
+
this._name = this._savedState._name;
|
|
1266
|
+
this._scriptPath = null;
|
|
1267
|
+
this.rawArgs = [];
|
|
1268
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
1269
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
1270
|
+
this.args = [];
|
|
1271
|
+
this.processedArgs = [];
|
|
1272
|
+
}
|
|
1273
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
1274
|
+
if (fs.existsSync(executableFile))
|
|
1275
|
+
return;
|
|
1276
|
+
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";
|
|
1277
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1278
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1279
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1280
|
+
- ${executableDirMessage}`;
|
|
1281
|
+
throw new Error(executableMissing);
|
|
1282
|
+
}
|
|
1283
|
+
_executeSubCommand(subcommand, args) {
|
|
1284
|
+
args = args.slice();
|
|
1285
|
+
let launchWithNode = false;
|
|
1286
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1287
|
+
function findFile(baseDir, baseName) {
|
|
1288
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1289
|
+
if (fs.existsSync(localBin))
|
|
1290
|
+
return localBin;
|
|
1291
|
+
if (sourceExt.includes(path.extname(baseName)))
|
|
1292
|
+
return;
|
|
1293
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1294
|
+
if (foundExt)
|
|
1295
|
+
return `${localBin}${foundExt}`;
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
this._checkForMissingMandatoryOptions();
|
|
1299
|
+
this._checkForConflictingOptions();
|
|
1300
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1301
|
+
let executableDir = this._executableDir || "";
|
|
1302
|
+
if (this._scriptPath) {
|
|
1303
|
+
let resolvedScriptPath;
|
|
1304
|
+
try {
|
|
1305
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1306
|
+
} catch {
|
|
1307
|
+
resolvedScriptPath = this._scriptPath;
|
|
1308
|
+
}
|
|
1309
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1310
|
+
}
|
|
1311
|
+
if (executableDir) {
|
|
1312
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1313
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1314
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1315
|
+
if (legacyName !== this._name) {
|
|
1316
|
+
localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
executableFile = localFile || executableFile;
|
|
1320
|
+
}
|
|
1321
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1322
|
+
let proc;
|
|
1323
|
+
if (process2.platform !== "win32") {
|
|
1324
|
+
if (launchWithNode) {
|
|
1325
|
+
args.unshift(executableFile);
|
|
1326
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1327
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
1328
|
+
} else {
|
|
1329
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1330
|
+
}
|
|
1331
|
+
} else {
|
|
1332
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1333
|
+
args.unshift(executableFile);
|
|
1334
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1335
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
1336
|
+
}
|
|
1337
|
+
if (!proc.killed) {
|
|
1338
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1339
|
+
signals.forEach((signal) => {
|
|
1340
|
+
process2.on(signal, () => {
|
|
1341
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1342
|
+
proc.kill(signal);
|
|
1343
|
+
}
|
|
1344
|
+
});
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
const exitCallback = this._exitCallback;
|
|
1348
|
+
proc.on("close", (code) => {
|
|
1349
|
+
code = code ?? 1;
|
|
1350
|
+
if (!exitCallback) {
|
|
1351
|
+
process2.exit(code);
|
|
1352
|
+
} else {
|
|
1353
|
+
exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1354
|
+
}
|
|
1355
|
+
});
|
|
1356
|
+
proc.on("error", (err) => {
|
|
1357
|
+
if (err.code === "ENOENT") {
|
|
1358
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1359
|
+
} else if (err.code === "EACCES") {
|
|
1360
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
1361
|
+
}
|
|
1362
|
+
if (!exitCallback) {
|
|
1363
|
+
process2.exit(1);
|
|
1364
|
+
} else {
|
|
1365
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1366
|
+
wrappedError.nestedError = err;
|
|
1367
|
+
exitCallback(wrappedError);
|
|
1368
|
+
}
|
|
1369
|
+
});
|
|
1370
|
+
this.runningCommand = proc;
|
|
1371
|
+
}
|
|
1372
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1373
|
+
const subCommand = this._findCommand(commandName);
|
|
1374
|
+
if (!subCommand)
|
|
1375
|
+
this.help({ error: true });
|
|
1376
|
+
subCommand._prepareForParse();
|
|
1377
|
+
let promiseChain;
|
|
1378
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1379
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1380
|
+
if (subCommand._executableHandler) {
|
|
1381
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1382
|
+
} else {
|
|
1383
|
+
return subCommand._parseCommand(operands, unknown);
|
|
1384
|
+
}
|
|
1385
|
+
});
|
|
1386
|
+
return promiseChain;
|
|
1387
|
+
}
|
|
1388
|
+
_dispatchHelpCommand(subcommandName) {
|
|
1389
|
+
if (!subcommandName) {
|
|
1390
|
+
this.help();
|
|
1391
|
+
}
|
|
1392
|
+
const subCommand = this._findCommand(subcommandName);
|
|
1393
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
1394
|
+
subCommand.help();
|
|
1395
|
+
}
|
|
1396
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
1397
|
+
}
|
|
1398
|
+
_checkNumberOfArguments() {
|
|
1399
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
1400
|
+
if (arg.required && this.args[i] == null) {
|
|
1401
|
+
this.missingArgument(arg.name());
|
|
1402
|
+
}
|
|
1403
|
+
});
|
|
1404
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
1408
|
+
this._excessArguments(this.args);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
_processArguments() {
|
|
1412
|
+
const myParseArg = (argument, value, previous) => {
|
|
1413
|
+
let parsedValue = value;
|
|
1414
|
+
if (value !== null && argument.parseArg) {
|
|
1415
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
1416
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
1417
|
+
}
|
|
1418
|
+
return parsedValue;
|
|
1419
|
+
};
|
|
1420
|
+
this._checkNumberOfArguments();
|
|
1421
|
+
const processedArgs = [];
|
|
1422
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
1423
|
+
let value = declaredArg.defaultValue;
|
|
1424
|
+
if (declaredArg.variadic) {
|
|
1425
|
+
if (index < this.args.length) {
|
|
1426
|
+
value = this.args.slice(index);
|
|
1427
|
+
if (declaredArg.parseArg) {
|
|
1428
|
+
value = value.reduce((processed, v) => {
|
|
1429
|
+
return myParseArg(declaredArg, v, processed);
|
|
1430
|
+
}, declaredArg.defaultValue);
|
|
1431
|
+
}
|
|
1432
|
+
} else if (value === undefined) {
|
|
1433
|
+
value = [];
|
|
1434
|
+
}
|
|
1435
|
+
} else if (index < this.args.length) {
|
|
1436
|
+
value = this.args[index];
|
|
1437
|
+
if (declaredArg.parseArg) {
|
|
1438
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
processedArgs[index] = value;
|
|
1442
|
+
});
|
|
1443
|
+
this.processedArgs = processedArgs;
|
|
1444
|
+
}
|
|
1445
|
+
_chainOrCall(promise, fn) {
|
|
1446
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
1447
|
+
return promise.then(() => fn());
|
|
1448
|
+
}
|
|
1449
|
+
return fn();
|
|
1450
|
+
}
|
|
1451
|
+
_chainOrCallHooks(promise, event) {
|
|
1452
|
+
let result = promise;
|
|
1453
|
+
const hooks = [];
|
|
1454
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
|
|
1455
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
1456
|
+
hooks.push({ hookedCommand, callback });
|
|
1457
|
+
});
|
|
1458
|
+
});
|
|
1459
|
+
if (event === "postAction") {
|
|
1460
|
+
hooks.reverse();
|
|
1461
|
+
}
|
|
1462
|
+
hooks.forEach((hookDetail) => {
|
|
1463
|
+
result = this._chainOrCall(result, () => {
|
|
1464
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
1465
|
+
});
|
|
1466
|
+
});
|
|
1467
|
+
return result;
|
|
1468
|
+
}
|
|
1469
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
1470
|
+
let result = promise;
|
|
1471
|
+
if (this._lifeCycleHooks[event] !== undefined) {
|
|
1472
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
1473
|
+
result = this._chainOrCall(result, () => {
|
|
1474
|
+
return hook(this, subCommand);
|
|
1475
|
+
});
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1478
|
+
return result;
|
|
1479
|
+
}
|
|
1480
|
+
_parseCommand(operands, unknown) {
|
|
1481
|
+
const parsed = this.parseOptions(unknown);
|
|
1482
|
+
this._parseOptionsEnv();
|
|
1483
|
+
this._parseOptionsImplied();
|
|
1484
|
+
operands = operands.concat(parsed.operands);
|
|
1485
|
+
unknown = parsed.unknown;
|
|
1486
|
+
this.args = operands.concat(unknown);
|
|
1487
|
+
if (operands && this._findCommand(operands[0])) {
|
|
1488
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
1489
|
+
}
|
|
1490
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
1491
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
1492
|
+
}
|
|
1493
|
+
if (this._defaultCommandName) {
|
|
1494
|
+
this._outputHelpIfRequested(unknown);
|
|
1495
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
1496
|
+
}
|
|
1497
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
1498
|
+
this.help({ error: true });
|
|
1499
|
+
}
|
|
1500
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
1501
|
+
this._checkForMissingMandatoryOptions();
|
|
1502
|
+
this._checkForConflictingOptions();
|
|
1503
|
+
const checkForUnknownOptions = () => {
|
|
1504
|
+
if (parsed.unknown.length > 0) {
|
|
1505
|
+
this.unknownOption(parsed.unknown[0]);
|
|
1506
|
+
}
|
|
1507
|
+
};
|
|
1508
|
+
const commandEvent = `command:${this.name()}`;
|
|
1509
|
+
if (this._actionHandler) {
|
|
1510
|
+
checkForUnknownOptions();
|
|
1511
|
+
this._processArguments();
|
|
1512
|
+
let promiseChain;
|
|
1513
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
1514
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
1515
|
+
if (this.parent) {
|
|
1516
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1517
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
1521
|
+
return promiseChain;
|
|
1522
|
+
}
|
|
1523
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
1524
|
+
checkForUnknownOptions();
|
|
1525
|
+
this._processArguments();
|
|
1526
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1527
|
+
} else if (operands.length) {
|
|
1528
|
+
if (this._findCommand("*")) {
|
|
1529
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
1530
|
+
}
|
|
1531
|
+
if (this.listenerCount("command:*")) {
|
|
1532
|
+
this.emit("command:*", operands, unknown);
|
|
1533
|
+
} else if (this.commands.length) {
|
|
1534
|
+
this.unknownCommand();
|
|
1535
|
+
} else {
|
|
1536
|
+
checkForUnknownOptions();
|
|
1537
|
+
this._processArguments();
|
|
1538
|
+
}
|
|
1539
|
+
} else if (this.commands.length) {
|
|
1540
|
+
checkForUnknownOptions();
|
|
1541
|
+
this.help({ error: true });
|
|
1542
|
+
} else {
|
|
1543
|
+
checkForUnknownOptions();
|
|
1544
|
+
this._processArguments();
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
_findCommand(name) {
|
|
1548
|
+
if (!name)
|
|
1549
|
+
return;
|
|
1550
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
1551
|
+
}
|
|
1552
|
+
_findOption(arg) {
|
|
1553
|
+
return this.options.find((option) => option.is(arg));
|
|
1554
|
+
}
|
|
1555
|
+
_checkForMissingMandatoryOptions() {
|
|
1556
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1557
|
+
cmd.options.forEach((anOption) => {
|
|
1558
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
|
|
1559
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
1560
|
+
}
|
|
1561
|
+
});
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
_checkForConflictingLocalOptions() {
|
|
1565
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
1566
|
+
const optionKey = option.attributeName();
|
|
1567
|
+
if (this.getOptionValue(optionKey) === undefined) {
|
|
1568
|
+
return false;
|
|
1569
|
+
}
|
|
1570
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
1571
|
+
});
|
|
1572
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
|
|
1573
|
+
optionsWithConflicting.forEach((option) => {
|
|
1574
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
1575
|
+
if (conflictingAndDefined) {
|
|
1576
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
1577
|
+
}
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
_checkForConflictingOptions() {
|
|
1581
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1582
|
+
cmd._checkForConflictingLocalOptions();
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
parseOptions(args) {
|
|
1586
|
+
const operands = [];
|
|
1587
|
+
const unknown = [];
|
|
1588
|
+
let dest = operands;
|
|
1589
|
+
function maybeOption(arg) {
|
|
1590
|
+
return arg.length > 1 && arg[0] === "-";
|
|
1591
|
+
}
|
|
1592
|
+
const negativeNumberArg = (arg) => {
|
|
1593
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
|
|
1594
|
+
return false;
|
|
1595
|
+
return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
|
|
1596
|
+
};
|
|
1597
|
+
let activeVariadicOption = null;
|
|
1598
|
+
let activeGroup = null;
|
|
1599
|
+
let i = 0;
|
|
1600
|
+
while (i < args.length || activeGroup) {
|
|
1601
|
+
const arg = activeGroup ?? args[i++];
|
|
1602
|
+
activeGroup = null;
|
|
1603
|
+
if (arg === "--") {
|
|
1604
|
+
if (dest === unknown)
|
|
1605
|
+
dest.push(arg);
|
|
1606
|
+
dest.push(...args.slice(i));
|
|
1607
|
+
break;
|
|
1608
|
+
}
|
|
1609
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
1610
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
1611
|
+
continue;
|
|
1612
|
+
}
|
|
1613
|
+
activeVariadicOption = null;
|
|
1614
|
+
if (maybeOption(arg)) {
|
|
1615
|
+
const option = this._findOption(arg);
|
|
1616
|
+
if (option) {
|
|
1617
|
+
if (option.required) {
|
|
1618
|
+
const value = args[i++];
|
|
1619
|
+
if (value === undefined)
|
|
1620
|
+
this.optionMissingArgument(option);
|
|
1621
|
+
this.emit(`option:${option.name()}`, value);
|
|
1622
|
+
} else if (option.optional) {
|
|
1623
|
+
let value = null;
|
|
1624
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
1625
|
+
value = args[i++];
|
|
1626
|
+
}
|
|
1627
|
+
this.emit(`option:${option.name()}`, value);
|
|
1628
|
+
} else {
|
|
1629
|
+
this.emit(`option:${option.name()}`);
|
|
1630
|
+
}
|
|
1631
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
1632
|
+
continue;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
1636
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
1637
|
+
if (option) {
|
|
1638
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
1639
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
1640
|
+
} else {
|
|
1641
|
+
this.emit(`option:${option.name()}`);
|
|
1642
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
1643
|
+
}
|
|
1644
|
+
continue;
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
1648
|
+
const index = arg.indexOf("=");
|
|
1649
|
+
const option = this._findOption(arg.slice(0, index));
|
|
1650
|
+
if (option && (option.required || option.optional)) {
|
|
1651
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
1652
|
+
continue;
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
1656
|
+
dest = unknown;
|
|
1657
|
+
}
|
|
1658
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
1659
|
+
if (this._findCommand(arg)) {
|
|
1660
|
+
operands.push(arg);
|
|
1661
|
+
unknown.push(...args.slice(i));
|
|
1662
|
+
break;
|
|
1663
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
1664
|
+
operands.push(arg, ...args.slice(i));
|
|
1665
|
+
break;
|
|
1666
|
+
} else if (this._defaultCommandName) {
|
|
1667
|
+
unknown.push(arg, ...args.slice(i));
|
|
1668
|
+
break;
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
if (this._passThroughOptions) {
|
|
1672
|
+
dest.push(arg, ...args.slice(i));
|
|
1673
|
+
break;
|
|
1674
|
+
}
|
|
1675
|
+
dest.push(arg);
|
|
1676
|
+
}
|
|
1677
|
+
return { operands, unknown };
|
|
1678
|
+
}
|
|
1679
|
+
opts() {
|
|
1680
|
+
if (this._storeOptionsAsProperties) {
|
|
1681
|
+
const result = {};
|
|
1682
|
+
const len = this.options.length;
|
|
1683
|
+
for (let i = 0;i < len; i++) {
|
|
1684
|
+
const key = this.options[i].attributeName();
|
|
1685
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
1686
|
+
}
|
|
1687
|
+
return result;
|
|
1688
|
+
}
|
|
1689
|
+
return this._optionValues;
|
|
1690
|
+
}
|
|
1691
|
+
optsWithGlobals() {
|
|
1692
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
1693
|
+
}
|
|
1694
|
+
error(message, errorOptions) {
|
|
1695
|
+
this._outputConfiguration.outputError(`${message}
|
|
1696
|
+
`, this._outputConfiguration.writeErr);
|
|
1697
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
1698
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
1699
|
+
`);
|
|
1700
|
+
} else if (this._showHelpAfterError) {
|
|
1701
|
+
this._outputConfiguration.writeErr(`
|
|
1702
|
+
`);
|
|
1703
|
+
this.outputHelp({ error: true });
|
|
1704
|
+
}
|
|
1705
|
+
const config = errorOptions || {};
|
|
1706
|
+
const exitCode = config.exitCode || 1;
|
|
1707
|
+
const code = config.code || "commander.error";
|
|
1708
|
+
this._exit(exitCode, code, message);
|
|
1709
|
+
}
|
|
1710
|
+
_parseOptionsEnv() {
|
|
1711
|
+
this.options.forEach((option) => {
|
|
1712
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
1713
|
+
const optionKey = option.attributeName();
|
|
1714
|
+
if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
|
|
1715
|
+
if (option.required || option.optional) {
|
|
1716
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
1717
|
+
} else {
|
|
1718
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
});
|
|
1723
|
+
}
|
|
1724
|
+
_parseOptionsImplied() {
|
|
1725
|
+
const dualHelper = new DualOptions(this.options);
|
|
1726
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
1727
|
+
return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
1728
|
+
};
|
|
1729
|
+
this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
1730
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
1731
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
1732
|
+
});
|
|
1733
|
+
});
|
|
1734
|
+
}
|
|
1735
|
+
missingArgument(name) {
|
|
1736
|
+
const message = `error: missing required argument '${name}'`;
|
|
1737
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
1738
|
+
}
|
|
1739
|
+
optionMissingArgument(option) {
|
|
1740
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
1741
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
1742
|
+
}
|
|
1743
|
+
missingMandatoryOptionValue(option) {
|
|
1744
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
1745
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
1746
|
+
}
|
|
1747
|
+
_conflictingOption(option, conflictingOption) {
|
|
1748
|
+
const findBestOptionFromValue = (option) => {
|
|
1749
|
+
const optionKey = option.attributeName();
|
|
1750
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
1751
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
1752
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
1753
|
+
if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
|
|
1754
|
+
return negativeOption;
|
|
1755
|
+
}
|
|
1756
|
+
return positiveOption || option;
|
|
1757
|
+
};
|
|
1758
|
+
const getErrorMessage = (option) => {
|
|
1759
|
+
const bestOption = findBestOptionFromValue(option);
|
|
1760
|
+
const optionKey = bestOption.attributeName();
|
|
1761
|
+
const source = this.getOptionValueSource(optionKey);
|
|
1762
|
+
if (source === "env") {
|
|
1763
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
1764
|
+
}
|
|
1765
|
+
return `option '${bestOption.flags}'`;
|
|
1766
|
+
};
|
|
1767
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
1768
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
1769
|
+
}
|
|
1770
|
+
unknownOption(flag) {
|
|
1771
|
+
if (this._allowUnknownOption)
|
|
1772
|
+
return;
|
|
1773
|
+
let suggestion = "";
|
|
1774
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
1775
|
+
let candidateFlags = [];
|
|
1776
|
+
let command = this;
|
|
1777
|
+
do {
|
|
1778
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
1779
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
1780
|
+
command = command.parent;
|
|
1781
|
+
} while (command && !command._enablePositionalOptions);
|
|
1782
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
1783
|
+
}
|
|
1784
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
1785
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
1786
|
+
}
|
|
1787
|
+
_excessArguments(receivedArgs) {
|
|
1788
|
+
if (this._allowExcessArguments)
|
|
1789
|
+
return;
|
|
1790
|
+
const expected = this.registeredArguments.length;
|
|
1791
|
+
const s = expected === 1 ? "" : "s";
|
|
1792
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
1793
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
1794
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
1795
|
+
}
|
|
1796
|
+
unknownCommand() {
|
|
1797
|
+
const unknownName = this.args[0];
|
|
1798
|
+
let suggestion = "";
|
|
1799
|
+
if (this._showSuggestionAfterError) {
|
|
1800
|
+
const candidateNames = [];
|
|
1801
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
1802
|
+
candidateNames.push(command.name());
|
|
1803
|
+
if (command.alias())
|
|
1804
|
+
candidateNames.push(command.alias());
|
|
1805
|
+
});
|
|
1806
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
1807
|
+
}
|
|
1808
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
1809
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
1810
|
+
}
|
|
1811
|
+
version(str, flags, description) {
|
|
1812
|
+
if (str === undefined)
|
|
1813
|
+
return this._version;
|
|
1814
|
+
this._version = str;
|
|
1815
|
+
flags = flags || "-V, --version";
|
|
1816
|
+
description = description || "output the version number";
|
|
1817
|
+
const versionOption = this.createOption(flags, description);
|
|
1818
|
+
this._versionOptionName = versionOption.attributeName();
|
|
1819
|
+
this._registerOption(versionOption);
|
|
1820
|
+
this.on("option:" + versionOption.name(), () => {
|
|
1821
|
+
this._outputConfiguration.writeOut(`${str}
|
|
1822
|
+
`);
|
|
1823
|
+
this._exit(0, "commander.version", str);
|
|
1824
|
+
});
|
|
1825
|
+
return this;
|
|
1826
|
+
}
|
|
1827
|
+
description(str, argsDescription) {
|
|
1828
|
+
if (str === undefined && argsDescription === undefined)
|
|
1829
|
+
return this._description;
|
|
1830
|
+
this._description = str;
|
|
1831
|
+
if (argsDescription) {
|
|
1832
|
+
this._argsDescription = argsDescription;
|
|
1833
|
+
}
|
|
1834
|
+
return this;
|
|
1835
|
+
}
|
|
1836
|
+
summary(str) {
|
|
1837
|
+
if (str === undefined)
|
|
1838
|
+
return this._summary;
|
|
1839
|
+
this._summary = str;
|
|
1840
|
+
return this;
|
|
1841
|
+
}
|
|
1842
|
+
alias(alias) {
|
|
1843
|
+
if (alias === undefined)
|
|
1844
|
+
return this._aliases[0];
|
|
1845
|
+
let command = this;
|
|
1846
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
1847
|
+
command = this.commands[this.commands.length - 1];
|
|
1848
|
+
}
|
|
1849
|
+
if (alias === command._name)
|
|
1850
|
+
throw new Error("Command alias can't be the same as its name");
|
|
1851
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
1852
|
+
if (matchingCommand) {
|
|
1853
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
1854
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
1855
|
+
}
|
|
1856
|
+
command._aliases.push(alias);
|
|
1857
|
+
return this;
|
|
1858
|
+
}
|
|
1859
|
+
aliases(aliases) {
|
|
1860
|
+
if (aliases === undefined)
|
|
1861
|
+
return this._aliases;
|
|
1862
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
1863
|
+
return this;
|
|
1864
|
+
}
|
|
1865
|
+
usage(str) {
|
|
1866
|
+
if (str === undefined) {
|
|
1867
|
+
if (this._usage)
|
|
1868
|
+
return this._usage;
|
|
1869
|
+
const args = this.registeredArguments.map((arg) => {
|
|
1870
|
+
return humanReadableArgName(arg);
|
|
1871
|
+
});
|
|
1872
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
1873
|
+
}
|
|
1874
|
+
this._usage = str;
|
|
1875
|
+
return this;
|
|
1876
|
+
}
|
|
1877
|
+
name(str) {
|
|
1878
|
+
if (str === undefined)
|
|
1879
|
+
return this._name;
|
|
1880
|
+
this._name = str;
|
|
1881
|
+
return this;
|
|
1882
|
+
}
|
|
1883
|
+
helpGroup(heading) {
|
|
1884
|
+
if (heading === undefined)
|
|
1885
|
+
return this._helpGroupHeading ?? "";
|
|
1886
|
+
this._helpGroupHeading = heading;
|
|
1887
|
+
return this;
|
|
1888
|
+
}
|
|
1889
|
+
commandsGroup(heading) {
|
|
1890
|
+
if (heading === undefined)
|
|
1891
|
+
return this._defaultCommandGroup ?? "";
|
|
1892
|
+
this._defaultCommandGroup = heading;
|
|
1893
|
+
return this;
|
|
1894
|
+
}
|
|
1895
|
+
optionsGroup(heading) {
|
|
1896
|
+
if (heading === undefined)
|
|
1897
|
+
return this._defaultOptionGroup ?? "";
|
|
1898
|
+
this._defaultOptionGroup = heading;
|
|
1899
|
+
return this;
|
|
1900
|
+
}
|
|
1901
|
+
_initOptionGroup(option) {
|
|
1902
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
1903
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
1904
|
+
}
|
|
1905
|
+
_initCommandGroup(cmd) {
|
|
1906
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
1907
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
1908
|
+
}
|
|
1909
|
+
nameFromFilename(filename) {
|
|
1910
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
1911
|
+
return this;
|
|
1912
|
+
}
|
|
1913
|
+
executableDir(path) {
|
|
1914
|
+
if (path === undefined)
|
|
1915
|
+
return this._executableDir;
|
|
1916
|
+
this._executableDir = path;
|
|
1917
|
+
return this;
|
|
1918
|
+
}
|
|
1919
|
+
helpInformation(contextOptions) {
|
|
1920
|
+
const helper = this.createHelp();
|
|
1921
|
+
const context = this._getOutputContext(contextOptions);
|
|
1922
|
+
helper.prepareContext({
|
|
1923
|
+
error: context.error,
|
|
1924
|
+
helpWidth: context.helpWidth,
|
|
1925
|
+
outputHasColors: context.hasColors
|
|
1926
|
+
});
|
|
1927
|
+
const text = helper.formatHelp(this, helper);
|
|
1928
|
+
if (context.hasColors)
|
|
1929
|
+
return text;
|
|
1930
|
+
return this._outputConfiguration.stripColor(text);
|
|
1931
|
+
}
|
|
1932
|
+
_getOutputContext(contextOptions) {
|
|
1933
|
+
contextOptions = contextOptions || {};
|
|
1934
|
+
const error = !!contextOptions.error;
|
|
1935
|
+
let baseWrite;
|
|
1936
|
+
let hasColors;
|
|
1937
|
+
let helpWidth;
|
|
1938
|
+
if (error) {
|
|
1939
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
1940
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
1941
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
1942
|
+
} else {
|
|
1943
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
1944
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
1945
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
1946
|
+
}
|
|
1947
|
+
const write = (str) => {
|
|
1948
|
+
if (!hasColors)
|
|
1949
|
+
str = this._outputConfiguration.stripColor(str);
|
|
1950
|
+
return baseWrite(str);
|
|
1951
|
+
};
|
|
1952
|
+
return { error, write, hasColors, helpWidth };
|
|
1953
|
+
}
|
|
1954
|
+
outputHelp(contextOptions) {
|
|
1955
|
+
let deprecatedCallback;
|
|
1956
|
+
if (typeof contextOptions === "function") {
|
|
1957
|
+
deprecatedCallback = contextOptions;
|
|
1958
|
+
contextOptions = undefined;
|
|
1959
|
+
}
|
|
1960
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
1961
|
+
const eventContext = {
|
|
1962
|
+
error: outputContext.error,
|
|
1963
|
+
write: outputContext.write,
|
|
1964
|
+
command: this
|
|
1965
|
+
};
|
|
1966
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
1967
|
+
this.emit("beforeHelp", eventContext);
|
|
1968
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
1969
|
+
if (deprecatedCallback) {
|
|
1970
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
1971
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
1972
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
outputContext.write(helpInformation);
|
|
1976
|
+
if (this._getHelpOption()?.long) {
|
|
1977
|
+
this.emit(this._getHelpOption().long);
|
|
1978
|
+
}
|
|
1979
|
+
this.emit("afterHelp", eventContext);
|
|
1980
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
|
|
1981
|
+
}
|
|
1982
|
+
helpOption(flags, description) {
|
|
1983
|
+
if (typeof flags === "boolean") {
|
|
1984
|
+
if (flags) {
|
|
1985
|
+
if (this._helpOption === null)
|
|
1986
|
+
this._helpOption = undefined;
|
|
1987
|
+
if (this._defaultOptionGroup) {
|
|
1988
|
+
this._initOptionGroup(this._getHelpOption());
|
|
1989
|
+
}
|
|
1990
|
+
} else {
|
|
1991
|
+
this._helpOption = null;
|
|
1992
|
+
}
|
|
1993
|
+
return this;
|
|
1994
|
+
}
|
|
1995
|
+
this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
|
|
1996
|
+
if (flags || description)
|
|
1997
|
+
this._initOptionGroup(this._helpOption);
|
|
1998
|
+
return this;
|
|
1999
|
+
}
|
|
2000
|
+
_getHelpOption() {
|
|
2001
|
+
if (this._helpOption === undefined) {
|
|
2002
|
+
this.helpOption(undefined, undefined);
|
|
2003
|
+
}
|
|
2004
|
+
return this._helpOption;
|
|
2005
|
+
}
|
|
2006
|
+
addHelpOption(option) {
|
|
2007
|
+
this._helpOption = option;
|
|
2008
|
+
this._initOptionGroup(option);
|
|
2009
|
+
return this;
|
|
2010
|
+
}
|
|
2011
|
+
help(contextOptions) {
|
|
2012
|
+
this.outputHelp(contextOptions);
|
|
2013
|
+
let exitCode2 = Number(process2.exitCode ?? 0);
|
|
2014
|
+
if (exitCode2 === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
2015
|
+
exitCode2 = 1;
|
|
2016
|
+
}
|
|
2017
|
+
this._exit(exitCode2, "commander.help", "(outputHelp)");
|
|
2018
|
+
}
|
|
2019
|
+
addHelpText(position, text) {
|
|
2020
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
2021
|
+
if (!allowedValues.includes(position)) {
|
|
2022
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
2023
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2024
|
+
}
|
|
2025
|
+
const helpEvent = `${position}Help`;
|
|
2026
|
+
this.on(helpEvent, (context) => {
|
|
2027
|
+
let helpStr;
|
|
2028
|
+
if (typeof text === "function") {
|
|
2029
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
2030
|
+
} else {
|
|
2031
|
+
helpStr = text;
|
|
2032
|
+
}
|
|
2033
|
+
if (helpStr) {
|
|
2034
|
+
context.write(`${helpStr}
|
|
2035
|
+
`);
|
|
2036
|
+
}
|
|
2037
|
+
});
|
|
2038
|
+
return this;
|
|
2039
|
+
}
|
|
2040
|
+
_outputHelpIfRequested(args) {
|
|
2041
|
+
const helpOption = this._getHelpOption();
|
|
2042
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
2043
|
+
if (helpRequested) {
|
|
2044
|
+
this.outputHelp();
|
|
2045
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
function incrementNodeInspectorPort(args) {
|
|
2050
|
+
return args.map((arg) => {
|
|
2051
|
+
if (!arg.startsWith("--inspect")) {
|
|
2052
|
+
return arg;
|
|
2053
|
+
}
|
|
2054
|
+
let debugOption;
|
|
2055
|
+
let debugHost = "127.0.0.1";
|
|
2056
|
+
let debugPort = "9229";
|
|
2057
|
+
let match;
|
|
2058
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
2059
|
+
debugOption = match[1];
|
|
2060
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2061
|
+
debugOption = match[1];
|
|
2062
|
+
if (/^\d+$/.test(match[3])) {
|
|
2063
|
+
debugPort = match[3];
|
|
2064
|
+
} else {
|
|
2065
|
+
debugHost = match[3];
|
|
2066
|
+
}
|
|
2067
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2068
|
+
debugOption = match[1];
|
|
2069
|
+
debugHost = match[3];
|
|
2070
|
+
debugPort = match[4];
|
|
2071
|
+
}
|
|
2072
|
+
if (debugOption && debugPort !== "0") {
|
|
2073
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2074
|
+
}
|
|
2075
|
+
return arg;
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
function useColor() {
|
|
2079
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
2080
|
+
return false;
|
|
2081
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
|
|
2082
|
+
return true;
|
|
2083
|
+
return;
|
|
2084
|
+
}
|
|
2085
|
+
exports.Command = Command;
|
|
2086
|
+
exports.useColor = useColor;
|
|
2087
|
+
});
|
|
2088
|
+
|
|
2089
|
+
// src/cli.ts
|
|
2090
|
+
import { pathToFileURL } from "node:url";
|
|
2091
|
+
|
|
2092
|
+
// ../../node_modules/commander/index.js
|
|
2093
|
+
var exports_commander = {};
|
|
2094
|
+
__exportCjs(exports_commander, {
|
|
2095
|
+
program: () => $program,
|
|
2096
|
+
createCommand: () => $createCommand,
|
|
2097
|
+
createOption: () => $createOption,
|
|
2098
|
+
createArgument: () => $createArgument,
|
|
2099
|
+
Command: () => $Command,
|
|
2100
|
+
Option: () => $Option,
|
|
2101
|
+
Argument: () => $Argument,
|
|
2102
|
+
Help: () => $Help,
|
|
2103
|
+
CommanderError: () => $CommanderError,
|
|
2104
|
+
InvalidArgumentError: () => $InvalidArgumentError,
|
|
2105
|
+
InvalidOptionArgumentError: () => $InvalidOptionArgumentError
|
|
2106
|
+
}, {
|
|
2107
|
+
program: (value) => $program = value,
|
|
2108
|
+
createCommand: (value) => $createCommand = value,
|
|
2109
|
+
createOption: (value) => $createOption = value,
|
|
2110
|
+
createArgument: (value) => $createArgument = value,
|
|
2111
|
+
Command: (value) => $Command = value,
|
|
2112
|
+
Option: (value) => $Option = value,
|
|
2113
|
+
Argument: (value) => $Argument = value,
|
|
2114
|
+
Help: (value) => $Help = value,
|
|
2115
|
+
CommanderError: (value) => $CommanderError = value,
|
|
2116
|
+
InvalidArgumentError: (value) => $InvalidArgumentError = value,
|
|
2117
|
+
InvalidOptionArgumentError: (value) => $InvalidOptionArgumentError = value
|
|
2118
|
+
});
|
|
2119
|
+
var { Argument } = require_argument();
|
|
2120
|
+
var { Command } = require_command();
|
|
2121
|
+
var { CommanderError, InvalidArgumentError } = require_error();
|
|
2122
|
+
var { Help } = require_help();
|
|
2123
|
+
var { Option } = require_option();
|
|
2124
|
+
var $program = new Command;
|
|
2125
|
+
var $createCommand = (name) => new Command(name);
|
|
2126
|
+
var $createOption = (flags, description) => new Option(flags, description);
|
|
2127
|
+
var $createArgument = (name, description) => new Argument(name, description);
|
|
2128
|
+
var $Command = Command;
|
|
2129
|
+
var $Option = Option;
|
|
2130
|
+
var $Argument = Argument;
|
|
2131
|
+
var $Help = Help;
|
|
2132
|
+
var $CommanderError = CommanderError;
|
|
2133
|
+
var $InvalidArgumentError = InvalidArgumentError;
|
|
2134
|
+
var $InvalidOptionArgumentError = InvalidArgumentError;
|
|
2135
|
+
|
|
2136
|
+
// ../../node_modules/commander/esm.mjs
|
|
2137
|
+
var {
|
|
2138
|
+
program,
|
|
2139
|
+
createCommand,
|
|
2140
|
+
createArgument,
|
|
2141
|
+
createOption,
|
|
2142
|
+
CommanderError: CommanderError2,
|
|
2143
|
+
InvalidArgumentError: InvalidArgumentError2,
|
|
2144
|
+
InvalidOptionArgumentError,
|
|
2145
|
+
Command: Command2,
|
|
2146
|
+
Argument: Argument2,
|
|
2147
|
+
Option: Option2,
|
|
2148
|
+
Help: Help2
|
|
2149
|
+
} = exports_commander;
|
|
2150
|
+
|
|
2151
|
+
// src/cli/plan.ts
|
|
2152
|
+
import { resolve as resolve4 } from "node:path";
|
|
2153
|
+
|
|
2154
|
+
// src/extensions/processx.ts
|
|
2155
|
+
import { spawn } from "node:child_process";
|
|
2156
|
+
function run(command, args, options = {}) {
|
|
2157
|
+
return new Promise((resolve, reject) => {
|
|
2158
|
+
const child = spawn(command, args, {
|
|
2159
|
+
cwd: options.cwd,
|
|
2160
|
+
env: options.env ?? process.env,
|
|
2161
|
+
stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
|
|
2162
|
+
});
|
|
2163
|
+
let stdout = "";
|
|
2164
|
+
let stderr = "";
|
|
2165
|
+
const stdoutChunks = [];
|
|
2166
|
+
const stderrChunks = [];
|
|
2167
|
+
const unbounded = options.capture === "unbounded";
|
|
2168
|
+
child.stdout?.on("data", (chunk) => {
|
|
2169
|
+
const text = chunk.toString();
|
|
2170
|
+
if (unbounded)
|
|
2171
|
+
stdoutChunks.push(text);
|
|
2172
|
+
else
|
|
2173
|
+
stdout = appendBounded(stdout, text);
|
|
2174
|
+
});
|
|
2175
|
+
child.stderr?.on("data", (chunk) => {
|
|
2176
|
+
const text = chunk.toString();
|
|
2177
|
+
if (unbounded)
|
|
2178
|
+
stderrChunks.push(text);
|
|
2179
|
+
else
|
|
2180
|
+
stderr = appendBounded(stderr, text);
|
|
2181
|
+
});
|
|
2182
|
+
child.on("error", reject);
|
|
2183
|
+
child.on("close", (code) => resolve({
|
|
2184
|
+
code: code ?? 1,
|
|
2185
|
+
stdout: unbounded ? stdoutChunks.join("") : stdout,
|
|
2186
|
+
stderr: unbounded ? stderrChunks.join("") : stderr
|
|
2187
|
+
}));
|
|
2188
|
+
if (options.input !== undefined && child.stdin)
|
|
2189
|
+
child.stdin.end(options.input);
|
|
2190
|
+
});
|
|
2191
|
+
}
|
|
2192
|
+
async function runChecked(command, args, options = {}) {
|
|
2193
|
+
const result = await run(command, args, options);
|
|
2194
|
+
if (result.code === 0)
|
|
2195
|
+
return result;
|
|
2196
|
+
const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.code}`;
|
|
2197
|
+
throw new Error(`${command} ${args.join(" ")} failed: ${detail}`);
|
|
2198
|
+
}
|
|
2199
|
+
var MAX_CAPTURED_OUTPUT_LENGTH = 65536;
|
|
2200
|
+
function appendBounded(current, next) {
|
|
2201
|
+
const combined = current + next;
|
|
2202
|
+
return combined.length <= MAX_CAPTURED_OUTPUT_LENGTH ? combined : combined.slice(-MAX_CAPTURED_OUTPUT_LENGTH);
|
|
2203
|
+
}
|
|
2204
|
+
|
|
2205
|
+
// src/plan/annotations.ts
|
|
2206
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
2207
|
+
import { readFile as readFile2, rename, writeFile as writeFile2 } from "node:fs/promises";
|
|
2208
|
+
import { basename, dirname, join as join2 } from "node:path";
|
|
2209
|
+
|
|
2210
|
+
// src/plan/lock.ts
|
|
2211
|
+
import { randomUUID } from "node:crypto";
|
|
2212
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2213
|
+
import { hostname } from "node:os";
|
|
2214
|
+
import { join } from "node:path";
|
|
2215
|
+
async function withPlanLock(planDir, operation, options = {}) {
|
|
2216
|
+
const lockDir = join(planDir, ".lock");
|
|
2217
|
+
const waitMs = options.waitMs ?? 5000;
|
|
2218
|
+
const pollMs = options.pollMs ?? 25;
|
|
2219
|
+
const owner = {
|
|
2220
|
+
token: randomUUID(),
|
|
2221
|
+
pid: process.pid,
|
|
2222
|
+
hostname: hostname(),
|
|
2223
|
+
operation: options.operation ?? "plan mutation",
|
|
2224
|
+
acquiredAt: new Date().toISOString()
|
|
2225
|
+
};
|
|
2226
|
+
const started = Date.now();
|
|
2227
|
+
while (true) {
|
|
2228
|
+
try {
|
|
2229
|
+
await mkdir(lockDir);
|
|
2230
|
+
await writeFile(join(lockDir, "owner.json"), `${JSON.stringify(owner)}
|
|
2231
|
+
`, { mode: 384 });
|
|
2232
|
+
break;
|
|
2233
|
+
} catch (error) {
|
|
2234
|
+
if (error.code !== "EEXIST")
|
|
2235
|
+
throw error;
|
|
2236
|
+
if (Date.now() - started >= waitMs) {
|
|
2237
|
+
let existing = "unknown owner";
|
|
2238
|
+
try {
|
|
2239
|
+
existing = (await readFile(join(lockDir, "owner.json"), "utf8")).trim();
|
|
2240
|
+
} catch {}
|
|
2241
|
+
throw new Error(`Timed out waiting for plan lock ${lockDir}; owner: ${existing}. Remove it only after confirming the owner is stale.`);
|
|
2242
|
+
}
|
|
2243
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
try {
|
|
2247
|
+
return await operation();
|
|
2248
|
+
} finally {
|
|
2249
|
+
let current;
|
|
2250
|
+
try {
|
|
2251
|
+
current = JSON.parse(await readFile(join(lockDir, "owner.json"), "utf8"));
|
|
2252
|
+
} catch {}
|
|
2253
|
+
if (current?.token === owner.token)
|
|
2254
|
+
await rm(lockDir, { recursive: true, force: true });
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
// src/plan/annotations.ts
|
|
2259
|
+
async function annotatePlan(record, runtime = {}) {
|
|
2260
|
+
const execute = runtime.execute ?? executeProcess;
|
|
2261
|
+
const result = await execute("tuicr", ["--file", record.planPath], dirname(record.planPath), true);
|
|
2262
|
+
const sessionSlug = [...result.stderr.matchAll(/^tuicr-session:\s*(\S+)\s*$/gm)].at(-1)?.[1];
|
|
2263
|
+
if (result.code !== 0)
|
|
2264
|
+
throw new Error(result.stderr.trim() || `tuicr exited with status ${result.code}.`);
|
|
2265
|
+
if (!sessionSlug)
|
|
2266
|
+
throw new Error("tuicr did not report a tuicr-session marker.");
|
|
2267
|
+
const state = await withPlanLock(record.dir, async () => {
|
|
2268
|
+
const previous = await readAnnotationState(record).catch(() => {
|
|
2269
|
+
return;
|
|
2270
|
+
});
|
|
2271
|
+
const next = {
|
|
2272
|
+
schemaVersion: 1,
|
|
2273
|
+
sessionSlug,
|
|
2274
|
+
updatedAt: new Date().toISOString(),
|
|
2275
|
+
appliedCommentIds: previous?.appliedCommentIds ?? []
|
|
2276
|
+
};
|
|
2277
|
+
await atomicJson(annotationStatePath(record), next);
|
|
2278
|
+
return next;
|
|
2279
|
+
}, { operation: "save annotation session" });
|
|
2280
|
+
return { sessionSlug, code: result.code, state };
|
|
2281
|
+
}
|
|
2282
|
+
async function readPlanAnnotations(record, options = {}) {
|
|
2283
|
+
const state = await readAnnotationState(record).catch((error) => {
|
|
2284
|
+
if (error.code === "ENOENT")
|
|
2285
|
+
return;
|
|
2286
|
+
throw error;
|
|
2287
|
+
});
|
|
2288
|
+
if (!state)
|
|
2289
|
+
return { comments: [], pending: [] };
|
|
2290
|
+
const execute = options.runtime?.execute ?? executeProcess;
|
|
2291
|
+
const response = await execute("tuicr", ["review", "comments", "--session", state.sessionSlug], record.dir, false);
|
|
2292
|
+
if (response.code !== 0) {
|
|
2293
|
+
if (/not found|no session|deleted/i.test(response.stderr))
|
|
2294
|
+
return { state, comments: [], pending: [] };
|
|
2295
|
+
throw new Error(response.stderr.trim() || "Cannot read tuicr comments.");
|
|
2296
|
+
}
|
|
2297
|
+
let raw;
|
|
2298
|
+
try {
|
|
2299
|
+
raw = JSON.parse(response.stdout);
|
|
2300
|
+
} catch {
|
|
2301
|
+
throw new Error("tuicr returned malformed comment JSON.");
|
|
2302
|
+
}
|
|
2303
|
+
if (!Array.isArray(raw))
|
|
2304
|
+
throw new Error("tuicr comment output must be a JSON array.");
|
|
2305
|
+
const lines = record.source.split(`
|
|
2306
|
+
`);
|
|
2307
|
+
const applied = new Set(state.appliedCommentIds);
|
|
2308
|
+
const comments = raw.map((value, index) => normalizeComment(value, index, lines, applied));
|
|
2309
|
+
const pending = comments.filter((comment) => !comment.applied);
|
|
2310
|
+
return { state, comments: options.includeApplied ? comments : pending, pending };
|
|
2311
|
+
}
|
|
2312
|
+
function annotationStatePath(record) {
|
|
2313
|
+
return join2(record.dir, "annotations.json");
|
|
2314
|
+
}
|
|
2315
|
+
async function readAnnotationState(record) {
|
|
2316
|
+
const value = JSON.parse(await readFile2(annotationStatePath(record), "utf8"));
|
|
2317
|
+
if (value.schemaVersion !== 1 || typeof value.sessionSlug !== "string" || !Array.isArray(value.appliedCommentIds)) {
|
|
2318
|
+
throw new Error(`Malformed annotation state: ${annotationStatePath(record)}.`);
|
|
2319
|
+
}
|
|
2320
|
+
return value;
|
|
2321
|
+
}
|
|
2322
|
+
function normalizeComment(value, index, lines, applied) {
|
|
2323
|
+
if (!value || typeof value !== "object")
|
|
2324
|
+
throw new Error(`Malformed tuicr comment at index ${index}.`);
|
|
2325
|
+
const raw = value;
|
|
2326
|
+
if (typeof raw.id !== "string" || typeof raw.content !== "string")
|
|
2327
|
+
throw new Error(`Malformed tuicr comment at index ${index}.`);
|
|
2328
|
+
const line = integer(raw.start_line) ?? integer(raw.line);
|
|
2329
|
+
const endLine = integer(raw.end_line) ?? line;
|
|
2330
|
+
const targetPath = typeof raw.path === "string" ? raw.path : undefined;
|
|
2331
|
+
const appliesToPlan = !targetPath || basename(targetPath) === basename("PLAN.md");
|
|
2332
|
+
const validAnchor = appliesToPlan && line !== undefined && line > 0 && line <= lines.length;
|
|
2333
|
+
return {
|
|
2334
|
+
id: raw.id,
|
|
2335
|
+
body: raw.content,
|
|
2336
|
+
file: targetPath,
|
|
2337
|
+
line,
|
|
2338
|
+
endLine,
|
|
2339
|
+
context: validAnchor ? lines.slice(line - 1, Math.min(endLine ?? line, lines.length)).join(`
|
|
2340
|
+
`) : undefined,
|
|
2341
|
+
stale: line !== undefined && !validAnchor,
|
|
2342
|
+
applied: applied.has(raw.id)
|
|
2343
|
+
};
|
|
2344
|
+
}
|
|
2345
|
+
async function executeProcess(command, args, cwd, interactive) {
|
|
2346
|
+
if (!interactive) {
|
|
2347
|
+
const result = await run(command, args, { cwd, capture: "unbounded" });
|
|
2348
|
+
return { code: result.code, stdout: result.stdout, stderr: result.stderr };
|
|
2349
|
+
}
|
|
2350
|
+
return new Promise((resolve, reject) => {
|
|
2351
|
+
const child = spawn2(command, args, { cwd, stdio: ["inherit", "inherit", "pipe"] });
|
|
2352
|
+
let stderr = "";
|
|
2353
|
+
child.stderr.on("data", (chunk) => {
|
|
2354
|
+
const text = chunk.toString();
|
|
2355
|
+
stderr += text;
|
|
2356
|
+
process.stderr.write(text);
|
|
2357
|
+
});
|
|
2358
|
+
child.on("error", reject);
|
|
2359
|
+
child.on("close", (code) => resolve({ code: code ?? 1, stdout: "", stderr }));
|
|
2360
|
+
});
|
|
2361
|
+
}
|
|
2362
|
+
async function atomicJson(path, value) {
|
|
2363
|
+
const temp = join2(dirname(path), `.${basename(path)}.${crypto.randomUUID()}.tmp`);
|
|
2364
|
+
await writeFile2(temp, `${JSON.stringify(value, null, 2)}
|
|
2365
|
+
`, { mode: 384, flag: "wx" });
|
|
2366
|
+
await rename(temp, path);
|
|
2367
|
+
}
|
|
2368
|
+
function integer(value) {
|
|
2369
|
+
return typeof value === "number" && Number.isInteger(value) ? value : undefined;
|
|
2370
|
+
}
|
|
2371
|
+
// src/plan/escalation.ts
|
|
2372
|
+
import { z } from "zod";
|
|
2373
|
+
var escalationSchema = z.object({
|
|
2374
|
+
planId: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
|
2375
|
+
executionId: z.string().min(1),
|
|
2376
|
+
phaseId: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
|
2377
|
+
taskId: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).optional(),
|
|
2378
|
+
blocker: z.string().min(1),
|
|
2379
|
+
attempts: z.array(z.string()),
|
|
2380
|
+
evidence: z.array(z.string()),
|
|
2381
|
+
needsUserDecision: z.boolean()
|
|
2382
|
+
}).strict();
|
|
2383
|
+
// src/plan/transitions.ts
|
|
2384
|
+
var STABLE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
2385
|
+
function isStableId(value) {
|
|
2386
|
+
return STABLE_ID.test(value) && value.length <= 80;
|
|
2387
|
+
}
|
|
2388
|
+
function assertStableId(value, label = "identifier") {
|
|
2389
|
+
if (!isStableId(value))
|
|
2390
|
+
throw new Error(`${label} must be a lowercase stable slug, not a path: ${value}`);
|
|
2391
|
+
}
|
|
2392
|
+
function assertUniqueIds(ids, label) {
|
|
2393
|
+
const seen = new Set;
|
|
2394
|
+
for (const id of ids) {
|
|
2395
|
+
assertStableId(id, label);
|
|
2396
|
+
if (seen.has(id))
|
|
2397
|
+
throw new Error(`Duplicate ${label}: ${id}.`);
|
|
2398
|
+
seen.add(id);
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// src/plan/markdown.ts
|
|
2403
|
+
var PLAN_MARKER = /<!-- diffpi-plan: (\{[^\n]+\}) -->/;
|
|
2404
|
+
var PHASE_MARKER = /<!-- diffpi-phase: (\{[^\n]+\}) -->/g;
|
|
2405
|
+
var TASK_MARKER = /<!-- diffpi-task: (\{[^\n]+\}) -->/g;
|
|
2406
|
+
var SUPPORTED_SCHEMA = 1;
|
|
2407
|
+
function countDesignWords(plan) {
|
|
2408
|
+
return [plan.design.bigIdeas, plan.design.keyApiUpdates, plan.design.consequences].join(" ").trim().split(/\s+/).filter(Boolean).length;
|
|
2409
|
+
}
|
|
2410
|
+
function validatePlanDocument(plan, options = {}) {
|
|
2411
|
+
const issues = [];
|
|
2412
|
+
const add = (code, severity, message, path) => issues.push({ code, severity, message, path });
|
|
2413
|
+
try {
|
|
2414
|
+
assertStableId(plan.id, "plan id");
|
|
2415
|
+
assertUniqueIds(plan.phases.map((phase) => phase.id), "phase id");
|
|
2416
|
+
assertUniqueIds(plan.phases.flatMap((phase) => phase.tasks.map((task) => task.id)), "task id");
|
|
2417
|
+
} catch (error) {
|
|
2418
|
+
add("invalid-id", "error", error.message);
|
|
2419
|
+
}
|
|
2420
|
+
if (plan.schemaVersion !== SUPPORTED_SCHEMA)
|
|
2421
|
+
add("schema", "error", `Unsupported plan schema: ${plan.schemaVersion}.`);
|
|
2422
|
+
const phaseIds = new Set(plan.phases.map((phase) => phase.id));
|
|
2423
|
+
const taskIds = new Set(plan.phases.flatMap((phase) => phase.tasks.map((task) => task.id)));
|
|
2424
|
+
for (const phase of plan.phases) {
|
|
2425
|
+
for (const dependency of phase.dependencies) {
|
|
2426
|
+
if (!phaseIds.has(dependency))
|
|
2427
|
+
add("dangling-dependency", "error", `Phase ${phase.id} depends on missing ${dependency}.`);
|
|
2428
|
+
}
|
|
2429
|
+
for (const task of phase.tasks) {
|
|
2430
|
+
for (const dependency of task.dependencies) {
|
|
2431
|
+
if (!taskIds.has(dependency))
|
|
2432
|
+
add("dangling-dependency", "error", `Task ${task.id} depends on missing ${dependency}.`);
|
|
2433
|
+
}
|
|
2434
|
+
if (options.strict && task.acceptanceCriteria.length === 0)
|
|
2435
|
+
add("acceptance", "error", `Task ${task.id} has no acceptance criteria.`, task.id);
|
|
2436
|
+
}
|
|
2437
|
+
if (options.strict && phase.tasks.length === 0)
|
|
2438
|
+
add("empty-phase", "error", `Phase ${phase.id} has no tasks.`, phase.id);
|
|
2439
|
+
}
|
|
2440
|
+
for (const cycle of dependencyCycles(plan))
|
|
2441
|
+
add("dependency-cycle", "error", `Dependency cycle: ${cycle.join(" -> ")}.`);
|
|
2442
|
+
const designWords = countDesignWords(plan);
|
|
2443
|
+
if (designWords > 300)
|
|
2444
|
+
add("design-length", "warning", `Design is ${designWords} words; prefer 300 or fewer.`);
|
|
2445
|
+
if (options.strict && designWords > 800)
|
|
2446
|
+
add("design-too-long", "error", `Design is ${designWords} words; finalization allows at most 800.`);
|
|
2447
|
+
if (options.strict && plan.phases.length === 0)
|
|
2448
|
+
add("no-phases", "error", "Finalization requires at least one phase.");
|
|
2449
|
+
if (options.strict && (options.pendingAnnotations ?? 0) > 0)
|
|
2450
|
+
add("pending-annotations", "error", `${options.pendingAnnotations} annotations remain pending.`);
|
|
2451
|
+
return issues;
|
|
2452
|
+
}
|
|
2453
|
+
function parsePlanDocument(source, ref = "PLAN.md") {
|
|
2454
|
+
const planMatch = source.match(PLAN_MARKER);
|
|
2455
|
+
if (!planMatch)
|
|
2456
|
+
throw new Error(`${ref}: missing or malformed diffpi-plan marker.`);
|
|
2457
|
+
if ((source.match(new RegExp(PLAN_MARKER.source, "g")) ?? []).length !== 1)
|
|
2458
|
+
throw new Error(`${ref}: duplicate diffpi-plan marker.`);
|
|
2459
|
+
const marker = parseMarker(planMatch[1], `${ref} plan`);
|
|
2460
|
+
if (marker.schemaVersion !== SUPPORTED_SCHEMA)
|
|
2461
|
+
throw new Error(`${ref}: unsupported plan schema ${String(marker.schemaVersion)}.`);
|
|
2462
|
+
assertStableId(marker.id, "plan id");
|
|
2463
|
+
const title = source.match(/^# (.+)$/m)?.[1]?.trim();
|
|
2464
|
+
if (!title)
|
|
2465
|
+
throw new Error(`${ref}: missing plan title.`);
|
|
2466
|
+
const phases = parsePhases(section(source, "Implementation"), ref);
|
|
2467
|
+
const document = {
|
|
2468
|
+
...marker,
|
|
2469
|
+
schemaVersion: 1,
|
|
2470
|
+
title,
|
|
2471
|
+
intent: cleanPlaceholder(section(source, "Intent")),
|
|
2472
|
+
requirements: parseBullets(section(source, "Requirements")),
|
|
2473
|
+
design: {
|
|
2474
|
+
bigIdeas: cleanPlaceholder(subsection(source, "Design", "Big Ideas")),
|
|
2475
|
+
keyApiUpdates: cleanPlaceholder(subsection(source, "Design", "Key API Addition/Updates")),
|
|
2476
|
+
consequences: cleanPlaceholder(subsection(source, "Design", "Consequences"))
|
|
2477
|
+
},
|
|
2478
|
+
phases,
|
|
2479
|
+
references: parseReferences(section(source, "References"))
|
|
2480
|
+
};
|
|
2481
|
+
const errors = validatePlanDocument(document).filter((issue) => issue.severity === "error");
|
|
2482
|
+
if (errors.length)
|
|
2483
|
+
throw new Error(`${ref}: ${errors.map((issue) => issue.message).join(" ")}`);
|
|
2484
|
+
return document;
|
|
2485
|
+
}
|
|
2486
|
+
function parsePhases(input, ref) {
|
|
2487
|
+
const starts = [...input.matchAll(PHASE_MARKER)];
|
|
2488
|
+
const phases = starts.map((match, index) => {
|
|
2489
|
+
const start = match.index;
|
|
2490
|
+
const end = input.indexOf("<!-- /diffpi-phase -->", start);
|
|
2491
|
+
if (end < 0)
|
|
2492
|
+
throw new Error(`${ref}: phase marker has no closing marker.`);
|
|
2493
|
+
const next = starts[index + 1]?.index;
|
|
2494
|
+
if (next !== undefined && next < end)
|
|
2495
|
+
throw new Error(`${ref}: nested or unclosed phase marker.`);
|
|
2496
|
+
const body = input.slice(start + match[0].length, end);
|
|
2497
|
+
const marker = parseMarker(match[1], `${ref} phase`);
|
|
2498
|
+
assertStableId(marker.id, "phase id");
|
|
2499
|
+
const title = body.match(/^### Phase: (.+)$/m)?.[1]?.trim();
|
|
2500
|
+
const objective = body.match(/^\*\*Objective:\*\*\s*(.*)$/m)?.[1]?.trim();
|
|
2501
|
+
if (!title || !objective)
|
|
2502
|
+
throw new Error(`${ref}: phase ${marker.id} is missing title or objective.`);
|
|
2503
|
+
return {
|
|
2504
|
+
...marker,
|
|
2505
|
+
title,
|
|
2506
|
+
objective,
|
|
2507
|
+
dependencies: parseCsv(body.match(/^\*\*Dependencies:\*\*\s*(.*)$/m)?.[1]),
|
|
2508
|
+
tasks: parseTasks(body, ref)
|
|
2509
|
+
};
|
|
2510
|
+
});
|
|
2511
|
+
assertUniqueIds(phases.map((phase) => phase.id), "phase id");
|
|
2512
|
+
return phases;
|
|
2513
|
+
}
|
|
2514
|
+
function parseTasks(input, ref) {
|
|
2515
|
+
const starts = [...input.matchAll(TASK_MARKER)];
|
|
2516
|
+
const tasks = starts.map((match, index) => {
|
|
2517
|
+
const start = match.index;
|
|
2518
|
+
const end = input.indexOf("<!-- /diffpi-task -->", start);
|
|
2519
|
+
if (end < 0)
|
|
2520
|
+
throw new Error(`${ref}: task marker has no closing marker.`);
|
|
2521
|
+
const next = starts[index + 1]?.index;
|
|
2522
|
+
if (next !== undefined && next < end)
|
|
2523
|
+
throw new Error(`${ref}: nested or unclosed task marker.`);
|
|
2524
|
+
const body = input.slice(start + match[0].length, end);
|
|
2525
|
+
const marker = parseMarker(match[1], `${ref} task`);
|
|
2526
|
+
assertStableId(marker.id, "task id");
|
|
2527
|
+
const title = body.match(/^- \[[ xX]\] \*\*(.+)\*\*$/m)?.[1]?.trim();
|
|
2528
|
+
if (!title)
|
|
2529
|
+
throw new Error(`${ref}: task ${marker.id} is missing its checkbox title.`);
|
|
2530
|
+
return {
|
|
2531
|
+
...marker,
|
|
2532
|
+
title,
|
|
2533
|
+
steps: parseListValue(body, "Steps"),
|
|
2534
|
+
dependencies: parseListValue(body, "Dependencies"),
|
|
2535
|
+
fileScopes: parseListValue(body, "File scopes"),
|
|
2536
|
+
acceptanceCriteria: parseListValue(body, "Acceptance criteria")
|
|
2537
|
+
};
|
|
2538
|
+
});
|
|
2539
|
+
assertUniqueIds(tasks.map((task) => task.id), "task id");
|
|
2540
|
+
return tasks;
|
|
2541
|
+
}
|
|
2542
|
+
function parseReferences(input) {
|
|
2543
|
+
return [...input.matchAll(/^- <!-- diffpi-reference: (\{[^\n]+\}) -->\s*(.*)$/gm)].map((match) => {
|
|
2544
|
+
const marker = parseMarker(match[1], "reference");
|
|
2545
|
+
assertStableId(marker.id, "reference id");
|
|
2546
|
+
return { id: marker.id, value: match[2].trim() || marker.value };
|
|
2547
|
+
});
|
|
2548
|
+
}
|
|
2549
|
+
function dependencyCycles(plan) {
|
|
2550
|
+
const graph = new Map;
|
|
2551
|
+
for (const phase of plan.phases)
|
|
2552
|
+
graph.set(phase.id, phase.dependencies);
|
|
2553
|
+
for (const task of plan.phases.flatMap((phase) => phase.tasks))
|
|
2554
|
+
graph.set(task.id, task.dependencies);
|
|
2555
|
+
const cycles = [];
|
|
2556
|
+
const visiting = new Set;
|
|
2557
|
+
const visited = new Set;
|
|
2558
|
+
const walk = (id, path) => {
|
|
2559
|
+
if (visiting.has(id)) {
|
|
2560
|
+
cycles.push([...path.slice(path.indexOf(id)), id]);
|
|
2561
|
+
return;
|
|
2562
|
+
}
|
|
2563
|
+
if (visited.has(id))
|
|
2564
|
+
return;
|
|
2565
|
+
visiting.add(id);
|
|
2566
|
+
for (const dependency of graph.get(id) ?? [])
|
|
2567
|
+
walk(dependency, [...path, id]);
|
|
2568
|
+
visiting.delete(id);
|
|
2569
|
+
visited.add(id);
|
|
2570
|
+
};
|
|
2571
|
+
for (const id of graph.keys())
|
|
2572
|
+
walk(id, []);
|
|
2573
|
+
return cycles;
|
|
2574
|
+
}
|
|
2575
|
+
function section(source, heading) {
|
|
2576
|
+
const match = source.match(new RegExp(`^## ${escapeRegExp(heading)}\\s*$`, "m"));
|
|
2577
|
+
if (!match?.index) {
|
|
2578
|
+
if (match?.index === 0)
|
|
2579
|
+
return "";
|
|
2580
|
+
throw new Error(`Missing required heading: ${heading}.`);
|
|
2581
|
+
}
|
|
2582
|
+
const start = match.index + match[0].length;
|
|
2583
|
+
const rest = source.slice(start);
|
|
2584
|
+
const end = rest.search(/^## /m);
|
|
2585
|
+
return (end < 0 ? rest : rest.slice(0, end)).trim();
|
|
2586
|
+
}
|
|
2587
|
+
function subsection(source, parent, heading) {
|
|
2588
|
+
const body = section(source, parent);
|
|
2589
|
+
const match = body.match(new RegExp(`^### ${escapeRegExp(heading)}\\s*$`, "m"));
|
|
2590
|
+
if (match?.index === undefined)
|
|
2591
|
+
throw new Error(`Missing required heading: ${parent}/${heading}.`);
|
|
2592
|
+
const rest = body.slice(match.index + match[0].length);
|
|
2593
|
+
const end = rest.search(/^### /m);
|
|
2594
|
+
return (end < 0 ? rest : rest.slice(0, end)).trim();
|
|
2595
|
+
}
|
|
2596
|
+
function parseBullets(input) {
|
|
2597
|
+
return [...input.matchAll(/^- (?!<!--)(.+)$/gm)].map((match) => match[1].trim());
|
|
2598
|
+
}
|
|
2599
|
+
function parseListValue(body, label) {
|
|
2600
|
+
const value = body.match(new RegExp(`^ - ${escapeRegExp(label)}:\\s*(.*)$`, "m"))?.[1];
|
|
2601
|
+
return parseCsv(value);
|
|
2602
|
+
}
|
|
2603
|
+
function parseCsv(value) {
|
|
2604
|
+
if (!value || value.trim().toLowerCase() === "none")
|
|
2605
|
+
return [];
|
|
2606
|
+
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
2607
|
+
}
|
|
2608
|
+
function cleanPlaceholder(value) {
|
|
2609
|
+
return value.replace(/<!--[^]*?-->/g, "").trim();
|
|
2610
|
+
}
|
|
2611
|
+
function parseMarker(value, label) {
|
|
2612
|
+
try {
|
|
2613
|
+
return JSON.parse(value);
|
|
2614
|
+
} catch {
|
|
2615
|
+
throw new Error(`Malformed ${label} marker JSON.`);
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
function escapeRegExp(value) {
|
|
2619
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2620
|
+
}
|
|
2621
|
+
// src/plan/store.ts
|
|
2622
|
+
import { open, mkdir as mkdir3, readdir, readFile as readFile3, realpath as realpath3, rename as rename2, rm as rm2 } from "node:fs/promises";
|
|
2623
|
+
import { basename as basename3, dirname as dirname3, join as join5, resolve as resolve3, sep } from "node:path";
|
|
2624
|
+
|
|
2625
|
+
// src/store.ts
|
|
2626
|
+
import { createHash } from "node:crypto";
|
|
2627
|
+
import { lstat, mkdir as mkdir2, readlink, realpath as realpath2, symlink, unlink } from "node:fs/promises";
|
|
2628
|
+
import { homedir } from "node:os";
|
|
2629
|
+
import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4, resolve as resolve2 } from "node:path";
|
|
2630
|
+
|
|
2631
|
+
// src/extensions/gitx.ts
|
|
2632
|
+
import { realpath } from "node:fs/promises";
|
|
2633
|
+
import { basename as basename2, isAbsolute, join as join3, resolve } from "node:path";
|
|
2634
|
+
async function gitToplevel(cwd) {
|
|
2635
|
+
const result = await run("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
|
|
2636
|
+
const top = result.stdout.trim();
|
|
2637
|
+
return result.code === 0 && top ? top : resolve(cwd);
|
|
2638
|
+
}
|
|
2639
|
+
async function inspectGitRepository(cwd) {
|
|
2640
|
+
const root = await gitToplevel(cwd);
|
|
2641
|
+
const remoteResult = await run("git", ["-C", root, "remote", "get-url", "origin"]);
|
|
2642
|
+
const remote = remoteResult.code === 0 ? remoteResult.stdout.trim() : "";
|
|
2643
|
+
const commonResult = await run("git", ["-C", root, "rev-parse", "--git-common-dir"]);
|
|
2644
|
+
const common = commonResult.stdout.trim();
|
|
2645
|
+
const commonPath = commonResult.code === 0 && common ? resolve(isAbsolute(common) ? common : join3(root, common)) : root;
|
|
2646
|
+
const commonDir = await canonicalPath(commonPath);
|
|
2647
|
+
return {
|
|
2648
|
+
root,
|
|
2649
|
+
commonDir,
|
|
2650
|
+
...remote ? { remote } : {},
|
|
2651
|
+
name: remote ? repositoryName(remote) : basename2(resolve(commonDir, "..")) || basename2(root),
|
|
2652
|
+
identity: remote ? `remote:${normalizeRemote(remote)}` : `git-common-dir:${commonDir}`
|
|
2653
|
+
};
|
|
2654
|
+
}
|
|
2655
|
+
function normalizeRemote(remote) {
|
|
2656
|
+
return remote.trim().replace(/\.git\/?$/i, "").replace(/\/+$/, "").toLowerCase();
|
|
2657
|
+
}
|
|
2658
|
+
function repositoryName(remote) {
|
|
2659
|
+
const normalized = remote.trim().replace(/\.git\/?$/i, "").replace(/\/+$/, "");
|
|
2660
|
+
return normalized.split(/[/\\:]/).filter(Boolean).at(-1) ?? "";
|
|
2661
|
+
}
|
|
2662
|
+
async function canonicalPath(path) {
|
|
2663
|
+
try {
|
|
2664
|
+
return await realpath(path);
|
|
2665
|
+
} catch {
|
|
2666
|
+
return resolve(path);
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2670
|
+
// src/store.ts
|
|
2671
|
+
var STORE_LINK = ".diffpi";
|
|
2672
|
+
var LEGACY_STORE_LINK = join4(".pi", "diffpi");
|
|
2673
|
+
function storeGlobalRoot(homeDir = homedir()) {
|
|
2674
|
+
return join4(homeDir, ".difflab", "diffpi", "projects");
|
|
2675
|
+
}
|
|
2676
|
+
async function ensureStore(cwd, homeDir = homedir()) {
|
|
2677
|
+
const repository = await inspectGitRepository(cwd);
|
|
2678
|
+
const root = repository.root;
|
|
2679
|
+
const slug = projectSlug(repository);
|
|
2680
|
+
const dest = join4(storeGlobalRoot(homeDir), slug);
|
|
2681
|
+
const link = join4(root, STORE_LINK);
|
|
2682
|
+
await mkdir2(dest, { recursive: true });
|
|
2683
|
+
try {
|
|
2684
|
+
await assertStoreLink(link, dest);
|
|
2685
|
+
} catch (error) {
|
|
2686
|
+
if (error.code !== "ENOENT")
|
|
2687
|
+
throw error;
|
|
2688
|
+
await symlink(dest, link);
|
|
2689
|
+
}
|
|
2690
|
+
await removeLegacyStoreLink(join4(root, LEGACY_STORE_LINK), dest);
|
|
2691
|
+
return { slug, root, dest, link, linked: true };
|
|
2692
|
+
}
|
|
2693
|
+
async function plansDir(cwd, homeDir = homedir()) {
|
|
2694
|
+
const store = await ensureStore(cwd, homeDir);
|
|
2695
|
+
const dir = join4(store.link, "plan");
|
|
2696
|
+
await mkdir2(dir, { recursive: true });
|
|
2697
|
+
return dir;
|
|
2698
|
+
}
|
|
2699
|
+
async function assertStoreLink(path, dest) {
|
|
2700
|
+
const entry = await lstat(path);
|
|
2701
|
+
if (!entry.isSymbolicLink())
|
|
2702
|
+
throw new Error(`${path} exists and is not a symlink.`);
|
|
2703
|
+
const target = await symlinkTarget(path);
|
|
2704
|
+
if (target !== await canonicalPath2(dest))
|
|
2705
|
+
throw new Error(`${path} points to ${target}, not ${dest}.`);
|
|
2706
|
+
}
|
|
2707
|
+
async function removeLegacyStoreLink(path, dest) {
|
|
2708
|
+
try {
|
|
2709
|
+
const entry = await lstat(path);
|
|
2710
|
+
if (!entry.isSymbolicLink())
|
|
2711
|
+
return;
|
|
2712
|
+
const target = await symlinkTarget(path);
|
|
2713
|
+
if (target === await canonicalPath2(dest))
|
|
2714
|
+
await unlink(path);
|
|
2715
|
+
} catch (error) {
|
|
2716
|
+
if (error.code !== "ENOENT")
|
|
2717
|
+
throw error;
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
async function symlinkTarget(path) {
|
|
2721
|
+
const target = await readlink(path);
|
|
2722
|
+
return canonicalPath2(isAbsolute2(target) ? target : resolve2(dirname2(path), target));
|
|
2723
|
+
}
|
|
2724
|
+
async function canonicalPath2(path) {
|
|
2725
|
+
try {
|
|
2726
|
+
return await realpath2(path);
|
|
2727
|
+
} catch {
|
|
2728
|
+
return resolve2(path);
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
function projectSlug(repository) {
|
|
2732
|
+
const readable = repository.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "unnamed";
|
|
2733
|
+
const digest = createHash("sha256").update(repository.identity).digest("hex").slice(0, 12);
|
|
2734
|
+
return `${readable}-${digest}`;
|
|
2735
|
+
}
|
|
2736
|
+
|
|
2737
|
+
// src/plan/store.ts
|
|
2738
|
+
async function resolvePlan(cwd, query, filters = {}, options = {}) {
|
|
2739
|
+
const root = await plansDir(cwd, options.homeDir);
|
|
2740
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
2741
|
+
const normalizedQuery = query ? normalizeQuery(query) : undefined;
|
|
2742
|
+
const records = [];
|
|
2743
|
+
for (const entry of entries) {
|
|
2744
|
+
if (!entry.isDirectory() || entry.name === ".tmp" || entry.name === ".lock")
|
|
2745
|
+
continue;
|
|
2746
|
+
if (normalizedQuery && entry.name !== normalizedQuery && stripDate(entry.name) !== normalizedQuery)
|
|
2747
|
+
continue;
|
|
2748
|
+
const dir = join5(root, entry.name);
|
|
2749
|
+
await assertContained(root, dir);
|
|
2750
|
+
try {
|
|
2751
|
+
const record = await readRecord(dir);
|
|
2752
|
+
if (filters.branch && record.document.branch !== filters.branch)
|
|
2753
|
+
continue;
|
|
2754
|
+
if (filters.statuses && !filters.statuses.includes(record.document.status))
|
|
2755
|
+
continue;
|
|
2756
|
+
records.push(record);
|
|
2757
|
+
} catch (error) {
|
|
2758
|
+
if (error.code !== "ENOENT")
|
|
2759
|
+
throw error;
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
records.sort((left, right) => left.id.localeCompare(right.id));
|
|
2763
|
+
return { candidates: records, record: records.length === 1 ? records[0] : undefined, ambiguous: records.length > 1 };
|
|
2764
|
+
}
|
|
2765
|
+
async function readRecord(dir) {
|
|
2766
|
+
const planPath = join5(dir, "PLAN.md");
|
|
2767
|
+
const logPath = join5(dir, "logs.txt");
|
|
2768
|
+
const source = await readFile3(planPath, "utf8");
|
|
2769
|
+
const document = parsePlanDocument(source, planPath);
|
|
2770
|
+
return { id: basename3(dir), dir, planPath, logPath, document, source };
|
|
2771
|
+
}
|
|
2772
|
+
async function assertContained(root, candidate) {
|
|
2773
|
+
const canonicalRoot = await realpath3(root);
|
|
2774
|
+
let canonicalCandidate;
|
|
2775
|
+
try {
|
|
2776
|
+
canonicalCandidate = await realpath3(candidate);
|
|
2777
|
+
} catch {
|
|
2778
|
+
canonicalCandidate = resolve3(candidate);
|
|
2779
|
+
}
|
|
2780
|
+
if (canonicalCandidate !== canonicalRoot && !canonicalCandidate.startsWith(`${canonicalRoot}${sep}`)) {
|
|
2781
|
+
throw new Error(`Plan path escapes the shared store: ${candidate}.`);
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
function normalizeQuery(value) {
|
|
2785
|
+
if (!value || value.includes("\x00") || value.includes("/") || value.includes("\\") || value.includes("..")) {
|
|
2786
|
+
throw new Error(`Invalid plan query: ${value}.`);
|
|
2787
|
+
}
|
|
2788
|
+
return value.toLowerCase();
|
|
2789
|
+
}
|
|
2790
|
+
function stripDate(value) {
|
|
2791
|
+
return value.replace(/^\d{6}-/, "");
|
|
2792
|
+
}
|
|
2793
|
+
// src/cli/plan.ts
|
|
2794
|
+
async function runPlanCli(args, io = process) {
|
|
2795
|
+
const program = new Command2().name("diffpi plan").description("Plan annotation commands").showHelpAfterError().exitOverride().configureOutput({
|
|
2796
|
+
writeOut: (message) => io.stdout.write(message),
|
|
2797
|
+
writeErr: (message) => io.stderr.write(message)
|
|
2798
|
+
});
|
|
2799
|
+
addAnnotationCommand(program, "annotate", io);
|
|
2800
|
+
addAnnotationCommand(program, "annotations", io);
|
|
2801
|
+
try {
|
|
2802
|
+
await program.parseAsync(["node", "diffpi plan", ...args]);
|
|
2803
|
+
return 0;
|
|
2804
|
+
} catch (error) {
|
|
2805
|
+
if (error instanceof CommanderError2)
|
|
2806
|
+
return error.exitCode;
|
|
2807
|
+
throw error;
|
|
2808
|
+
}
|
|
2809
|
+
}
|
|
2810
|
+
function addAnnotationCommand(program, verb, io) {
|
|
2811
|
+
program.command(`${verb} [plan]`).description(verb === "annotate" ? "Open a plan in tuicr for annotation" : "Print plan annotations as JSON").option("--cwd <path>", "Repository working directory", process.cwd()).action(async (query, options) => {
|
|
2812
|
+
const cwd = resolve4(options.cwd);
|
|
2813
|
+
const record = await resolveCliPlan(cwd, query);
|
|
2814
|
+
if (verb === "annotate") {
|
|
2815
|
+
const result = await annotatePlan(record);
|
|
2816
|
+
io.stdout.write(`Annotated ${record.id} in tuicr session ${result.sessionSlug}.\\n`);
|
|
2817
|
+
return;
|
|
2818
|
+
}
|
|
2819
|
+
io.stdout.write(`${JSON.stringify(await readPlanAnnotations(record, { includeApplied: true }), null, 2)}\\n`);
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
async function resolveCliPlan(cwd, query) {
|
|
2823
|
+
const branch = (await runChecked("git", ["-C", cwd, "branch", "--show-current"])).stdout.trim();
|
|
2824
|
+
const resolution = await resolvePlan(cwd, query, query ? {} : { branch, statuses: ["draft", "ready", "in_progress", "blocked"] });
|
|
2825
|
+
if (resolution.record)
|
|
2826
|
+
return resolution.record;
|
|
2827
|
+
if (resolution.ambiguous)
|
|
2828
|
+
throw new Error(`Plan selection is ambiguous: ${resolution.candidates.map((candidate) => candidate.id).join(", ")}.`);
|
|
2829
|
+
throw new Error(query ? `Plan "${query}" was not found.` : `No unfinished plan matches branch ${branch}.`);
|
|
2830
|
+
}
|
|
2831
|
+
|
|
2832
|
+
// src/cli.ts
|
|
2833
|
+
async function main(argv = process.argv.slice(2)) {
|
|
2834
|
+
const [command, ...args] = argv;
|
|
2835
|
+
if (command === "--help" || command === "-h" || !command) {
|
|
2836
|
+
process.stdout.write(`Usage: diffpi plan <annotate|annotations> [options]
|
|
2837
|
+
`);
|
|
2838
|
+
return 0;
|
|
2839
|
+
}
|
|
2840
|
+
if (command !== "plan")
|
|
2841
|
+
throw new Error(`Unknown command: ${command}.`);
|
|
2842
|
+
return runPlanCli(args);
|
|
2843
|
+
}
|
|
2844
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
|
2845
|
+
main().then((code) => {
|
|
2846
|
+
process.exitCode = code;
|
|
2847
|
+
}, (error) => {
|
|
2848
|
+
process.stderr.write(`diffpi: ${error instanceof Error ? error.message : String(error)}
|
|
2849
|
+
`);
|
|
2850
|
+
process.exitCode = 1;
|
|
2851
|
+
});
|
|
2852
|
+
}
|
|
2853
|
+
export {
|
|
2854
|
+
main
|
|
2855
|
+
};
|