Skip to content

feat: allow overriding --version and --help with custom args #196

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

Open
wants to merge 1 commit 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
28 changes: 27 additions & 1 deletion src/command.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { CommandContext, CommandDef, ArgsDef } from "./types";
import { CLIError, resolveValue } from "./_utils";
import { parseArgs } from "./args";
import { parseArgs, resolveArgs } from "./args";

export function defineCommand<const T extends ArgsDef = ArgsDef>(
def: CommandDef<T>,
Expand Down Expand Up @@ -92,3 +92,29 @@ export async function resolveSubCommand<T extends ArgsDef = ArgsDef>(
}
return [cmd, parent];
}

export async function extendCmd<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
rawArgs: string[],
extendedArgs: string[],
extendedCmd: (
cmd: CommandDef<T>,
parent?: CommandDef<T>,
) => void | Promise<void>,
) {
const extendedArg = rawArgs.find((arg) => extendedArgs.includes(arg));

if (extendedArg) {
const [subCmd, parent] = await resolveSubCommand(cmd, rawArgs);
const cmdArgs = resolveArgs(await resolveValue(subCmd.args || {}));

const supportedArgs = cmdArgs.flatMap((arg) => [
`--${arg.name}`,
...arg.alias.map((a) => `-${a}`),
]);

if (!supportedArgs.includes(extendedArg)) {
await extendedCmd(subCmd, parent);
}
}
}
18 changes: 11 additions & 7 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import consola from "consola";
import type { ArgsDef, CommandDef } from "./types";
import { resolveSubCommand, runCommand } from "./command";
import { extendCmd, resolveSubCommand, runCommand } from "./command";
import { CLIError } from "./_utils";
import { showUsage as _showUsage } from "./usage";

Expand All @@ -15,20 +15,24 @@ export async function runMain<T extends ArgsDef = ArgsDef>(
) {
const rawArgs = opts.rawArgs || process.argv.slice(2);
const showUsage = opts.showUsage || _showUsage;

try {
if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
await extendCmd(cmd, rawArgs, ["--help", "-h"], async (cmd, parent) => {
await showUsage(cmd, parent);
process.exit(0);
} else if (rawArgs.length === 1 && rawArgs[0] === "--version") {
});

await extendCmd(cmd, rawArgs, ["--version", "-v"], async (cmd) => {
const meta =
typeof cmd.meta === "function" ? await cmd.meta() : await cmd.meta;
if (!meta?.version) {
throw new CLIError("No version specified", "E_NO_VERSION");
}
consola.log(meta.version);
} else {
await runCommand(cmd, { rawArgs });
}
process.exit(0);
});

await runCommand(cmd, { rawArgs });
} catch (error: any) {
const isCLIError = error instanceof CLIError;
if (isCLIError) {
Expand Down
104 changes: 103 additions & 1 deletion test/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, afterAll } from "vitest";
import { describe, it, expect, vi, afterAll, beforeEach } from "vitest";
import consola from "consola";
import {
createMain,
Expand All @@ -20,6 +20,11 @@ describe("runMain", () => {
.spyOn(consola, "error")
.mockImplementation(() => undefined);

beforeEach(() => {
consoleMock.mockClear();
consolaErrorMock.mockClear();
});

afterAll(() => {
consoleMock.mockReset();
});
Expand Down Expand Up @@ -62,6 +67,54 @@ describe("runMain", () => {
expect(consolaErrorMock).toHaveBeenCalledWith("No version specified");
});

it.each([["--version"], ["-v"]])(
"can override default `%s` behavior",
async (flag) => {
const calls: string[] = [];
const command = defineCommand({
meta: {
version: "1.0.0",
},
args: {
version: {
type: "boolean",
description: "Override default `version` behavior",
alias: "v",
},
},
subCommands: {
foo: {
args: {
version: {
type: "boolean",
description: "Override subcommand's default `version` behavior",
alias: "v",
},
},
run() {
calls.push("SubCommand Overridden");
},
},
},
run() {
calls.push("TopCommand Overridden");
},
});

await runMain(command, { rawArgs: [flag] });
expect(calls).toMatchObject(["TopCommand Overridden"]);
expect(consoleMock).not.toHaveBeenCalledWith("1.0.0");

calls.length = 0;
await runMain(command, { rawArgs: ["foo", flag] });
expect(calls).toMatchObject([
"SubCommand Overridden",
"TopCommand Overridden",
]);
expect(consoleMock).not.toHaveBeenCalledWith("1.0.0");
},
);

it.each([["--help"], ["-h"]])("shows usage with flag `%s`", async (flag) => {
const command = defineCommand({
meta: {
Expand Down Expand Up @@ -96,6 +149,55 @@ describe("runMain", () => {
},
);

it.each([["--help"], ["-h"]])(
"can override default `%s` behavior",
async (flag) => {
const calls: string[] = [];
const command = defineCommand({
meta: {
name: "test",
description: "Test command",
},
args: {
help: {
type: "boolean",
description: "Override default `help` behavior",
alias: "h",
},
},
subCommands: {
foo: {
args: {
help: {
type: "boolean",
description: "Override subcommand's default `help` behavior",
alias: "h",
},
},
run() {
calls.push("SubCommand Overridden");
},
},
},
run() {
calls.push("TopCommand Overridden");
},
});

await runMain(command, { rawArgs: [flag] });
expect(calls).toMatchObject(["TopCommand Overridden"]);
expect(consoleMock).not.toHaveBeenCalledWith("Test command");

calls.length = 0;
await runMain(command, { rawArgs: ["foo", flag] });
expect(calls).toMatchObject([
"SubCommand Overridden",
"TopCommand Overridden",
]);
expect(consoleMock).not.toHaveBeenCalledWith("Test command");
},
);

it("runs the command", async () => {
const mockRunCommand = vi.spyOn(commandModule, "runCommand");

Expand Down