All files / infrastructure/scripts/src/worktree main.ts

95.45% Statements 21/22
75% Branches 9/12
100% Functions 6/6
100% Lines 18/18

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                      1x 1x     1x       1x 4x 4x   4x 4x 1x 2x         3x 4x 4x   2x   2x 2x 1x               1x    
import { resolve } from "node:path";
import process from "node:process";
import { out } from "../shared/adapters/io.ts";
import type { Args } from "../shared/cli.ts";
import { excerpt } from "../shared/domain/logs.ts";
import { ExpectedError } from "../shared/errors.ts";
import { canonical, copyMissing, isInstalled } from "./adapters/files.ts";
import { envFiles, worktreeList } from "./adapters/git.ts";
import { install } from "./adapters/pnpm.ts";
import { parseWorktrees, preparedLine } from "./domain/worktree.ts";
 
const usage = (unprepared: string[]): string =>
    [
        "Name the worktree: pnpm worktree:prepare <path>",
        ...(unprepared.length > 0
            ? ["Linked worktrees with no node_modules:", ...unprepared.map((path) => `  ${path}`)]
            : ["Every linked worktree already has node_modules."]),
    ].join("\n");
 
export const main = ({ positionals }: Args): void => {
    const [primary, ...linked] = parseWorktrees(worktreeList());
    Iif (!primary) throw new ExpectedError("git worktree list printed nothing.");
 
    const [requested] = positionals;
    if (!requested) {
        throw new ExpectedError(
            usage(linked.map(({ path }) => path).filter((path) => !isInstalled(path))),
        );
    }
 
    // pnpm runs this from the package directory, and INIT_CWD is where the command was typed.
    const path = canonical(resolve(process.env.INIT_CWD ?? process.cwd(), requested));
    const target = linked.find((tree) => canonical(tree.path) === path);
    if (!target) throw new ExpectedError(`${path} is not a linked worktree of this repository.`);
 
    const copied = copyMissing(primary.path, target.path, envFiles(primary.path));
 
    const { status, stdout, stderr } = install(target.path);
    if (status !== 0) {
        throw new ExpectedError(
            [
                `pnpm install failed in ${target.path}:`,
                ...excerpt(`${stdout}\n${stderr}`).lines,
            ].join("\n"),
        );
    }
 
    out.success(preparedLine(target.path, copied));
};