mirror of
https://github.com/chenasraf/massarg.git
synced 2026-05-18 01:39:05 +00:00
fix: required options
This commit is contained in:
@@ -397,6 +397,7 @@ export class MassargCommand<Args extends ArgsObject = ArgsObject> {
|
||||
}
|
||||
// merge args
|
||||
this.args = { ...this.args, ..._args }
|
||||
this.assertRequired()
|
||||
// dry run, just exit
|
||||
if (!parseCommands) {
|
||||
return this.args as Args
|
||||
@@ -408,6 +409,19 @@ export class MassargCommand<Args extends ArgsObject = ArgsObject> {
|
||||
}
|
||||
}
|
||||
|
||||
private assertRequired() {
|
||||
const required = this.options.filter((o) => o.isRequired)
|
||||
const missing = required.filter((o) => this.args[o.getOutputName() as keyof Args] === undefined)
|
||||
if (missing.length) {
|
||||
const plural = missing.length > 1 ? 's' : ''
|
||||
throw new ValidationError({
|
||||
code: 'missing_required_options',
|
||||
message: `Missing required option${plural}: ${missing.map((o) => o.name).join(', ')}`,
|
||||
path: [this.name],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the help output for this command, and return it as a string.
|
||||
*/
|
||||
|
||||
@@ -126,6 +126,7 @@ export class MassargOption<OptionType extends any = unknown, Args extends ArgsOb
|
||||
aliases: string[]
|
||||
parse: Parser<Args, OptionType>
|
||||
isArray: boolean
|
||||
isRequired: boolean
|
||||
isDefault: boolean
|
||||
outputName?: string
|
||||
|
||||
@@ -138,6 +139,7 @@ export class MassargOption<OptionType extends any = unknown, Args extends ArgsOb
|
||||
this.parse = options.parse ?? ((x: string) => x as OptionType)
|
||||
this.isArray = options.array ?? false
|
||||
this.isDefault = options.isDefault ?? false
|
||||
this.isRequired = options.required ?? false
|
||||
this.outputName = options.outputName
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,15 @@ describe('option', () => {
|
||||
})
|
||||
expect(command.getArgs(['--test2', 'test'])).toHaveProperty('test', 'test')
|
||||
})
|
||||
test('required', () => {
|
||||
const command = massarg(opts).option({
|
||||
name: 'test2',
|
||||
description: 'test2',
|
||||
aliases: [],
|
||||
required: true,
|
||||
})
|
||||
expect(() => command.getArgs([])).toThrow('Missing required option: test2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('flag', () => {
|
||||
|
||||
Reference in New Issue
Block a user