@gitruck/cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT.md +137 -0
- package/LICENSE +21 -0
- package/README.md +148 -0
- package/assets/jianying-draft-path.png +0 -0
- package/dist/index.js +2589 -0
- package/package.json +47 -0
- package/skills/gtrk-oralcut/SKILL.md +51 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2589 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
function __accessProp(key) {
|
|
9
|
+
return this[key];
|
|
10
|
+
}
|
|
11
|
+
var __toESMCache_node;
|
|
12
|
+
var __toESMCache_esm;
|
|
13
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
14
|
+
var canCache = mod != null && typeof mod === "object";
|
|
15
|
+
if (canCache) {
|
|
16
|
+
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
|
|
17
|
+
var cached = cache.get(mod);
|
|
18
|
+
if (cached)
|
|
19
|
+
return cached;
|
|
20
|
+
}
|
|
21
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
22
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
23
|
+
for (let key of __getOwnPropNames(mod))
|
|
24
|
+
if (!__hasOwnProp.call(to, key))
|
|
25
|
+
__defProp(to, key, {
|
|
26
|
+
get: __accessProp.bind(mod, key),
|
|
27
|
+
enumerable: true
|
|
28
|
+
});
|
|
29
|
+
if (canCache)
|
|
30
|
+
cache.set(mod, to);
|
|
31
|
+
return to;
|
|
32
|
+
};
|
|
33
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
34
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
35
|
+
|
|
36
|
+
// node_modules/commander/lib/error.js
|
|
37
|
+
var require_error = __commonJS((exports) => {
|
|
38
|
+
class CommanderError extends Error {
|
|
39
|
+
constructor(exitCode, code, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
Error.captureStackTrace(this, this.constructor);
|
|
42
|
+
this.name = this.constructor.name;
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.exitCode = exitCode;
|
|
45
|
+
this.nestedError = undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
class InvalidArgumentError extends CommanderError {
|
|
50
|
+
constructor(message) {
|
|
51
|
+
super(1, "commander.invalidArgument", message);
|
|
52
|
+
Error.captureStackTrace(this, this.constructor);
|
|
53
|
+
this.name = this.constructor.name;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
exports.CommanderError = CommanderError;
|
|
57
|
+
exports.InvalidArgumentError = InvalidArgumentError;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// node_modules/commander/lib/argument.js
|
|
61
|
+
var require_argument = __commonJS((exports) => {
|
|
62
|
+
var { InvalidArgumentError } = require_error();
|
|
63
|
+
|
|
64
|
+
class Argument {
|
|
65
|
+
constructor(name, description) {
|
|
66
|
+
this.description = description || "";
|
|
67
|
+
this.variadic = false;
|
|
68
|
+
this.parseArg = undefined;
|
|
69
|
+
this.defaultValue = undefined;
|
|
70
|
+
this.defaultValueDescription = undefined;
|
|
71
|
+
this.argChoices = undefined;
|
|
72
|
+
switch (name[0]) {
|
|
73
|
+
case "<":
|
|
74
|
+
this.required = true;
|
|
75
|
+
this._name = name.slice(1, -1);
|
|
76
|
+
break;
|
|
77
|
+
case "[":
|
|
78
|
+
this.required = false;
|
|
79
|
+
this._name = name.slice(1, -1);
|
|
80
|
+
break;
|
|
81
|
+
default:
|
|
82
|
+
this.required = true;
|
|
83
|
+
this._name = name;
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
if (this._name.length > 3 && this._name.slice(-3) === "...") {
|
|
87
|
+
this.variadic = true;
|
|
88
|
+
this._name = this._name.slice(0, -3);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
name() {
|
|
92
|
+
return this._name;
|
|
93
|
+
}
|
|
94
|
+
_concatValue(value, previous) {
|
|
95
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
96
|
+
return [value];
|
|
97
|
+
}
|
|
98
|
+
return previous.concat(value);
|
|
99
|
+
}
|
|
100
|
+
default(value, description) {
|
|
101
|
+
this.defaultValue = value;
|
|
102
|
+
this.defaultValueDescription = description;
|
|
103
|
+
return this;
|
|
104
|
+
}
|
|
105
|
+
argParser(fn) {
|
|
106
|
+
this.parseArg = fn;
|
|
107
|
+
return this;
|
|
108
|
+
}
|
|
109
|
+
choices(values) {
|
|
110
|
+
this.argChoices = values.slice();
|
|
111
|
+
this.parseArg = (arg, previous) => {
|
|
112
|
+
if (!this.argChoices.includes(arg)) {
|
|
113
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
114
|
+
}
|
|
115
|
+
if (this.variadic) {
|
|
116
|
+
return this._concatValue(arg, previous);
|
|
117
|
+
}
|
|
118
|
+
return arg;
|
|
119
|
+
};
|
|
120
|
+
return this;
|
|
121
|
+
}
|
|
122
|
+
argRequired() {
|
|
123
|
+
this.required = true;
|
|
124
|
+
return this;
|
|
125
|
+
}
|
|
126
|
+
argOptional() {
|
|
127
|
+
this.required = false;
|
|
128
|
+
return this;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function humanReadableArgName(arg) {
|
|
132
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
133
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
134
|
+
}
|
|
135
|
+
exports.Argument = Argument;
|
|
136
|
+
exports.humanReadableArgName = humanReadableArgName;
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
// node_modules/commander/lib/help.js
|
|
140
|
+
var require_help = __commonJS((exports) => {
|
|
141
|
+
var { humanReadableArgName } = require_argument();
|
|
142
|
+
|
|
143
|
+
class Help {
|
|
144
|
+
constructor() {
|
|
145
|
+
this.helpWidth = undefined;
|
|
146
|
+
this.sortSubcommands = false;
|
|
147
|
+
this.sortOptions = false;
|
|
148
|
+
this.showGlobalOptions = false;
|
|
149
|
+
}
|
|
150
|
+
visibleCommands(cmd) {
|
|
151
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
152
|
+
const helpCommand = cmd._getHelpCommand();
|
|
153
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
154
|
+
visibleCommands.push(helpCommand);
|
|
155
|
+
}
|
|
156
|
+
if (this.sortSubcommands) {
|
|
157
|
+
visibleCommands.sort((a, b) => {
|
|
158
|
+
return a.name().localeCompare(b.name());
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return visibleCommands;
|
|
162
|
+
}
|
|
163
|
+
compareOptions(a, b) {
|
|
164
|
+
const getSortKey = (option) => {
|
|
165
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
166
|
+
};
|
|
167
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
168
|
+
}
|
|
169
|
+
visibleOptions(cmd) {
|
|
170
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
171
|
+
const helpOption = cmd._getHelpOption();
|
|
172
|
+
if (helpOption && !helpOption.hidden) {
|
|
173
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
174
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
175
|
+
if (!removeShort && !removeLong) {
|
|
176
|
+
visibleOptions.push(helpOption);
|
|
177
|
+
} else if (helpOption.long && !removeLong) {
|
|
178
|
+
visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
179
|
+
} else if (helpOption.short && !removeShort) {
|
|
180
|
+
visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (this.sortOptions) {
|
|
184
|
+
visibleOptions.sort(this.compareOptions);
|
|
185
|
+
}
|
|
186
|
+
return visibleOptions;
|
|
187
|
+
}
|
|
188
|
+
visibleGlobalOptions(cmd) {
|
|
189
|
+
if (!this.showGlobalOptions)
|
|
190
|
+
return [];
|
|
191
|
+
const globalOptions = [];
|
|
192
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
193
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
194
|
+
globalOptions.push(...visibleOptions);
|
|
195
|
+
}
|
|
196
|
+
if (this.sortOptions) {
|
|
197
|
+
globalOptions.sort(this.compareOptions);
|
|
198
|
+
}
|
|
199
|
+
return globalOptions;
|
|
200
|
+
}
|
|
201
|
+
visibleArguments(cmd) {
|
|
202
|
+
if (cmd._argsDescription) {
|
|
203
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
204
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
208
|
+
return cmd.registeredArguments;
|
|
209
|
+
}
|
|
210
|
+
return [];
|
|
211
|
+
}
|
|
212
|
+
subcommandTerm(cmd) {
|
|
213
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
214
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
215
|
+
}
|
|
216
|
+
optionTerm(option) {
|
|
217
|
+
return option.flags;
|
|
218
|
+
}
|
|
219
|
+
argumentTerm(argument) {
|
|
220
|
+
return argument.name();
|
|
221
|
+
}
|
|
222
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
223
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
224
|
+
return Math.max(max, helper.subcommandTerm(command).length);
|
|
225
|
+
}, 0);
|
|
226
|
+
}
|
|
227
|
+
longestOptionTermLength(cmd, helper) {
|
|
228
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
229
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
230
|
+
}, 0);
|
|
231
|
+
}
|
|
232
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
233
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
234
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
235
|
+
}, 0);
|
|
236
|
+
}
|
|
237
|
+
longestArgumentTermLength(cmd, helper) {
|
|
238
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
239
|
+
return Math.max(max, helper.argumentTerm(argument).length);
|
|
240
|
+
}, 0);
|
|
241
|
+
}
|
|
242
|
+
commandUsage(cmd) {
|
|
243
|
+
let cmdName = cmd._name;
|
|
244
|
+
if (cmd._aliases[0]) {
|
|
245
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
246
|
+
}
|
|
247
|
+
let ancestorCmdNames = "";
|
|
248
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
249
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
250
|
+
}
|
|
251
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
252
|
+
}
|
|
253
|
+
commandDescription(cmd) {
|
|
254
|
+
return cmd.description();
|
|
255
|
+
}
|
|
256
|
+
subcommandDescription(cmd) {
|
|
257
|
+
return cmd.summary() || cmd.description();
|
|
258
|
+
}
|
|
259
|
+
optionDescription(option) {
|
|
260
|
+
const extraInfo = [];
|
|
261
|
+
if (option.argChoices) {
|
|
262
|
+
extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
263
|
+
}
|
|
264
|
+
if (option.defaultValue !== undefined) {
|
|
265
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
266
|
+
if (showDefault) {
|
|
267
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (option.presetArg !== undefined && option.optional) {
|
|
271
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
272
|
+
}
|
|
273
|
+
if (option.envVar !== undefined) {
|
|
274
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
275
|
+
}
|
|
276
|
+
if (extraInfo.length > 0) {
|
|
277
|
+
return `${option.description} (${extraInfo.join(", ")})`;
|
|
278
|
+
}
|
|
279
|
+
return option.description;
|
|
280
|
+
}
|
|
281
|
+
argumentDescription(argument) {
|
|
282
|
+
const extraInfo = [];
|
|
283
|
+
if (argument.argChoices) {
|
|
284
|
+
extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
285
|
+
}
|
|
286
|
+
if (argument.defaultValue !== undefined) {
|
|
287
|
+
extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
288
|
+
}
|
|
289
|
+
if (extraInfo.length > 0) {
|
|
290
|
+
const extraDescripton = `(${extraInfo.join(", ")})`;
|
|
291
|
+
if (argument.description) {
|
|
292
|
+
return `${argument.description} ${extraDescripton}`;
|
|
293
|
+
}
|
|
294
|
+
return extraDescripton;
|
|
295
|
+
}
|
|
296
|
+
return argument.description;
|
|
297
|
+
}
|
|
298
|
+
formatHelp(cmd, helper) {
|
|
299
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
300
|
+
const helpWidth = helper.helpWidth || 80;
|
|
301
|
+
const itemIndentWidth = 2;
|
|
302
|
+
const itemSeparatorWidth = 2;
|
|
303
|
+
function formatItem(term, description) {
|
|
304
|
+
if (description) {
|
|
305
|
+
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
|
|
306
|
+
return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
|
|
307
|
+
}
|
|
308
|
+
return term;
|
|
309
|
+
}
|
|
310
|
+
function formatList(textArray) {
|
|
311
|
+
return textArray.join(`
|
|
312
|
+
`).replace(/^/gm, " ".repeat(itemIndentWidth));
|
|
313
|
+
}
|
|
314
|
+
let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
|
|
315
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
316
|
+
if (commandDescription.length > 0) {
|
|
317
|
+
output = output.concat([
|
|
318
|
+
helper.wrap(commandDescription, helpWidth, 0),
|
|
319
|
+
""
|
|
320
|
+
]);
|
|
321
|
+
}
|
|
322
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
323
|
+
return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
|
|
324
|
+
});
|
|
325
|
+
if (argumentList.length > 0) {
|
|
326
|
+
output = output.concat(["Arguments:", formatList(argumentList), ""]);
|
|
327
|
+
}
|
|
328
|
+
const optionList = helper.visibleOptions(cmd).map((option) => {
|
|
329
|
+
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
|
|
330
|
+
});
|
|
331
|
+
if (optionList.length > 0) {
|
|
332
|
+
output = output.concat(["Options:", formatList(optionList), ""]);
|
|
333
|
+
}
|
|
334
|
+
if (this.showGlobalOptions) {
|
|
335
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
336
|
+
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
|
|
337
|
+
});
|
|
338
|
+
if (globalOptionList.length > 0) {
|
|
339
|
+
output = output.concat([
|
|
340
|
+
"Global Options:",
|
|
341
|
+
formatList(globalOptionList),
|
|
342
|
+
""
|
|
343
|
+
]);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
|
|
347
|
+
return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
|
|
348
|
+
});
|
|
349
|
+
if (commandList.length > 0) {
|
|
350
|
+
output = output.concat(["Commands:", formatList(commandList), ""]);
|
|
351
|
+
}
|
|
352
|
+
return output.join(`
|
|
353
|
+
`);
|
|
354
|
+
}
|
|
355
|
+
padWidth(cmd, helper) {
|
|
356
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
357
|
+
}
|
|
358
|
+
wrap(str, width, indent, minColumnWidth = 40) {
|
|
359
|
+
const indents = " \\f\\t\\v - \uFEFF";
|
|
360
|
+
const manualIndent = new RegExp(`[\\n][${indents}]+`);
|
|
361
|
+
if (str.match(manualIndent))
|
|
362
|
+
return str;
|
|
363
|
+
const columnWidth = width - indent;
|
|
364
|
+
if (columnWidth < minColumnWidth)
|
|
365
|
+
return str;
|
|
366
|
+
const leadingStr = str.slice(0, indent);
|
|
367
|
+
const columnText = str.slice(indent).replace(`\r
|
|
368
|
+
`, `
|
|
369
|
+
`);
|
|
370
|
+
const indentString = " ".repeat(indent);
|
|
371
|
+
const zeroWidthSpace = "";
|
|
372
|
+
const breaks = `\\s${zeroWidthSpace}`;
|
|
373
|
+
const regex = new RegExp(`
|
|
374
|
+
|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
|
|
375
|
+
const lines = columnText.match(regex) || [];
|
|
376
|
+
return leadingStr + lines.map((line, i) => {
|
|
377
|
+
if (line === `
|
|
378
|
+
`)
|
|
379
|
+
return "";
|
|
380
|
+
return (i > 0 ? indentString : "") + line.trimEnd();
|
|
381
|
+
}).join(`
|
|
382
|
+
`);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
exports.Help = Help;
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
// node_modules/commander/lib/option.js
|
|
389
|
+
var require_option = __commonJS((exports) => {
|
|
390
|
+
var { InvalidArgumentError } = require_error();
|
|
391
|
+
|
|
392
|
+
class Option {
|
|
393
|
+
constructor(flags, description) {
|
|
394
|
+
this.flags = flags;
|
|
395
|
+
this.description = description || "";
|
|
396
|
+
this.required = flags.includes("<");
|
|
397
|
+
this.optional = flags.includes("[");
|
|
398
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
399
|
+
this.mandatory = false;
|
|
400
|
+
const optionFlags = splitOptionFlags(flags);
|
|
401
|
+
this.short = optionFlags.shortFlag;
|
|
402
|
+
this.long = optionFlags.longFlag;
|
|
403
|
+
this.negate = false;
|
|
404
|
+
if (this.long) {
|
|
405
|
+
this.negate = this.long.startsWith("--no-");
|
|
406
|
+
}
|
|
407
|
+
this.defaultValue = undefined;
|
|
408
|
+
this.defaultValueDescription = undefined;
|
|
409
|
+
this.presetArg = undefined;
|
|
410
|
+
this.envVar = undefined;
|
|
411
|
+
this.parseArg = undefined;
|
|
412
|
+
this.hidden = false;
|
|
413
|
+
this.argChoices = undefined;
|
|
414
|
+
this.conflictsWith = [];
|
|
415
|
+
this.implied = undefined;
|
|
416
|
+
}
|
|
417
|
+
default(value, description) {
|
|
418
|
+
this.defaultValue = value;
|
|
419
|
+
this.defaultValueDescription = description;
|
|
420
|
+
return this;
|
|
421
|
+
}
|
|
422
|
+
preset(arg) {
|
|
423
|
+
this.presetArg = arg;
|
|
424
|
+
return this;
|
|
425
|
+
}
|
|
426
|
+
conflicts(names) {
|
|
427
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
428
|
+
return this;
|
|
429
|
+
}
|
|
430
|
+
implies(impliedOptionValues) {
|
|
431
|
+
let newImplied = impliedOptionValues;
|
|
432
|
+
if (typeof impliedOptionValues === "string") {
|
|
433
|
+
newImplied = { [impliedOptionValues]: true };
|
|
434
|
+
}
|
|
435
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
436
|
+
return this;
|
|
437
|
+
}
|
|
438
|
+
env(name) {
|
|
439
|
+
this.envVar = name;
|
|
440
|
+
return this;
|
|
441
|
+
}
|
|
442
|
+
argParser(fn) {
|
|
443
|
+
this.parseArg = fn;
|
|
444
|
+
return this;
|
|
445
|
+
}
|
|
446
|
+
makeOptionMandatory(mandatory = true) {
|
|
447
|
+
this.mandatory = !!mandatory;
|
|
448
|
+
return this;
|
|
449
|
+
}
|
|
450
|
+
hideHelp(hide = true) {
|
|
451
|
+
this.hidden = !!hide;
|
|
452
|
+
return this;
|
|
453
|
+
}
|
|
454
|
+
_concatValue(value, previous) {
|
|
455
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
456
|
+
return [value];
|
|
457
|
+
}
|
|
458
|
+
return previous.concat(value);
|
|
459
|
+
}
|
|
460
|
+
choices(values) {
|
|
461
|
+
this.argChoices = values.slice();
|
|
462
|
+
this.parseArg = (arg, previous) => {
|
|
463
|
+
if (!this.argChoices.includes(arg)) {
|
|
464
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
465
|
+
}
|
|
466
|
+
if (this.variadic) {
|
|
467
|
+
return this._concatValue(arg, previous);
|
|
468
|
+
}
|
|
469
|
+
return arg;
|
|
470
|
+
};
|
|
471
|
+
return this;
|
|
472
|
+
}
|
|
473
|
+
name() {
|
|
474
|
+
if (this.long) {
|
|
475
|
+
return this.long.replace(/^--/, "");
|
|
476
|
+
}
|
|
477
|
+
return this.short.replace(/^-/, "");
|
|
478
|
+
}
|
|
479
|
+
attributeName() {
|
|
480
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
481
|
+
}
|
|
482
|
+
is(arg) {
|
|
483
|
+
return this.short === arg || this.long === arg;
|
|
484
|
+
}
|
|
485
|
+
isBoolean() {
|
|
486
|
+
return !this.required && !this.optional && !this.negate;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
class DualOptions {
|
|
491
|
+
constructor(options) {
|
|
492
|
+
this.positiveOptions = new Map;
|
|
493
|
+
this.negativeOptions = new Map;
|
|
494
|
+
this.dualOptions = new Set;
|
|
495
|
+
options.forEach((option) => {
|
|
496
|
+
if (option.negate) {
|
|
497
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
498
|
+
} else {
|
|
499
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
this.negativeOptions.forEach((value, key) => {
|
|
503
|
+
if (this.positiveOptions.has(key)) {
|
|
504
|
+
this.dualOptions.add(key);
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
valueFromOption(value, option) {
|
|
509
|
+
const optionKey = option.attributeName();
|
|
510
|
+
if (!this.dualOptions.has(optionKey))
|
|
511
|
+
return true;
|
|
512
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
513
|
+
const negativeValue = preset !== undefined ? preset : false;
|
|
514
|
+
return option.negate === (negativeValue === value);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
function camelcase(str) {
|
|
518
|
+
return str.split("-").reduce((str2, word) => {
|
|
519
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
function splitOptionFlags(flags) {
|
|
523
|
+
let shortFlag;
|
|
524
|
+
let longFlag;
|
|
525
|
+
const flagParts = flags.split(/[ |,]+/);
|
|
526
|
+
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
|
|
527
|
+
shortFlag = flagParts.shift();
|
|
528
|
+
longFlag = flagParts.shift();
|
|
529
|
+
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
|
|
530
|
+
shortFlag = longFlag;
|
|
531
|
+
longFlag = undefined;
|
|
532
|
+
}
|
|
533
|
+
return { shortFlag, longFlag };
|
|
534
|
+
}
|
|
535
|
+
exports.Option = Option;
|
|
536
|
+
exports.DualOptions = DualOptions;
|
|
537
|
+
});
|
|
538
|
+
|
|
539
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
540
|
+
var require_suggestSimilar = __commonJS((exports) => {
|
|
541
|
+
var maxDistance = 3;
|
|
542
|
+
function editDistance(a, b) {
|
|
543
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
544
|
+
return Math.max(a.length, b.length);
|
|
545
|
+
const d = [];
|
|
546
|
+
for (let i = 0;i <= a.length; i++) {
|
|
547
|
+
d[i] = [i];
|
|
548
|
+
}
|
|
549
|
+
for (let j = 0;j <= b.length; j++) {
|
|
550
|
+
d[0][j] = j;
|
|
551
|
+
}
|
|
552
|
+
for (let j = 1;j <= b.length; j++) {
|
|
553
|
+
for (let i = 1;i <= a.length; i++) {
|
|
554
|
+
let cost = 1;
|
|
555
|
+
if (a[i - 1] === b[j - 1]) {
|
|
556
|
+
cost = 0;
|
|
557
|
+
} else {
|
|
558
|
+
cost = 1;
|
|
559
|
+
}
|
|
560
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
561
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
562
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return d[a.length][b.length];
|
|
567
|
+
}
|
|
568
|
+
function suggestSimilar(word, candidates) {
|
|
569
|
+
if (!candidates || candidates.length === 0)
|
|
570
|
+
return "";
|
|
571
|
+
candidates = Array.from(new Set(candidates));
|
|
572
|
+
const searchingOptions = word.startsWith("--");
|
|
573
|
+
if (searchingOptions) {
|
|
574
|
+
word = word.slice(2);
|
|
575
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
576
|
+
}
|
|
577
|
+
let similar = [];
|
|
578
|
+
let bestDistance = maxDistance;
|
|
579
|
+
const minSimilarity = 0.4;
|
|
580
|
+
candidates.forEach((candidate) => {
|
|
581
|
+
if (candidate.length <= 1)
|
|
582
|
+
return;
|
|
583
|
+
const distance = editDistance(word, candidate);
|
|
584
|
+
const length = Math.max(word.length, candidate.length);
|
|
585
|
+
const similarity = (length - distance) / length;
|
|
586
|
+
if (similarity > minSimilarity) {
|
|
587
|
+
if (distance < bestDistance) {
|
|
588
|
+
bestDistance = distance;
|
|
589
|
+
similar = [candidate];
|
|
590
|
+
} else if (distance === bestDistance) {
|
|
591
|
+
similar.push(candidate);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
596
|
+
if (searchingOptions) {
|
|
597
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
598
|
+
}
|
|
599
|
+
if (similar.length > 1) {
|
|
600
|
+
return `
|
|
601
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
602
|
+
}
|
|
603
|
+
if (similar.length === 1) {
|
|
604
|
+
return `
|
|
605
|
+
(Did you mean ${similar[0]}?)`;
|
|
606
|
+
}
|
|
607
|
+
return "";
|
|
608
|
+
}
|
|
609
|
+
exports.suggestSimilar = suggestSimilar;
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
// node_modules/commander/lib/command.js
|
|
613
|
+
var require_command = __commonJS((exports) => {
|
|
614
|
+
var EventEmitter = __require("node:events").EventEmitter;
|
|
615
|
+
var childProcess = __require("node:child_process");
|
|
616
|
+
var path = __require("node:path");
|
|
617
|
+
var fs = __require("node:fs");
|
|
618
|
+
var process2 = __require("node:process");
|
|
619
|
+
var { Argument, humanReadableArgName } = require_argument();
|
|
620
|
+
var { CommanderError } = require_error();
|
|
621
|
+
var { Help } = require_help();
|
|
622
|
+
var { Option, DualOptions } = require_option();
|
|
623
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
624
|
+
|
|
625
|
+
class Command extends EventEmitter {
|
|
626
|
+
constructor(name) {
|
|
627
|
+
super();
|
|
628
|
+
this.commands = [];
|
|
629
|
+
this.options = [];
|
|
630
|
+
this.parent = null;
|
|
631
|
+
this._allowUnknownOption = false;
|
|
632
|
+
this._allowExcessArguments = true;
|
|
633
|
+
this.registeredArguments = [];
|
|
634
|
+
this._args = this.registeredArguments;
|
|
635
|
+
this.args = [];
|
|
636
|
+
this.rawArgs = [];
|
|
637
|
+
this.processedArgs = [];
|
|
638
|
+
this._scriptPath = null;
|
|
639
|
+
this._name = name || "";
|
|
640
|
+
this._optionValues = {};
|
|
641
|
+
this._optionValueSources = {};
|
|
642
|
+
this._storeOptionsAsProperties = false;
|
|
643
|
+
this._actionHandler = null;
|
|
644
|
+
this._executableHandler = false;
|
|
645
|
+
this._executableFile = null;
|
|
646
|
+
this._executableDir = null;
|
|
647
|
+
this._defaultCommandName = null;
|
|
648
|
+
this._exitCallback = null;
|
|
649
|
+
this._aliases = [];
|
|
650
|
+
this._combineFlagAndOptionalValue = true;
|
|
651
|
+
this._description = "";
|
|
652
|
+
this._summary = "";
|
|
653
|
+
this._argsDescription = undefined;
|
|
654
|
+
this._enablePositionalOptions = false;
|
|
655
|
+
this._passThroughOptions = false;
|
|
656
|
+
this._lifeCycleHooks = {};
|
|
657
|
+
this._showHelpAfterError = false;
|
|
658
|
+
this._showSuggestionAfterError = true;
|
|
659
|
+
this._outputConfiguration = {
|
|
660
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
661
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
662
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
|
|
663
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
|
|
664
|
+
outputError: (str, write) => write(str)
|
|
665
|
+
};
|
|
666
|
+
this._hidden = false;
|
|
667
|
+
this._helpOption = undefined;
|
|
668
|
+
this._addImplicitHelpCommand = undefined;
|
|
669
|
+
this._helpCommand = undefined;
|
|
670
|
+
this._helpConfiguration = {};
|
|
671
|
+
}
|
|
672
|
+
copyInheritedSettings(sourceCommand) {
|
|
673
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
674
|
+
this._helpOption = sourceCommand._helpOption;
|
|
675
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
676
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
677
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
678
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
679
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
680
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
681
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
682
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
683
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
684
|
+
return this;
|
|
685
|
+
}
|
|
686
|
+
_getCommandAndAncestors() {
|
|
687
|
+
const result = [];
|
|
688
|
+
for (let command = this;command; command = command.parent) {
|
|
689
|
+
result.push(command);
|
|
690
|
+
}
|
|
691
|
+
return result;
|
|
692
|
+
}
|
|
693
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
694
|
+
let desc = actionOptsOrExecDesc;
|
|
695
|
+
let opts = execOpts;
|
|
696
|
+
if (typeof desc === "object" && desc !== null) {
|
|
697
|
+
opts = desc;
|
|
698
|
+
desc = null;
|
|
699
|
+
}
|
|
700
|
+
opts = opts || {};
|
|
701
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
702
|
+
const cmd = this.createCommand(name);
|
|
703
|
+
if (desc) {
|
|
704
|
+
cmd.description(desc);
|
|
705
|
+
cmd._executableHandler = true;
|
|
706
|
+
}
|
|
707
|
+
if (opts.isDefault)
|
|
708
|
+
this._defaultCommandName = cmd._name;
|
|
709
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
710
|
+
cmd._executableFile = opts.executableFile || null;
|
|
711
|
+
if (args)
|
|
712
|
+
cmd.arguments(args);
|
|
713
|
+
this._registerCommand(cmd);
|
|
714
|
+
cmd.parent = this;
|
|
715
|
+
cmd.copyInheritedSettings(this);
|
|
716
|
+
if (desc)
|
|
717
|
+
return this;
|
|
718
|
+
return cmd;
|
|
719
|
+
}
|
|
720
|
+
createCommand(name) {
|
|
721
|
+
return new Command(name);
|
|
722
|
+
}
|
|
723
|
+
createHelp() {
|
|
724
|
+
return Object.assign(new Help, this.configureHelp());
|
|
725
|
+
}
|
|
726
|
+
configureHelp(configuration) {
|
|
727
|
+
if (configuration === undefined)
|
|
728
|
+
return this._helpConfiguration;
|
|
729
|
+
this._helpConfiguration = configuration;
|
|
730
|
+
return this;
|
|
731
|
+
}
|
|
732
|
+
configureOutput(configuration) {
|
|
733
|
+
if (configuration === undefined)
|
|
734
|
+
return this._outputConfiguration;
|
|
735
|
+
Object.assign(this._outputConfiguration, configuration);
|
|
736
|
+
return this;
|
|
737
|
+
}
|
|
738
|
+
showHelpAfterError(displayHelp = true) {
|
|
739
|
+
if (typeof displayHelp !== "string")
|
|
740
|
+
displayHelp = !!displayHelp;
|
|
741
|
+
this._showHelpAfterError = displayHelp;
|
|
742
|
+
return this;
|
|
743
|
+
}
|
|
744
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
745
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
746
|
+
return this;
|
|
747
|
+
}
|
|
748
|
+
addCommand(cmd, opts) {
|
|
749
|
+
if (!cmd._name) {
|
|
750
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
751
|
+
- specify the name in Command constructor or using .name()`);
|
|
752
|
+
}
|
|
753
|
+
opts = opts || {};
|
|
754
|
+
if (opts.isDefault)
|
|
755
|
+
this._defaultCommandName = cmd._name;
|
|
756
|
+
if (opts.noHelp || opts.hidden)
|
|
757
|
+
cmd._hidden = true;
|
|
758
|
+
this._registerCommand(cmd);
|
|
759
|
+
cmd.parent = this;
|
|
760
|
+
cmd._checkForBrokenPassThrough();
|
|
761
|
+
return this;
|
|
762
|
+
}
|
|
763
|
+
createArgument(name, description) {
|
|
764
|
+
return new Argument(name, description);
|
|
765
|
+
}
|
|
766
|
+
argument(name, description, fn, defaultValue) {
|
|
767
|
+
const argument = this.createArgument(name, description);
|
|
768
|
+
if (typeof fn === "function") {
|
|
769
|
+
argument.default(defaultValue).argParser(fn);
|
|
770
|
+
} else {
|
|
771
|
+
argument.default(fn);
|
|
772
|
+
}
|
|
773
|
+
this.addArgument(argument);
|
|
774
|
+
return this;
|
|
775
|
+
}
|
|
776
|
+
arguments(names) {
|
|
777
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
778
|
+
this.argument(detail);
|
|
779
|
+
});
|
|
780
|
+
return this;
|
|
781
|
+
}
|
|
782
|
+
addArgument(argument) {
|
|
783
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
784
|
+
if (previousArgument && previousArgument.variadic) {
|
|
785
|
+
throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
786
|
+
}
|
|
787
|
+
if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
|
|
788
|
+
throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
789
|
+
}
|
|
790
|
+
this.registeredArguments.push(argument);
|
|
791
|
+
return this;
|
|
792
|
+
}
|
|
793
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
794
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
795
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
796
|
+
return this;
|
|
797
|
+
}
|
|
798
|
+
enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
799
|
+
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
|
|
800
|
+
const helpDescription = description ?? "display help for command";
|
|
801
|
+
const helpCommand = this.createCommand(helpName);
|
|
802
|
+
helpCommand.helpOption(false);
|
|
803
|
+
if (helpArgs)
|
|
804
|
+
helpCommand.arguments(helpArgs);
|
|
805
|
+
if (helpDescription)
|
|
806
|
+
helpCommand.description(helpDescription);
|
|
807
|
+
this._addImplicitHelpCommand = true;
|
|
808
|
+
this._helpCommand = helpCommand;
|
|
809
|
+
return this;
|
|
810
|
+
}
|
|
811
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
812
|
+
if (typeof helpCommand !== "object") {
|
|
813
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
814
|
+
return this;
|
|
815
|
+
}
|
|
816
|
+
this._addImplicitHelpCommand = true;
|
|
817
|
+
this._helpCommand = helpCommand;
|
|
818
|
+
return this;
|
|
819
|
+
}
|
|
820
|
+
_getHelpCommand() {
|
|
821
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
822
|
+
if (hasImplicitHelpCommand) {
|
|
823
|
+
if (this._helpCommand === undefined) {
|
|
824
|
+
this.helpCommand(undefined, undefined);
|
|
825
|
+
}
|
|
826
|
+
return this._helpCommand;
|
|
827
|
+
}
|
|
828
|
+
return null;
|
|
829
|
+
}
|
|
830
|
+
hook(event, listener) {
|
|
831
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
832
|
+
if (!allowedValues.includes(event)) {
|
|
833
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
834
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
835
|
+
}
|
|
836
|
+
if (this._lifeCycleHooks[event]) {
|
|
837
|
+
this._lifeCycleHooks[event].push(listener);
|
|
838
|
+
} else {
|
|
839
|
+
this._lifeCycleHooks[event] = [listener];
|
|
840
|
+
}
|
|
841
|
+
return this;
|
|
842
|
+
}
|
|
843
|
+
exitOverride(fn) {
|
|
844
|
+
if (fn) {
|
|
845
|
+
this._exitCallback = fn;
|
|
846
|
+
} else {
|
|
847
|
+
this._exitCallback = (err) => {
|
|
848
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
849
|
+
throw err;
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
return this;
|
|
854
|
+
}
|
|
855
|
+
_exit(exitCode, code, message) {
|
|
856
|
+
if (this._exitCallback) {
|
|
857
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
858
|
+
}
|
|
859
|
+
process2.exit(exitCode);
|
|
860
|
+
}
|
|
861
|
+
action(fn) {
|
|
862
|
+
const listener = (args) => {
|
|
863
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
864
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
865
|
+
if (this._storeOptionsAsProperties) {
|
|
866
|
+
actionArgs[expectedArgsCount] = this;
|
|
867
|
+
} else {
|
|
868
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
869
|
+
}
|
|
870
|
+
actionArgs.push(this);
|
|
871
|
+
return fn.apply(this, actionArgs);
|
|
872
|
+
};
|
|
873
|
+
this._actionHandler = listener;
|
|
874
|
+
return this;
|
|
875
|
+
}
|
|
876
|
+
createOption(flags, description) {
|
|
877
|
+
return new Option(flags, description);
|
|
878
|
+
}
|
|
879
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
880
|
+
try {
|
|
881
|
+
return target.parseArg(value, previous);
|
|
882
|
+
} catch (err) {
|
|
883
|
+
if (err.code === "commander.invalidArgument") {
|
|
884
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
885
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
886
|
+
}
|
|
887
|
+
throw err;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
_registerOption(option) {
|
|
891
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
892
|
+
if (matchingOption) {
|
|
893
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
894
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
895
|
+
- already used by option '${matchingOption.flags}'`);
|
|
896
|
+
}
|
|
897
|
+
this.options.push(option);
|
|
898
|
+
}
|
|
899
|
+
_registerCommand(command) {
|
|
900
|
+
const knownBy = (cmd) => {
|
|
901
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
902
|
+
};
|
|
903
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
904
|
+
if (alreadyUsed) {
|
|
905
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
906
|
+
const newCmd = knownBy(command).join("|");
|
|
907
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
908
|
+
}
|
|
909
|
+
this.commands.push(command);
|
|
910
|
+
}
|
|
911
|
+
addOption(option) {
|
|
912
|
+
this._registerOption(option);
|
|
913
|
+
const oname = option.name();
|
|
914
|
+
const name = option.attributeName();
|
|
915
|
+
if (option.negate) {
|
|
916
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
917
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
918
|
+
this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
|
|
919
|
+
}
|
|
920
|
+
} else if (option.defaultValue !== undefined) {
|
|
921
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
922
|
+
}
|
|
923
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
924
|
+
if (val == null && option.presetArg !== undefined) {
|
|
925
|
+
val = option.presetArg;
|
|
926
|
+
}
|
|
927
|
+
const oldValue = this.getOptionValue(name);
|
|
928
|
+
if (val !== null && option.parseArg) {
|
|
929
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
930
|
+
} else if (val !== null && option.variadic) {
|
|
931
|
+
val = option._concatValue(val, oldValue);
|
|
932
|
+
}
|
|
933
|
+
if (val == null) {
|
|
934
|
+
if (option.negate) {
|
|
935
|
+
val = false;
|
|
936
|
+
} else if (option.isBoolean() || option.optional) {
|
|
937
|
+
val = true;
|
|
938
|
+
} else {
|
|
939
|
+
val = "";
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
943
|
+
};
|
|
944
|
+
this.on("option:" + oname, (val) => {
|
|
945
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
946
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
947
|
+
});
|
|
948
|
+
if (option.envVar) {
|
|
949
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
950
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
951
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
return this;
|
|
955
|
+
}
|
|
956
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
957
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
958
|
+
throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
959
|
+
}
|
|
960
|
+
const option = this.createOption(flags, description);
|
|
961
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
962
|
+
if (typeof fn === "function") {
|
|
963
|
+
option.default(defaultValue).argParser(fn);
|
|
964
|
+
} else if (fn instanceof RegExp) {
|
|
965
|
+
const regex = fn;
|
|
966
|
+
fn = (val, def) => {
|
|
967
|
+
const m = regex.exec(val);
|
|
968
|
+
return m ? m[0] : def;
|
|
969
|
+
};
|
|
970
|
+
option.default(defaultValue).argParser(fn);
|
|
971
|
+
} else {
|
|
972
|
+
option.default(fn);
|
|
973
|
+
}
|
|
974
|
+
return this.addOption(option);
|
|
975
|
+
}
|
|
976
|
+
option(flags, description, parseArg, defaultValue) {
|
|
977
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
978
|
+
}
|
|
979
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
980
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
981
|
+
}
|
|
982
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
983
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
984
|
+
return this;
|
|
985
|
+
}
|
|
986
|
+
allowUnknownOption(allowUnknown = true) {
|
|
987
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
988
|
+
return this;
|
|
989
|
+
}
|
|
990
|
+
allowExcessArguments(allowExcess = true) {
|
|
991
|
+
this._allowExcessArguments = !!allowExcess;
|
|
992
|
+
return this;
|
|
993
|
+
}
|
|
994
|
+
enablePositionalOptions(positional = true) {
|
|
995
|
+
this._enablePositionalOptions = !!positional;
|
|
996
|
+
return this;
|
|
997
|
+
}
|
|
998
|
+
passThroughOptions(passThrough = true) {
|
|
999
|
+
this._passThroughOptions = !!passThrough;
|
|
1000
|
+
this._checkForBrokenPassThrough();
|
|
1001
|
+
return this;
|
|
1002
|
+
}
|
|
1003
|
+
_checkForBrokenPassThrough() {
|
|
1004
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1005
|
+
throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1009
|
+
if (this.options.length) {
|
|
1010
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1011
|
+
}
|
|
1012
|
+
if (Object.keys(this._optionValues).length) {
|
|
1013
|
+
throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1014
|
+
}
|
|
1015
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1016
|
+
return this;
|
|
1017
|
+
}
|
|
1018
|
+
getOptionValue(key) {
|
|
1019
|
+
if (this._storeOptionsAsProperties) {
|
|
1020
|
+
return this[key];
|
|
1021
|
+
}
|
|
1022
|
+
return this._optionValues[key];
|
|
1023
|
+
}
|
|
1024
|
+
setOptionValue(key, value) {
|
|
1025
|
+
return this.setOptionValueWithSource(key, value, undefined);
|
|
1026
|
+
}
|
|
1027
|
+
setOptionValueWithSource(key, value, source) {
|
|
1028
|
+
if (this._storeOptionsAsProperties) {
|
|
1029
|
+
this[key] = value;
|
|
1030
|
+
} else {
|
|
1031
|
+
this._optionValues[key] = value;
|
|
1032
|
+
}
|
|
1033
|
+
this._optionValueSources[key] = source;
|
|
1034
|
+
return this;
|
|
1035
|
+
}
|
|
1036
|
+
getOptionValueSource(key) {
|
|
1037
|
+
return this._optionValueSources[key];
|
|
1038
|
+
}
|
|
1039
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1040
|
+
let source;
|
|
1041
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1042
|
+
if (cmd.getOptionValueSource(key) !== undefined) {
|
|
1043
|
+
source = cmd.getOptionValueSource(key);
|
|
1044
|
+
}
|
|
1045
|
+
});
|
|
1046
|
+
return source;
|
|
1047
|
+
}
|
|
1048
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1049
|
+
if (argv !== undefined && !Array.isArray(argv)) {
|
|
1050
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1051
|
+
}
|
|
1052
|
+
parseOptions = parseOptions || {};
|
|
1053
|
+
if (argv === undefined && parseOptions.from === undefined) {
|
|
1054
|
+
if (process2.versions?.electron) {
|
|
1055
|
+
parseOptions.from = "electron";
|
|
1056
|
+
}
|
|
1057
|
+
const execArgv = process2.execArgv ?? [];
|
|
1058
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
1059
|
+
parseOptions.from = "eval";
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
if (argv === undefined) {
|
|
1063
|
+
argv = process2.argv;
|
|
1064
|
+
}
|
|
1065
|
+
this.rawArgs = argv.slice();
|
|
1066
|
+
let userArgs;
|
|
1067
|
+
switch (parseOptions.from) {
|
|
1068
|
+
case undefined:
|
|
1069
|
+
case "node":
|
|
1070
|
+
this._scriptPath = argv[1];
|
|
1071
|
+
userArgs = argv.slice(2);
|
|
1072
|
+
break;
|
|
1073
|
+
case "electron":
|
|
1074
|
+
if (process2.defaultApp) {
|
|
1075
|
+
this._scriptPath = argv[1];
|
|
1076
|
+
userArgs = argv.slice(2);
|
|
1077
|
+
} else {
|
|
1078
|
+
userArgs = argv.slice(1);
|
|
1079
|
+
}
|
|
1080
|
+
break;
|
|
1081
|
+
case "user":
|
|
1082
|
+
userArgs = argv.slice(0);
|
|
1083
|
+
break;
|
|
1084
|
+
case "eval":
|
|
1085
|
+
userArgs = argv.slice(1);
|
|
1086
|
+
break;
|
|
1087
|
+
default:
|
|
1088
|
+
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1089
|
+
}
|
|
1090
|
+
if (!this._name && this._scriptPath)
|
|
1091
|
+
this.nameFromFilename(this._scriptPath);
|
|
1092
|
+
this._name = this._name || "program";
|
|
1093
|
+
return userArgs;
|
|
1094
|
+
}
|
|
1095
|
+
parse(argv, parseOptions) {
|
|
1096
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1097
|
+
this._parseCommand([], userArgs);
|
|
1098
|
+
return this;
|
|
1099
|
+
}
|
|
1100
|
+
async parseAsync(argv, parseOptions) {
|
|
1101
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1102
|
+
await this._parseCommand([], userArgs);
|
|
1103
|
+
return this;
|
|
1104
|
+
}
|
|
1105
|
+
_executeSubCommand(subcommand, args) {
|
|
1106
|
+
args = args.slice();
|
|
1107
|
+
let launchWithNode = false;
|
|
1108
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1109
|
+
function findFile(baseDir, baseName) {
|
|
1110
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1111
|
+
if (fs.existsSync(localBin))
|
|
1112
|
+
return localBin;
|
|
1113
|
+
if (sourceExt.includes(path.extname(baseName)))
|
|
1114
|
+
return;
|
|
1115
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1116
|
+
if (foundExt)
|
|
1117
|
+
return `${localBin}${foundExt}`;
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
this._checkForMissingMandatoryOptions();
|
|
1121
|
+
this._checkForConflictingOptions();
|
|
1122
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1123
|
+
let executableDir = this._executableDir || "";
|
|
1124
|
+
if (this._scriptPath) {
|
|
1125
|
+
let resolvedScriptPath;
|
|
1126
|
+
try {
|
|
1127
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1128
|
+
} catch (err) {
|
|
1129
|
+
resolvedScriptPath = this._scriptPath;
|
|
1130
|
+
}
|
|
1131
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1132
|
+
}
|
|
1133
|
+
if (executableDir) {
|
|
1134
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1135
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1136
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1137
|
+
if (legacyName !== this._name) {
|
|
1138
|
+
localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
executableFile = localFile || executableFile;
|
|
1142
|
+
}
|
|
1143
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1144
|
+
let proc;
|
|
1145
|
+
if (process2.platform !== "win32") {
|
|
1146
|
+
if (launchWithNode) {
|
|
1147
|
+
args.unshift(executableFile);
|
|
1148
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1149
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
1150
|
+
} else {
|
|
1151
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1152
|
+
}
|
|
1153
|
+
} else {
|
|
1154
|
+
args.unshift(executableFile);
|
|
1155
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1156
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
1157
|
+
}
|
|
1158
|
+
if (!proc.killed) {
|
|
1159
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1160
|
+
signals.forEach((signal) => {
|
|
1161
|
+
process2.on(signal, () => {
|
|
1162
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1163
|
+
proc.kill(signal);
|
|
1164
|
+
}
|
|
1165
|
+
});
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
const exitCallback = this._exitCallback;
|
|
1169
|
+
proc.on("close", (code) => {
|
|
1170
|
+
code = code ?? 1;
|
|
1171
|
+
if (!exitCallback) {
|
|
1172
|
+
process2.exit(code);
|
|
1173
|
+
} else {
|
|
1174
|
+
exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1175
|
+
}
|
|
1176
|
+
});
|
|
1177
|
+
proc.on("error", (err) => {
|
|
1178
|
+
if (err.code === "ENOENT") {
|
|
1179
|
+
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";
|
|
1180
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1181
|
+
- if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1182
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1183
|
+
- ${executableDirMessage}`;
|
|
1184
|
+
throw new Error(executableMissing);
|
|
1185
|
+
} else if (err.code === "EACCES") {
|
|
1186
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
1187
|
+
}
|
|
1188
|
+
if (!exitCallback) {
|
|
1189
|
+
process2.exit(1);
|
|
1190
|
+
} else {
|
|
1191
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1192
|
+
wrappedError.nestedError = err;
|
|
1193
|
+
exitCallback(wrappedError);
|
|
1194
|
+
}
|
|
1195
|
+
});
|
|
1196
|
+
this.runningCommand = proc;
|
|
1197
|
+
}
|
|
1198
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1199
|
+
const subCommand = this._findCommand(commandName);
|
|
1200
|
+
if (!subCommand)
|
|
1201
|
+
this.help({ error: true });
|
|
1202
|
+
let promiseChain;
|
|
1203
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1204
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1205
|
+
if (subCommand._executableHandler) {
|
|
1206
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1207
|
+
} else {
|
|
1208
|
+
return subCommand._parseCommand(operands, unknown);
|
|
1209
|
+
}
|
|
1210
|
+
});
|
|
1211
|
+
return promiseChain;
|
|
1212
|
+
}
|
|
1213
|
+
_dispatchHelpCommand(subcommandName) {
|
|
1214
|
+
if (!subcommandName) {
|
|
1215
|
+
this.help();
|
|
1216
|
+
}
|
|
1217
|
+
const subCommand = this._findCommand(subcommandName);
|
|
1218
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
1219
|
+
subCommand.help();
|
|
1220
|
+
}
|
|
1221
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
1222
|
+
}
|
|
1223
|
+
_checkNumberOfArguments() {
|
|
1224
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
1225
|
+
if (arg.required && this.args[i] == null) {
|
|
1226
|
+
this.missingArgument(arg.name());
|
|
1227
|
+
}
|
|
1228
|
+
});
|
|
1229
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
1233
|
+
this._excessArguments(this.args);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
_processArguments() {
|
|
1237
|
+
const myParseArg = (argument, value, previous) => {
|
|
1238
|
+
let parsedValue = value;
|
|
1239
|
+
if (value !== null && argument.parseArg) {
|
|
1240
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
1241
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
1242
|
+
}
|
|
1243
|
+
return parsedValue;
|
|
1244
|
+
};
|
|
1245
|
+
this._checkNumberOfArguments();
|
|
1246
|
+
const processedArgs = [];
|
|
1247
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
1248
|
+
let value = declaredArg.defaultValue;
|
|
1249
|
+
if (declaredArg.variadic) {
|
|
1250
|
+
if (index < this.args.length) {
|
|
1251
|
+
value = this.args.slice(index);
|
|
1252
|
+
if (declaredArg.parseArg) {
|
|
1253
|
+
value = value.reduce((processed, v) => {
|
|
1254
|
+
return myParseArg(declaredArg, v, processed);
|
|
1255
|
+
}, declaredArg.defaultValue);
|
|
1256
|
+
}
|
|
1257
|
+
} else if (value === undefined) {
|
|
1258
|
+
value = [];
|
|
1259
|
+
}
|
|
1260
|
+
} else if (index < this.args.length) {
|
|
1261
|
+
value = this.args[index];
|
|
1262
|
+
if (declaredArg.parseArg) {
|
|
1263
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
processedArgs[index] = value;
|
|
1267
|
+
});
|
|
1268
|
+
this.processedArgs = processedArgs;
|
|
1269
|
+
}
|
|
1270
|
+
_chainOrCall(promise, fn) {
|
|
1271
|
+
if (promise && promise.then && typeof promise.then === "function") {
|
|
1272
|
+
return promise.then(() => fn());
|
|
1273
|
+
}
|
|
1274
|
+
return fn();
|
|
1275
|
+
}
|
|
1276
|
+
_chainOrCallHooks(promise, event) {
|
|
1277
|
+
let result = promise;
|
|
1278
|
+
const hooks = [];
|
|
1279
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
|
|
1280
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
1281
|
+
hooks.push({ hookedCommand, callback });
|
|
1282
|
+
});
|
|
1283
|
+
});
|
|
1284
|
+
if (event === "postAction") {
|
|
1285
|
+
hooks.reverse();
|
|
1286
|
+
}
|
|
1287
|
+
hooks.forEach((hookDetail) => {
|
|
1288
|
+
result = this._chainOrCall(result, () => {
|
|
1289
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
1290
|
+
});
|
|
1291
|
+
});
|
|
1292
|
+
return result;
|
|
1293
|
+
}
|
|
1294
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
1295
|
+
let result = promise;
|
|
1296
|
+
if (this._lifeCycleHooks[event] !== undefined) {
|
|
1297
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
1298
|
+
result = this._chainOrCall(result, () => {
|
|
1299
|
+
return hook(this, subCommand);
|
|
1300
|
+
});
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
return result;
|
|
1304
|
+
}
|
|
1305
|
+
_parseCommand(operands, unknown) {
|
|
1306
|
+
const parsed = this.parseOptions(unknown);
|
|
1307
|
+
this._parseOptionsEnv();
|
|
1308
|
+
this._parseOptionsImplied();
|
|
1309
|
+
operands = operands.concat(parsed.operands);
|
|
1310
|
+
unknown = parsed.unknown;
|
|
1311
|
+
this.args = operands.concat(unknown);
|
|
1312
|
+
if (operands && this._findCommand(operands[0])) {
|
|
1313
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
1314
|
+
}
|
|
1315
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
1316
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
1317
|
+
}
|
|
1318
|
+
if (this._defaultCommandName) {
|
|
1319
|
+
this._outputHelpIfRequested(unknown);
|
|
1320
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
1321
|
+
}
|
|
1322
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
1323
|
+
this.help({ error: true });
|
|
1324
|
+
}
|
|
1325
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
1326
|
+
this._checkForMissingMandatoryOptions();
|
|
1327
|
+
this._checkForConflictingOptions();
|
|
1328
|
+
const checkForUnknownOptions = () => {
|
|
1329
|
+
if (parsed.unknown.length > 0) {
|
|
1330
|
+
this.unknownOption(parsed.unknown[0]);
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
const commandEvent = `command:${this.name()}`;
|
|
1334
|
+
if (this._actionHandler) {
|
|
1335
|
+
checkForUnknownOptions();
|
|
1336
|
+
this._processArguments();
|
|
1337
|
+
let promiseChain;
|
|
1338
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
1339
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
1340
|
+
if (this.parent) {
|
|
1341
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1342
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
1346
|
+
return promiseChain;
|
|
1347
|
+
}
|
|
1348
|
+
if (this.parent && this.parent.listenerCount(commandEvent)) {
|
|
1349
|
+
checkForUnknownOptions();
|
|
1350
|
+
this._processArguments();
|
|
1351
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1352
|
+
} else if (operands.length) {
|
|
1353
|
+
if (this._findCommand("*")) {
|
|
1354
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
1355
|
+
}
|
|
1356
|
+
if (this.listenerCount("command:*")) {
|
|
1357
|
+
this.emit("command:*", operands, unknown);
|
|
1358
|
+
} else if (this.commands.length) {
|
|
1359
|
+
this.unknownCommand();
|
|
1360
|
+
} else {
|
|
1361
|
+
checkForUnknownOptions();
|
|
1362
|
+
this._processArguments();
|
|
1363
|
+
}
|
|
1364
|
+
} else if (this.commands.length) {
|
|
1365
|
+
checkForUnknownOptions();
|
|
1366
|
+
this.help({ error: true });
|
|
1367
|
+
} else {
|
|
1368
|
+
checkForUnknownOptions();
|
|
1369
|
+
this._processArguments();
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
_findCommand(name) {
|
|
1373
|
+
if (!name)
|
|
1374
|
+
return;
|
|
1375
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
1376
|
+
}
|
|
1377
|
+
_findOption(arg) {
|
|
1378
|
+
return this.options.find((option) => option.is(arg));
|
|
1379
|
+
}
|
|
1380
|
+
_checkForMissingMandatoryOptions() {
|
|
1381
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1382
|
+
cmd.options.forEach((anOption) => {
|
|
1383
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
|
|
1384
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
1385
|
+
}
|
|
1386
|
+
});
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
_checkForConflictingLocalOptions() {
|
|
1390
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
1391
|
+
const optionKey = option.attributeName();
|
|
1392
|
+
if (this.getOptionValue(optionKey) === undefined) {
|
|
1393
|
+
return false;
|
|
1394
|
+
}
|
|
1395
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
1396
|
+
});
|
|
1397
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
|
|
1398
|
+
optionsWithConflicting.forEach((option) => {
|
|
1399
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
1400
|
+
if (conflictingAndDefined) {
|
|
1401
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
1402
|
+
}
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
_checkForConflictingOptions() {
|
|
1406
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1407
|
+
cmd._checkForConflictingLocalOptions();
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
parseOptions(argv) {
|
|
1411
|
+
const operands = [];
|
|
1412
|
+
const unknown = [];
|
|
1413
|
+
let dest = operands;
|
|
1414
|
+
const args = argv.slice();
|
|
1415
|
+
function maybeOption(arg) {
|
|
1416
|
+
return arg.length > 1 && arg[0] === "-";
|
|
1417
|
+
}
|
|
1418
|
+
let activeVariadicOption = null;
|
|
1419
|
+
while (args.length) {
|
|
1420
|
+
const arg = args.shift();
|
|
1421
|
+
if (arg === "--") {
|
|
1422
|
+
if (dest === unknown)
|
|
1423
|
+
dest.push(arg);
|
|
1424
|
+
dest.push(...args);
|
|
1425
|
+
break;
|
|
1426
|
+
}
|
|
1427
|
+
if (activeVariadicOption && !maybeOption(arg)) {
|
|
1428
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
activeVariadicOption = null;
|
|
1432
|
+
if (maybeOption(arg)) {
|
|
1433
|
+
const option = this._findOption(arg);
|
|
1434
|
+
if (option) {
|
|
1435
|
+
if (option.required) {
|
|
1436
|
+
const value = args.shift();
|
|
1437
|
+
if (value === undefined)
|
|
1438
|
+
this.optionMissingArgument(option);
|
|
1439
|
+
this.emit(`option:${option.name()}`, value);
|
|
1440
|
+
} else if (option.optional) {
|
|
1441
|
+
let value = null;
|
|
1442
|
+
if (args.length > 0 && !maybeOption(args[0])) {
|
|
1443
|
+
value = args.shift();
|
|
1444
|
+
}
|
|
1445
|
+
this.emit(`option:${option.name()}`, value);
|
|
1446
|
+
} else {
|
|
1447
|
+
this.emit(`option:${option.name()}`);
|
|
1448
|
+
}
|
|
1449
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
1450
|
+
continue;
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
1454
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
1455
|
+
if (option) {
|
|
1456
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
1457
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
1458
|
+
} else {
|
|
1459
|
+
this.emit(`option:${option.name()}`);
|
|
1460
|
+
args.unshift(`-${arg.slice(2)}`);
|
|
1461
|
+
}
|
|
1462
|
+
continue;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
1466
|
+
const index = arg.indexOf("=");
|
|
1467
|
+
const option = this._findOption(arg.slice(0, index));
|
|
1468
|
+
if (option && (option.required || option.optional)) {
|
|
1469
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
1470
|
+
continue;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
if (maybeOption(arg)) {
|
|
1474
|
+
dest = unknown;
|
|
1475
|
+
}
|
|
1476
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
1477
|
+
if (this._findCommand(arg)) {
|
|
1478
|
+
operands.push(arg);
|
|
1479
|
+
if (args.length > 0)
|
|
1480
|
+
unknown.push(...args);
|
|
1481
|
+
break;
|
|
1482
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
1483
|
+
operands.push(arg);
|
|
1484
|
+
if (args.length > 0)
|
|
1485
|
+
operands.push(...args);
|
|
1486
|
+
break;
|
|
1487
|
+
} else if (this._defaultCommandName) {
|
|
1488
|
+
unknown.push(arg);
|
|
1489
|
+
if (args.length > 0)
|
|
1490
|
+
unknown.push(...args);
|
|
1491
|
+
break;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
if (this._passThroughOptions) {
|
|
1495
|
+
dest.push(arg);
|
|
1496
|
+
if (args.length > 0)
|
|
1497
|
+
dest.push(...args);
|
|
1498
|
+
break;
|
|
1499
|
+
}
|
|
1500
|
+
dest.push(arg);
|
|
1501
|
+
}
|
|
1502
|
+
return { operands, unknown };
|
|
1503
|
+
}
|
|
1504
|
+
opts() {
|
|
1505
|
+
if (this._storeOptionsAsProperties) {
|
|
1506
|
+
const result = {};
|
|
1507
|
+
const len = this.options.length;
|
|
1508
|
+
for (let i = 0;i < len; i++) {
|
|
1509
|
+
const key = this.options[i].attributeName();
|
|
1510
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
1511
|
+
}
|
|
1512
|
+
return result;
|
|
1513
|
+
}
|
|
1514
|
+
return this._optionValues;
|
|
1515
|
+
}
|
|
1516
|
+
optsWithGlobals() {
|
|
1517
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
1518
|
+
}
|
|
1519
|
+
error(message, errorOptions) {
|
|
1520
|
+
this._outputConfiguration.outputError(`${message}
|
|
1521
|
+
`, this._outputConfiguration.writeErr);
|
|
1522
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
1523
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
1524
|
+
`);
|
|
1525
|
+
} else if (this._showHelpAfterError) {
|
|
1526
|
+
this._outputConfiguration.writeErr(`
|
|
1527
|
+
`);
|
|
1528
|
+
this.outputHelp({ error: true });
|
|
1529
|
+
}
|
|
1530
|
+
const config = errorOptions || {};
|
|
1531
|
+
const exitCode = config.exitCode || 1;
|
|
1532
|
+
const code = config.code || "commander.error";
|
|
1533
|
+
this._exit(exitCode, code, message);
|
|
1534
|
+
}
|
|
1535
|
+
_parseOptionsEnv() {
|
|
1536
|
+
this.options.forEach((option) => {
|
|
1537
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
1538
|
+
const optionKey = option.attributeName();
|
|
1539
|
+
if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
|
|
1540
|
+
if (option.required || option.optional) {
|
|
1541
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
1542
|
+
} else {
|
|
1543
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
_parseOptionsImplied() {
|
|
1550
|
+
const dualHelper = new DualOptions(this.options);
|
|
1551
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
1552
|
+
return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
1553
|
+
};
|
|
1554
|
+
this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
1555
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
1556
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
1557
|
+
});
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
missingArgument(name) {
|
|
1561
|
+
const message = `error: missing required argument '${name}'`;
|
|
1562
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
1563
|
+
}
|
|
1564
|
+
optionMissingArgument(option) {
|
|
1565
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
1566
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
1567
|
+
}
|
|
1568
|
+
missingMandatoryOptionValue(option) {
|
|
1569
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
1570
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
1571
|
+
}
|
|
1572
|
+
_conflictingOption(option, conflictingOption) {
|
|
1573
|
+
const findBestOptionFromValue = (option2) => {
|
|
1574
|
+
const optionKey = option2.attributeName();
|
|
1575
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
1576
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
1577
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
1578
|
+
if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
|
|
1579
|
+
return negativeOption;
|
|
1580
|
+
}
|
|
1581
|
+
return positiveOption || option2;
|
|
1582
|
+
};
|
|
1583
|
+
const getErrorMessage = (option2) => {
|
|
1584
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
1585
|
+
const optionKey = bestOption.attributeName();
|
|
1586
|
+
const source = this.getOptionValueSource(optionKey);
|
|
1587
|
+
if (source === "env") {
|
|
1588
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
1589
|
+
}
|
|
1590
|
+
return `option '${bestOption.flags}'`;
|
|
1591
|
+
};
|
|
1592
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
1593
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
1594
|
+
}
|
|
1595
|
+
unknownOption(flag) {
|
|
1596
|
+
if (this._allowUnknownOption)
|
|
1597
|
+
return;
|
|
1598
|
+
let suggestion = "";
|
|
1599
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
1600
|
+
let candidateFlags = [];
|
|
1601
|
+
let command = this;
|
|
1602
|
+
do {
|
|
1603
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
1604
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
1605
|
+
command = command.parent;
|
|
1606
|
+
} while (command && !command._enablePositionalOptions);
|
|
1607
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
1608
|
+
}
|
|
1609
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
1610
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
1611
|
+
}
|
|
1612
|
+
_excessArguments(receivedArgs) {
|
|
1613
|
+
if (this._allowExcessArguments)
|
|
1614
|
+
return;
|
|
1615
|
+
const expected = this.registeredArguments.length;
|
|
1616
|
+
const s = expected === 1 ? "" : "s";
|
|
1617
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
1618
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
1619
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
1620
|
+
}
|
|
1621
|
+
unknownCommand() {
|
|
1622
|
+
const unknownName = this.args[0];
|
|
1623
|
+
let suggestion = "";
|
|
1624
|
+
if (this._showSuggestionAfterError) {
|
|
1625
|
+
const candidateNames = [];
|
|
1626
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
1627
|
+
candidateNames.push(command.name());
|
|
1628
|
+
if (command.alias())
|
|
1629
|
+
candidateNames.push(command.alias());
|
|
1630
|
+
});
|
|
1631
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
1632
|
+
}
|
|
1633
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
1634
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
1635
|
+
}
|
|
1636
|
+
version(str, flags, description) {
|
|
1637
|
+
if (str === undefined)
|
|
1638
|
+
return this._version;
|
|
1639
|
+
this._version = str;
|
|
1640
|
+
flags = flags || "-V, --version";
|
|
1641
|
+
description = description || "output the version number";
|
|
1642
|
+
const versionOption = this.createOption(flags, description);
|
|
1643
|
+
this._versionOptionName = versionOption.attributeName();
|
|
1644
|
+
this._registerOption(versionOption);
|
|
1645
|
+
this.on("option:" + versionOption.name(), () => {
|
|
1646
|
+
this._outputConfiguration.writeOut(`${str}
|
|
1647
|
+
`);
|
|
1648
|
+
this._exit(0, "commander.version", str);
|
|
1649
|
+
});
|
|
1650
|
+
return this;
|
|
1651
|
+
}
|
|
1652
|
+
description(str, argsDescription) {
|
|
1653
|
+
if (str === undefined && argsDescription === undefined)
|
|
1654
|
+
return this._description;
|
|
1655
|
+
this._description = str;
|
|
1656
|
+
if (argsDescription) {
|
|
1657
|
+
this._argsDescription = argsDescription;
|
|
1658
|
+
}
|
|
1659
|
+
return this;
|
|
1660
|
+
}
|
|
1661
|
+
summary(str) {
|
|
1662
|
+
if (str === undefined)
|
|
1663
|
+
return this._summary;
|
|
1664
|
+
this._summary = str;
|
|
1665
|
+
return this;
|
|
1666
|
+
}
|
|
1667
|
+
alias(alias) {
|
|
1668
|
+
if (alias === undefined)
|
|
1669
|
+
return this._aliases[0];
|
|
1670
|
+
let command = this;
|
|
1671
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
1672
|
+
command = this.commands[this.commands.length - 1];
|
|
1673
|
+
}
|
|
1674
|
+
if (alias === command._name)
|
|
1675
|
+
throw new Error("Command alias can't be the same as its name");
|
|
1676
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
1677
|
+
if (matchingCommand) {
|
|
1678
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
1679
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
1680
|
+
}
|
|
1681
|
+
command._aliases.push(alias);
|
|
1682
|
+
return this;
|
|
1683
|
+
}
|
|
1684
|
+
aliases(aliases) {
|
|
1685
|
+
if (aliases === undefined)
|
|
1686
|
+
return this._aliases;
|
|
1687
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
1688
|
+
return this;
|
|
1689
|
+
}
|
|
1690
|
+
usage(str) {
|
|
1691
|
+
if (str === undefined) {
|
|
1692
|
+
if (this._usage)
|
|
1693
|
+
return this._usage;
|
|
1694
|
+
const args = this.registeredArguments.map((arg) => {
|
|
1695
|
+
return humanReadableArgName(arg);
|
|
1696
|
+
});
|
|
1697
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
1698
|
+
}
|
|
1699
|
+
this._usage = str;
|
|
1700
|
+
return this;
|
|
1701
|
+
}
|
|
1702
|
+
name(str) {
|
|
1703
|
+
if (str === undefined)
|
|
1704
|
+
return this._name;
|
|
1705
|
+
this._name = str;
|
|
1706
|
+
return this;
|
|
1707
|
+
}
|
|
1708
|
+
nameFromFilename(filename) {
|
|
1709
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
1710
|
+
return this;
|
|
1711
|
+
}
|
|
1712
|
+
executableDir(path2) {
|
|
1713
|
+
if (path2 === undefined)
|
|
1714
|
+
return this._executableDir;
|
|
1715
|
+
this._executableDir = path2;
|
|
1716
|
+
return this;
|
|
1717
|
+
}
|
|
1718
|
+
helpInformation(contextOptions) {
|
|
1719
|
+
const helper = this.createHelp();
|
|
1720
|
+
if (helper.helpWidth === undefined) {
|
|
1721
|
+
helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
|
|
1722
|
+
}
|
|
1723
|
+
return helper.formatHelp(this, helper);
|
|
1724
|
+
}
|
|
1725
|
+
_getHelpContext(contextOptions) {
|
|
1726
|
+
contextOptions = contextOptions || {};
|
|
1727
|
+
const context = { error: !!contextOptions.error };
|
|
1728
|
+
let write;
|
|
1729
|
+
if (context.error) {
|
|
1730
|
+
write = (arg) => this._outputConfiguration.writeErr(arg);
|
|
1731
|
+
} else {
|
|
1732
|
+
write = (arg) => this._outputConfiguration.writeOut(arg);
|
|
1733
|
+
}
|
|
1734
|
+
context.write = contextOptions.write || write;
|
|
1735
|
+
context.command = this;
|
|
1736
|
+
return context;
|
|
1737
|
+
}
|
|
1738
|
+
outputHelp(contextOptions) {
|
|
1739
|
+
let deprecatedCallback;
|
|
1740
|
+
if (typeof contextOptions === "function") {
|
|
1741
|
+
deprecatedCallback = contextOptions;
|
|
1742
|
+
contextOptions = undefined;
|
|
1743
|
+
}
|
|
1744
|
+
const context = this._getHelpContext(contextOptions);
|
|
1745
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
|
|
1746
|
+
this.emit("beforeHelp", context);
|
|
1747
|
+
let helpInformation = this.helpInformation(context);
|
|
1748
|
+
if (deprecatedCallback) {
|
|
1749
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
1750
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
1751
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
context.write(helpInformation);
|
|
1755
|
+
if (this._getHelpOption()?.long) {
|
|
1756
|
+
this.emit(this._getHelpOption().long);
|
|
1757
|
+
}
|
|
1758
|
+
this.emit("afterHelp", context);
|
|
1759
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
|
|
1760
|
+
}
|
|
1761
|
+
helpOption(flags, description) {
|
|
1762
|
+
if (typeof flags === "boolean") {
|
|
1763
|
+
if (flags) {
|
|
1764
|
+
this._helpOption = this._helpOption ?? undefined;
|
|
1765
|
+
} else {
|
|
1766
|
+
this._helpOption = null;
|
|
1767
|
+
}
|
|
1768
|
+
return this;
|
|
1769
|
+
}
|
|
1770
|
+
flags = flags ?? "-h, --help";
|
|
1771
|
+
description = description ?? "display help for command";
|
|
1772
|
+
this._helpOption = this.createOption(flags, description);
|
|
1773
|
+
return this;
|
|
1774
|
+
}
|
|
1775
|
+
_getHelpOption() {
|
|
1776
|
+
if (this._helpOption === undefined) {
|
|
1777
|
+
this.helpOption(undefined, undefined);
|
|
1778
|
+
}
|
|
1779
|
+
return this._helpOption;
|
|
1780
|
+
}
|
|
1781
|
+
addHelpOption(option) {
|
|
1782
|
+
this._helpOption = option;
|
|
1783
|
+
return this;
|
|
1784
|
+
}
|
|
1785
|
+
help(contextOptions) {
|
|
1786
|
+
this.outputHelp(contextOptions);
|
|
1787
|
+
let exitCode = process2.exitCode || 0;
|
|
1788
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
1789
|
+
exitCode = 1;
|
|
1790
|
+
}
|
|
1791
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
1792
|
+
}
|
|
1793
|
+
addHelpText(position, text) {
|
|
1794
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
1795
|
+
if (!allowedValues.includes(position)) {
|
|
1796
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
1797
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1798
|
+
}
|
|
1799
|
+
const helpEvent = `${position}Help`;
|
|
1800
|
+
this.on(helpEvent, (context) => {
|
|
1801
|
+
let helpStr;
|
|
1802
|
+
if (typeof text === "function") {
|
|
1803
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
1804
|
+
} else {
|
|
1805
|
+
helpStr = text;
|
|
1806
|
+
}
|
|
1807
|
+
if (helpStr) {
|
|
1808
|
+
context.write(`${helpStr}
|
|
1809
|
+
`);
|
|
1810
|
+
}
|
|
1811
|
+
});
|
|
1812
|
+
return this;
|
|
1813
|
+
}
|
|
1814
|
+
_outputHelpIfRequested(args) {
|
|
1815
|
+
const helpOption = this._getHelpOption();
|
|
1816
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
1817
|
+
if (helpRequested) {
|
|
1818
|
+
this.outputHelp();
|
|
1819
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
function incrementNodeInspectorPort(args) {
|
|
1824
|
+
return args.map((arg) => {
|
|
1825
|
+
if (!arg.startsWith("--inspect")) {
|
|
1826
|
+
return arg;
|
|
1827
|
+
}
|
|
1828
|
+
let debugOption;
|
|
1829
|
+
let debugHost = "127.0.0.1";
|
|
1830
|
+
let debugPort = "9229";
|
|
1831
|
+
let match;
|
|
1832
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
1833
|
+
debugOption = match[1];
|
|
1834
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
1835
|
+
debugOption = match[1];
|
|
1836
|
+
if (/^\d+$/.test(match[3])) {
|
|
1837
|
+
debugPort = match[3];
|
|
1838
|
+
} else {
|
|
1839
|
+
debugHost = match[3];
|
|
1840
|
+
}
|
|
1841
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
1842
|
+
debugOption = match[1];
|
|
1843
|
+
debugHost = match[3];
|
|
1844
|
+
debugPort = match[4];
|
|
1845
|
+
}
|
|
1846
|
+
if (debugOption && debugPort !== "0") {
|
|
1847
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
1848
|
+
}
|
|
1849
|
+
return arg;
|
|
1850
|
+
});
|
|
1851
|
+
}
|
|
1852
|
+
exports.Command = Command;
|
|
1853
|
+
});
|
|
1854
|
+
|
|
1855
|
+
// node_modules/commander/index.js
|
|
1856
|
+
var require_commander = __commonJS((exports) => {
|
|
1857
|
+
var { Argument } = require_argument();
|
|
1858
|
+
var { Command } = require_command();
|
|
1859
|
+
var { CommanderError, InvalidArgumentError } = require_error();
|
|
1860
|
+
var { Help } = require_help();
|
|
1861
|
+
var { Option } = require_option();
|
|
1862
|
+
exports.program = new Command;
|
|
1863
|
+
exports.createCommand = (name) => new Command(name);
|
|
1864
|
+
exports.createOption = (flags, description) => new Option(flags, description);
|
|
1865
|
+
exports.createArgument = (name, description) => new Argument(name, description);
|
|
1866
|
+
exports.Command = Command;
|
|
1867
|
+
exports.Option = Option;
|
|
1868
|
+
exports.Argument = Argument;
|
|
1869
|
+
exports.Help = Help;
|
|
1870
|
+
exports.CommanderError = CommanderError;
|
|
1871
|
+
exports.InvalidArgumentError = InvalidArgumentError;
|
|
1872
|
+
exports.InvalidOptionArgumentError = InvalidArgumentError;
|
|
1873
|
+
});
|
|
1874
|
+
|
|
1875
|
+
// node_modules/commander/esm.mjs
|
|
1876
|
+
var import__ = __toESM(require_commander(), 1);
|
|
1877
|
+
var {
|
|
1878
|
+
program,
|
|
1879
|
+
createCommand,
|
|
1880
|
+
createArgument,
|
|
1881
|
+
createOption,
|
|
1882
|
+
CommanderError,
|
|
1883
|
+
InvalidArgumentError,
|
|
1884
|
+
InvalidOptionArgumentError,
|
|
1885
|
+
Command,
|
|
1886
|
+
Argument,
|
|
1887
|
+
Option,
|
|
1888
|
+
Help
|
|
1889
|
+
} = import__.default;
|
|
1890
|
+
|
|
1891
|
+
// src/commands/init.ts
|
|
1892
|
+
import { join as join4, resolve as resolve2 } from "node:path";
|
|
1893
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
1894
|
+
|
|
1895
|
+
// src/lib/user-config.ts
|
|
1896
|
+
import { homedir } from "node:os";
|
|
1897
|
+
import { join } from "node:path";
|
|
1898
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
1899
|
+
var DEFAULT_API_BASE = "https://api.ai-mcn.tv:10000";
|
|
1900
|
+
var DIR = join(homedir(), ".gtrk-cli");
|
|
1901
|
+
var FILE = join(DIR, "config.json");
|
|
1902
|
+
function configPath() {
|
|
1903
|
+
return FILE;
|
|
1904
|
+
}
|
|
1905
|
+
function readUserConfig() {
|
|
1906
|
+
if (!existsSync(FILE))
|
|
1907
|
+
return {};
|
|
1908
|
+
try {
|
|
1909
|
+
return JSON.parse(readFileSync(FILE, "utf8"));
|
|
1910
|
+
} catch {
|
|
1911
|
+
return {};
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
function writeUserConfig(patch) {
|
|
1915
|
+
mkdirSync(DIR, { recursive: true });
|
|
1916
|
+
const merged = { ...readUserConfig(), ...patch };
|
|
1917
|
+
writeFileSync(FILE, JSON.stringify(merged, null, 2));
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
// src/lib/jianying.ts
|
|
1921
|
+
import { join as join2, resolve } from "node:path";
|
|
1922
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
1923
|
+
function probeJianyingDraftDir() {
|
|
1924
|
+
const local = process.env.LOCALAPPDATA;
|
|
1925
|
+
if (!local)
|
|
1926
|
+
return;
|
|
1927
|
+
const candidates = [
|
|
1928
|
+
join2(local, "JianyingPro", "User Data", "Projects", "com.lveditor.draft"),
|
|
1929
|
+
join2(local, "CapCut", "User Data", "Projects", "com.lveditor.draft")
|
|
1930
|
+
];
|
|
1931
|
+
return candidates.find((p) => existsSync2(p));
|
|
1932
|
+
}
|
|
1933
|
+
function resolveJianyingDraftDir(opt) {
|
|
1934
|
+
if (opt && opt !== "auto")
|
|
1935
|
+
return resolve(opt);
|
|
1936
|
+
const saved = readUserConfig().jianyingDraftDir;
|
|
1937
|
+
if (saved && existsSync2(saved))
|
|
1938
|
+
return saved;
|
|
1939
|
+
return probeJianyingDraftDir();
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
// src/lib/open.ts
|
|
1943
|
+
import { spawn } from "node:child_process";
|
|
1944
|
+
function openFolder(dir) {
|
|
1945
|
+
const plat = process.platform;
|
|
1946
|
+
const cmd = plat === "win32" ? ["explorer", dir] : plat === "darwin" ? ["open", dir] : ["xdg-open", dir];
|
|
1947
|
+
launch(cmd);
|
|
1948
|
+
}
|
|
1949
|
+
function openFile(path) {
|
|
1950
|
+
const plat = process.platform;
|
|
1951
|
+
const cmd = plat === "win32" ? ["cmd", "/c", "start", "", path] : plat === "darwin" ? ["open", path] : ["xdg-open", path];
|
|
1952
|
+
launch(cmd);
|
|
1953
|
+
}
|
|
1954
|
+
function launch(cmd) {
|
|
1955
|
+
try {
|
|
1956
|
+
spawn(cmd[0], cmd.slice(1), { stdio: "ignore", detached: true }).unref();
|
|
1957
|
+
} catch {}
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
// src/lib/paths.ts
|
|
1961
|
+
import { dirname, join as join3 } from "node:path";
|
|
1962
|
+
import { fileURLToPath } from "node:url";
|
|
1963
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
1964
|
+
function packageRoot() {
|
|
1965
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
1966
|
+
for (let i = 0;i < 8; i++) {
|
|
1967
|
+
if (existsSync3(join3(dir, "package.json")))
|
|
1968
|
+
return dir;
|
|
1969
|
+
const parent = dirname(dir);
|
|
1970
|
+
if (parent === dir)
|
|
1971
|
+
break;
|
|
1972
|
+
dir = parent;
|
|
1973
|
+
}
|
|
1974
|
+
return dir;
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
// src/lib/prompt.ts
|
|
1978
|
+
import { stdin, stdout } from "node:process";
|
|
1979
|
+
import { spawnSync } from "node:child_process";
|
|
1980
|
+
var c = {
|
|
1981
|
+
dim: (s) => `\x1B[2m${s}\x1B[0m`,
|
|
1982
|
+
cyan: (s) => `\x1B[36m${s}\x1B[0m`
|
|
1983
|
+
};
|
|
1984
|
+
function readClipboard() {
|
|
1985
|
+
try {
|
|
1986
|
+
if (process.platform === "win32") {
|
|
1987
|
+
const r = spawnSync("powershell", ["-NoProfile", "-Command", "Get-Clipboard"], {
|
|
1988
|
+
encoding: "utf8"
|
|
1989
|
+
});
|
|
1990
|
+
return (r.stdout ?? "").replace(/\r?\n$/, "");
|
|
1991
|
+
}
|
|
1992
|
+
if (process.platform === "darwin") {
|
|
1993
|
+
return spawnSync("pbpaste", { encoding: "utf8" }).stdout ?? "";
|
|
1994
|
+
}
|
|
1995
|
+
const x = spawnSync("xclip", ["-selection", "clipboard", "-o"], { encoding: "utf8" });
|
|
1996
|
+
if (x.status === 0)
|
|
1997
|
+
return x.stdout ?? "";
|
|
1998
|
+
return spawnSync("wl-paste", ["-n"], { encoding: "utf8" }).stdout ?? "";
|
|
1999
|
+
} catch {
|
|
2000
|
+
return "";
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
function ask(message, opts = {}) {
|
|
2004
|
+
return new Promise((resolve2) => {
|
|
2005
|
+
const hint = opts.defaultValue ? c.dim(` (${opts.defaultValue})`) : "";
|
|
2006
|
+
stdout.write(`${c.cyan("?")} ${message}${hint} `);
|
|
2007
|
+
let value = "";
|
|
2008
|
+
const echo = (s) => stdout.write(opts.mask ? "•".repeat([...s].length) : s);
|
|
2009
|
+
const wasRaw = stdin.isRaw ?? false;
|
|
2010
|
+
stdin.setRawMode?.(true);
|
|
2011
|
+
stdin.resume();
|
|
2012
|
+
stdin.setEncoding("utf8");
|
|
2013
|
+
const cleanup = () => {
|
|
2014
|
+
stdin.off("data", onData);
|
|
2015
|
+
stdin.setRawMode?.(wasRaw);
|
|
2016
|
+
stdin.pause();
|
|
2017
|
+
};
|
|
2018
|
+
const onData = (chunk) => {
|
|
2019
|
+
for (const ch of chunk) {
|
|
2020
|
+
if (ch === "\r" || ch === `
|
|
2021
|
+
`) {
|
|
2022
|
+
stdout.write(`
|
|
2023
|
+
`);
|
|
2024
|
+
cleanup();
|
|
2025
|
+
resolve2(value || opts.defaultValue || "");
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
if (ch === "\x03") {
|
|
2029
|
+
stdout.write(`
|
|
2030
|
+
`);
|
|
2031
|
+
cleanup();
|
|
2032
|
+
process.exit(130);
|
|
2033
|
+
}
|
|
2034
|
+
if (ch === "\x16") {
|
|
2035
|
+
const clip = readClipboard().replace(/[\r\n]+/g, "");
|
|
2036
|
+
value += clip;
|
|
2037
|
+
echo(clip);
|
|
2038
|
+
continue;
|
|
2039
|
+
}
|
|
2040
|
+
if (ch === "" || ch === "\b") {
|
|
2041
|
+
if (value.length) {
|
|
2042
|
+
value = value.slice(0, -1);
|
|
2043
|
+
stdout.write("\b \b");
|
|
2044
|
+
}
|
|
2045
|
+
continue;
|
|
2046
|
+
}
|
|
2047
|
+
if (ch.charCodeAt(0) >= 32) {
|
|
2048
|
+
value += ch;
|
|
2049
|
+
echo(ch);
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
};
|
|
2053
|
+
stdin.on("data", onData);
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
function promptText(message, opts = {}) {
|
|
2057
|
+
return ask(message, { defaultValue: opts.defaultValue });
|
|
2058
|
+
}
|
|
2059
|
+
function promptSecret(message) {
|
|
2060
|
+
return ask(message, { mask: true });
|
|
2061
|
+
}
|
|
2062
|
+
async function promptConfirm(message, defaultYes = true) {
|
|
2063
|
+
const a = (await ask(`${message} ${c.dim(defaultYes ? "[Y/n]" : "[y/N]")}`)).trim().toLowerCase();
|
|
2064
|
+
if (!a)
|
|
2065
|
+
return defaultYes;
|
|
2066
|
+
return a === "y" || a === "yes";
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
// src/commands/doctor.ts
|
|
2070
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
2071
|
+
function registerDoctor(program2) {
|
|
2072
|
+
program2.command("doctor").description("体检:配置 / 云端连通 / 剪映目录 / 运行时是否就绪").action(async () => {
|
|
2073
|
+
await runDoctor();
|
|
2074
|
+
});
|
|
2075
|
+
}
|
|
2076
|
+
var MARK = { ok: "✅", warn: "⚠️ ", fail: "❌" };
|
|
2077
|
+
async function runDoctor() {
|
|
2078
|
+
const rows = [];
|
|
2079
|
+
const bunVer = process.versions.bun;
|
|
2080
|
+
rows.push({
|
|
2081
|
+
name: "运行时",
|
|
2082
|
+
status: "ok",
|
|
2083
|
+
detail: bunVer ? `bun ${bunVer}` : `node ${process.version}`
|
|
2084
|
+
});
|
|
2085
|
+
const uc = readUserConfig();
|
|
2086
|
+
const apiKey = (process.env.GITRUCK_API_KEY ?? uc.apiKey ?? "").trim();
|
|
2087
|
+
const apiBase = (process.env.GITRUCK_API_BASE ?? uc.apiBase ?? DEFAULT_API_BASE).trim().replace(/\/+$/, "");
|
|
2088
|
+
rows.push({
|
|
2089
|
+
name: "API Key",
|
|
2090
|
+
status: apiKey ? "ok" : "fail",
|
|
2091
|
+
detail: apiKey ? `已配(${apiKey.slice(0, 6)}…,来源 ${process.env.GITRUCK_API_KEY ? "环境变量" : "gtrk init"})` : "未配 —— 跑 gtrk init"
|
|
2092
|
+
});
|
|
2093
|
+
rows.push({ name: "API 根地址", status: "ok", detail: apiBase });
|
|
2094
|
+
let apiStatus = "warn";
|
|
2095
|
+
let apiDetail = "跳过(未配 Key)";
|
|
2096
|
+
if (apiKey) {
|
|
2097
|
+
try {
|
|
2098
|
+
const res = await fetch(`${apiBase}/user/get_user_info`, {
|
|
2099
|
+
method: "POST",
|
|
2100
|
+
headers: { accept: "application/json", Authorization: apiKey },
|
|
2101
|
+
body: "",
|
|
2102
|
+
signal: AbortSignal.timeout(8000)
|
|
2103
|
+
});
|
|
2104
|
+
const data = await res.json().catch(() => ({}));
|
|
2105
|
+
if (data.code === 200) {
|
|
2106
|
+
apiStatus = "ok";
|
|
2107
|
+
apiDetail = "可达,鉴权通过";
|
|
2108
|
+
} else {
|
|
2109
|
+
apiStatus = "fail";
|
|
2110
|
+
apiDetail = `可达,但鉴权失败(code=${data.code ?? res.status}${data.msg ? `,${data.msg}` : ""})—— 检查 API Key`;
|
|
2111
|
+
}
|
|
2112
|
+
} catch (e) {
|
|
2113
|
+
apiStatus = "fail";
|
|
2114
|
+
apiDetail = `连不上:${e instanceof Error ? e.message : String(e)}`;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
rows.push({ name: "云端连通 + 鉴权", status: apiStatus, detail: apiDetail });
|
|
2118
|
+
const draftDir = resolveJianyingDraftDir(undefined);
|
|
2119
|
+
const draftOk = !!draftDir && existsSync4(draftDir);
|
|
2120
|
+
rows.push({
|
|
2121
|
+
name: "剪映草稿目录",
|
|
2122
|
+
status: draftOk ? "ok" : "warn",
|
|
2123
|
+
detail: draftOk ? draftDir : "未配/未探到 —— 要剪映直开就跑 gtrk init 或加 --jianying-draft-dir"
|
|
2124
|
+
});
|
|
2125
|
+
rows.push({
|
|
2126
|
+
name: "配置文件",
|
|
2127
|
+
status: existsSync4(configPath()) ? "ok" : "warn",
|
|
2128
|
+
detail: existsSync4(configPath()) ? configPath() : `未生成 —— 跑 gtrk init(${configPath()})`
|
|
2129
|
+
});
|
|
2130
|
+
console.log(`
|
|
2131
|
+
gtrk 体检:
|
|
2132
|
+
`);
|
|
2133
|
+
for (const r of rows)
|
|
2134
|
+
console.log(` ${MARK[r.status]} ${r.name}:${r.detail}`);
|
|
2135
|
+
const failed = rows.some((r) => r.status === "fail");
|
|
2136
|
+
console.log(failed ? `
|
|
2137
|
+
有项不通,按提示处理后再开剪。
|
|
2138
|
+
` : `
|
|
2139
|
+
一切就绪,可以开剪。
|
|
2140
|
+
`);
|
|
2141
|
+
if (failed)
|
|
2142
|
+
process.exitCode = 1;
|
|
2143
|
+
return !failed;
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
// src/lib/log.ts
|
|
2147
|
+
var c2 = {
|
|
2148
|
+
dim: (s) => `\x1B[2m${s}\x1B[0m`,
|
|
2149
|
+
cyan: (s) => `\x1B[36m${s}\x1B[0m`,
|
|
2150
|
+
green: (s) => `\x1B[32m${s}\x1B[0m`,
|
|
2151
|
+
yellow: (s) => `\x1B[33m${s}\x1B[0m`,
|
|
2152
|
+
red: (s) => `\x1B[31m${s}\x1B[0m`
|
|
2153
|
+
};
|
|
2154
|
+
var humanOut = process.stdout;
|
|
2155
|
+
function routeLogsToStderr() {
|
|
2156
|
+
humanOut = process.stderr;
|
|
2157
|
+
}
|
|
2158
|
+
var line = (s) => humanOut.write(`${s}
|
|
2159
|
+
`);
|
|
2160
|
+
var log = {
|
|
2161
|
+
step: (msg) => line(c2.cyan(msg)),
|
|
2162
|
+
info: (msg) => line(c2.dim(` ${msg}`)),
|
|
2163
|
+
ok: (msg) => line(c2.green(`✅ ${msg}`)),
|
|
2164
|
+
warn: (msg) => line(c2.yellow(`⚠️ ${msg}`)),
|
|
2165
|
+
err: (msg) => process.stderr.write(`${c2.red(`❌ ${msg}`)}
|
|
2166
|
+
`),
|
|
2167
|
+
tick: (msg) => humanOut.write(`\r ${msg}\x1B[K`),
|
|
2168
|
+
tickEnd: () => humanOut.write(`
|
|
2169
|
+
`)
|
|
2170
|
+
};
|
|
2171
|
+
|
|
2172
|
+
// src/commands/init.ts
|
|
2173
|
+
var GUIDE_IMAGE = join4(packageRoot(), "assets", "jianying-draft-path.png");
|
|
2174
|
+
function registerInit(program2) {
|
|
2175
|
+
program2.command("init").description("一次性配置:API Key + 剪映草稿目录(之后所有命令免重复配置)").option("--api-key <key>", "非交互:直接指定 API Key").option("--api-base <url>", "非交互:指定 API 根地址(缺省用默认生产地址)").option("--jianying-draft-dir <dir>", "非交互:剪映草稿目录(传 auto 则自动探测)").option("-y, --yes", "非交互:用传入值 + 自动探测,不弹任何提示").action(runInit);
|
|
2176
|
+
}
|
|
2177
|
+
async function runInit(opts) {
|
|
2178
|
+
if (opts.yes || opts.apiKey)
|
|
2179
|
+
return runInitNonInteractive(opts);
|
|
2180
|
+
if (!process.stdin.isTTY) {
|
|
2181
|
+
log.err("交互式 init 需要真实终端;脚本/agent 请用:gtrk init --api-key <KEY> -y");
|
|
2182
|
+
process.exitCode = 1;
|
|
2183
|
+
return;
|
|
2184
|
+
}
|
|
2185
|
+
const existing = readUserConfig();
|
|
2186
|
+
log.step("▶ gtrk 安装配置");
|
|
2187
|
+
let apiKey = "";
|
|
2188
|
+
while (!apiKey) {
|
|
2189
|
+
apiKey = (await promptSecret("粘贴同合云 API Key(Ctrl+V 粘贴):")).trim();
|
|
2190
|
+
if (!apiKey)
|
|
2191
|
+
log.warn("API Key 不能为空,再来一次");
|
|
2192
|
+
}
|
|
2193
|
+
const apiBase = (await promptText("云端 API 根地址(回车用默认):", {
|
|
2194
|
+
defaultValue: existing.apiBase ?? DEFAULT_API_BASE
|
|
2195
|
+
})).trim();
|
|
2196
|
+
let jianyingDraftDir;
|
|
2197
|
+
const probed = probeJianyingDraftDir();
|
|
2198
|
+
if (probed) {
|
|
2199
|
+
if (await promptConfirm(`自动找到剪映草稿目录:${probed},用它吗?`, true)) {
|
|
2200
|
+
jianyingDraftDir = probed;
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
if (!jianyingDraftDir) {
|
|
2204
|
+
log.info("没自动找到(或你选了手动)。已打开一张指引图:剪映 → 全局设置 → 草稿 →「草稿位置」,把那一行路径复制过来;留空则跳过(剪映只产 draft_content.json、缺 meta、需手动导入)。");
|
|
2205
|
+
openFile(GUIDE_IMAGE);
|
|
2206
|
+
const manual = (await promptText("剪映草稿根目录(…\\com.lveditor.draft),留空跳过:")).trim();
|
|
2207
|
+
if (manual) {
|
|
2208
|
+
if (existsSync5(manual))
|
|
2209
|
+
jianyingDraftDir = resolve2(manual);
|
|
2210
|
+
else
|
|
2211
|
+
log.warn(`目录不存在,已跳过:${manual}`);
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
const patch = { apiKey, apiBase };
|
|
2215
|
+
if (jianyingDraftDir)
|
|
2216
|
+
patch.jianyingDraftDir = jianyingDraftDir;
|
|
2217
|
+
writeUserConfig(patch);
|
|
2218
|
+
log.ok(`配置已写入 ${configPath()}`);
|
|
2219
|
+
if (!jianyingDraftDir) {
|
|
2220
|
+
log.warn("未配剪映草稿目录:要剪映直接打开,之后可重跑 gtrk init,或单次加 --jianying-draft-dir");
|
|
2221
|
+
}
|
|
2222
|
+
const healthy = await runDoctor();
|
|
2223
|
+
if (healthy) {
|
|
2224
|
+
log.step("装好了!两种用法任选:");
|
|
2225
|
+
log.info('① 命令行直接剪:gtrk oralcut "<毛片.mp4>" --script "<文字稿.txt>"(无稿就别加 --script)');
|
|
2226
|
+
log.info("② 重启你常用的 AI agent(Claude / Codex / Trae / WorkBuddy 等),用 /gtrk-oralcut <你的口播剪辑需求>,一句话交给它,体验更智能的剪辑~");
|
|
2227
|
+
} else {
|
|
2228
|
+
log.warn("上面体检有项没通,按提示处理好再开剪(多半是 API Key 或剪映目录)。");
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
async function runInitNonInteractive(opts) {
|
|
2232
|
+
const existing = readUserConfig();
|
|
2233
|
+
const apiKey = (opts.apiKey ?? existing.apiKey ?? "").trim();
|
|
2234
|
+
if (!apiKey) {
|
|
2235
|
+
log.err("非交互模式需要 --api-key(或改用交互式 gtrk init)");
|
|
2236
|
+
process.exitCode = 1;
|
|
2237
|
+
return;
|
|
2238
|
+
}
|
|
2239
|
+
const apiBase = (opts.apiBase ?? existing.apiBase ?? DEFAULT_API_BASE).trim();
|
|
2240
|
+
let jianyingDraftDir;
|
|
2241
|
+
const dirOpt = opts.jianyingDraftDir;
|
|
2242
|
+
if (dirOpt && dirOpt !== "auto")
|
|
2243
|
+
jianyingDraftDir = resolve2(dirOpt);
|
|
2244
|
+
else if (dirOpt === "auto" || !existing.jianyingDraftDir)
|
|
2245
|
+
jianyingDraftDir = probeJianyingDraftDir();
|
|
2246
|
+
else
|
|
2247
|
+
jianyingDraftDir = existing.jianyingDraftDir;
|
|
2248
|
+
const patch = { apiKey, apiBase };
|
|
2249
|
+
if (jianyingDraftDir)
|
|
2250
|
+
patch.jianyingDraftDir = jianyingDraftDir;
|
|
2251
|
+
writeUserConfig(patch);
|
|
2252
|
+
log.ok(`配置已写入 ${configPath()}`);
|
|
2253
|
+
log.info(`剪映草稿目录:${jianyingDraftDir ?? "未配(剪映需手动导入,可加 --jianying-draft-dir)"}`);
|
|
2254
|
+
await runDoctor();
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
// src/commands/oralcut.ts
|
|
2258
|
+
import { resolve as resolve3, join as join6, dirname as dirname2, basename as basename2, extname } from "node:path";
|
|
2259
|
+
import { mkdir as mkdir2, cp, readFile as readFile2 } from "node:fs/promises";
|
|
2260
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
2261
|
+
|
|
2262
|
+
// src/lib/config.ts
|
|
2263
|
+
function loadConfig() {
|
|
2264
|
+
const uc = readUserConfig();
|
|
2265
|
+
const apiKey = (process.env.GITRUCK_API_KEY ?? uc.apiKey ?? "").trim();
|
|
2266
|
+
const base = (process.env.GITRUCK_API_BASE ?? uc.apiBase ?? DEFAULT_API_BASE).trim().replace(/\/+$/, "");
|
|
2267
|
+
if (!apiKey) {
|
|
2268
|
+
throw new Error("缺 API Key —— 先跑 `gtrk init` 配置(或设环境变量 GITRUCK_API_KEY)");
|
|
2269
|
+
}
|
|
2270
|
+
return { base, apiKey };
|
|
2271
|
+
}
|
|
2272
|
+
|
|
2273
|
+
// src/lib/cloud.ts
|
|
2274
|
+
import { basename } from "node:path";
|
|
2275
|
+
import { writeFile } from "node:fs/promises";
|
|
2276
|
+
import { openAsBlob } from "node:fs";
|
|
2277
|
+
|
|
2278
|
+
class CloudError extends Error {
|
|
2279
|
+
code;
|
|
2280
|
+
constructor(code, message) {
|
|
2281
|
+
super(message);
|
|
2282
|
+
this.code = code;
|
|
2283
|
+
this.name = "CloudError";
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
async function parseJson(res) {
|
|
2287
|
+
try {
|
|
2288
|
+
return await res.json();
|
|
2289
|
+
} catch {
|
|
2290
|
+
throw new Error(`服务响应解析失败 (HTTP ${res.status})`);
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
async function uploadFile(cfg, path) {
|
|
2294
|
+
const form = new FormData;
|
|
2295
|
+
form.append("file", await openAsBlob(path), basename(path));
|
|
2296
|
+
const res = await fetch(`${cfg.base}/base/file/upload`, {
|
|
2297
|
+
method: "POST",
|
|
2298
|
+
headers: { Authorization: cfg.apiKey },
|
|
2299
|
+
body: form
|
|
2300
|
+
});
|
|
2301
|
+
const r = await parseJson(res);
|
|
2302
|
+
const fid = r.data?.file_id ?? r.data?.id;
|
|
2303
|
+
if (r.code === 200 && fid)
|
|
2304
|
+
return String(fid);
|
|
2305
|
+
throw new Error(`上传失败 (code=${r.code ?? "?"}):${r.msg ?? "未知错误"}`);
|
|
2306
|
+
}
|
|
2307
|
+
async function submitTask(cfg, taskType, payload) {
|
|
2308
|
+
const res = await fetch(`${cfg.base}/task/${taskType}`, {
|
|
2309
|
+
method: "POST",
|
|
2310
|
+
headers: { Authorization: cfg.apiKey, "Content-Type": "application/json" },
|
|
2311
|
+
body: JSON.stringify(payload)
|
|
2312
|
+
});
|
|
2313
|
+
const r = await parseJson(res);
|
|
2314
|
+
if (r.code === 200 && r.data?.task_id)
|
|
2315
|
+
return String(r.data.task_id);
|
|
2316
|
+
throw new Error(`提交失败 (code=${r.code ?? "?"}):${r.msg ?? "未知错误"}`);
|
|
2317
|
+
}
|
|
2318
|
+
async function pollTask(cfg, taskType, taskId, onTick) {
|
|
2319
|
+
const start = Date.now();
|
|
2320
|
+
const TIMEOUT_MS = 30 * 60 * 1000;
|
|
2321
|
+
const INTERVAL_MS = 5000;
|
|
2322
|
+
for (;; ) {
|
|
2323
|
+
if (Date.now() - start > TIMEOUT_MS) {
|
|
2324
|
+
throw new Error("任务超时(超过 30 分钟)。可稍后在云端查任务或重试。");
|
|
2325
|
+
}
|
|
2326
|
+
await new Promise((r2) => setTimeout(r2, INTERVAL_MS));
|
|
2327
|
+
let r;
|
|
2328
|
+
try {
|
|
2329
|
+
const res = await fetch(`${cfg.base}/task/${taskType}/${taskId}`, {
|
|
2330
|
+
headers: { Authorization: cfg.apiKey }
|
|
2331
|
+
});
|
|
2332
|
+
r = await parseJson(res);
|
|
2333
|
+
} catch {
|
|
2334
|
+
continue;
|
|
2335
|
+
}
|
|
2336
|
+
if (r.code != null && r.code !== 200) {
|
|
2337
|
+
throw new Error(`任务错误 (code=${r.code}):${r.msg ?? ""}`);
|
|
2338
|
+
}
|
|
2339
|
+
const data = r.data ?? {};
|
|
2340
|
+
const status = String(data.status ?? "");
|
|
2341
|
+
if (status === "completed") {
|
|
2342
|
+
return data.output_result ?? {};
|
|
2343
|
+
}
|
|
2344
|
+
if (status === "failed" || status === "cancelled") {
|
|
2345
|
+
const out = data.output_result;
|
|
2346
|
+
throw new Error(out?.error ?? (status === "failed" ? "任务失败" : "任务已取消"));
|
|
2347
|
+
}
|
|
2348
|
+
onTick?.(status || "处理中", typeof data.progress === "number" ? data.progress : undefined);
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
async function download(url, dest) {
|
|
2352
|
+
const res = await fetch(url);
|
|
2353
|
+
if (!res.ok)
|
|
2354
|
+
throw new Error(`下载失败 HTTP ${res.status}:${url}`);
|
|
2355
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
2356
|
+
await writeFile(dest, buf);
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
// src/lib/upload-cache.ts
|
|
2360
|
+
import { homedir as homedir2 } from "node:os";
|
|
2361
|
+
import { join as join5 } from "node:path";
|
|
2362
|
+
import { stat, mkdir, readFile, writeFile as writeFile2 } from "node:fs/promises";
|
|
2363
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
2364
|
+
var CACHE_DIR = join5(homedir2(), ".gtrk-cli");
|
|
2365
|
+
var CACHE_FILE = join5(CACHE_DIR, "upload-cache.json");
|
|
2366
|
+
async function fingerprint(path) {
|
|
2367
|
+
const s = await stat(path);
|
|
2368
|
+
return `${s.size}:${Math.round(s.mtimeMs)}`;
|
|
2369
|
+
}
|
|
2370
|
+
async function load() {
|
|
2371
|
+
if (!existsSync6(CACHE_FILE))
|
|
2372
|
+
return {};
|
|
2373
|
+
try {
|
|
2374
|
+
return JSON.parse(await readFile(CACHE_FILE, "utf8"));
|
|
2375
|
+
} catch {
|
|
2376
|
+
return {};
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
async function save(cache) {
|
|
2380
|
+
await mkdir(CACHE_DIR, { recursive: true });
|
|
2381
|
+
await writeFile2(CACHE_FILE, JSON.stringify(cache, null, 2));
|
|
2382
|
+
}
|
|
2383
|
+
async function invalidateUpload(path) {
|
|
2384
|
+
const fp = await fingerprint(path);
|
|
2385
|
+
const cache = await load();
|
|
2386
|
+
if (cache[fp]) {
|
|
2387
|
+
delete cache[fp];
|
|
2388
|
+
await save(cache);
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
async function uploadCached(cfg, path, opts) {
|
|
2392
|
+
const fp = await fingerprint(path);
|
|
2393
|
+
const cache = await load();
|
|
2394
|
+
const hit = cache[fp]?.fileId;
|
|
2395
|
+
if (!opts?.force && hit)
|
|
2396
|
+
return { fileId: hit, cached: true };
|
|
2397
|
+
const fileId = await uploadFile(cfg, path);
|
|
2398
|
+
const s = await stat(path);
|
|
2399
|
+
cache[fp] = {
|
|
2400
|
+
fileId,
|
|
2401
|
+
size: s.size,
|
|
2402
|
+
mtimeMs: Math.round(s.mtimeMs),
|
|
2403
|
+
path,
|
|
2404
|
+
uploadedAt: Date.now()
|
|
2405
|
+
};
|
|
2406
|
+
await save(cache);
|
|
2407
|
+
return { fileId, cached: false };
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
// src/commands/oralcut.ts
|
|
2411
|
+
var TASK_TYPE = "video_oral_cut";
|
|
2412
|
+
function timestamp() {
|
|
2413
|
+
const d = new Date;
|
|
2414
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
2415
|
+
return `${p(d.getFullYear() % 100)}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
2416
|
+
}
|
|
2417
|
+
function baseFormat(fmt) {
|
|
2418
|
+
if (fmt.startsWith("jianying"))
|
|
2419
|
+
return "jianying";
|
|
2420
|
+
if (fmt.startsWith("capcut"))
|
|
2421
|
+
return "capcut";
|
|
2422
|
+
return fmt;
|
|
2423
|
+
}
|
|
2424
|
+
var FORMAT_META = {
|
|
2425
|
+
gtrk: { label: "客户端 (gtrk)", openHint: (p) => `客户端里「打开工程」选 ${p}` },
|
|
2426
|
+
jianying: { label: "剪映 (jianying)", openHint: (p) => `剪映里打开即见草稿(目录 ${p})` },
|
|
2427
|
+
capcut: { label: "CapCut", openHint: (p) => `CapCut 里打开即见草稿(目录 ${p})` },
|
|
2428
|
+
xml: { label: "PR/FCP (Premiere XML)", openHint: (p) => `Premiere Pro:文件 > 导入 ${p}` },
|
|
2429
|
+
fcpxml: { label: "Final Cut (fcpxml)", openHint: (p) => `Final Cut Pro:导入 ${p}` },
|
|
2430
|
+
otio: { label: "OpenTimelineIO", openHint: (p) => `用支持 OTIO 的工具打开 ${p}` }
|
|
2431
|
+
};
|
|
2432
|
+
function registerOralCut(program2) {
|
|
2433
|
+
program2.command("oralcut <input>").description("智能口播剪辑闭环:上传毛片 → 云端剪辑 → 拉回 gtrk/剪映/PR 工程文件 → 打开").option("-s, --script <file>", "文稿 txt 路径(缺省走无稿智能重建)").option("-p, --preset <preset>", "节奏预设 steady|concise|compact", "concise").option("-o, --out <dir>", "工程产物目录(缺省 = <毛片同目录>/<毛片名>-video-project-<YYMMDD-HHMMSS>)").option("-f, --formats <list>", "三方格式(逗号分隔)", "gtrk,jianying,xml").option("--jianying-draft-dir <dir>", "剪映草稿根目录;传路径或 auto(默认读 gtrk init 配置 / 自动探测)").option("--reupload", "强制重新上传,忽略本地上传缓存(毛片改了但指纹意外没变时用)").option("--no-open", "完成后不自动打开产物目录(默认会自动打开,省得你找文件去哪了)").option("--json", "机读模式:人读日志转 stderr,stdout 只输出结果 JSON(给 agent/脚本解析)").action(async (input, opts) => {
|
|
2434
|
+
await runOralCut(input, opts);
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
async function runOralCut(input, opts) {
|
|
2438
|
+
if (opts.json)
|
|
2439
|
+
routeLogsToStderr();
|
|
2440
|
+
const cfg = loadConfig();
|
|
2441
|
+
const inputAbs = resolve3(input);
|
|
2442
|
+
if (!existsSync7(inputAbs))
|
|
2443
|
+
throw new Error(`毛片不存在:${inputAbs}`);
|
|
2444
|
+
const projName = basename2(inputAbs, extname(inputAbs));
|
|
2445
|
+
const formats = opts.formats.split(",").map((s) => s.trim()).filter(Boolean);
|
|
2446
|
+
const wantJianying = formats.some((f) => f === "jianying" || f === "capcut");
|
|
2447
|
+
const outDir = resolve3(opts.out ?? join6(dirname2(inputAbs), `${projName}-video-project-${timestamp()}`));
|
|
2448
|
+
await mkdir2(outDir, { recursive: true });
|
|
2449
|
+
let scriptPath = opts.script ? resolve3(opts.script) : undefined;
|
|
2450
|
+
if (!scriptPath) {
|
|
2451
|
+
const sibling = join6(dirname2(inputAbs), `${projName}.txt`);
|
|
2452
|
+
if (existsSync7(sibling)) {
|
|
2453
|
+
scriptPath = sibling;
|
|
2454
|
+
log.info(`自动识别到同名文稿:${sibling}(按有稿剪辑;不想用就改名或显式 --script)`);
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
const script = scriptPath ? await readFile2(scriptPath, "utf8") : undefined;
|
|
2458
|
+
let draftDir;
|
|
2459
|
+
if (wantJianying) {
|
|
2460
|
+
draftDir = resolveJianyingDraftDir(opts.jianyingDraftDir);
|
|
2461
|
+
if (draftDir)
|
|
2462
|
+
log.info(`剪映草稿目录:${draftDir}`);
|
|
2463
|
+
else
|
|
2464
|
+
log.warn("没找到剪映草稿目录(剪映/CapCut 未装在标准位置)→ 将只产 draft_content.json、缺 meta,剪映无法直接打开。可加 --jianying-draft-dir <你的草稿目录> 重跑。");
|
|
2465
|
+
}
|
|
2466
|
+
log.step(`▶ 智能口播剪辑:${basename2(inputAbs)}(预设 ${opts.preset},格式 ${formats.join("/")})`);
|
|
2467
|
+
log.step("① 上传毛片到云端…");
|
|
2468
|
+
let up = await uploadCached(cfg, inputAbs, { force: opts.reupload });
|
|
2469
|
+
log.info(up.cached ? `命中上传缓存,复用 file_id = ${up.fileId}(免二次上传)` : `file_id = ${up.fileId}`);
|
|
2470
|
+
const buildPayload = (fid) => {
|
|
2471
|
+
const p = {
|
|
2472
|
+
file_id: fid,
|
|
2473
|
+
la: "zh-CN",
|
|
2474
|
+
outputs: ["project"],
|
|
2475
|
+
project_formats: formats,
|
|
2476
|
+
source_path: inputAbs,
|
|
2477
|
+
rhythm_preset: opts.preset
|
|
2478
|
+
};
|
|
2479
|
+
if (script)
|
|
2480
|
+
p.script = script;
|
|
2481
|
+
if (draftDir)
|
|
2482
|
+
p.struct_meta = { nle_draft_dir: draftDir };
|
|
2483
|
+
return p;
|
|
2484
|
+
};
|
|
2485
|
+
log.step("② 提交智能口播剪辑任务…");
|
|
2486
|
+
let taskId;
|
|
2487
|
+
try {
|
|
2488
|
+
taskId = await submitTask(cfg, TASK_TYPE, buildPayload(up.fileId));
|
|
2489
|
+
} catch (e) {
|
|
2490
|
+
if (up.cached && e instanceof CloudError && e.code === 6004) {
|
|
2491
|
+
log.warn("缓存的 file_id 在云端已失效,重新上传后重试…");
|
|
2492
|
+
await invalidateUpload(inputAbs);
|
|
2493
|
+
up = await uploadCached(cfg, inputAbs, { force: true });
|
|
2494
|
+
taskId = await submitTask(cfg, TASK_TYPE, buildPayload(up.fileId));
|
|
2495
|
+
} else
|
|
2496
|
+
throw e;
|
|
2497
|
+
}
|
|
2498
|
+
log.info(`task_id = ${taskId}`);
|
|
2499
|
+
log.step("③ 云端处理中(每 5s 轮询)…");
|
|
2500
|
+
const result = await pollTask(cfg, TASK_TYPE, taskId, (status, progress) => {
|
|
2501
|
+
log.tick(`${status}${progress != null ? ` ${Math.round(progress)}%` : ""}`);
|
|
2502
|
+
});
|
|
2503
|
+
log.tickEnd();
|
|
2504
|
+
const files = result.files ?? [];
|
|
2505
|
+
if (!files.length)
|
|
2506
|
+
throw new Error("任务完成但无工程文件产物(检查 project_formats)");
|
|
2507
|
+
log.step(`④ 拉回 ${files.length} 个产物到本地…`);
|
|
2508
|
+
const byFormat = {};
|
|
2509
|
+
for (const f of files) {
|
|
2510
|
+
const base = baseFormat(f.format);
|
|
2511
|
+
const fmtDir = join6(outDir, base);
|
|
2512
|
+
await mkdir2(fmtDir, { recursive: true });
|
|
2513
|
+
const dest = join6(fmtDir, f.filename);
|
|
2514
|
+
await download(f.download_url, dest);
|
|
2515
|
+
(byFormat[base] ??= []).push(dest);
|
|
2516
|
+
log.info(`${FORMAT_META[base]?.label ?? f.format} ← ${f.filename}`);
|
|
2517
|
+
}
|
|
2518
|
+
if (result.errors && Object.keys(result.errors).length) {
|
|
2519
|
+
log.warn(`部分产物失败:${JSON.stringify(result.errors)}`);
|
|
2520
|
+
}
|
|
2521
|
+
let jianyingDraftPath;
|
|
2522
|
+
if (byFormat.jianying && draftDir) {
|
|
2523
|
+
jianyingDraftPath = join6(draftDir, basename2(outDir));
|
|
2524
|
+
await mkdir2(jianyingDraftPath, { recursive: true });
|
|
2525
|
+
await cp(join6(outDir, "jianying"), jianyingDraftPath, { recursive: true });
|
|
2526
|
+
log.info(`剪映草稿已落到:${jianyingDraftPath}`);
|
|
2527
|
+
}
|
|
2528
|
+
if (!opts.json) {
|
|
2529
|
+
log.step("⑤ 三方打开(产物已就位,按需自取):");
|
|
2530
|
+
for (const base of Object.keys(byFormat)) {
|
|
2531
|
+
const meta = FORMAT_META[base];
|
|
2532
|
+
const target = base === "jianying" ? jianyingDraftPath ?? join6(outDir, "jianying") : byFormat[base][0];
|
|
2533
|
+
console.log(` • ${meta?.label ?? base}:${meta?.openHint(target) ?? target}`);
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
if (opts.open) {
|
|
2537
|
+
openFolder(outDir);
|
|
2538
|
+
log.info("已打开产物目录文件夹");
|
|
2539
|
+
}
|
|
2540
|
+
log.ok(`闭环完成。产物目录:${outDir}`);
|
|
2541
|
+
if (opts.json) {
|
|
2542
|
+
const errors = result.errors ?? {};
|
|
2543
|
+
console.log(JSON.stringify({
|
|
2544
|
+
ok: Object.keys(errors).length === 0,
|
|
2545
|
+
outDir,
|
|
2546
|
+
files: byFormat,
|
|
2547
|
+
jianyingDraftPath: jianyingDraftPath ?? null,
|
|
2548
|
+
errors,
|
|
2549
|
+
taskId,
|
|
2550
|
+
fileId: up.fileId
|
|
2551
|
+
}));
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
|
|
2555
|
+
// src/commands/skills.ts
|
|
2556
|
+
import { homedir as homedir3 } from "node:os";
|
|
2557
|
+
import { join as join7 } from "node:path";
|
|
2558
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync2, copyFileSync } from "node:fs";
|
|
2559
|
+
var SKILL_NAME = "gtrk-oralcut";
|
|
2560
|
+
var SRC = join7(packageRoot(), "skills", SKILL_NAME, "SKILL.md");
|
|
2561
|
+
function registerSkills(program2) {
|
|
2562
|
+
const skills = program2.command("skills").description("管理 agent skill(安装到 Claude Code)");
|
|
2563
|
+
skills.command("install").description(`把 /${SKILL_NAME} 安装到 ~/.claude/skills(对标飞书 skills add)`).option("--dir <dir>", "自定义 skills 目录(缺省 ~/.claude/skills)").action((opts) => {
|
|
2564
|
+
if (!existsSync8(SRC))
|
|
2565
|
+
throw new Error(`找不到打包的 skill 源:${SRC}`);
|
|
2566
|
+
const base = opts.dir ?? join7(homedir3(), ".claude", "skills");
|
|
2567
|
+
const dest = join7(base, SKILL_NAME);
|
|
2568
|
+
mkdirSync2(dest, { recursive: true });
|
|
2569
|
+
copyFileSync(SRC, join7(dest, "SKILL.md"));
|
|
2570
|
+
console.log(`✅ 已安装 /${SKILL_NAME} → ${join7(dest, "SKILL.md")}`);
|
|
2571
|
+
console.log(" 在 Claude Code 里打 /gtrk-oralcut,或直接说「帮我剪个口播」即可触发(可能需重载会话)。");
|
|
2572
|
+
});
|
|
2573
|
+
}
|
|
2574
|
+
|
|
2575
|
+
// src/index.ts
|
|
2576
|
+
try {
|
|
2577
|
+
process.loadEnvFile?.();
|
|
2578
|
+
} catch {}
|
|
2579
|
+
var program2 = new Command;
|
|
2580
|
+
program2.name("gtrk").description("同合云成片流水线 CLI —— agent 驱动云端任务、产物拉回本地、三方工程文件(客户端/剪映/PR)互通").version("0.1.0");
|
|
2581
|
+
registerInit(program2);
|
|
2582
|
+
registerOralCut(program2);
|
|
2583
|
+
registerDoctor(program2);
|
|
2584
|
+
registerSkills(program2);
|
|
2585
|
+
program2.parseAsync(process.argv).catch((e) => {
|
|
2586
|
+
console.error(`
|
|
2587
|
+
❌ ${e instanceof Error ? e.message : String(e)}`);
|
|
2588
|
+
process.exit(1);
|
|
2589
|
+
});
|