From df95846b86132626295a19b8346bcc51d77fb2e9 Mon Sep 17 00:00:00 2001 From: Kevin Gibbons Date: Sat, 9 Apr 2022 17:58:32 -0700 Subject: [PATCH] disallow specifying multiple:true for boolean arguments --- errors.js | 9 ++++++++- index.js | 9 ++++++++- test/index.js | 11 +++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/errors.js b/errors.js index 1b9eb95..ecb12f8 100644 --- a/errors.js +++ b/errors.js @@ -14,9 +14,16 @@ class ERR_INVALID_SHORT_OPTION extends TypeError { } } +class ERR_MULTIPLE_FLAG extends TypeError { + constructor(longOption) { + super(`options.${longOption}.multiple cannot be used with \`type: 'boolean'\``); + this.code = 'ERR_MULTIPLE_FLAG'; + } +} module.exports = { codes: { ERR_INVALID_ARG_TYPE, - ERR_INVALID_SHORT_OPTION + ERR_INVALID_SHORT_OPTION, + ERR_MULTIPLE_FLAG } }; diff --git a/index.js b/index.js index 48bc422..7f969b9 100644 --- a/index.js +++ b/index.js @@ -35,6 +35,7 @@ const { const { codes: { ERR_INVALID_SHORT_OPTION, + ERR_MULTIPLE_FLAG, }, } = require('./errors'); @@ -111,7 +112,8 @@ const parseArgs = ({ ({ 0: longOption, 1: optionConfig }) => { validateObject(optionConfig, `options.${longOption}`); - if (ObjectHasOwn(optionConfig, 'type')) { + const hasType = ObjectHasOwn(optionConfig, 'type'); + if (hasType) { validateUnion(optionConfig.type, `options.${longOption}.type`, ['string', 'boolean']); } @@ -125,6 +127,11 @@ const parseArgs = ({ if (ObjectHasOwn(optionConfig, 'multiple')) { validateBoolean(optionConfig.multiple, `options.${longOption}.multiple`); + if (optionConfig.multiple && + hasType && + optionConfig.type === 'boolean') { + throw new ERR_MULTIPLE_FLAG(longOption); + } } } ); diff --git a/test/index.js b/test/index.js index e995d76..2d4c6b6 100644 --- a/test/index.js +++ b/test/index.js @@ -391,3 +391,14 @@ test('invalid short option length', function(t) { t.end(); }); + +test('`type: boolean` used with `multiple: true`', function(t) { + const passedArgs = []; + const passedOptions = { foo: { type: 'boolean', multiple: true } }; + + t.throws(function() { parseArgs({ args: passedArgs, options: passedOptions }); }, { + code: 'ERR_MULTIPLE_FLAG' + }); + + t.end(); +});