Skip to content

Commit c9bd79c

Browse files
elsbreebcoe
authored andcommitted
fix: ensure consistent parsing of dot-notation arguments (#102)
1 parent 507aaef commit c9bd79c

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

index.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -574,9 +574,24 @@ function parse (args, opts) {
574574

575575
if (!configuration['dot-notation']) keys = [keys.join('.')]
576576

577-
keys.slice(0, -1).forEach(function (key) {
578-
if (o[key] === undefined) o[key] = {}
579-
o = o[key]
577+
keys.slice(0, -1).forEach(function (key, index) {
578+
if (typeof o === 'object' && o[key] === undefined) {
579+
o[key] = {}
580+
}
581+
582+
if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
583+
// ensure that o[key] is an array, and that the last item is an empty object.
584+
if (Array.isArray(o[key])) {
585+
o[key].push({})
586+
} else {
587+
o[key] = [o[key], {}]
588+
}
589+
590+
// we want to update the empty object at the end of the o[key] array, so set o to that object
591+
o = o[key][o[key].length - 1]
592+
} else {
593+
o = o[key]
594+
}
580595
})
581596

582597
var key = keys[keys.length - 1]

test/yargs-parser.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2485,4 +2485,31 @@ describe('yargs-parser', function () {
24852485
})
24862486
argv.foo.should.equal(9.39404959509494e+22)
24872487
})
2488+
2489+
// see: https://github.com/yargs/yargs-parser/issues/101
2490+
describe('dot-notation array arguments combined with string arguments', function () {
2491+
it('parses correctly when dot-notation argument is first', function () {
2492+
var argv = parser([ '--foo.bar', 'baz', '--foo', 'bux' ])
2493+
Array.isArray(argv.foo).should.equal(true)
2494+
argv.foo[0].bar.should.equal('baz')
2495+
argv.foo[1].should.equal('bux')
2496+
})
2497+
2498+
it('parses correctly when dot-notation argument is last', function () {
2499+
var argv = parser([ '--foo', 'bux', '--foo.bar', 'baz' ])
2500+
Array.isArray(argv.foo).should.equal(true)
2501+
argv.foo[0].should.equal('bux')
2502+
argv.foo[1].bar.should.equal('baz')
2503+
})
2504+
2505+
it('parses correctly when there are multiple dot-notation arguments', function () {
2506+
var argv = parser([ '--foo.first', 'firstvalue', '--foo', 'bux', '--foo.bar', 'baz', '--foo.bla', 'banana' ])
2507+
Array.isArray(argv.foo).should.equal(true)
2508+
argv.foo.length.should.equal(4)
2509+
argv.foo[0].first.should.equal('firstvalue')
2510+
argv.foo[1].should.equal('bux')
2511+
argv.foo[2].bar.should.equal('baz')
2512+
argv.foo[3].bla.should.equal('banana')
2513+
})
2514+
})
24882515
})

0 commit comments

Comments
 (0)