Skip to content

Commit 60bb9b3

Browse files
authored
feat: narg arguments no longer consume flag arguments (#114)
BREAKING CHANGE: arguments of form --foo, -abc, will no longer be consumed by nargs
1 parent 29b0248 commit 60bb9b3

3 files changed

Lines changed: 22 additions & 3 deletions

File tree

index.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -302,11 +302,20 @@ function parse (args, opts) {
302302
// how many arguments should we consume, based
303303
// on the nargs option?
304304
function eatNargs (i, key, args) {
305+
var ii
305306
var toEat = checkAllAliases(key, flags.nargs)
306307

307-
if (args.length - (i + 1) < toEat) error = Error(__('Not enough arguments following: %s', key))
308+
// nargs will not consume flag arguments, e.g., -abc, --foo,
309+
// and terminates when one is observed.
310+
var available = 0
311+
for (ii = i + 1; ii < args.length; ii++) {
312+
if (!args[ii].match(/^-[^0-9]/)) available++
313+
else break
314+
}
315+
316+
if (available < toEat) error = Error(__('Not enough arguments following: %s', key))
308317

309-
for (var ii = i + 1; ii < (toEat + i + 1); ii++) {
318+
for (ii = i + 1; ii < (available + i + 1); ii++) {
310319
setArg(key, args[ii])
311320
}
312321

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
"description": "the mighty option parser used by yargs",
55
"main": "index.js",
66
"scripts": {
7-
"pretest": "standard",
87
"test": "nyc mocha test/*.js",
8+
"posttest": "standard",
99
"coverage": "nyc report --reporter=text-lcov | coveralls",
1010
"release": "standard-version"
1111
},

test/yargs-parser.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1643,6 +1643,16 @@ describe('yargs-parser', function () {
16431643
result['1'][0].should.equal('a')
16441644
result['1'][1].should.equal('b')
16451645
})
1646+
1647+
it('should not treat flag arguments as satisfying narg requirements', function () {
1648+
var result = parser.detailed(['--foo', '--bar'], {
1649+
narg: {
1650+
foo: 1
1651+
}
1652+
})
1653+
1654+
result.error.message.should.equal('Not enough arguments following: foo')
1655+
})
16461656
})
16471657

16481658
describe('env vars', function () {

0 commit comments

Comments
 (0)