Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support before/after hooks #100

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import type { Resolvable } from "./types";

export function runIfFunction<T extends (...args: any[]) => Promise<void> | void>(val: T | undefined) {
return async function (...args: Parameters<T>) {
if (typeof val === 'function') {
await val(...args)
}
}
}

export function toArray(val: any) {
if (Array.isArray(val)) {
return val;
Expand Down
16 changes: 6 additions & 10 deletions src/command.ts
Original file line number Diff line number Diff line change
@@ -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<T extends ArgsDef = ArgsDef>(
Expand Down Expand Up @@ -29,9 +29,7 @@ export async function runCommand<T extends ArgsDef = ArgsDef>(
};

// Setup hook
if (typeof cmd.setup === "function") {
await cmd.setup(context);
}
await runIfFunction(cmd.setup)(context);

// Handle sub command
try {
Expand Down Expand Up @@ -60,13 +58,11 @@ export async function runCommand<T extends ArgsDef = ArgsDef>(
}

// 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);
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export type CommandDef<T extends ArgsDef = ArgsDef> = {
meta?: Resolvable<CommandMeta>;
args?: Resolvable<T>;
subCommands?: Resolvable<SubCommandsDef>;
before?: (context: CommandContext<T>) => any | Promise<any>;
after?: (context: CommandContext<T>) => any | Promise<any>;
setup?: (context: CommandContext<T>) => any | Promise<any>;
cleanup?: (context: CommandContext<T>) => any | Promise<any>;
run?: (context: CommandContext<T>) => any | Promise<any>;
Expand Down