From 4ca69da4c9734ed101cbc0e076e057ee9bdfcb8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Rittm=C3=BCller?= Date: Thu, 8 Sep 2016 04:36:36 +0200 Subject: [PATCH] fix: coerce should be applied to the final objects and arrays created (#57) BREAKING CHANGE: coerce is no longer applied to individual arguments in an implicit array. --- index.js | 16 +++------------- test/yargs-parser.js | 16 +++++++++++++++- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/index.js b/index.js index e2b35b62..5b092c9e 100644 --- a/index.js +++ b/index.js @@ -280,7 +280,7 @@ function parse (args, opts) { setConfig(argv) setConfigObjects() applyEnvVars(argv, false) - applyArrayCoercions(argv) + applyCoercions(argv) applyDefaultsAndAliases(argv, flags.aliases, defaults) // for any counts either not in args or without an explicit default, set to 0 @@ -483,11 +483,9 @@ function parse (args, opts) { }) } - function applyArrayCoercions (argv) { + function applyCoercions (argv) { var coerce - Object.keys(argv).filter(function (key) { - return key === '_' || checkAllAliases(key, flags.arrays) - }).forEach(function (key) { + Object.keys(argv).forEach(function (key) { coerce = checkAllAliases(key, flags.coercions) if (typeof coerce === 'function') { try { @@ -538,14 +536,6 @@ function parse (args, opts) { }) var key = keys[keys.length - 1] - var coerce = !checkAllAliases(key, flags.arrays) && checkAllAliases(key, flags.coercions) - if (typeof coerce === 'function') { - try { - value = coerce(value) - } catch (err) { - error = err - } - } if (value === increment) { o[key] = increment(o[key]) diff --git a/test/yargs-parser.js b/test/yargs-parser.js index 926e750a..dac993c9 100644 --- a/test/yargs-parser.js +++ b/test/yargs-parser.js @@ -1980,11 +1980,25 @@ describe('yargs-parser', function () { parsed.f.should.equal(-99) }) + it('applies coercion function to all dot options', function () { + var parsed = parser(['--foo.bar', 'nananana'], { + coerce: { + foo: function (val) { + val.bar += ', batman!' + return val + } + } + }) + parsed.foo.bar.should.equal('nananana, batman!') + }) + it('applies coercion function to an implicit array', function () { var parsed = parser(['--foo', '99', '-f', '33'], { coerce: { f: function (arg) { - return arg * -1 + return arg.map(function (a) { + return a * -1 + }) } }, alias: {