Skip to content

Commit

Permalink
feat(completion): completion now better handles aliases, and avoids d…
Browse files Browse the repository at this point in the history
…uplicating keys.
  • Loading branch information
elas7 authored and bcoe committed Apr 5, 2016
1 parent eb6e03f commit 86416c8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/completion.js
Expand Up @@ -14,6 +14,7 @@ module.exports = function (yargs, usage, command) {
var current = process.argv[process.argv.length - 1]
var previous = process.argv.slice(process.argv.indexOf('--' + self.completionKey) + 1)
var argv = yargs.parse(previous)
var aliases = yargs.parsed.aliases

// a custom completion function can be provided
// to completion().
Expand Down Expand Up @@ -57,7 +58,14 @@ module.exports = function (yargs, usage, command) {

if (current.match(/^-/)) {
Object.keys(yargs.getOptions().key).forEach(function (key) {
completions.push('--' + key)
// If the key and its aliases aren't in 'previous', add the key to 'completions'
var keyAndAliases = [key].concat(aliases[key] || [])
var notInPrevious = keyAndAliases.every(function (val) {
return previous.indexOf('--' + val) === -1
})
if (notInPrevious) {
completions.push('--' + key)
}
})
}

Expand Down
30 changes: 30 additions & 0 deletions test/completion.js
Expand Up @@ -38,6 +38,36 @@ describe('Completion', function () {
r.logs.should.not.include('apple')
})

it('avoids repeating already included options', function () {
var r = checkUsage(function () {
return yargs(['--get-yargs-completions'])
.options({
foo: {describe: 'foo option'},
bar: {describe: 'bar option'}
})
.completion()
.argv
}, ['./completion', '--get-yargs-completions', './completion', '--foo', '--'])

r.logs.should.include('--bar')
r.logs.should.not.include('--foo')
})

it('avoids repeating options whose aliases are already included', function () {
var r = checkUsage(function () {
return yargs(['--get-yargs-completions'])
.options({
foo: {describe: 'foo option', alias: 'f'},
bar: {describe: 'bar option'}
})
.completion()
.argv
}, ['./completion', '--get-yargs-completions', './completion', '--f', '--'])

r.logs.should.include('--bar')
r.logs.should.not.include('--foo')
})

it('completes options for a command', function () {
var r = checkUsage(function () {
return yargs(['--get-yargs-completions'])
Expand Down
2 changes: 1 addition & 1 deletion test/integration.js
Expand Up @@ -44,7 +44,7 @@ describe('integration tests', function () {

// see #177
it('allows --help to be completed without returning help message', function (done) {
testCmd('./bin.js', [ '--get-yargs-completions', '--help' ], function (code, stdout) {
testCmd('./bin.js', [ '--get-yargs-completions', '--h' ], function (code, stdout) {
if (code) {
done(new Error('cmd exited with code ' + code))
return
Expand Down

0 comments on commit 86416c8

Please sign in to comment.