diff --git a/index.js b/index.js index 1a2c7cb5..0f087efa 100644 --- a/index.js +++ b/index.js @@ -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 + } } } }) diff --git a/test/yargs-parser.js b/test/yargs-parser.js index 0c9bb97c..b8e14bc5 100644 --- a/test/yargs-parser.js +++ b/test/yargs-parser.js @@ -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