/** * bash-command-collapse/git-meta.ts 的测试:真 git fixture 驱动(tmpdir 里 `git init`)。 * * 要钉住的是「什么时候**不**返回根」:主仓根会话、非 git 目录、git 跑不起来都必须返回 `[]`, * 否则 sandbox profile 会在主仓根会话里多出无关的可删根(等于无谓扩大删除边界)。 * * node --test clients/pi/extensions/bash-command-collapse/git-meta.test.ts */ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { gitMetaWriteRoots } from "./git-meta.ts"; const cleanup: Array<() => void> = []; test.after(() => { for (const fn of cleanup) fn(); }); function makeRepo(): { repo: string; worktree: string } { const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pi-gitmeta-"))); const repo = path.join(root, "repo"); fs.mkdirSync(repo); const git = (cwd: string, ...args: string[]) => { const r = spawnSync("git", args, { cwd, encoding: "utf8" }); assert.equal(r.status, 0, `git ${args.join(" ")}: ${r.stderr}`); }; git(repo, "init", "-q"); git(repo, "config", "user.email", "t@example.com"); git(repo, "config", "user.name", "t"); git(repo, "config", "commit.gpgsign", "false"); fs.writeFileSync(path.join(repo, "a.txt"), "a\n"); git(repo, "add", "."); git(repo, "commit", "-qm", "init"); const worktree = path.join(repo, ".worktrees", "feat"); git(repo, "worktree", "add", "-q", worktree, "-b", "feat"); cleanup.push(() => fs.rmSync(root, { recursive: true, force: true })); return { repo, worktree }; } test("主仓根作 cwd:不返回任何额外根", () => { const { repo } = makeRepo(); assert.deepEqual(gitMetaWriteRoots(repo), []); }); test("linked worktree 作 cwd:返回主仓的 .git 目录(realpath)", () => { const { repo, worktree } = makeRepo(); const roots = gitMetaWriteRoots(worktree); assert.equal(roots.length, 1); assert.equal(fs.realpathSync(roots[0]), fs.realpathSync(path.join(repo, ".git"))); }); test("非 git 目录:不返回根,也不抛", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-gitmeta-nogit-")); cleanup.push(() => fs.rmSync(dir, { recursive: true, force: true })); assert.deepEqual(gitMetaWriteRoots(dir), []); }); test("git 跑不起来(注入抛错的执行器):不返回根,也不抛", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-gitmeta-broken-")); cleanup.push(() => fs.rmSync(dir, { recursive: true, force: true })); const boom = () => { throw new Error("git not found"); }; assert.deepEqual(gitMetaWriteRoots(dir, boom), []); }); test("子目录作 cwd(在主仓里):仍不返回根", () => { const { repo } = makeRepo(); const sub = path.join(repo, "sub"); fs.mkdirSync(sub); assert.deepEqual(gitMetaWriteRoots(sub), []); });