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: exports low level APIs #135

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,21 @@ Runs a command with usage support and graceful error handling.

Create a wrapper around command that calls `runMain` when called.

### `runRawMain`

Runs a command. Unlike `runMain`, this function requires you to define command execution handling like `handleCommand` and error handling yourself like `handleError` and specify them as arguments.

> [!NOTE]
> This function is a low-level function compared to `runMain`. You should also implement your own `showUsage` etc. and specify it as an option.

### `handleCommand`

A handler that implements the logic to execute commands with usage support. It is used inside in `runMain`. You can specify it as a helper to `run`.

### `handleError`

An error handler that implementes the logic to graceful error handling. It is used inside `runMain`. You can specify it as a helper to `run`.

### `runCommand`

Parses input args and runs command and sub-commands (unsupervised). You can access `result` key from returnd/awaited value to access command's result.
Expand All @@ -104,6 +119,10 @@ Renders command usage to a string value.

Renders usage and prints to the console

### `formatLineColumns`

Formats line columns. If you define custom `showUsage`, it is convenient to adjust the format with this function.

## Development

- Clone this repository
Expand Down
19 changes: 0 additions & 19 deletions src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,6 @@ export function toArray(val: any) {
return val === undefined ? [] : [val];
}

export function formatLineColumns(lines: string[][], linePrefix = "") {
const maxLengh: number[] = [];
for (const line of lines) {
for (const [i, element] of line.entries()) {
maxLengh[i] = Math.max(maxLengh[i] || 0, element.length);
}
}
return lines
.map((l) =>
l
.map(
(c, i) =>
linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLengh[i]),
)
.join(" "),
)
.join("\n");
}

export function resolveValue<T>(input: Resolvable<T>): T | Promise<T> {
return typeof input === "function" ? (input as any)() : input;
}
Expand Down
12 changes: 9 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
export * from "./types";
export type { RunCommandOptions } from "./command";
export type { RunMainOptions } from "./main";
export type { RunMainOptions, RunArgs, RunHandlers } from "./main";

export { defineCommand, runCommand } from "./command";
export { parseArgs } from "./args";
export { renderUsage, showUsage } from "./usage";
export { runMain, createMain } from "./main";
export { renderUsage, showUsage, formatLineColumns } from "./usage";
export {
runMain,
createMain,
runRawMain,
handleCommand,
handleError,
} from "./main";
86 changes: 62 additions & 24 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,77 @@ export interface RunMainOptions {
showUsage?: typeof _showUsage;
}

export async function runMain<T extends ArgsDef = ArgsDef>(
export interface RunArgs<T extends ArgsDef = ArgsDef> {
cmd: CommandDef<T>;
rawArgs: string[];
showUsage?: typeof _showUsage;
}

export interface RunHandlers<
T extends ArgsDef = ArgsDef,
E extends Error = Error,
> {
command: (args: RunArgs<T>) => Promise<void>;
error: (args: RunArgs<T>, error: E) => Promise<void>;
}

export async function handleCommand<T extends ArgsDef = ArgsDef>({
cmd,
rawArgs,
showUsage,
}: RunArgs<T>): Promise<void> {
if ((rawArgs.includes("--help") || rawArgs.includes("-h")) && showUsage) {
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
process.exit(0);
} else if (rawArgs.length === 1 && rawArgs[0] === "--version") {
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 });
}
}

export async function handleError<
T extends ArgsDef = ArgsDef,
E extends Error = Error,
>({ cmd, rawArgs, showUsage }: RunArgs<T>, error: E) {
const isCLIError = error instanceof CLIError;
if (!isCLIError) {
consola.error(error, "\n");
}
if (isCLIError && showUsage) {
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
}
consola.error(error.message);
process.exit(1);
}

export async function runRawMain<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
handlers: RunHandlers<T>,
opts: RunMainOptions = {},
) {
const rawArgs = opts.rawArgs || process.argv.slice(2);
const showUsage = opts.showUsage || _showUsage;
const args = { cmd, rawArgs, showUsage: opts.showUsage };
try {
if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
process.exit(0);
} else if (rawArgs.length === 1 && rawArgs[0] === "--version") {
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 });
}
await handlers.command(args);
} catch (error: any) {
const isCLIError = error instanceof CLIError;
if (!isCLIError) {
consola.error(error, "\n");
}
if (isCLIError) {
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
}
consola.error(error.message);
process.exit(1);
await handlers.error(args, error);
}
}

export async function runMain<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
opts: RunMainOptions = {},
) {
opts.showUsage = opts.showUsage || _showUsage;
await runRawMain(cmd, { command: handleCommand, error: handleError }, opts);
}

export function createMain<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
): (opts?: RunMainOptions) => Promise<void> {
Expand Down
21 changes: 20 additions & 1 deletion src/usage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import consola from "consola";
import { colors } from "consola/utils";
import { formatLineColumns, resolveValue } from "./_utils";
import { resolveValue } from "./_utils";
import type { ArgsDef, CommandDef } from "./types";
import { resolveArgs } from "./args";

Expand Down Expand Up @@ -136,3 +136,22 @@ export async function renderUsage<T extends ArgsDef = ArgsDef>(

return usageLines.filter((l) => typeof l === "string").join("\n");
}

export function formatLineColumns(lines: string[][], linePrefix = "") {
const maxLengh: number[] = [];
for (const line of lines) {
for (const [i, element] of line.entries()) {
maxLengh[i] = Math.max(maxLengh[i] || 0, element.length);
}
}
return lines
.map((l) =>
l
.map(
(c, i) =>
linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLengh[i]),
)
.join(" "),
)
.join("\n");
}