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: add .catch to command declaration #113

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"dev": "vitest dev",
"lint": "eslint --cache --ext .ts,.js,.mjs,.cjs . && prettier -c src test",
"lint:fix": "eslint --cache --ext .ts,.js,.mjs,.cjs . --fix && prettier -c src test -w",
"format": "prettier -c src test -w",
"prepack": "pnpm run build",
"play": "jiti ./playground/cli.ts",
"release": "pnpm test && changelogen --release --push && npm publish",
Expand Down
9 changes: 7 additions & 2 deletions playground/cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { defineCommand, runMain } from "../src";

const main = defineCommand({
export const main = defineCommand({
meta: {
name: "citty",
version: "1.0.0",
Expand All @@ -15,8 +15,13 @@ const main = defineCommand({
subCommands: {
build: () => import("./commands/build").then((r) => r.default),
deploy: () => import("./commands/deploy").then((r) => r.default),
error: () => import("./commands/error").then((r) => r.default),
"error-no-catch": () =>
import("./commands/error-no-catch").then((r) => r.default),
debug: () => import("./commands/debug").then((r) => r.default),
},
});

runMain(main);
if (process.env.NODE_ENV !== "test") {
runMain(main);
}
36 changes: 36 additions & 0 deletions playground/commands/error-no-catch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { defineCommand } from "../../src";

export default defineCommand({
meta: {
name: "error-no-catch",
description:
"Throws an error to test .catch functionality, does not have error handling",
},

args: {
throwType: {
type: "string",
},
},

run({ args }) {
switch (args.throwType) {
case "string": {
console.log("Throw string");
// we intentionally are throwing something invalid for testing purposes
// eslint-disable-next-line no-throw-literal
throw "Not an error!";
}
case "empty": {
console.log("Throw undefined");
// we intentionally are throwing something invalid for testing purposes
// eslint-disable-next-line no-throw-literal
throw undefined;
}
default: {
console.log("Throw Error");
throw new Error("Error!");
}
}
},
});
19 changes: 19 additions & 0 deletions playground/commands/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import consola from "consola";
import { defineCommand } from "../../src";

export default defineCommand({
meta: {
name: "error",
description: "Throws an error to test .catch functionality",
},

run() {
throw new Error("Hello World");
},
catch(_, e) {
consola.error(`Caught error: ${e}`);
if (!(e instanceof Error)) {
throw new TypeError("Recieved non-error value");
}
},
});
11 changes: 11 additions & 0 deletions src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ export async function runCommand<T extends ArgsDef = ArgsDef>(
if (typeof cmd.run === "function") {
result = await cmd.run(context);
}
} catch (error_) {
const error =
error_ instanceof Error
? error_
: new Error(error_?.toString() ?? "Unknown Error", { cause: error_ });
if (typeof cmd.catch === "function") {
// Attempt to coerce e into an error to ensure type safety
await cmd.catch(context, error);
} else {
throw error;
}
} finally {
if (typeof cmd.cleanup === "function") {
await cmd.cleanup(context);
Expand Down
4 changes: 3 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ export async function runMain<T extends ArgsDef = ArgsDef>(
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
}
consola.error(error.message);
process.exit(1);
if (process.env.NODE_ENV !== "test") {
process.exit(1);
}
}
}

Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export type CommandDef<T extends ArgsDef = ArgsDef> = {
subCommands?: Resolvable<SubCommandsDef>;
setup?: (context: CommandContext<T>) => any | Promise<any>;
cleanup?: (context: CommandContext<T>) => any | Promise<any>;
catch?: (context: CommandContext<T>, e: Error) => any | Promise<any>;
run?: (context: CommandContext<T>) => any | Promise<any>;
};

Expand Down
36 changes: 36 additions & 0 deletions test/error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect, it, describe } from "vitest";
import { main } from "../playground/cli";
import { runCommand } from "../src/command";

describe("citty", () => {
it.todo("pass", () => {
expect(true).toBe(true);
});

describe("commands", () => {
describe("error", () => {
it("should catch thrown errors when present", () => {
expect(() =>
runCommand(main, { rawArgs: ["error"] }),
).not.toThrowError();
});
it("should still recieve an error when a string is thrown from the command", () =>
expect(
runCommand(main, {
rawArgs: ["error-no-catch", "--throwType", "string"],
}),
).rejects.toThrowError());
it("should still recieve an error when undefined is thrown from the command", () =>
expect(
runCommand(main, {
rawArgs: ["error-no-catch", "--throwType", "empty"],
}),
).rejects.toThrowError());

it("should not interfere with default error handling when not present", () =>
expect(() =>
runCommand(main, { rawArgs: ["error-no-catch"] }),
).rejects.toBeInstanceOf(Error));
});
});
});