Skip to content

Commit

Permalink
fix(completion): support for default flags
Browse files Browse the repository at this point in the history
  • Loading branch information
zuozp8 committed Apr 25, 2022
1 parent 6192990 commit db35423
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 7 deletions.
13 changes: 6 additions & 7 deletions lib/completion.ts
Expand Up @@ -128,7 +128,7 @@ export class Completion implements CompletionInstance {
if (
!isPositionalKey &&
!options.hiddenOptions.includes(key) &&
!this.argsContainKey(args, argv, key, negable)
!this.argsContainKey(args, key, negable)
) {
this.completeOptionKey(key, completions, current);
if (negable && !!options.default[key])
Expand Down Expand Up @@ -229,17 +229,16 @@ export class Completion implements CompletionInstance {

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;
const argsContains = (s: string) =>
args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1;
if (argsContains(key)) return true;
if (negable && argsContains(`no-${key}`)) 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;
if (argsContains(alias)) return true;
}
}
return false;
Expand Down
44 changes: 44 additions & 0 deletions test/completion.cjs
Expand Up @@ -163,6 +163,50 @@ describe('Completion', () => {
r.logs.should.include('--bar');
});

it('includes flags that have default', () => {
const r = checkUsage(
() =>
yargs([
'./completion',
'--get-yargs-completions',
'--used',
'--no-usedwithnegation',
'-x',
'',
])
.help(false)
.version(false)
.options({
used: {type: 'boolean', default: true},
usedwithnegation: {type: 'boolean', default: true},
usedwithalias: {
type: 'boolean',
alias: ['x', 'y'],
default: true,
},
somebool: {type: 'boolean', default: false},
somebool2: {type: 'boolean', default: true},
somestringwithalias: {
type: 'string',
alias: 's',
default: 'foo',
},
})
.help(false)
.parserConfiguration({'boolean-negation': true}).argv
);

r.logs
.sort()
.should.deep.eq([
'--no-somebool2',
'--somebool',
'--somebool2',
'--somestringwithalias',
'-s',
]);
});

it('completes options for the correct command', () => {
process.env.SHELL = '/bin/bash';
const r = checkUsage(
Expand Down

0 comments on commit db35423

Please sign in to comment.