Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions lib/yargs-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,8 @@ export class YargsParser {

// increment a count given as arg (either no value or value parsed as boolean)
if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
value = increment()
// COUNT_INCREMENT is a unique sentinel, not the number 1.
value = COUNT_INCREMENT as unknown as typeof value
}

// Set normalized value when key is in 'normalize' and in 'arrays'
Expand Down Expand Up @@ -850,7 +851,7 @@ export class YargsParser {
}
}

if (value === increment()) {
if (value === COUNT_INCREMENT) {
o[key] = increment(o[key])
} else if (Array.isArray(o[key])) {
if (duplicate && isTypeArray && isValueArray) {
Expand Down Expand Up @@ -1098,6 +1099,11 @@ function combineAliases (aliases: Dictionary<string | string[]>): Dictionary<str
return combined
}

// Sentinel so a real option value of 1 is not treated as a count step.
// processValue used to assign increment(), which returns 1, and setKey
// compared value === increment(), so `-x 3 -x 1` became 4 instead of [3, 1].
const COUNT_INCREMENT = Symbol('yargs-parser-count-increment')

// this function should only be called when a count is given as an arg
// it is NOT called to set a default value
// thus we can start the count at 1 instead of 0
Expand Down
10 changes: 10 additions & 0 deletions test/yargs-parser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1666,6 +1666,16 @@ describe('yargs-parser', function () {
parse.should.have.property('v').and.deep.equal(['a', 'b', 'c'])
parse.should.have.property('_').with.length(0)
})
it('should not treat a later value of 1 as a count increment (#506)', function () {
const parse = parser(['-x', '3', '-x', '1'])
parse.should.have.property('x').and.deep.equal([3, 1])
parse.should.have.property('_').with.length(0)
})
it('should keep a later value of 1 when duplicate-arguments-array is false (#506)', function () {
const parse = parser(['-x', '3', '-x', '1'], { configuration: { 'duplicate-arguments-array': false } })
parse.should.have.property('x').and.equal(1)
parse.should.have.property('_').with.length(0)
})
it('should keep only the last value if the same option is specified multiple times (duplicate-arguments-false)', function () {
const parse = parser(['-v', 'a', '-v', 'b', '-v', 'c'], { configuration: { 'duplicate-arguments-array': false } })
parse.should.have.property('v').and.equal('c')
Expand Down