-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathmain.ts
More file actions
50 lines (45 loc) · 1.51 KB
/
main.ts
File metadata and controls
50 lines (45 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import consola from "consola";
import { resolveSubCommand, runCommand } from "./command.ts";
import { CLIError } from "./_utils.ts";
import { showUsage as _showUsage } from "./usage.ts";
import type { ArgsDef, CommandDef } from "./types.ts";
export interface RunMainOptions {
rawArgs?: string[];
showUsage?: typeof _showUsage;
}
export async function runMain<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
opts: RunMainOptions = {},
) {
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)));
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 });
}
} catch (error: any) {
const isCLIError = error instanceof CLIError;
if (isCLIError) {
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
consola.error(error.message);
} else {
consola.error(error, "\n");
}
process.exit(1);
}
}
export function createMain<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
): (opts?: RunMainOptions) => Promise<void> {
return (opts: RunMainOptions = {}) => runMain(cmd, opts);
}