Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(unknown-options-as-args): convert positionals that look like numb…
…ers (#326)
  • Loading branch information
bcoe committed Sep 21, 2020
1 parent c8580a2 commit f85ebb4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
15 changes: 10 additions & 5 deletions lib/yargs-parser.ts
Expand Up @@ -212,7 +212,7 @@ export class YargsParser {

// any unknown option (except for end-of-options, "--")
if (arg !== '--' && isUnknownOptionAsArg(arg)) {
argv._.push(arg)
pushPositional(arg)
// -- separated by =
} else if (arg.match(/^--.+=/) || (
!configuration['short-option-groups'] && arg.match(/^-.+=/)
Expand Down Expand Up @@ -382,10 +382,7 @@ export class YargsParser {
notFlags = args.slice(i)
break
} else {
const maybeCoercedNumber = maybeCoerceNumber('_', arg)
if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
argv._.push(maybeCoercedNumber)
}
pushPositional(arg)
}
}

Expand Down Expand Up @@ -430,6 +427,14 @@ export class YargsParser {
})
}

// Push argument into positional array, applying numeric coercion:
function pushPositional (arg: string) {
const maybeCoercedNumber = maybeCoerceNumber('_', arg)
if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
argv._.push(maybeCoercedNumber)
}
}

// how many arguments should we consume, based
// on the nargs option?
function eatNargs (i: number, key: string, args: string[], argAfterEqualSign?: string): number {
Expand Down
15 changes: 13 additions & 2 deletions test/yargs-parser.cjs
Expand Up @@ -3072,7 +3072,7 @@ describe('yargs-parser', function () {
}
})
argv.should.deep.equal({
_: ['-u.arg', '2'],
_: ['-u.arg', 2],
k: {
arg: 1
}
Expand Down Expand Up @@ -3110,7 +3110,7 @@ describe('yargs-parser', function () {
}
})
argv.should.deep.equal({
_: ['-u', '2'],
_: ['-u', 2],
k: 1
})
})
Expand Down Expand Up @@ -3258,6 +3258,17 @@ describe('yargs-parser', function () {
knownArg: 1
})
})

it('should coerce unknown options that look numeric into numbers', () => {
const argv = parser('--known-arg 33', {
boolean: ['known-arg']
})
argv.should.deep.equal({
_: [33],
'known-arg': true,
knownArg: true
})
})
})

// See: https://github.com/yargs/yargs-parser/issues/231
Expand Down

0 comments on commit f85ebb4

Please sign in to comment.