Skip to content

Commit 507aaef

Browse files
Mike111177bcoe
authored andcommitted
fix: only run coercion functions once, despite aliases. (#76) (#103)
1 parent f34ead9 commit 507aaef

2 files changed

Lines changed: 31 additions & 6 deletions

File tree

index.js

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -523,13 +523,19 @@ function parse (args, opts) {
523523

524524
function applyCoercions (argv) {
525525
var coerce
526+
var applied = {}
526527
Object.keys(argv).forEach(function (key) {
527-
coerce = checkAllAliases(key, flags.coercions)
528-
if (typeof coerce === 'function') {
529-
try {
530-
argv[key] = coerce(argv[key])
531-
} catch (err) {
532-
error = err
528+
if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
529+
coerce = checkAllAliases(key, flags.coercions)
530+
if (typeof coerce === 'function') {
531+
try {
532+
var value = coerce(argv[key])
533+
;([].concat(flags.aliases[key] || [], key)).forEach(ali => {
534+
applied[ali] = argv[ali] = value
535+
})
536+
} catch (err) {
537+
error = err
538+
}
533539
}
534540
}
535541
})

test/yargs-parser.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2442,6 +2442,25 @@ describe('yargs-parser', function () {
24422442
})
24432443
parsed.error.message.should.equal('foo is array: true')
24442444
})
2445+
2446+
// see: https://github.com/yargs/yargs-parser/issues/76
2447+
it('only runs coercion functions once, even with aliases', function () {
2448+
var runcount = 0
2449+
var func = (arg) => {
2450+
runcount++
2451+
return undefined
2452+
}
2453+
parser([ '--foo', 'bar' ], {
2454+
alias: {
2455+
foo: ['f', 'foo-bar', 'bar'],
2456+
b: ['bar']
2457+
},
2458+
coerce: {
2459+
bar: func
2460+
}
2461+
})
2462+
runcount.should.equal(1)
2463+
})
24452464
})
24462465

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

0 commit comments

Comments
 (0)