Skip to content

Commit

Permalink
feat: complete short options with a single dash (#1507)
Browse files Browse the repository at this point in the history
  • Loading branch information
mleguen authored and bcoe committed Jan 2, 2020
1 parent f9a18bf commit 99011ab
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
7 changes: 5 additions & 2 deletions lib/completion.js
Expand Up @@ -81,11 +81,14 @@ module.exports = function completion (yargs, usage, command) {
const keyAndAliases = [key].concat(aliases[key] || [])
const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1)
if (notInArgs) {
const startsByTwoDashes = s => /^--/.test(s)
const isShortOption = s => /^[^0-9]$/.test(s)
const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'
if (!zshShell) {
completions.push(`--${key}`)
completions.push(dashes + key)
} else {
const desc = descs[key] || ''
completions.push(`--${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`)
completions.push(dashes + `${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`)
}
}
})
Expand Down
38 changes: 37 additions & 1 deletion test/completion.js
Expand Up @@ -58,6 +58,42 @@ describe('Completion', () => {
r.logs.should.not.include('--foo')
})

it('completes short options with a single dash when the user did not already enter two dashes', () => {
const r = checkUsage(() => yargs(['./completion', '--get-yargs-completions', './completion', ''])
.options({
f: { describe: 'f option', alias: 'foo' }
})
.argv
)

r.logs.should.include('-f')
r.logs.should.not.include('--f')
})

it('completes short options with two dashes when the user already entered two dashes', () => {
const r = checkUsage(() => yargs(['./completion', '--get-yargs-completions', './completion', '--'])
.options({
f: { describe: 'f option', alias: 'foo' }
})
.argv
)

r.logs.should.include('--f')
r.logs.should.not.include('-f')
})

it('completes single digit options with two dashes', () => {
const r = checkUsage(() => yargs(['./completion', '--get-yargs-completions', './completion', ''])
.options({
1: { describe: '1 option', alias: 'one' }
})
.argv
)

r.logs.should.include('--1')
r.logs.should.not.include('-1')
})

it('completes options for the correct command', () => {
process.env.SHELL = '/bin/bash'
const r = checkUsage(() => yargs(['./completion', '--get-yargs-completions', 'cmd2', '--o'])
Expand Down Expand Up @@ -98,7 +134,7 @@ describe('Completion', () => {
r.logs.should.include('cmd1')
})

it('does not include possitional arguments', function () {
it('does not include positional arguments', function () {
process.env.SHELL = '/bin/bash'
var r = checkUsage(function () {
return yargs(['./completion', '--get-yargs-completions', 'cmd'])
Expand Down

0 comments on commit 99011ab

Please sign in to comment.