Skip to content
Closed
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
11 changes: 8 additions & 3 deletions lib/yargs-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -620,13 +620,13 @@ export class YargsParser {
if (typeof val === 'string') val = val === 'true'
}

let value = Array.isArray(val)
let value: string | number | boolean | typeof incrementMarker | Array<string | number | null | undefined> | null | undefined = Array.isArray(val)
? val.map(function (v) { return maybeCoerceNumber(key, v) })
: maybeCoerceNumber(key, val)

// 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()
value = incrementMarker
}

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

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

// A count argument carries no value of its own: it is replaced by this marker
// so that `setKey` can tell "increment the count" apart from a real value, and
// a literal `1` passed to a non-count option is not mistaken for a count.
const incrementMarker = Symbol('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
14 changes: 14 additions & 0 deletions test/yargs-parser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1658,6 +1658,20 @@ describe('yargs-parser', function () {

argv.error.message.should.equal('Invalid configuration: counter, opts.count excludes opts.narg.')
})

// See: https://github.com/yargs/yargs-parser/issues/506
it('should not increment an option that is not a counter when its value is 1', function () {
parser('-x 3 -x 1').x.should.deep.equal([3, 1])
parser('-x 1 -x 3').x.should.deep.equal([1, 3])
parser('--foo 2 --foo 1').foo.should.deep.equal([2, 1])
})

it('should not increment a non-counter with value 1 when duplicate-arguments-array is false', function () {
const parsed = parser('-x 3 -x 1', {
configuration: { 'duplicate-arguments-array': false }
})
parsed.x.should.equal(1)
})
})

describe('array', function () {
Expand Down