Skip to content

Commit

Permalink
fix negative number handling (closes vercel#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
Qix- authored and nevilm-lt committed Apr 22, 2022
1 parent 09e5fe3 commit 9248ed1
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
16 changes: 15 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,21 @@ function arg(opts, {argv = process.argv.slice(2), permissive = false, stopAtPosi
if (isFlag) {
result[argName] = type(true, argName, result[argName]);
} else if (argStr === undefined) {
if (argv.length < i + 2 || (argv[i + 1].length > 1 && argv[i + 1][0] === '-')) {
if (
argv.length < i + 2 ||
(
argv[i + 1].length > 1 &&
(argv[i + 1][0] === '-') &&
!(
argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) &&
(
type === Number ||
// eslint-disable-next-line no-undef
(typeof BigInt !== 'undefined' && type === BigInt)
)
)
)
) {
const extended = originalArgName === argName ? '' : ` (alias for ${argName})`;
throw new Error(`Option requires argument: ${originalArgName}${extended}`);
}
Expand Down
50 changes: 50 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -347,3 +347,53 @@ test('should stop parsing early with permissive', () => {
'-d': 2
});
});

test('should parse negative numbers (GNU equals form)', () => {
const argv = ['--int=-5'];

const result = arg({
'--int': Number
}, {
argv
});

expect(result).to.deep.equal({
_: [],
'--int': -5
});
});

test('should parse negative numbers (separate argument form)', () => {
const argv = ['--int', '-5'];

const result = arg({
'--int': Number
}, {
argv
});

expect(result).to.deep.equal({
_: [],
'--int': -5
});
});

test('should error if numeric type is followed by non-negative, non-argument', () => {
const argv = ['--int', '-abc'];

expect(() => arg({
'--int': Number
}, {
argv
})).to.throw(Error, 'Option requires argument: --int');
});

test('should error if negative numeric argument is passed to non-negative argument', () => {
const argv = ['--str', '-15'];

expect(() => arg({
'--str': String
}, {
argv
})).to.throw(Error, 'Option requires argument: --str');
});

0 comments on commit 9248ed1

Please sign in to comment.