Skip to content

Commit

Permalink
fix: only run coercion functions once, despite aliases. (yargs#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike111177 committed Sep 6, 2017
1 parent 00bde7d commit e986482
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
20 changes: 14 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -513,14 +513,22 @@ 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[key] === undefined) {
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
}
}
} else { // If we already coerced this option via one of its aliases
argv[key] = applied[key]
}
})
}
Expand Down
19 changes: 19 additions & 0 deletions test/yargs-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -2429,6 +2429,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 runcount
}
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 e986482

Please sign in to comment.