mirror of
https://gitlab.com/soapbox-pub/ditto.git
synced 2025-12-06 11:29:46 +00:00
handle required options
This commit is contained in:
parent
8184c18bd7
commit
81eb1fafc3
1 changed files with 11 additions and 12 deletions
|
|
@ -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<void> = (_) => {};
|
||||
options: Record<string, Option> = {};
|
||||
commands: Record<string, Command> = {};
|
||||
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 };
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue