From f85ebb4face9d4b0f56147659404cbe0002f3dad Mon Sep 17 00:00:00 2001 From: "Benjamin E. Coe" Date: Sun, 20 Sep 2020 19:44:14 -0700 Subject: [PATCH] fix(unknown-options-as-args): convert positionals that look like numbers (#326) --- lib/yargs-parser.ts | 15 ++++++++++----- test/yargs-parser.cjs | 15 +++++++++++++-- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/lib/yargs-parser.ts b/lib/yargs-parser.ts index b682c4c6..ffc4c639 100644 --- a/lib/yargs-parser.ts +++ b/lib/yargs-parser.ts @@ -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(/^-.+=/) @@ -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) } } @@ -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 { diff --git a/test/yargs-parser.cjs b/test/yargs-parser.cjs index 8bb526b8..48c82f77 100644 --- a/test/yargs-parser.cjs +++ b/test/yargs-parser.cjs @@ -3072,7 +3072,7 @@ describe('yargs-parser', function () { } }) argv.should.deep.equal({ - _: ['-u.arg', '2'], + _: ['-u.arg', 2], k: { arg: 1 } @@ -3110,7 +3110,7 @@ describe('yargs-parser', function () { } }) argv.should.deep.equal({ - _: ['-u', '2'], + _: ['-u', 2], k: 1 }) }) @@ -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