Skip to content

Commit

Permalink
fix(completion): don't show positional args choices with option choic…
Browse files Browse the repository at this point in the history
…es (#2148)
  • Loading branch information
alan-agius4 committed Mar 23, 2022
1 parent 0bb49c3 commit b58b5bc
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
17 changes: 12 additions & 5 deletions lib/completion.ts
Expand Up @@ -147,7 +147,7 @@ export class Completion implements CompletionInstance {
if (this.previousArgHasChoices(args)) {
const choices = this.getPreviousArgChoices(args);
if (choices && choices.length > 0) {
completions.push(...choices);
completions.push(...choices.map(c => c.replace(/:/g, '\\:')));
}
}
}
Expand All @@ -158,24 +158,31 @@ export class Completion implements CompletionInstance {
argv: Arguments,
current: string
) {
if (
current === '' &&
completions.length > 0 &&
this.previousArgHasChoices(args)
) {
return;
}

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];

const positionalKey = positionalKeys[argv._.length - offset - 1];
if (!positionalKey) {
return;
}

const choices = this.yargs.getOptions().choices[positionalKey] || [];
for (const choice of choices) {
if (choice.startsWith(current)) {
completions.push(choice);
completions.push(choice.replace(/:/g, '\\:'));
}
}
}
Expand Down
30 changes: 30 additions & 0 deletions test/completion.cjs
Expand Up @@ -426,6 +426,36 @@ describe('Completion', () => {
r.logs.should.include('--amount');
});

it('options choices should not be display with positional choices', () => {
process.env.SHELL = '/bin/bash';
const r = checkUsage(
() =>
yargs([
...firstArguments,
'./completion',
'cmd',
'apple',
'--foo',
'',
])
.help(false)
.version(false)
.command('cmd [fruit]', 'command', subYargs => {
subYargs
.positional('fruit', {choices: ['apple', 'banana', 'pear']})
.options('foo', {
choices: ['bar', 'buz'],
})
.options({amount: {describe: 'amount', type: 'number'}});
}).argv
);

r.logs.should.have.length(2);
r.logs.should.include('bar');
r.logs.should.include('buz');
r.logs.should.not.include('apple');
});

it('completes choices for positional with prefix', () => {
process.env.SHELL = '/bin/bash';
const r = checkUsage(
Expand Down

0 comments on commit b58b5bc

Please sign in to comment.