From c9bd79c657dabedb21b1cacf4c3f86b41180d24b Mon Sep 17 00:00:00 2001 From: Nick Elsbree Date: Sun, 17 Dec 2017 20:30:55 -0800 Subject: [PATCH] fix: ensure consistent parsing of dot-notation arguments (#102) --- index.js | 21 ++++++++++++++++++--- test/yargs-parser.js | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 0f087efa..85145834 100644 --- a/index.js +++ b/index.js @@ -574,9 +574,24 @@ function parse (args, opts) { if (!configuration['dot-notation']) keys = [keys.join('.')] - keys.slice(0, -1).forEach(function (key) { - if (o[key] === undefined) o[key] = {} - o = o[key] + keys.slice(0, -1).forEach(function (key, index) { + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {} + } + + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}) + } else { + o[key] = [o[key], {}] + } + + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1] + } else { + o = o[key] + } }) var key = keys[keys.length - 1] diff --git a/test/yargs-parser.js b/test/yargs-parser.js index b8e14bc5..055d056c 100644 --- a/test/yargs-parser.js +++ b/test/yargs-parser.js @@ -2485,4 +2485,31 @@ describe('yargs-parser', function () { }) argv.foo.should.equal(9.39404959509494e+22) }) + + // see: https://github.com/yargs/yargs-parser/issues/101 + describe('dot-notation array arguments combined with string arguments', function () { + it('parses correctly when dot-notation argument is first', function () { + var argv = parser([ '--foo.bar', 'baz', '--foo', 'bux' ]) + Array.isArray(argv.foo).should.equal(true) + argv.foo[0].bar.should.equal('baz') + argv.foo[1].should.equal('bux') + }) + + it('parses correctly when dot-notation argument is last', function () { + var argv = parser([ '--foo', 'bux', '--foo.bar', 'baz' ]) + Array.isArray(argv.foo).should.equal(true) + argv.foo[0].should.equal('bux') + argv.foo[1].bar.should.equal('baz') + }) + + it('parses correctly when there are multiple dot-notation arguments', function () { + var argv = parser([ '--foo.first', 'firstvalue', '--foo', 'bux', '--foo.bar', 'baz', '--foo.bla', 'banana' ]) + Array.isArray(argv.foo).should.equal(true) + argv.foo.length.should.equal(4) + argv.foo[0].first.should.equal('firstvalue') + argv.foo[1].should.equal('bux') + argv.foo[2].bar.should.equal('baz') + argv.foo[3].bla.should.equal('banana') + }) + }) })