All files / infrastructure/scripts/src/shared cli.ts

90% Statements 36/40
52.38% Branches 11/21
85.71% Functions 6/7
89.47% Lines 34/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99                      7x     3x 8x 8x     3x 4x 4x 1x 1x     3x     3x 7x 7x 5x 1x     2x 7x 1x 1x     1x         4x         3x   3x           7x 7x           7x                             3x 7x 7x     7x       7x   7x   7x 7x    
import process from "node:process";
import { out } from "./adapters/io.ts";
import { appendUsage, currentBranch, projectNames } from "./adapters/usage.ts";
import { dispatch, invocation, parse, report as classifyError, type Args } from "./domain/cli.ts";
import { areaOf, callerOf, flagLabels, isRecorded, scriptOf, targetOf } from "./domain/usage.ts";
 
export type { Args } from "./domain/cli.ts";
 
export type Command = (args: Args) => void | Promise<void>;
 
/** Read per call so importing a module cannot freeze the flag's value. */
export const flag = (name: string): boolean => process.argv.includes(`--${name}`);
 
// `pnpm docs:map --check | tee log` truncated with `process.exit` — a write to a pipe is async in Node.
export const fail = (message: string): void => {
    out.error(message);
    process.exitCode = 1;
};
 
const report = (error: unknown): void => {
    const result = classifyError(error);
    if (result.cancelled) {
        out.cancelled(result.message);
        return;
    }
 
    fail(result.message);
};
 
const execute = async (commands: Command | Record<string, Command>, args: Args): Promise<void> => {
    try {
        if (typeof commands === "function") {
            await commands(args);
            return;
        }
 
        const result = dispatch(commands, args, invocation(process.argv[1] ?? "", process.cwd()));
        if (!result.matched) {
            fail(result.usage);
            return;
        }
 
        await result.command({
            flags: result.args.flags,
            positionals: result.args.positionalsWithoutCommandName,
        });
    } catch (error) {
        report(error);
    }
};
 
/** The shell's code for a process ended by Ctrl+C. */
const INTERRUPTED = 130;
 
const record = (
    commands: Command | Record<string, Command>,
    args: Args,
    startedAt: number,
    exit: number,
): void => {
    const script = scriptOf(process.argv[1] ?? "");
    Eif (!isRecorded(process.env, script)) return;
 
    const [first] = args.positionals;
    const isSubcommand =
        typeof commands !== "function" && first !== undefined && Object.hasOwn(commands, first);
 
    appendUsage({
        // The repo is public, so a time of day would publish when its owner works.
        at: new Date(startedAt).toISOString().slice(0, 10),
        script,
        command: isSubcommand ? first : "",
        target: targetOf(args.positionals, projectNames()),
        flags: flagLabels(args.flags),
        area: areaOf(currentBranch()),
        caller: callerOf(process.env),
        tty: process.stdout.isTTY ? "1" : "0",
        exit: String(exit),
        ms: String(Date.now() - startedAt),
    });
};
 
export const run = async (commands: Command | Record<string, Command>): Promise<void> => {
    const startedAt = Date.now();
    const args = parse(process.argv.slice(2));
 
    // Without this a Ctrl+C on `pnpm dev` kills the process before the row below is written.
    const interrupt = (): void => {
        record(commands, args, startedAt, INTERRUPTED);
        process.exit(INTERRUPTED);
    };
    process.once("SIGINT", interrupt);
 
    await execute(commands, args);
 
    process.off("SIGINT", interrupt);
    record(commands, args, startedAt, Number(process.exitCode ?? 0));
};