-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.ts
More file actions
203 lines (165 loc) · 5.73 KB
/
command.ts
File metadata and controls
203 lines (165 loc) · 5.73 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import type { ParseArgsOptionDescriptor } from "node:util";
import { parseArgs } from "node:util";
import { dedent, formatTable } from "./string";
export type CommandConfig = {
name: string;
description: string;
sections?: Record<string, string>;
positionals?: Record<string, { description: string; required?: boolean }>;
options?: Record<string, ParseArgsOptionDescriptor & { description: string; required?: boolean }>;
};
type CommandHandlerArgs<T extends CommandConfig> = ParseArgsReturnType<T> & {
values: ParseArgsRequiredValues<T>;
};
type ParseArgsReturnType<T extends CommandConfig> = ReturnType<
typeof parseArgs<T & { allowPositionals: T["positionals"] extends undefined ? false : true }>
>;
type ParseArgsRequiredValues<T extends CommandConfig> = {
[P in keyof T["options"] as NonNullable<NonNullable<T["options"]>[P]>["required"] extends true
? P
: never]: P extends keyof ParseArgsReturnType<T>["values"]
? NonNullable<ParseArgsReturnType<T>["values"][P]>
: never;
};
export function createCommand<T extends CommandConfig>(
config: T,
handler: (args: CommandHandlerArgs<T>) => Promise<void>,
): () => Promise<void> {
return async function () {
const { positionals = {}, options = {} } = config;
const depth = config.name.split(" ").length;
const args = process.argv.slice(1 + depth);
const allowPositionals = Object.keys(positionals).length > 0;
const result = parseArgs({
args,
options: {
...options,
help: { type: "boolean", short: "h" },
},
allowPositionals,
strict: true,
});
if (result.values.help) {
console.info(buildCommandHelp(config));
return;
}
for (const [index, [name, config]] of Object.entries(positionals).entries()) {
if (config.required && !result.positionals[index]) {
throw new CommandError(`Missing required argument: <${name}>`);
}
}
for (const [name, config] of Object.entries(options)) {
if (config.required && !(name in result.values)) {
throw new CommandError(`Missing required option: --${name}`);
}
}
await handler(result as CommandHandlerArgs<T>);
};
}
function buildCommandHelp(config: CommandConfig): string {
const { description, sections, positionals = {}, options } = config;
const positionalNames = Object.keys(positionals);
const lines = [dedent(description)];
lines.push("");
lines.push("USAGE");
let usage = ` ${config.name}`;
if (positionalNames.length > 0) {
usage += " " + positionalNames.map((positionalName) => `<${positionalName}>`).join(" ");
}
usage += " [options]";
lines.push(usage);
if (positionalNames.length > 0) {
lines.push("");
lines.push("ARGUMENTS");
const rows: string[][] = [];
for (const positionalName in positionals) {
const positional = positionals[positionalName];
const description = positional.description + (positional.required ? " (required)" : "");
rows.push([` <${positionalName}>`, description]);
}
lines.push(formatTable(rows));
}
lines.push("");
lines.push("OPTIONS");
const optionEntries: { left: string; description: string }[] = [];
if (options) {
const optionNames = Object.keys(options);
for (const optionName of optionNames) {
const option = options[optionName];
const shortPart = option.short ? `-${option.short}, ` : " ";
const typeSuffix = option.type === "string" ? " string" : "";
const left = `${shortPart}--${optionName}${typeSuffix}`;
const description = option.description + (option.required ? " (required)" : "");
optionEntries.push({ left, description });
}
}
optionEntries.push({ left: "-h, --help", description: "Show help for command" });
const optionRows = optionEntries.map((entry) => [` ${entry.left}`, entry.description]);
lines.push(formatTable(optionRows));
if (sections) {
for (const sectionName in sections) {
const content = dedent(sections[sectionName]);
lines.push("");
lines.push(sectionName);
for (const line of content.split("\n")) {
lines.push(line ? ` ${line}` : "");
}
}
}
lines.push("");
lines.push("LEARN MORE");
const bin = config.name.split(" ")[0];
lines.push(` Use \`${bin} <command> --help\` for more information about a command.`);
return lines.join("\n");
}
type CreateCommandRouterConfig = {
name: string;
description: string;
commands: Record<string, RouterCommand>;
};
type RouterCommand = { handler: () => Promise<void>; description: string };
export function createCommandRouter(config: CreateCommandRouterConfig): () => Promise<void> {
const { name, description, commands } = config;
const depth = name.split(" ").length;
return async function () {
const args = process.argv.slice(1 + depth);
const {
positionals: [subcommand],
} = parseArgs({
args,
options: { help: { type: "boolean", short: "h" } },
allowPositionals: true,
strict: false,
});
const entry = subcommand ? config.commands[subcommand] : undefined;
if (entry) {
await entry.handler();
return;
}
if (subcommand) {
throw new CommandError(`Unknown command: ${subcommand}`);
}
console.info(buildRouterHelp({ name, description, commands }));
};
}
function buildRouterHelp(config: CreateCommandRouterConfig): string {
const { name, description, commands } = config;
const lines = [description];
lines.push("");
lines.push("USAGE");
lines.push(` ${name} <command> [options]`);
lines.push("");
lines.push("COMMANDS");
const commandRows = Object.entries(commands).map(([name, cmd]) => [` ${name}`, cmd.description]);
lines.push(formatTable(commandRows));
lines.push("");
lines.push("OPTIONS");
lines.push(" -h, --help Show help for command");
lines.push("");
lines.push("LEARN MORE");
lines.push(` Use \`${name} <command> --help\` for more information about a command.`);
return lines.join("\n");
}
export class CommandError extends Error {
name = "CommandError";
}