Skip to content

Commit

Permalink
Add error when flag.default isn't a valid choice (#231)
Browse files Browse the repository at this point in the history
  • Loading branch information
tommy-mitchell authored Mar 24, 2023
1 parent c73c297 commit b2d7ce7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
12 changes: 8 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)}`,
},
},
};

Expand Down
15 changes: 15 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down

0 comments on commit b2d7ce7

Please sign in to comment.