forked from unjs/citty
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.ts
More file actions
184 lines (166 loc) Β· 5.22 KB
/
command.ts
File metadata and controls
184 lines (166 loc) Β· 5.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import { camelCase } from "scule";
import type { CommandContext, CommandDef, ArgsDef, SubCommandsDef } from "./types.ts";
import { CLIError, resolveValue, toArray } from "./_utils.ts";
import { parseArgs } from "./args.ts";
import { cyan } from "./_color.ts";
import { resolvePlugins } from "./plugin.ts";
export function defineCommand<const T extends ArgsDef = ArgsDef>(
def: CommandDef<T>,
): CommandDef<T> {
return def;
}
export interface RunCommandOptions {
rawArgs: string[];
data?: any;
showUsage?: boolean;
}
export async function runCommand<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
opts: RunCommandOptions,
): Promise<{ result: unknown }> {
const cmdArgs = await resolveValue(cmd.args || {});
const parsedArgs = parseArgs<T>(opts.rawArgs, cmdArgs);
const context: CommandContext<T> = {
rawArgs: opts.rawArgs,
args: parsedArgs,
data: opts.data,
cmd,
};
// Resolve plugins
const plugins = await resolvePlugins(cmd.plugins ?? []);
// Resolve default sub command
const defaultSubCommand = await resolveValue(cmd.default);
if (defaultSubCommand && cmd.run) {
throw new CLIError(
`Command has a handler specified and a default sub command.`,
"E_DUPLICATE_COMMAND",
);
}
let result: unknown;
let runError: unknown;
try {
// Plugin setup hooks
for (const plugin of plugins) {
await plugin.setup?.(context);
}
// Setup hook
if (typeof cmd.setup === "function") {
await cmd.setup(context);
}
// Handle sub command
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const subCommandArgIndex = findSubCommandIndex(opts.rawArgs, cmdArgs);
const subCommandName =
opts.rawArgs[subCommandArgIndex] || defaultSubCommand;
if (subCommandName) {
const subCommand = await _findSubCommand(subCommands, subCommandName);
if (!subCommand) {
throw new CLIError(`Unknown command ${cyan(subCommandName)}`, "E_UNKNOWN_COMMAND");
}
await runCommand(subCommand, {
rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1),
});
} else if (!cmd.run) {
throw new CLIError(`No command specified.`, "E_NO_COMMAND");
}
}
// Handle main command
if (typeof cmd.run === "function") {
result = await cmd.run(context);
}
} catch (error) {
runError = error;
}
// Cleanup (always runs)
const cleanupErrors: unknown[] = [];
if (typeof cmd.cleanup === "function") {
try {
await cmd.cleanup(context);
} catch (error) {
cleanupErrors.push(error);
}
}
// Plugin cleanup hooks (reverse order)
for (const plugin of [...plugins].reverse()) {
try {
await plugin.cleanup?.(context);
} catch (error) {
cleanupErrors.push(error);
}
}
// Rethrow errors
if (runError) {
throw runError;
}
if (cleanupErrors.length === 1) {
throw cleanupErrors[0];
}
if (cleanupErrors.length > 1) {
throw new Error("Multiple cleanup errors", { cause: cleanupErrors });
}
return { result };
}
export async function resolveSubCommand<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
rawArgs: string[],
parent?: CommandDef<T>,
): Promise<[CommandDef<T>, CommandDef<T>?]> {
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const cmdArgs = await resolveValue(cmd.args || {});
const subCommandArgIndex = findSubCommandIndex(rawArgs, cmdArgs);
const subCommandName = rawArgs[subCommandArgIndex]!;
const subCommand = await _findSubCommand(subCommands, subCommandName);
if (subCommand) {
return resolveSubCommand(subCommand, rawArgs.slice(subCommandArgIndex + 1), cmd);
}
}
return [cmd, parent];
}
// --- internal ---
async function _findSubCommand(
subCommands: SubCommandsDef,
name: string,
): Promise<CommandDef<any> | undefined> {
// Direct key match (fast path β no resolution needed)
if (name in subCommands) {
return resolveValue(subCommands[name]);
}
// Alias lookup (resolves subcommands to check meta.alias)
for (const sub of Object.values(subCommands)) {
const resolved = await resolveValue(sub);
const meta = await resolveValue(resolved?.meta);
if (meta?.alias) {
const aliases = toArray(meta.alias);
if (aliases.includes(name)) {
return resolved;
}
}
}
}
function findSubCommandIndex(rawArgs: string[], argsDef: ArgsDef): number {
for (let i = 0; i < rawArgs.length; i++) {
const arg = rawArgs[i]!;
if (arg === "--") return -1;
if (arg.startsWith("-")) {
if (!arg.includes("=") && _isValueFlag(arg, argsDef)) {
i++; // skip the flag's value
}
continue;
}
return i;
}
return -1;
}
function _isValueFlag(flag: string, argsDef: ArgsDef): boolean {
const name = flag.replace(/^-{1,2}/, "");
const normalized = camelCase(name);
for (const [key, def] of Object.entries(argsDef)) {
if (def.type !== "string" && def.type !== "enum") continue;
if (normalized === camelCase(key)) return true;
const aliases = Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : [];
if (aliases.includes(name)) return true;
}
return false;
}