From 2743846aef5d37d67a596b6c498e6cac709ac88d Mon Sep 17 00:00:00 2001 From: Michele Piccirillo Date: Sun, 25 Apr 2021 13:29:09 +0200 Subject: [PATCH] Add support to parse GNU-style short options (`-F=value`) --- index.js | 4 ++-- test.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 67b5ec4..854ef82 100644 --- a/index.js +++ b/index.js @@ -76,14 +76,14 @@ function arg(opts, {argv = process.argv.slice(2), permissive = false, stopAtPosi if (wholeArg.length > 1 && wholeArg[0] === '-') { /* eslint-disable operator-linebreak */ - const separatedArguments = (wholeArg[1] === '-' || wholeArg.length === 2) + const separatedArguments = (wholeArg[1] === '-' || /^-.=.*$/.test(wholeArg)) ? [wholeArg] : wholeArg.slice(1).split('').map(a => `-${a}`); /* eslint-enable operator-linebreak */ for (let j = 0; j < separatedArguments.length; j++) { const arg = separatedArguments[j]; - const [originalArgName, argStr] = arg[1] === '-' ? arg.split(/=(.*)/, 2) : [arg, undefined]; + const [originalArgName, argStr] = arg.split(/=(.*)/, 2); let argName = originalArgName; while (argName in aliases) { diff --git a/test.js b/test.js index 59db895..dc69caf 100644 --- a/test.js +++ b/test.js @@ -363,6 +363,51 @@ test('should parse negative numbers (GNU equals form)', () => { }); }); +test('should parse long options (GNU equals form)', () => { + const argv = ['--option=value']; + + const result = arg({ + '--option': String + }, { + argv + }); + + expect(result).to.deep.equal({ + _: [], + '--option': 'value' + }); +}); + +test('should parse short options (GNU equals form)', () => { + const argv = ['-O=value']; + + const result = arg({ + '-O': String + }, { + argv + }); + + expect(result).to.deep.equal({ + _: [], + '-O': 'value' + }); +}); + +test('should parse negative numbers in short options options (GNU equals form)', () => { + const argv = ['-I=-15']; + + const result = arg({ + '-I': Number + }, { + argv + }); + + expect(result).to.deep.equal({ + _: [], + '-I': -15 + }); +}); + test('should parse negative numbers (separate argument form)', () => { const argv = ['--int', '-5'];