diff --git a/src/_utils.ts b/src/_utils.ts index 467fe01..dc357fd 100644 --- a/src/_utils.ts +++ b/src/_utils.ts @@ -1,5 +1,13 @@ import type { Resolvable } from "./types"; +export function runIfFunction Promise | void>(val: T | undefined) { + return async function (...args: Parameters) { + if (typeof val === 'function') { + await val(...args) + } + } +} + export function toArray(val: any) { if (Array.isArray(val)) { return val; diff --git a/src/command.ts b/src/command.ts index 77df00d..fe6386b 100644 --- a/src/command.ts +++ b/src/command.ts @@ -1,5 +1,5 @@ import type { CommandContext, CommandDef, ArgsDef } from "./types"; -import { CLIError, resolveValue } from "./_utils"; +import { CLIError, resolveValue, runIfFunction } from "./_utils"; import { parseArgs } from "./args"; export function defineCommand( @@ -29,9 +29,7 @@ export async function runCommand( }; // Setup hook - if (typeof cmd.setup === "function") { - await cmd.setup(context); - } + await runIfFunction(cmd.setup)(context); // Handle sub command try { @@ -60,13 +58,11 @@ export async function runCommand( } // Handle main command - if (typeof cmd.run === "function") { - await cmd.run(context); - } + await runIfFunction(cmd.before)(context); + await runIfFunction(cmd.run)(context); } finally { - if (typeof cmd.cleanup === "function") { - await cmd.cleanup(context); - } + await runIfFunction(cmd.after)(context); + await runIfFunction(cmd.cleanup)(context); } } diff --git a/src/types.ts b/src/types.ts index cd71977..a903154 100644 --- a/src/types.ts +++ b/src/types.ts @@ -54,6 +54,8 @@ export type CommandDef = { meta?: Resolvable; args?: Resolvable; subCommands?: Resolvable; + before?: (context: CommandContext) => any | Promise; + after?: (context: CommandContext) => any | Promise; setup?: (context: CommandContext) => any | Promise; cleanup?: (context: CommandContext) => any | Promise; run?: (context: CommandContext) => any | Promise;