From 274cd0742dcbd61eea0455184917656ee7cde4d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E5=90=91=E5=A4=9C?= Date: Fri, 5 Jul 2024 22:24:55 +0800 Subject: [PATCH] feat(default): support default sub command (#153) --- src/command.ts | 12 +++++++++++- src/types.ts | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/command.ts b/src/command.ts index 1abfe44..0dd7ed8 100644 --- a/src/command.ts +++ b/src/command.ts @@ -33,6 +33,15 @@ export async function runCommand( await cmd.setup(context); } + // Checkout default sub command + const defaultSubCommand = await resolveValue(cmd.default); + if (defaultSubCommand && cmd.run) { + throw new CLIError( + `Command has a handler specified and a default sub command.`, + "E_DUPLICATE_COMMAND", + ); + } + // Handle sub command let result: unknown; try { @@ -41,7 +50,8 @@ export async function runCommand( const subCommandArgIndex = opts.rawArgs.findIndex( (arg) => !arg.startsWith("-"), ); - const subCommandName = opts.rawArgs[subCommandArgIndex]; + const subCommandName = + opts.rawArgs[subCommandArgIndex] || defaultSubCommand; if (subCommandName) { if (!subCommands[subCommandName]) { throw new CLIError( diff --git a/src/types.ts b/src/types.ts index a622922..ba2df6b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -90,6 +90,7 @@ export type SubCommandsDef = Record>>; export type CommandDef = { meta?: Resolvable; args?: Resolvable; + default?: Resolvable; subCommands?: Resolvable; setup?: (context: CommandContext) => any | Promise; cleanup?: (context: CommandContext) => any | Promise;