Skip to content

Commit

Permalink
fix required bug
Browse files Browse the repository at this point in the history
  • Loading branch information
talentlessguy committed Jan 17, 2024
1 parent e4e386a commit b25a1ff
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
17 changes: 15 additions & 2 deletions parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,21 @@ export const handleArgParsing = (
},
)

for (const [arg, value] of Object.entries(parsed)) {
const requiredOptions = options.filter((opt) => opt.required)

const parsedArgs = Object.entries(parsed)

for (const opt of requiredOptions) {
if (
!parsedArgs.find((arg) =>
arg[0] === opt.name || (opt.aliases || []).includes(arg[0])
)
) {
throw new Error(`Argument ${opt.name} is required`)
}
}

for (const [arg, value] of parsedArgs) {
const opt = options.find((x) =>
x.name === arg || (x.aliases || []).includes(arg)
)
Expand All @@ -41,7 +55,6 @@ export const handleArgParsing = (
`Invalid argument type for ${arg}: expected ${opt.type}, got ${actualType}`,
)
}
if (opt.required && !value) throw new Error(`Argument ${arg} is required`)
}

return {
Expand Down
27 changes: 27 additions & 0 deletions parse_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,31 @@ describe('handleArgParsing', () => {
)
}
})
it('throws if required arg is not present', () => {
try {
handleArgParsing({
options: [{ name: 'test', type: 'boolean', required: true }],
}, [])
} catch (e) {
expect((e as Error).message).toEqual(
'Argument test is required',
)
}
})
it('does not throw for required if alias is passed', () => {
try {
handleArgParsing({
options: [{
name: 'test',
type: 'boolean',
required: true,
aliases: ['t'],
}],
}, ['t'])
} catch (e) {
expect((e as Error).message).toEqual(
'Argument test is required',
)
}
})
})

0 comments on commit b25a1ff

Please sign in to comment.