Cotton code
194 lines · 8.1 KB · TypeScriptRaw
import { execFileSync } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { afterEach, describe, expect, it } from "vitest";/** * The pre-push hook refuses a push whose only news is a merge git would have * made by itself — a branch caught up to main (or to a sibling branch) with * nothing resolved by hand. Such a push buys nothing, because the merge queue * tests every train against main, and it costs the pull its run in flight: * `checks.yml` cancels in progress. On 28 Sep 2026, 242 of the 403 job * minutes thrown away by cancelled pull runs were these merges. * * Exercised by RUNNING the real hook against a scratch repository fed the ref * lines git would feed, with test runners stubbed, so a push the guard lets * through exits 0 and one it refuses exits 1. */const ROOT = resolve(__dirname, "../..");const HOOK = join(ROOT, "scripts/git-hooks/pre-push");const ZERO = "0".repeat(40);let scratch = "";afterEach(() => {  if (scratch) rmSync(scratch, { recursive: true, force: true });  scratch = "";});type Repo = { dir: string; bin: string; git: (...args: string[]) => string };function repo(): Repo {  scratch = mkdtempSync(join(tmpdir(), "pre-push-catch-up-"));  const bin = join(scratch, "bin");  mkdirSync(bin, { recursive: true });  writeFileSync(join(bin, "pnpm"), "#!/usr/bin/env bash\nexit 0\n", { mode: 0o755 });  const dir = join(scratch, "repo");  mkdirSync(join(dir, "scripts"), { recursive: true });  const git = (...args: string[]) =>    execFileSync("git", args, {      cwd: dir,      encoding: "utf8",      env: {        ...process.env,        GIT_AUTHOR_NAME: "t",        GIT_AUTHOR_EMAIL: "t@t",        GIT_COMMITTER_NAME: "t",        GIT_COMMITTER_EMAIL: "t@t",      },    }).trim();  git("init", "-q", "-b", "main");  writeFileSync(join(dir, "scripts/verify-fast.sh"), "#!/usr/bin/env bash\nexit 0\n", { mode: 0o755 });  writeFileSync(join(dir, "shared.txt"), "one\n");  git("add", "-A");  git("commit", "-q", "-m", "root");  return { dir, bin, git };}function commit(r: Repo, file: string, body: string, message: string): string {  writeFileSync(join(r.dir, file), body);  r.git("add", "-A");  r.git("commit", "-q", "-m", message);  return r.git("rev-parse", "HEAD");}/** A branch the remote already has (`pushed`), then main moves on. */function pulled(r: Repo): { pushed: string } {  r.git("checkout", "-q", "-b", "feature");  const pushed = commit(r, "feature.txt", "work\n", "feature work");  r.git("checkout", "-q", "main");  commit(r, "main.txt", "main moved\n", "main moves on");  r.git("checkout", "-q", "feature");  return { pushed };}function push(r: Repo, line: string, env: Record<string, string> = {}): { status: number; out: string } {  try {    const out = execFileSync("bash", ["-c", `bash "${HOOK}" 2>&1`], {      cwd: r.dir,      timeout: 5000,      encoding: "utf8",      input: `${line}\n`,      env: { ...process.env, CI: "", COTTON_MACHINE_LOCK_OS: "Linux", PATH: `${r.bin}:${process.env.PATH ?? ""}`, ...env },    });    return { status: 0, out };  } catch (e) {    const err = e as { status?: number; stdout?: string; stderr?: string };    return { status: err.status ?? 1, out: `${err.stdout ?? ""}${err.stderr ?? ""}` };  }}const feature = (local: string, remote: string) => `refs/heads/feature ${local} refs/heads/feature ${remote}`;describe("pre-push: a merge that only catches a branch up", () => {  /// RULE: pre-push runs no tests or build tools, even when harness files change; tests can wait on a build lock another lane holds and hang a push indefinitely.  it("pushes harness changes without starting a test runner or build tool", () => {    const r = repo();    const before = r.git("rev-parse", "HEAD");    const marker = join(scratch, "runner-started");    for (const tool of ["pnpm", "cargo", "swift", "xcodebuild"]) {      writeFileSync(join(r.bin, tool), `#!/usr/bin/env bash\ntouch "${marker}"\nexit 1\n`, { mode: 0o755 });    }    mkdirSync(join(r.dir, ".forgejo/workflows"), { recursive: true });    mkdirSync(join(r.dir, ".claude"), { recursive: true });    writeFileSync(join(r.dir, "scripts/change.sh"), "# synthetic\n");    writeFileSync(join(r.dir, ".forgejo/workflows/change.yml"), "# synthetic\n");    writeFileSync(join(r.dir, ".claude/change.json"), "{}\n");    const tip = commit(r, "package.json", "{}\n", "synthetic harness changes");    const result = push(r, feature(tip, before));    expect(result.status, result.out).toBe(0);    expect(existsSync(marker), result.out).toBe(false);  });  // RULE: A push that only merges main (or a sibling branch) into an open pull, with nothing resolved by hand, is refused — it would cancel that pull's run for nothing, since the merge queue tests every train against main.  it("refuses a clean merge of main pushed onto a branch the remote has", () => {    const r = repo();    const { pushed } = pulled(r);    r.git("merge", "-q", "--no-edit", "main");    const result = push(r, feature(r.git("rev-parse", "HEAD"), pushed));    expect(result.status).toBe(1);    expect(result.out).toContain("only catches a branch up");    expect(result.out).toContain("feature: ");  });  it("refuses it even with the retired COTTON_SKIP_PREPUSH switch", () => {    const r = repo();    const { pushed } = pulled(r);    r.git("merge", "-q", "--no-edit", "main");    expect(push(r, feature(r.git("rev-parse", "HEAD"), pushed), { COTTON_SKIP_PREPUSH: "1" }).status).toBe(1);  });  it("lets it through with COTTON_ALLOW_CATCH_UP_MERGE=1", () => {    const r = repo();    const { pushed } = pulled(r);    r.git("merge", "-q", "--no-edit", "main");    expect(push(r, feature(r.git("rev-parse", "HEAD"), pushed), { COTTON_ALLOW_CATCH_UP_MERGE: "1" }).status).toBe(0);  });  it("lets a merge through that resolved a conflict by hand — that is new work", () => {    const r = repo();    r.git("checkout", "-q", "-b", "feature");    const pushed = commit(r, "shared.txt", "feature side\n", "feature edits shared");    r.git("checkout", "-q", "main");    commit(r, "shared.txt", "main side\n", "main edits shared");    r.git("checkout", "-q", "feature");    try {      r.git("merge", "-q", "--no-edit", "main");    } catch {      // the conflict is the point of this case    }    writeFileSync(join(r.dir, "shared.txt"), "both sides\n");    r.git("add", "-A");    r.git("commit", "-q", "--no-edit");    expect(push(r, feature(r.git("rev-parse", "HEAD"), pushed)).status).toBe(0);  });  // RULE: Only a merge this push brings is judged — main's own merges, which a rebase carries past the old head, are not the pull catching up.  it("lets a branch rebased onto main through, though main's own history holds clean merges", () => {    const r = repo();    const { pushed } = pulled(r);    r.git("checkout", "-q", "-b", "side", "main");    commit(r, "side.txt", "side\n", "side work");    r.git("checkout", "-q", "main");    r.git("merge", "-q", "--no-ff", "--no-edit", "side");    r.git("checkout", "-q", "feature");    r.git("rebase", "-q", "main");    expect(r.git("rev-list", "--merges", `${pushed}..HEAD`)).not.toBe("");    const result = push(r, feature(r.git("rev-parse", "HEAD"), pushed));    expect(result.out).not.toContain("only catches a branch up");    expect(result.status, result.out).toBe(0);  });  it("lets ordinary new work through", () => {    const r = repo();    const { pushed } = pulled(r);    const next = commit(r, "feature.txt", "more work\n", "more feature work");    expect(push(r, feature(next, pushed)).status).toBe(0);  });  it("lets a new branch through, merge or not — it has no run to cancel", () => {    const r = repo();    pulled(r);    r.git("merge", "-q", "--no-edit", "main");    expect(push(r, feature(r.git("rev-parse", "HEAD"), ZERO)).status).toBe(0);  });  it("never stands in the way of main itself", () => {    const r = repo();    const { pushed } = pulled(r);    r.git("merge", "-q", "--no-edit", "main");    const head = r.git("rev-parse", "HEAD");    expect(push(r, `refs/heads/main ${head} refs/heads/main ${pushed}`).status).toBe(0);  });});