Skip to content

Commit

Permalink
for non-multiple defaultOptions, the first parsed value is now taken …
Browse files Browse the repository at this point in the history
…- not the last
  • Loading branch information
75lb committed Jan 28, 2017
1 parent 8f2ce47 commit 279cc83
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
14 changes: 13 additions & 1 deletion lib/output.js
Expand Up @@ -37,7 +37,19 @@ class Output {
: value

/* lookup the definition.. if no optionArg (--option) was supplied, use the defaultOption */
const def = t.isDefined(optionArg) ? this.definitions.get(optionArg) : this.definitions.getDefault()
let def
if (t.isDefined(optionArg)) {
def = this.definitions.get(optionArg)
} else {
def = this.definitions.getDefault()
if (def) {
/* if it's not a `multiple` and the defaultOption has already been set, move on */
if (!def.multiple && t.isDefined(this.output[def.name])) {
if (t.isDefined(value)) this.unknown.push(value)
return true
}
}
}

/* if there's no definition or defaultOption, do nothing and continue */
if (!def) {
Expand Down
26 changes: 25 additions & 1 deletion test/default-option.js
Expand Up @@ -11,7 +11,7 @@ runner.test('defaultOption: string', function () {
]
const argv = [ 'file1', 'file2' ]
a.deepStrictEqual(commandLineArgs(optionDefinitions, { argv }), {
files: 'file2'
files: 'file1'
})
})

Expand Down Expand Up @@ -73,3 +73,27 @@ runner.test('defaultOption: floating args present but no defaultOption', functio
{ one: true }
)
})

runner.test('defaultOption: non-multiple should take first value', function () {
const optionDefinitions = [
{ name: 'file', defaultOption: true }
]
const argv = [ 'file1', 'file2' ]
a.deepStrictEqual(commandLineArgs(optionDefinitions, { argv }), {
file: 'file1'
})
})

runner.test('defaultOption: non-multiple should take first value 2', function () {
const optionDefinitions = [
{ name: 'file', defaultOption: true },
{ name: 'one', type: Boolean },
{ name: 'two', type: Boolean }
]
const argv = [ '--two', 'file1', '--one', 'file2' ]
a.deepStrictEqual(commandLineArgs(optionDefinitions, { argv }), {
file: 'file1',
two: true,
one: true
})
})
16 changes: 16 additions & 0 deletions test/unknown-options.js
Expand Up @@ -58,3 +58,19 @@ runner.test('unknown option: multiple', function () {
_unknown: [ 'file1', '-t', '--two', '3', 'file3', '-a', '-b' ]
})
})

runner.test('unknown options: rejected defaultOption values end up in _unknown', function () {
const definitions = [
{ name: 'foo', type: String },
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'libs', type: String, defaultOption: true }
]
const argv = [ '--foo', 'bar', '-v', 'libfn', '--libarg', 'val1', '-r' ]
const options = commandLineArgs(definitions, { argv, partial: true })
a.deepStrictEqual(options, {
foo: 'bar',
verbose: true,
libs: 'libfn',
_unknown: [ '--libarg', 'val1', '-r' ]
})
})

0 comments on commit 279cc83

Please sign in to comment.