From 68155076a45520c8fda932bcc38245572d9234c8 Mon Sep 17 00:00:00 2001 From: Volker Mische Date: Fri, 28 Sep 2018 19:28:47 +0200 Subject: [PATCH] fix: make requiresArg work with arrays When `requiresArg` was used together with `array`, only the first argument of the array would end up being parsed. With this change things work as expected. The `requireArg` option sets the `nargs` options to `1`, so only one additional argument will be parsed. The problem was that that parsing step was checked before the array parsing one. The solution is as simple as flipping those if conditions and check if its an array first, hence ignoring the `nargs` option. Fixes https://github.com/yargs/yargs/issues/1170. --- index.js | 8 ++++---- test/yargs-parser.js | 11 +++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index a3849bce..4e6c47f8 100644 --- a/index.js +++ b/index.js @@ -166,12 +166,12 @@ function parse (args, opts) { )) { key = arg.match(/^--?(.+)/)[1] - // nargs format = '--foo a b c' - if (checkAllAliases(key, flags.nargs)) { - i = eatNargs(i, key, args) // array format = '--foo a b c' - } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { + if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { i = eatArray(i, key, args) + // nargs format = '--foo a b c' + } else if (checkAllAliases(key, flags.nargs)) { + i = eatNargs(i, key, args) } else { next = args[i + 1] diff --git a/test/yargs-parser.js b/test/yargs-parser.js index 29104246..a1b3089f 100644 --- a/test/yargs-parser.js +++ b/test/yargs-parser.js @@ -1664,6 +1664,17 @@ describe('yargs-parser', function () { result.foo.should.eql('a') }) + + it('should be ignored if input is an array', function () { + var result = parser(['--foo', 'a', 'b'], { + array: 'foo', + narg: { + foo: 1 + } + }) + + result.foo.should.eql(['a', 'b']) + }) }) describe('env vars', function () {