From eb41fa4c9b4b8141667db36e258809b9f2477c83 Mon Sep 17 00:00:00 2001 From: gholk Date: Fri, 16 Sep 2022 22:16:18 +0800 Subject: [PATCH] Do not split the arguments if any of them is undefined The permissive mode will store the undefined arguments in the `_` array, which is intendented to be processed by another arguments parsing library, and it may has its own logic to separate or parse arguments, so we should not process the unknown arguments. This will change one behavior defined in the test.js. --- index.js | 24 +++++++++++++++--------- test.js | 23 +++++++++++++++++++++-- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 3f60f4c..fc1478c 100644 --- a/index.js +++ b/index.js @@ -104,15 +104,21 @@ function arg( } if (wholeArg.length > 1 && wholeArg[0] === '-') { - /* eslint-disable operator-linebreak */ - const separatedArguments = - wholeArg[1] === '-' || wholeArg.length === 2 - ? [wholeArg] - : wholeArg - .slice(1) - .split('') - .map((a) => `-${a}`); - /* eslint-enable operator-linebreak */ + let separatedArguments = []; + if (wholeArg[1] === '-' || wholeArg.length === 2) { + separatedArguments.push(wholeArg); + } else { + for (const char of wholeArg.slice(1)) { + separatedArguments.push(`-${char}`); + } + } + + const allArgumentsExist = separatedArguments.every( + (flag) => flag in handlers + ); + if (!allArgumentsExist && permissive) { + separatedArguments = [wholeArg]; + } for (let j = 0; j < separatedArguments.length; j++) { const arg = separatedArguments[j]; diff --git a/test.js b/test.js index 49e638f..7a0f86b 100644 --- a/test.js +++ b/test.js @@ -481,8 +481,27 @@ test('should stop parsing early with permissive', () => { ); expect(result).to.deep.equal({ - _: ['-v', '--foo', 'bar'], - '-d': 2 + _: ['-dvd', '--foo', 'bar'] + }); +}); + +test('should not split unknown arguments with permissive', () => { + const argv = ['-dvd', '--foo', 'bar']; + + const result = arg( + { + '-d': arg.COUNT, + '--foo': Boolean + }, + { + argv, + permissive: true + } + ); + + expect(result).to.deep.equal({ + _: ['-dvd', 'bar'], + '--foo': true }); });