diff --git a/README.md b/README.md index b0914346..1035b42d 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ Parses command line arguments returning a simple mapping of keys and values. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). + * `opts.number`: keys should be treated as numbers. **returns:** diff --git a/index.js b/index.js index 85ff3bc9..6317a378 100644 --- a/index.js +++ b/index.js @@ -26,6 +26,7 @@ function parse (args, opts) { arrays: {}, bools: {}, strings: {}, + numbers: {}, counts: {}, normalize: {}, configs: {}, @@ -45,6 +46,10 @@ function parse (args, opts) { flags.strings[key] = true }) + ;[].concat(opts.number).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true + }) + ;[].concat(opts.count).filter(Boolean).forEach(function (key) { flags.counts[key] = true }) @@ -522,6 +527,7 @@ function parse (args, opts) { var def = { boolean: true, string: '', + number: undefined, array: [] } @@ -533,12 +539,14 @@ function parse (args, opts) { var type = 'boolean' if (flags.strings && flags.strings[key]) type = 'string' + else if (flags.numbers && flags.numbers[key]) type = 'number' else if (flags.arrays && flags.arrays[key]) type = 'array' return type } function isNumber (x) { + if (flags.numbers && flags.numbers[x] && !isNaN(x)) return true if (!configuration['parse-numbers']) return false if (typeof x === 'number') return true if (/^0x[0-9a-f]+$/i.test(x)) return true diff --git a/test/yargs-parser.js b/test/yargs-parser.js index 43b95d99..1a5e55d0 100644 --- a/test/yargs-parser.js +++ b/test/yargs-parser.js @@ -176,6 +176,20 @@ describe('yargs-parser', function () { x.should.be.a('string').and.equal('56') }) + it('should default numbers to undefined', function () { + var n = parser([ '-n' ], { + number: ['n'] + }).n + expect(n).to.equal(undefined) + }) + + it('should default number to NaN if value is not a valid number', function () { + var n = parser([ '-n', 'string' ], { + number: ['n'] + }).n + expect(n).to.equal(NaN) + }) + // Fixes: https://github.com/bcoe/yargs/issues/68 it('should parse flag arguments with no right-hand-value as strings, if defined as strings', function () { var s = parser([ '-s' ], {