From 81eb1fafc3fd666eb813f718284e73c7bf4eb7db Mon Sep 17 00:00:00 2001 From: Siddharth Singh Date: Mon, 30 Sep 2024 11:34:35 +0530 Subject: [PATCH] handle required options --- tribes-cli/utils/command.ts | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/tribes-cli/utils/command.ts b/tribes-cli/utils/command.ts index 01455731..735c8ea8 100644 --- a/tribes-cli/utils/command.ts +++ b/tribes-cli/utils/command.ts @@ -1,6 +1,6 @@ -import { Option, ParsedArgs } from './mod.ts'; +import { getOptionName, Option, ParsedArgs } from './mod.ts'; import { parseArgs } from '@std/cli'; -import { parseSubcommand } from './parsing.ts'; +import { parseCommand } from './parsing.ts'; export class Command { name: string; @@ -8,6 +8,7 @@ export class Command { private action: (args: ParsedArgs) => void | Promise = (_) => {}; options: Record = {}; commands: Record = {}; + requiredOptions: string[] = []; constructor(name: string, description: string) { this.name = name; @@ -39,9 +40,12 @@ export class Command { } async doAction(args: ParsedArgs) { - if (args.help) { - return console.log(this.help); + if (args.help) return console.log(this.help); + + for (const option of this.requiredOptions) { + if (!args[option]) throw new Error(`tribes-cli: missing required option ${option}`); } + return await this.action(args); } @@ -55,18 +59,13 @@ export class Command { option(fmt: string, option: Option) { this.options[fmt] = option; + if (option.required) this.requiredOptions.push(getOptionName(fmt)); return this; } parse(args: string[]) { - const parserArgs = parseSubcommand(this); - const parsed = parseArgs(args, { - ...parserArgs, - alias: { - 'help': ['h'], - }, - boolean: 'help', - }); + const parserArgs = parseCommand(this); + const parsed = parseArgs(args, parserArgs); return { parsed, parserArgs }; }