-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
_zsh_completions_generator.ts
375 lines (321 loc) 路 10.7 KB
/
_zsh_completions_generator.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import { MissingCommandNameCompletionsError } from "../_errors.ts";
import { getDescription } from "../_utils.ts";
import type { Command } from "../command.ts";
import type { Argument, Option, TypeDef } from "../types.ts";
import { FileType } from "../types/file.ts";
interface ICompletionAction {
arg: Argument;
label: string;
name: string;
cmd: string;
}
/** Generates zsh completions script. */
export class ZshCompletionsGenerator {
private actions: Map<string, ICompletionAction> = new Map();
/** Generates zsh completions script for given command. */
public static generate(name: string, cmd: Command) {
if (!name || name === "COMMAND") {
throw new MissingCommandNameCompletionsError("zsh");
}
return new ZshCompletionsGenerator(name, cmd).generate();
}
private constructor(
protected name: string,
protected cmd: Command,
) {}
/** Generates zsh completions code. */
private generate(): string {
const path = this.cmd.getPath(this.name);
const version: string | undefined = this.cmd.getVersion()
? ` v${this.cmd.getVersion()}`
: "";
return `#!/usr/bin/env zsh
# zsh completion support for ${path}${version}
autoload -U is-at-least
# shellcheck disable=SC2154
(( $+functions[__${replaceSpecialChars(this.name)}_complete] )) ||
function __${replaceSpecialChars(this.name)}_complete {
local name="$1"; shift
local action="$1"; shift
integer ret=1
local -a values
local expl lines
_tags "$name"
while _tags; do
if _requested "$name"; then
# shellcheck disable=SC2034
lines="$(${this.name} completions complete "\${action}" "\${@}")"
values=("\${(ps:\\n:)lines}")
if (( \${#values[@]} )); then
while _next_label "$name" expl "$action"; do
compadd -S '' "\${expl[@]}" "\${values[@]}"
done
fi
fi
done
}
${this.generateCompletions(this.name, this.cmd).trim()}
# _${replaceSpecialChars(path)} "\${@}"
compdef _${replaceSpecialChars(path)} ${path}`;
}
/** Generates zsh completions method for given command and child commands. */
private generateCompletions(
name: string,
command: Command,
path = "",
): string {
if (
!command.hasCommands(false) && !command.hasOptions(false) &&
!command.hasArguments()
) {
return "";
}
path = (path ? path + " " : "") + name;
return `# shellcheck disable=SC2154
(( $+functions[_${replaceSpecialChars(path)}] )) ||
function _${replaceSpecialChars(path)}() {` +
(!command.getParent()
? `
local state`
: "") +
this.generateCommandCompletions(command, path) +
this.generateSubCommandCompletions(command, path) +
this.generateArgumentCompletions(command, path) +
this.generateActions(command) +
`\n}\n\n` +
command.getCommands(false)
.filter((subCommand: Command) => subCommand !== command)
.map((subCommand: Command) =>
this.generateCompletions(subCommand.getName(), subCommand, path)
)
.join("");
}
private generateCommandCompletions(command: Command, path: string): string {
const commands = command.getCommands(false);
let completions: string = commands
.map((subCommand: Command) =>
`'${subCommand.getName().replace(/:/g, "\\:")}:${
subCommand.getShortDescription()
// escape single quotes
.replace(/'/g, "'\"'\"'")
}'`
)
.join("\n ");
if (completions) {
completions = `
local -a commands
# shellcheck disable=SC2034
commands=(
${completions}
)
_describe 'command' commands`;
}
// only complete first argument, rest arguments are completed with _arguments.
if (command.hasArguments()) {
const completionsPath: string = path.split(" ").slice(1).join(" ");
const arg: Argument = command.getArguments()[0];
const action = this.addAction(arg, completionsPath);
if (action && command.getCompletion(arg.action)) {
completions += `\n __${
replaceSpecialChars(this.name)
}_complete ${action.arg.name} ${action.arg.action} ${action.cmd}`;
}
}
if (command.hasArguments() || command.hasCommands(false)) {
completions = `\n\n function _commands() {${completions}\n }`;
}
return completions;
}
private generateSubCommandCompletions(
command: Command,
path: string,
): string {
if (command.hasCommands(false)) {
const actions: string = command
.getCommands(false)
.map((command: Command) => {
const aliases = [command.getName(), ...command.getAliases()]
.join("|");
const action = replaceSpecialChars(path + " " + command.getName());
return `${aliases}) _${action} ;;`;
})
.join("\n ");
return `\n
function _command_args() {
case "\${words[1]}" in\n ${actions}\n esac
}`;
}
return "";
}
private generateArgumentCompletions(command: Command, path: string): string {
/* clear actions from previously parsed command. */
this.actions.clear();
const options: string[] = this.generateOptions(command, path);
let argIndex = 0;
// @TODO: add stop early option: -A "-*"
// http://zsh.sourceforge.net/Doc/Release/Completion-System.html
let argsCommand = "\n\n _arguments -w -s -S -C";
if (command.hasOptions()) {
argsCommand += ` \\\n ${options.join(" \\\n ")}`;
}
if (command.hasArguments() || command.hasCommands(false)) {
argsCommand += ` \\\n '${++argIndex}:command:_commands'`;
const args: string[] = [];
// first argument is completed together with commands.
for (const arg of command.getArguments().slice(1)) {
const type = command.getType(arg.type);
if (type && type.handler instanceof FileType) {
const fileCompletions = this.getFileCompletions(type);
if (arg.variadic) {
argIndex++;
for (let i = 0; i < 5; i++) {
args.push(
`${argIndex + i}${
arg.optional ? "::" : ":"
}${arg.name}:${fileCompletions}`,
);
}
} else {
args.push(
`${++argIndex}${
arg.optional ? "::" : ":"
}${arg.name}:${fileCompletions}`,
);
}
} else {
const completionsPath: string = path.split(" ").slice(1).join(" ");
const action = this.addAction(arg, completionsPath);
args.push(
`${++argIndex}${
arg.optional ? "::" : ":"
}${arg.name}:->${action.name}`,
);
}
}
argsCommand += args.map((arg: string) => `\\\n '${arg}'`).join("");
if (command.hasCommands(false)) {
argsCommand += ` \\\n '*::sub command:->command_args'`;
}
}
return argsCommand;
}
private generateOptions(command: Command, path: string) {
const options: string[] = [];
const cmdArgs: string[] = path.split(" ");
const _baseName: string = cmdArgs.shift() as string;
const completionsPath: string = cmdArgs.join(" ");
const excludedFlags: string[] = command.getOptions(false)
.map((option) => option.standalone ? option.flags : false)
.flat()
.filter((flag) => typeof flag === "string") as string[];
for (const option of command.getOptions(false)) {
options.push(
this.generateOption(command, option, completionsPath, excludedFlags),
);
}
return options;
}
private generateOption(
command: Command,
option: Option,
completionsPath: string,
excludedOptions: string[],
): string {
let args = "";
for (const arg of option.args) {
const type = command.getType(arg.type);
const optionalValue = arg.optional ? "::" : ":";
if (type && type.handler instanceof FileType) {
const fileCompletions = this.getFileCompletions(type);
args += `${optionalValue}${arg.name}:${fileCompletions}`;
} else {
const action = this.addAction(arg, completionsPath);
args += `${optionalValue}${arg.name}:->${action.name}`;
}
}
const description: string = getDescription(option.description, true)
// escape brackets and quotes
.replace(/\[/g, "\\[")
.replace(/]/g, "\\]")
.replace(/"/g, '\\"')
.replace(/'/g, "'\"'\"'");
const collect: string = option.collect ? "*" : "";
const equalsSign = option.equalsSign ? "=" : "";
const flags = option.flags.map((flag) => `${flag}${equalsSign}`);
let result = "";
if (option.standalone) {
result += "'(- *)'";
} else {
const excludedFlags = [...excludedOptions];
if (option.conflicts?.length) {
excludedFlags.push(
...option.conflicts.map((opt) => "--" + opt.replace(/^--/, "")),
);
}
if (!option.collect) {
excludedFlags.push(...option.flags);
}
if (excludedFlags.length) {
result += `'(${excludedFlags.join(" ")})'`;
}
}
if (collect || flags.length > 1) {
result += `{${collect}${flags.join(",")}}`;
} else {
result += `${flags.join(",")}`;
}
return `${result}'[${description}]${args}'`;
}
private getFileCompletions(type: TypeDef) {
if (!(type.handler instanceof FileType)) {
return "";
}
return "_files";
// const fileOpts = type.handler.getOptions();
// let fileCompletions = "_files";
// if (fileOpts.dirsOnly) {
// fileCompletions += " -/";
// }
// if (fileOpts.pattern) {
// fileCompletions += ' -g "' + fileOpts.pattern + '"';
// }
// if (fileOpts.ignore) {
// fileCompletions += " -F " + fileOpts.ignore;
// }
// return fileCompletions;
}
private addAction(arg: Argument, cmd: string): ICompletionAction {
const action = `${arg.name}-${arg.action}`;
if (!this.actions.has(action)) {
this.actions.set(action, {
arg: arg,
label: `${arg.name}: ${arg.action}`,
name: action,
cmd,
});
}
return this.actions.get(action) as ICompletionAction;
}
private generateActions(command: Command): string {
let actions: string[] = [];
if (this.actions.size) {
actions = Array
.from(this.actions)
.map(([name, action]) =>
`${name}) __${
replaceSpecialChars(this.name)
}_complete ${action.arg.name} ${action.arg.action} ${action.cmd} ;;`
);
}
if (command.hasCommands(false)) {
actions.unshift(`command_args) _command_args ;;`);
}
if (actions.length) {
return `\n\n case "$state" in\n ${actions.join("\n ")}\n esac`;
}
return "";
}
}
function replaceSpecialChars(str: string): string {
return str.replace(/[^a-zA-Z0-9]/g, "_");
}