-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.ts
More file actions
520 lines (458 loc) · 14.7 KB
/
index.ts
File metadata and controls
520 lines (458 loc) · 14.7 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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import * as zsh from './zsh';
import * as bash from './bash';
import * as fish from './fish';
import * as powershell from './powershell';
import { execSync } from 'child_process';
import { Completion as CompletionItem } from './t';
const DEBUG = false;
function debugLog(...args: unknown[]) {
if (DEBUG) {
console.error('[DEBUG]', ...args);
}
}
async function checkCliHasCompletions(
cliName: string,
packageManager: string
): Promise<boolean> {
try {
debugLog(`Checking if ${cliName} has completions via ${packageManager}`);
const command = `${packageManager} ${cliName} complete --`;
const result = execSync(command, {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore'],
timeout: 1000,
});
const hasCompletions = !!result.trim();
debugLog(`${cliName} supports completions: ${hasCompletions}`);
return hasCompletions;
} catch (error) {
debugLog(`Error checking completions for ${cliName}:`, error);
return false;
}
}
async function getCliCompletions(
cliName: string,
packageManager: string,
args: string[]
): Promise<string[]> {
try {
const completeArgs = args.map((arg) =>
arg.includes(' ') ? `"${arg}"` : arg
);
const completeCommand = `${packageManager} ${cliName} complete -- ${completeArgs.join(' ')}`;
debugLog(`Getting completions with command: ${completeCommand}`);
const result = execSync(completeCommand, {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore'],
timeout: 1000,
});
const completions = result.trim().split('\n').filter(Boolean);
debugLog(`Got ${completions.length} completions from ${cliName}`);
return completions;
} catch (error) {
debugLog(`Error getting completions from ${cliName}:`, error);
return [];
}
}
// ShellCompRequestCmd is the name of the hidden command that is used to request
// completion results from the program. It is used by the shell completion scripts.
export const ShellCompRequestCmd: string = '__complete';
// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request
// completion results without their description. It is used by the shell completion scripts.
export const ShellCompNoDescRequestCmd: string = '__completeNoDesc';
// ShellCompDirective is a bit map representing the different behaviors the shell
// can be instructed to have once completions have been provided.
export const ShellCompDirective = {
// ShellCompDirectiveError indicates an error occurred and completions should be ignored.
ShellCompDirectiveError: 1 << 0,
// ShellCompDirectiveNoSpace indicates that the shell should not add a space
// after the completion even if there is a single completion provided.
ShellCompDirectiveNoSpace: 1 << 1,
// ShellCompDirectiveNoFileComp indicates that the shell should not provide
// file completion even when no completion is provided.
ShellCompDirectiveNoFileComp: 1 << 2,
// ShellCompDirectiveFilterFileExt indicates that the provided completions
// should be used as file extension filters.
// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()
// is a shortcut to using this directive explicitly. The BashCompFilenameExt
// annotation can also be used to obtain the same behavior for flags.
ShellCompDirectiveFilterFileExt: 1 << 3,
// ShellCompDirectiveFilterDirs indicates that only directory names should
// be provided in file completion. To request directory names within another
// directory, the returned completions should specify the directory within
// which to search. The BashCompSubdirsInDir annotation can be used to
// obtain the same behavior but only for flags.
ShellCompDirectiveFilterDirs: 1 << 4,
// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
// in which the completions are provided.
ShellCompDirectiveKeepOrder: 1 << 5,
// ===========================================================================
// All directives using iota (or equivalent in Go) should be above this one.
// For internal use.
shellCompDirectiveMaxValue: 1 << 6,
// ShellCompDirectiveDefault indicates to let the shell perform its default
// behavior after completions have been provided.
// This one must be last to avoid messing up the iota count.
ShellCompDirectiveDefault: 0,
};
export type Positional = {
required: boolean;
variadic: boolean;
completion: Handler;
};
type CompletionResult = {
items: CompletionItem[];
suppressDefault: boolean;
};
export type Handler = (
previousArgs: string[],
toComplete: string,
endsWithSpace: boolean
) => CompletionItem[] | Promise<CompletionItem[]>;
type Option = {
description: string;
handler: Handler;
alias?: string;
};
type Command = {
name: string;
description: string;
args: boolean[];
handler: Handler;
options: Map<string, Option>;
parent?: Command;
};
export class Completion {
commands = new Map<string, Command>();
completions: CompletionItem[] = [];
directive = ShellCompDirective.ShellCompDirectiveDefault;
result: CompletionResult = { items: [], suppressDefault: false };
private packageManager: string | null = null;
setPackageManager(packageManager: string) {
this.packageManager = packageManager;
}
// vite <entry> <another> [...files]
// args: [false, false, true], only the last argument can be variadic
addCommand(
name: string,
description: string,
args: boolean[],
handler: Handler,
parent?: string
) {
const key = parent ? `${parent} ${name}` : name;
this.commands.set(key, {
name: key,
description,
args,
handler,
options: new Map(),
parent: parent ? this.commands.get(parent) : undefined,
});
return key;
}
// --port
addOption(
command: string,
option: string,
description: string,
handler: Handler,
alias?: string
) {
const cmd = this.commands.get(command);
if (!cmd) {
throw new Error(`Command ${command} not found.`);
}
cmd.options.set(option, { description, handler, alias });
return option;
}
// TODO: this should be aware of boolean args and stuff
private stripOptions(args: string[]): string[] {
const parts: string[] = [];
let option = false;
for (const k of args) {
if (k.startsWith('-')) {
option = true;
continue;
}
if (option) {
option = false;
continue;
}
parts.push(k);
}
return parts;
}
private matchCommand(args: string[]): [Command, string[]] {
args = this.stripOptions(args);
const parts: string[] = [];
let remaining: string[] = [];
// TODO (43081j): we should probably remove this non-null assertion and
// throw if the `''` command doesn't exist
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
let matched: Command = this.commands.get('')!;
for (let i = 0; i < args.length; i++) {
const k = args[i];
parts.push(k);
const potential = this.commands.get(parts.join(' '));
if (potential) {
matched = potential;
} else {
remaining = args.slice(i, args.length);
break;
}
}
return [matched, remaining];
}
async parse(args: string[]) {
this.result = { items: [], suppressDefault: false };
// TODO: i did not notice this, this should not be handled here at all. package manager completions are something on top of this. just like any other completion system that is going to be built on top of tab.
// Handle package manager completions first
if (this.packageManager && args.length >= 1) {
const potentialCliName = args[0];
const knownCommands = [...this.commands.keys()];
if (!knownCommands.includes(potentialCliName)) {
const hasCompletions = await checkCliHasCompletions(
potentialCliName,
this.packageManager
);
if (hasCompletions) {
const cliArgs = args.slice(1);
const suggestions = await getCliCompletions(
potentialCliName,
this.packageManager,
cliArgs
);
if (suggestions.length > 0) {
this.result.suppressDefault = true;
for (const suggestion of suggestions) {
if (suggestion.startsWith(':')) continue;
if (suggestion.includes('\t')) {
const [value, description] = suggestion.split('\t');
this.result.items.push({ value, description });
} else {
this.result.items.push({ value: suggestion });
}
}
this.completions = this.result.items;
this.complete('');
return;
}
}
}
}
const endsWithSpace = args[args.length - 1] === '';
if (endsWithSpace) {
args.pop();
}
let toComplete = args[args.length - 1] || '';
const previousArgs = args.slice(0, -1);
if (endsWithSpace) {
previousArgs.push(toComplete);
toComplete = '';
}
const [matchedCommand] = this.matchCommand(previousArgs);
const lastPrevArg = previousArgs[previousArgs.length - 1];
// 1. Handle flag/option completion
if (this.shouldCompleteFlags(lastPrevArg, toComplete, endsWithSpace)) {
await this.handleFlagCompletion(
matchedCommand,
previousArgs,
toComplete,
endsWithSpace,
lastPrevArg
);
} else {
// 2. Handle command/subcommand completion
if (this.shouldCompleteCommands(toComplete, endsWithSpace)) {
await this.handleCommandCompletion(previousArgs, toComplete);
}
// 3. Handle positional arguments
if (matchedCommand && matchedCommand.args.length > 0) {
await this.handlePositionalCompletion(
matchedCommand,
previousArgs,
toComplete,
endsWithSpace
);
}
}
this.complete(toComplete);
}
private complete(toComplete: string) {
this.directive = ShellCompDirective.ShellCompDirectiveNoFileComp;
const seen = new Set<string>();
this.completions
.filter((comp) => {
if (seen.has(comp.value)) return false;
seen.add(comp.value);
return true;
})
.filter((comp) => comp.value.startsWith(toComplete))
.forEach((comp) =>
console.log(`${comp.value}\t${comp.description ?? ''}`)
);
console.log(`:${this.directive}`);
}
private shouldCompleteFlags(
lastPrevArg: string | undefined,
toComplete: string,
endsWithSpace: boolean
): boolean {
return (
lastPrevArg?.startsWith('--') ||
lastPrevArg?.startsWith('-') ||
toComplete.startsWith('--') ||
toComplete.startsWith('-')
);
}
private shouldCompleteCommands(
toComplete: string,
endsWithSpace: boolean
): boolean {
return !toComplete.startsWith('-');
}
private async handleFlagCompletion(
command: Command,
previousArgs: string[],
toComplete: string,
endsWithSpace: boolean,
lastPrevArg: string | undefined
) {
// Handle flag value completion
let flagName: string | undefined;
let valueToComplete = toComplete;
if (toComplete.includes('=')) {
// Handle --flag=value or -f=value case
const parts = toComplete.split('=');
flagName = parts[0];
valueToComplete = parts[1] || '';
} else if (lastPrevArg?.startsWith('-')) {
// Handle --flag value or -f value case
flagName = lastPrevArg;
}
if (flagName) {
// Try to find the option by long name or alias
let option = command.options.get(flagName);
if (!option) {
// If not found by direct match, try to find by alias
for (const [name, opt] of command.options) {
if (opt.alias && `-${opt.alias}` === flagName) {
option = opt;
flagName = name; // Use the long name for completion
break;
}
}
}
if (option) {
const suggestions = await option.handler(
previousArgs,
valueToComplete,
endsWithSpace
);
if (toComplete.includes('=')) {
// Reconstruct the full flag=value format
this.completions = suggestions.map((suggestion) => ({
value: `${flagName}=${suggestion.value}`,
description: suggestion.description,
}));
} else {
this.completions.push(...suggestions);
}
}
return;
}
// Handle flag name completion
if (toComplete.startsWith('-')) {
const isShortFlag =
toComplete.startsWith('-') && !toComplete.startsWith('--');
for (const [name, option] of command.options) {
// For short flags (-), only show aliases
if (isShortFlag) {
if (option.alias && `-${option.alias}`.startsWith(toComplete)) {
this.completions.push({
value: `-${option.alias}`,
description: option.description,
});
}
}
// For long flags (--), show the full names
else if (name.startsWith(toComplete)) {
this.completions.push({
value: name,
description: option.description,
});
}
}
}
}
private async handleCommandCompletion(
previousArgs: string[],
toComplete: string
) {
const commandParts = [...previousArgs].filter(Boolean);
for (const [k, command] of this.commands) {
if (k === '') continue;
const parts = k.split(' ');
let match = true;
let i = 0;
while (i < commandParts.length) {
if (parts[i] !== commandParts[i]) {
match = false;
break;
}
i++;
}
if (match && parts[i]?.startsWith(toComplete)) {
this.completions.push({
value: parts[i],
description: command.description,
});
}
}
}
private async handlePositionalCompletion(
command: Command,
previousArgs: string[],
toComplete: string,
endsWithSpace: boolean
) {
const suggestions = await command.handler(
previousArgs,
toComplete,
endsWithSpace
);
this.completions.push(...suggestions);
}
}
export function script(
shell: 'zsh' | 'bash' | 'fish' | 'powershell',
name: string,
x: string
) {
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;
}
default: {
throw new Error(`Unsupported shell: ${shell}`);
}
}
}