Skip to content

Commit

Permalink
fix: only run coercion functions once, despite aliases. (yargs#76) (y…
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike111177 authored and bcoe committed Dec 18, 2017
1 parent f34ead9 commit 507aaef
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
18 changes: 12 additions & 6 deletions index.js
Expand Up @@ -523,13 +523,19 @@ function parse (args, opts) {

function applyCoercions (argv) {
var coerce
var applied = {}
Object.keys(argv).forEach(function (key) {
coerce = checkAllAliases(key, flags.coercions)
if (typeof coerce === 'function') {
try {
argv[key] = coerce(argv[key])
} catch (err) {
error = err
if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
coerce = checkAllAliases(key, flags.coercions)
if (typeof coerce === 'function') {
try {
var value = coerce(argv[key])
;([].concat(flags.aliases[key] || [], key)).forEach(ali => {
applied[ali] = argv[ali] = value
})
} catch (err) {
error = err
}
}
}
})
Expand Down
19 changes: 19 additions & 0 deletions test/yargs-parser.js
Expand Up @@ -2442,6 +2442,25 @@ describe('yargs-parser', function () {
})
parsed.error.message.should.equal('foo is array: true')
})

// see: https://github.com/yargs/yargs-parser/issues/76
it('only runs coercion functions once, even with aliases', function () {
var runcount = 0
var func = (arg) => {
runcount++
return undefined
}
parser([ '--foo', 'bar' ], {
alias: {
foo: ['f', 'foo-bar', 'bar'],
b: ['bar']
},
coerce: {
bar: func
}
})
runcount.should.equal(1)
})
})

// see: https://github.com/yargs/yargs-parser/issues/37
Expand Down

0 comments on commit 507aaef

Please sign in to comment.