From e778e36221a7d5a974db1c7cfff343bc0a0c21e5 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 6 Sep 2017 18:09:34 -0400 Subject: [PATCH] fix: only run coercion functions once, despite aliases. (#76) --- index.js | 20 ++++++++++++++------ test/yargs-parser.js | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 2ab9c2cc..6e5daff0 100644 --- a/index.js +++ b/index.js @@ -513,13 +513,21 @@ 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 already coerced this option via one of its aliases + argv[key] = applied[key] + } else { + 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 fa296b6c..79b52377 100644 --- a/test/yargs-parser.js +++ b/test/yargs-parser.js @@ -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 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