Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(unknown-options-as-args): convert positionals that look like numbers #326

Merged
merged 1 commit into from Sep 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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