Skip to content

Commit

Permalink
feat(completion): positional arguments completion (#2090)
Browse files Browse the repository at this point in the history
  • Loading branch information
zuozp8 committed Jan 24, 2022
1 parent c066164 commit 00e4ebb
Show file tree
Hide file tree
Showing 2 changed files with 497 additions and 397 deletions.
35 changes: 33 additions & 2 deletions lib/completion.ts
Expand Up @@ -32,6 +32,7 @@ export class Completion implements CompletionInstance {

private aliases: DetailedArguments['aliases'] | null = null;
private customCompletionFunction: CompletionFunction | null = null;
private indexAfterLastReset = 0;
private readonly zshShell: boolean;

constructor(
Expand All @@ -57,6 +58,7 @@ export class Completion implements CompletionInstance {
if (handlers[args[i]] && handlers[args[i]].builder) {
const builder = handlers[args[i]].builder;
if (isCommandBuilderCallback(builder)) {
this.indexAfterLastReset = i + 1;
const y = this.yargs.getInternalMethods().reset();
builder(y, true);
return y.argv;
Expand All @@ -68,7 +70,8 @@ export class Completion implements CompletionInstance {

this.commandCompletions(completions, args, current);
this.optionCompletions(completions, args, argv, current);
this.choicesCompletions(completions, args, argv, current);
this.choicesFromOptionsCompletions(completions, args, argv, current);
this.choicesFromPositionalsCompletions(completions, args, argv, current);
done(null, completions);
}

Expand Down Expand Up @@ -134,7 +137,7 @@ export class Completion implements CompletionInstance {
}
}

private choicesCompletions(
private choicesFromOptionsCompletions(
completions: string[],
args: string[],
argv: Arguments,
Expand All @@ -148,6 +151,34 @@ export class Completion implements CompletionInstance {
}
}

private choicesFromPositionalsCompletions(
completions: string[],
args: string[],
argv: Arguments,
current: string
) {
const positionalKeys =
this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
const offset = Math.max(
this.indexAfterLastReset,
this.yargs.getInternalMethods().getContext().commands.length +
/* name of the script is first param */ 1
);
const positionalValues = argv._.slice(offset);

const positionalKey = positionalKeys[positionalValues.length - 1];

if (!positionalKey) {
return;
}
const choices = this.yargs.getOptions().choices[positionalKey] || [];
for (const choice of choices) {
if (choice.startsWith(current)) {
completions.push(choice);
}
}
}

private getPreviousArgChoices(args: string[]): string[] | void {
if (args.length < 1) return; // no args
let previousArg = args[args.length - 1];
Expand Down

0 comments on commit 00e4ebb

Please sign in to comment.