From 0f17d336fb41f7c39e8dc3f536861d9bd8ab6601 Mon Sep 17 00:00:00 2001 From: Chen Asraf Date: Mon, 4 Dec 2023 03:00:01 +0200 Subject: [PATCH] fix: required options --- src/command.ts | 14 ++++++++++++++ src/option.ts | 2 ++ test/option.test.ts | 9 +++++++++ 3 files changed, 25 insertions(+) diff --git a/src/command.ts b/src/command.ts index c0bc744..f82a4c4 100644 --- a/src/command.ts +++ b/src/command.ts @@ -397,6 +397,7 @@ export class MassargCommand { } // 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 { } } + 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. */ diff --git a/src/option.ts b/src/option.ts index 7ba4773..77fac40 100644 --- a/src/option.ts +++ b/src/option.ts @@ -126,6 +126,7 @@ export class MassargOption isArray: boolean + isRequired: boolean isDefault: boolean outputName?: string @@ -138,6 +139,7 @@ export class MassargOption x as OptionType) this.isArray = options.array ?? false this.isDefault = options.isDefault ?? false + this.isRequired = options.required ?? false this.outputName = options.outputName } diff --git a/test/option.test.ts b/test/option.test.ts index 7ccacb2..75ebf23 100644 --- a/test/option.test.ts +++ b/test/option.test.ts @@ -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', () => {