forked from yargs/yargs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
completion.ts
365 lines (326 loc) · 11 KB
/
completion.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
import {CommandInstance, isCommandBuilderCallback} from './command.js';
import {PlatformShim, assertNotStrictEqual} from './typings/common-types.js';
import * as templates from './completion-templates.js';
import {isPromise} from './utils/is-promise.js';
import {parseCommand} from './parse-command.js';
import {UsageInstance} from './usage.js';
import {YargsInstance} from './yargs-factory.js';
import {Arguments, DetailedArguments} from './typings/yargs-parser-types.js';
// add bash completions to your
// yargs-powered applications.
type CompletionCallback = (
err: Error | null,
completions: string[] | undefined
) => void;
/** Instance of the completion module. */
export interface CompletionInstance {
completionKey: string;
generateCompletionScript($0: string, cmd: string): string;
getCompletion(
args: string[],
done: (err: Error | null, completions: string[] | undefined) => void
): any;
registerFunction(fn: CompletionFunction): void;
setParsed(parsed: DetailedArguments): void;
}
export class Completion implements CompletionInstance {
completionKey = 'get-yargs-completions';
private aliases: DetailedArguments['aliases'] | null = null;
private customCompletionFunction: CompletionFunction | null = null;
private readonly zshShell: boolean;
constructor(
private readonly yargs: YargsInstance,
private readonly usage: UsageInstance,
private readonly command: CommandInstance,
private readonly shim: PlatformShim
) {
this.zshShell =
(this.shim.getEnv('SHELL')?.includes('zsh') ||
this.shim.getEnv('ZSH_NAME')?.includes('zsh')) ??
false;
}
private defaultCompletion(
args: string[],
argv: Arguments,
current: string,
done: CompletionCallback
): Arguments | void {
const handlers = this.command.getCommandHandlers();
for (let i = 0, ii = args.length; i < ii; ++i) {
if (handlers[args[i]] && handlers[args[i]].builder) {
const builder = handlers[args[i]].builder;
if (isCommandBuilderCallback(builder)) {
const y = this.yargs.getInternalMethods().reset();
builder(y, true);
return y.argv;
}
}
}
const completions: string[] = [];
this.commandCompletions(completions, args, current);
this.optionCompletions(completions, args, argv, current);
this.choicesCompletions(completions, args, argv, current);
done(null, completions);
}
// Default completions for commands
private commandCompletions(
completions: string[],
args: string[],
current: string
) {
const parentCommands = this.yargs
.getInternalMethods()
.getContext().commands;
if (
!current.match(/^-/) &&
parentCommands[parentCommands.length - 1] !== current &&
!this.previousArgHasChoices(args)
) {
this.usage.getCommands().forEach(usageCommand => {
const commandName = parseCommand(usageCommand[0]).cmd;
if (args.indexOf(commandName) === -1) {
if (!this.zshShell) {
completions.push(commandName);
} else {
const desc = usageCommand[1] || '';
completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
}
}
});
}
}
// Default completions for - and -- options
private optionCompletions(
completions: string[],
args: string[],
argv: Arguments,
current: string
) {
if (
(current.match(/^-/) || (current === '' && completions.length === 0)) &&
!this.previousArgHasChoices(args)
) {
const options = this.yargs.getOptions();
const positionalKeys =
this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
Object.keys(options.key).forEach(key => {
const negable =
!!options.configuration['boolean-negation'] &&
options.boolean.includes(key);
const isPositionalKey = positionalKeys.includes(key);
// If the key is not positional and its aliases aren't in 'args', add the key to 'completions'
if (
!isPositionalKey &&
!this.argsContainKey(args, argv, key, negable)
) {
this.completeOptionKey(key, completions, current);
if (negable && !!options.default[key])
this.completeOptionKey(`no-${key}`, completions, current);
}
});
}
}
private choicesCompletions(
completions: string[],
args: string[],
argv: Arguments,
current: string
) {
if (this.previousArgHasChoices(args)) {
const choices = this.getPreviousArgChoices(args);
if (choices && choices.length > 0) {
completions.push(...choices);
}
}
}
private getPreviousArgChoices(args: string[]): string[] | void {
if (args.length < 1) return; // no args
let previousArg = args[args.length - 1];
let filter = '';
// use second to last argument if the last one is not an option starting with --
if (!previousArg.startsWith('-') && args.length > 1) {
filter = previousArg; // use last arg as filter for choices
previousArg = args[args.length - 2];
}
if (!previousArg.startsWith('-')) return; // still no valid arg, abort
const previousArgKey = previousArg.replace(/^-+/, '');
const options = this.yargs.getOptions();
const possibleAliases = [
previousArgKey,
...(this.yargs.getAliases()[previousArgKey] || []),
];
let choices: string[] | undefined;
// Find choices across all possible aliases
for (const possibleAlias of possibleAliases) {
if (
Object.prototype.hasOwnProperty.call(options.key, possibleAlias) &&
Array.isArray(options.choices[possibleAlias])
) {
choices = options.choices[possibleAlias];
break;
}
}
if (choices) {
return choices.filter(choice => !filter || choice.startsWith(filter));
}
}
private previousArgHasChoices(args: string[]): boolean {
const choices = this.getPreviousArgChoices(args);
return choices !== undefined && choices.length > 0;
}
private argsContainKey(
args: string[],
argv: Arguments,
key: string,
negable: boolean
): boolean {
if (args.indexOf(`--${key}`) !== -1) return true;
if (negable && args.indexOf(`--no-${key}`) !== -1) return true;
if (this.aliases) {
// search for aliases in parsed argv
// can't do the same thing for main option names because argv can contain default values
for (const alias of this.aliases[key]) {
if (argv[alias] !== undefined) return true;
}
}
return false;
}
// Add completion for a single - or -- option
private completeOptionKey(
key: string,
completions: string[],
current: string
) {
const descs = this.usage.getDescriptions();
const startsByTwoDashes = (s: string) => /^--/.test(s);
const isShortOption = (s: string) => /^[^0-9]$/.test(s);
const dashes =
!startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
if (!this.zshShell) {
completions.push(dashes + key);
} else {
const desc = descs[key] || '';
completions.push(
dashes +
`${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`
);
}
}
// a custom completion function can be provided
// to completion().
private customCompletion(
args: string[],
argv: Arguments,
current: string,
done: CompletionCallback
) {
assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
if (isSyncCompletionFunction(this.customCompletionFunction)) {
const result = this.customCompletionFunction(current, argv);
// promise based completion function.
if (isPromise(result)) {
return result
.then(list => {
this.shim.process.nextTick(() => {
done(null, list);
});
})
.catch(err => {
this.shim.process.nextTick(() => {
done(err, undefined);
});
});
}
// synchronous completion function.
return done(null, result);
} else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
return (this.customCompletionFunction as FallbackCompletionFunction)(
current,
argv,
(onCompleted = done) =>
this.defaultCompletion(args, argv, current, onCompleted),
completions => {
done(null, completions);
}
);
} else {
return (this.customCompletionFunction as AsyncCompletionFunction)(
current,
argv,
completions => {
done(null, completions);
}
);
}
}
// get a list of completion commands.
// 'args' is the array of strings from the line to be completed
getCompletion(args: string[], done: CompletionCallback): any {
const current = args.length ? args[args.length - 1] : '';
const argv = this.yargs.parse(args, true);
const completionFunction = this.customCompletionFunction
? (argv: Arguments) => this.customCompletion(args, argv, current, done)
: (argv: Arguments) => this.defaultCompletion(args, argv, current, done);
return isPromise(argv)
? argv.then(completionFunction)
: completionFunction(argv);
}
// generate the completion script to add to your .bashrc.
generateCompletionScript($0: string, cmd: string): string {
let script = this.zshShell
? templates.completionZshTemplate
: templates.completionShTemplate;
const name = this.shim.path.basename($0);
// add ./ to applications not yet installed as bin.
if ($0.match(/\.js$/)) $0 = `./${$0}`;
script = script.replace(/{{app_name}}/g, name);
script = script.replace(/{{completion_command}}/g, cmd);
return script.replace(/{{app_path}}/g, $0);
}
// register a function to perform your own custom
// completions. this function can be either
// synchronous or asynchronous.
registerFunction(fn: CompletionFunction) {
this.customCompletionFunction = fn;
}
setParsed(parsed: DetailedArguments) {
this.aliases = parsed.aliases;
}
}
// For backwards compatibility
export function completion(
yargs: YargsInstance,
usage: UsageInstance,
command: CommandInstance,
shim: PlatformShim
): CompletionInstance {
return new Completion(yargs, usage, command, shim);
}
export type CompletionFunction =
| SyncCompletionFunction
| AsyncCompletionFunction
| FallbackCompletionFunction;
interface SyncCompletionFunction {
(current: string, argv: Arguments): string[] | Promise<string[]>;
}
interface AsyncCompletionFunction {
(current: string, argv: Arguments, done: (completions: string[]) => any): any;
}
interface FallbackCompletionFunction {
(
current: string,
argv: Arguments,
completionFilter: (onCompleted?: CompletionCallback) => any,
done: (completions: string[]) => any
): any;
}
function isSyncCompletionFunction(
completionFunction: CompletionFunction
): completionFunction is SyncCompletionFunction {
return completionFunction.length < 3;
}
function isFallbackCompletionFunction(
completionFunction: CompletionFunction
): completionFunction is FallbackCompletionFunction {
return completionFunction.length > 3;
}