fix: required options

This commit is contained in:
2023-12-04 03:00:01 +02:00
committed by Chen Asraf
parent c2149994dd
commit 0f17d336fb
3 changed files with 25 additions and 0 deletions

View File

@@ -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.
*/

View File

@@ -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
}

View File

@@ -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', () => {