From 5d700f77109c06715c29d68165b799b62dacd66c Mon Sep 17 00:00:00 2001 From: tommy-mitchell Date: Fri, 24 Mar 2023 13:21:31 -0500 Subject: [PATCH] feat(`flag`): add error when `default` and `choices` mismatch --- index.js | 12 ++++++++---- test/test.js | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 0748519..639f976 100644 --- a/index.js +++ b/index.js @@ -59,25 +59,29 @@ const joinFlagKeys = (flagKeys, prefix = '--') => `\`${prefix}${flagKeys.join(`\ const validateOptions = options => { const invalidOptionFilters = { flags: { - flagsWithDashes: { + keyContainsDashes: { filter: ([flagKey]) => flagKey.includes('-') && flagKey !== '--', message: flagKeys => `Flag keys may not contain '-'. Invalid flags: ${joinFlagKeys(flagKeys, '')}`, }, - flagsWithAlias: { + aliasIsSet: { filter: ([, flag]) => flag.alias !== undefined, message: flagKeys => `The option \`alias\` has been renamed to \`shortFlag\`. The following flags need to be updated: ${joinFlagKeys(flagKeys)}`, }, - flagsWithNonArrayChoices: { + choicesNotAnArray: { filter: ([, flag]) => flag.choices !== undefined && !Array.isArray(flag.choices), message: flagKeys => `The option \`choices\` must be an array. Invalid flags: ${joinFlagKeys(flagKeys)}`, }, - flagsWithChoicesOfDifferentTypes: { + choicesNotMatchFlagType: { filter: ([, flag]) => flag.type && Array.isArray(flag.choices) && flag.choices.some(choice => typeof choice !== flag.type), message(flagKeys) { const flagKeysAndTypes = flagKeys.map(flagKey => `(\`${decamelizeFlagKey(flagKey)}\`, type: '${options.flags[flagKey].type}')`); return `Each value of the option \`choices\` must be of the same type as its flag. Invalid flags: ${flagKeysAndTypes.join(', ')}`; }, }, + defaultNotInChoices: { + filter: ([, flag]) => flag.default && Array.isArray(flag.choices) && [flag.default].flat().every(value => flag.choices.includes(value)), + message: flagKeys => `Each value of the option \`default\` must exist within the option \`choices\`. Invalid flags: ${joinFlagKeys(flagKeys)}`, + }, }, }; diff --git a/test/test.js b/test/test.js index c489753..25b9edb 100644 --- a/test/test.js +++ b/test/test.js @@ -857,6 +857,21 @@ test('choices - choices must be of the same type', t => { }, {message: 'Each value of the option `choices` must be of the same type as its flag. Invalid flags: (`--number`, type: \'number\'), (`--boolean`, type: \'boolean\')'}); }); +test('choices - default must only include valid choices', t => { + t.throws(() => { + meow({ + importMeta, + flags: { + number: { + type: 'number', + choices: [1, 2, 3], + default: 1, + }, + }, + }); + }, {message: 'Each value of the option `default` must exist within the option `choices`. Invalid flags: `--number`'}); +}); + test('options - multiple validation errors', t => { t.throws(() => { meow({