Skip to content

Commit

Permalink
fix: ensure consistent parsing of dot-notation arguments (yargs#102)
Browse files Browse the repository at this point in the history
  • Loading branch information
elsbree authored and bcoe committed Dec 18, 2017
1 parent 507aaef commit c9bd79c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
21 changes: 18 additions & 3 deletions index.js
Expand Up @@ -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]
Expand Down
27 changes: 27 additions & 0 deletions test/yargs-parser.js
Expand Up @@ -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')
})
})
})

0 comments on commit c9bd79c

Please sign in to comment.