-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcitty.ts
More file actions
252 lines (225 loc) · 7.14 KB
/
citty.ts
File metadata and controls
252 lines (225 loc) · 7.14 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
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
248
249
250
251
252
import { defineCommand } from 'citty';
import type { ArgDef } from 'citty';
import * as zsh from './zsh';
import * as bash from './bash';
import * as fish from './fish';
import * as powershell from './powershell';
import type {
ArgsDef,
CommandDef,
PositionalArgDef,
SubCommandsDef,
} from 'citty';
import { generateFigSpec } from './fig';
import { assertDoubleDashes } from './shared';
import type { CompletionConfig } from './shared';
import t, { type RootCommand } from './t';
function quoteIfNeeded(path: string) {
return path.includes(' ') ? `'${path}'` : path;
}
const execPath = process.execPath;
const processArgs = process.argv.slice(1);
const quotedExecPath = quoteIfNeeded(execPath);
const quotedProcessArgs = processArgs.map(quoteIfNeeded);
const quotedProcessExecArgs = process.execArgv.map(quoteIfNeeded);
const x = `${quotedExecPath} ${quotedProcessExecArgs.join(' ')} ${quotedProcessArgs[0]}`;
function isConfigPositional<T extends ArgsDef>(config: CommandDef<T>) {
return (
config.args &&
Object.values(config.args).some((arg) => arg.type === 'positional')
);
}
async function handleSubCommands(
subCommands: SubCommandsDef,
parentCmd?: string,
completionConfig?: Record<string, CompletionConfig>
) {
for (const [cmd, resolvableConfig] of Object.entries(subCommands)) {
const config = await resolve(resolvableConfig);
const meta = await resolve(config.meta);
const subCommands = await resolve(config.subCommands);
const subCompletionConfig = completionConfig?.[cmd];
if (!meta || typeof meta?.description !== 'string') {
throw new Error('Invalid meta or missing description.');
}
const isPositional = isConfigPositional(config);
const commandName = parentCmd ? `${parentCmd} ${cmd}` : cmd;
const command = t.command(commandName, meta.description);
// Set args for the command if it has positional arguments
if (isPositional && config.args) {
for (const [argName, argConfig] of Object.entries(config.args)) {
const conf = argConfig as ArgDef;
if (conf.type === 'positional') {
const isVariadic = conf.required === false;
const argHandler = subCompletionConfig?.args?.[argName];
if (argHandler) {
command.argument(argName, argHandler, isVariadic);
} else {
command.argument(argName, undefined, isVariadic);
}
}
}
}
// subcommands (recursive)
if (subCommands) {
await handleSubCommands(
subCommands,
commandName,
subCompletionConfig?.subCommands
);
}
// args
if (config.args) {
for (const [argName, argConfig] of Object.entries(config.args)) {
const conf = argConfig as ArgDef;
// alias (if exists)
const shortFlag =
typeof conf === 'object' && 'alias' in conf
? Array.isArray(conf.alias)
? conf.alias[0]
: conf.alias
: undefined;
// option (without -- prefix)
const handler = subCompletionConfig?.options?.[argName];
if (handler) {
// value option (if has custom handler)
if (shortFlag) {
command.option(argName, conf.description ?? '', handler, shortFlag);
} else {
command.option(argName, conf.description ?? '', handler);
}
} else {
// boolean flag (if no custom handler)
if (shortFlag) {
command.option(argName, conf.description ?? '', shortFlag);
} else {
command.option(argName, conf.description ?? '');
}
}
}
}
}
}
export default async function tab<TArgs extends ArgsDef>(
instance: CommandDef<TArgs>,
completionConfig?: CompletionConfig
): Promise<RootCommand> {
const meta = await resolve(instance.meta);
if (!meta) {
throw new Error('Invalid meta.');
}
const name = meta.name;
if (!name) {
throw new Error('Invalid meta or missing name.');
}
const subCommands = await resolve(instance.subCommands);
const isPositional = isConfigPositional(instance);
// args (if has positional arguments)
if (isPositional && instance.args) {
for (const [argName, argConfig] of Object.entries(instance.args)) {
const conf = argConfig as PositionalArgDef;
if (conf.type === 'positional') {
const isVariadic = conf.required === false;
const argHandler = completionConfig?.args?.[argName];
if (argHandler) {
t.argument(argName, argHandler, isVariadic);
} else {
t.argument(argName, undefined, isVariadic);
}
}
}
}
if (subCommands) {
await handleSubCommands(
subCommands,
undefined,
completionConfig?.subCommands
);
}
if (instance.args) {
for (const [argName, argConfig] of Object.entries(instance.args)) {
const conf = argConfig as ArgDef;
const shortFlag =
typeof conf === 'object' && 'alias' in conf
? Array.isArray(conf.alias)
? conf.alias[0]
: conf.alias
: undefined;
const handler = completionConfig?.options?.[argName];
if (handler) {
if (shortFlag) {
t.option(argName, conf.description ?? '', handler, shortFlag);
} else {
t.option(argName, conf.description ?? '', handler);
}
} else {
if (shortFlag) {
t.option(argName, conf.description ?? '', shortFlag);
} else {
t.option(argName, conf.description ?? '');
}
}
}
}
const completeCommand = defineCommand({
meta: {
name: 'complete',
description: 'Generate shell completion scripts',
},
args: {
shell: {
type: 'positional',
description: 'Shell type (zsh, bash, fish, powershell, fig)',
required: false,
},
},
async run(ctx) {
let shell: string | undefined = ctx.rawArgs[0];
if (shell === '--') {
shell = undefined;
}
switch (shell) {
case 'zsh': {
const script = zsh.generate(name, x);
console.log(script);
break;
}
case 'bash': {
const script = bash.generate(name, x);
console.log(script);
break;
}
case 'fish': {
const script = fish.generate(name, x);
console.log(script);
break;
}
case 'powershell': {
const script = powershell.generate(name, x);
console.log(script);
break;
}
case 'fig': {
const spec = await generateFigSpec(instance);
console.log(spec);
break;
}
default: {
assertDoubleDashes(name);
const extra = ctx.rawArgs.slice(ctx.rawArgs.indexOf('--') + 1);
return t.parse(extra);
}
}
},
});
if (!subCommands) {
instance.subCommands = { complete: completeCommand };
} else {
subCommands.complete = completeCommand;
}
return t;
}
type Resolvable<T> = T | Promise<T> | (() => T) | (() => Promise<T>);
async function resolve<T>(resolvable: Resolvable<T>): Promise<T> {
return resolvable instanceof Function ? await resolvable() : await resolvable;
}