-
Notifications
You must be signed in to change notification settings - Fork 1
/
init.ts
247 lines (226 loc) · 6.47 KB
/
init.ts
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// deno-lint-ignore-file no-explicit-any
import { BaseContext, Command, command, CommandConfig } from "./command.ts";
import { Args as ArgsTuple, args, ArgsZodTypes } from "./args.ts";
import { helpFlag } from "./help.ts";
import { flag, Flags, flags, isFlags, walkFlags } from "./flags.ts";
import { z } from "./z.ts";
import { colors } from "./fmt.ts";
import { table } from "./lib/simple-table.ts";
import * as intl from "./intl.ts";
import { writeIterable } from "./lib/write-iterable.ts";
/**
* Initialize a command factory.
*
* @param config - The configuration for the command factory
*/
export function init<
Context extends Record<string, unknown>,
GlobalOpts extends Flags | unknown = unknown,
>(
config: InitConfig<Context, GlobalOpts> = {},
): CommandFactory<Context, GlobalOpts> {
const gOpts = isFlags(config.globalFlags)
? config.globalFlags.merge(helpOpts)
: helpOpts;
walkFlags(gOpts, (flag) => {
flag.__global = true;
});
return {
command<
Args extends
| ArgsTuple
| ArgsZodTypes
| unknown = unknown,
Opts extends Flags | unknown = unknown,
>(
name: string,
options: CommandConfig<
Context & BaseContext,
Args,
Opts
> = {},
): Command<
Context & BaseContext,
Args,
Opts,
GlobalOpts
> {
options = { ...options };
const subCommands = options.commands ? [...options.commands] : undefined;
if (subCommands?.length) {
const helpCommand = command("help", {
short: `Show help for a ${name} command`,
flags: gOpts,
commands: [
command("commands", {
short: `List ${name} commands`,
long: ({ path }) => `
List ${name} commands
Example:
\`\`\`
$ ${path.join(" ")} commands
\`\`\`
`,
flags: gOpts.merge(
flags({
all: flag({
aliases: ["a"],
short: "Show all commands, including hidden ones",
}).boolean().default(false),
}),
),
})
.run(async ({ flags, ctx }) => {
await writeIterable(
(function* listCommands() {
yield colors.bold(`${name} commands`);
const sortedCmds = intl.collate(
options.commands!.filter(
(cmd) => flags.all || !cmd.hidden,
),
{
get(item) {
return item.name;
},
},
);
const rows: string[][] = new Array(sortedCmds.length);
for (let i = 0; i < sortedCmds!.length; i++) {
const cmd = sortedCmds![i];
rows[i] = [cmd.name, cmd.short(ctx as any) ?? ""];
}
for (
const line of table(rows, {
indent: 2,
cellPadding: 2,
})
) {
yield line;
}
yield `\nUse "${
ctx.path.join(" ")
} [command]" for more information about a command.`;
})(),
);
}),
],
args: args().tuple([
z.enum(
subCommands.flatMap((c) => [c.name, ...c.aliases]).concat(
"help",
) as [
string,
...string[],
],
).describe("The command to show help for."),
]).optional(),
})
.run(async ({ args, ctx }) => {
if (!args[0]) {
return writeIterable(command_.help(ctx));
}
const cmd = subCommands.find(
(cmd) =>
cmd.name === args[0] ||
cmd.aliases.includes(args[0] as any),
)!;
await writeIterable(
cmd.help(
{ ...ctx, path: ctx.path.slice(0, -1).concat(cmd.name) } as any,
),
);
});
// @ts-expect-error: all good
subCommands.push(executeWithContext(helpCommand, config));
}
// @ts-expect-error: blah blah
options.flags = options.flags ? options.flags.merge(gOpts) : gOpts;
options.commands = subCommands;
const command_ = executeWithContext(
command(name, options),
config,
);
// @ts-expect-error: all good
return command_;
},
};
}
function executeWithContext(
command: Command<any, any, any>,
config: InitConfig<any, any>,
) {
return {
...command,
execute(
args: string[],
ctx?: any,
) {
const execute = command.execute.bind(this);
const path = ctx?.path ?? emptyArray;
const root = ctx?.root ?? this;
return execute(
args,
{
...(ctx ?? config.ctx),
root,
path: [...path, command.name],
},
);
},
};
}
const emptyArray: string[] = [];
const helpOpts = flags({
help: helpFlag({ short: "Show help for a command" }),
});
export type InitConfig<
Context extends Record<string, unknown>,
GlobalOpts extends Flags | unknown = unknown,
> = {
/**
* The context that will be passed to each command.
*/
ctx?: Context;
/**
* The global options that will be passed to each command.
*/
globalFlags?: GlobalOpts;
};
export type CommandFactory<
Context extends Record<string, unknown>,
GlobalOpts extends Flags | unknown = unknown,
> = {
/**
* Create a CLI command. Commands can be nested to create a tree
* of commands. Each command can have its own set of flags and
* arguments.
*
* @param name - The name of the command
* @param param1 - The command configuration
*/
command<
Args extends
| ArgsTuple
| ArgsZodTypes
| unknown = unknown,
Opts extends Flags | unknown = unknown,
>(
name: string,
config?: CommandConfig<
Context & BaseContext,
Args,
Opts
>,
): Command<
Context & BaseContext,
Args,
Opts,
GlobalOpts
>;
};
export type inferContext<Cmd extends CommandFactory<any, any>> = Cmd extends
CommandFactory<
infer Context,
any
> ? Context & BaseContext
: BaseContext;