/** * worktree/git.ts 的测试:**真 git fixture** 驱动(tmpdir 里 `git init` + 一次 commit), * 不起 pi、不 mock git。 * * 为什么真 git:这里要验证的正是 git 自己的语义 —— `worktree add` 挂已有分支、 * `worktree remove` 不带 --force 时对脏树的行为、`.git/info/exclude` 是否真的让 * `git status` 安静下来。假执行器只能重复我自己写的假设。 * * node --test clients/pi/extensions/worktree/git.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 { branchExists, createWorktreeAt, ensureExclude, gitArgv, listWorktrees, removeWorktree, repoInfo, } from "./git.ts"; const cleanup: Array<() => void> = []; test.after(() => { for (const fn of cleanup) fn(); }); /** 建一个临时仓库:`/repo`,一次 commit,返回 realpath 后的仓库根。 */ function makeRepo(): { root: string; repo: string } { const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-git-"))); const repo = path.join(root, "repo"); fs.mkdirSync(repo); const git = (...args: string[]) => { const r = spawnSync("git", args, { cwd: repo, encoding: "utf8" }); assert.equal(r.status, 0, `git ${args.join(" ")}: ${r.stderr}`); return r.stdout; }; git("init", "-q"); git("config", "user.email", "t@example.com"); git("config", "user.name", "t"); git("config", "commit.gpgsign", "false"); fs.writeFileSync(path.join(repo, "a.txt"), "a\n"); git("add", "."); git("commit", "-qm", "init"); cleanup.push(() => fs.rmSync(root, { recursive: true, force: true })); return { root, repo }; } /** 主仓工作区是否干净(含未跟踪文件)。exclude 没生效时这里会冒出一堆 `.worktrees/`。 */ function porcelain(repo: string): string { return spawnSync("git", ["status", "--porcelain"], { cwd: repo, encoding: "utf8" }).stdout.trim(); } function untracked(repo: string): string { return spawnSync("git", ["ls-files", "--others", "--exclude-standard"], { cwd: repo, encoding: "utf8" }).stdout.trim(); } test("repoInfo 在主仓里:不是 linked worktree,repoRoot 是仓库根", () => { const { repo } = makeRepo(); const r = repoInfo(repo); assert.equal(r.ok, true); if (!r.ok) return; assert.equal(r.info.isLinkedWorktree, false); assert.equal(fs.realpathSync(r.info.repoRoot), repo); assert.match(r.info.headSha, /^[0-9a-f]{40,64}$/); assert.equal(fs.realpathSync(r.info.commonDir), path.join(repo, ".git")); }); test("从 linked worktree 里 repoInfo:isLinkedWorktree 为真,repoRoot 仍指向主仓根", () => { const { repo } = makeRepo(); const created = createWorktreeAt({ repoRoot: repo, name: "feat/x" }); assert.equal(created.ok, true); if (!created.ok) return; const r = repoInfo(created.path); assert.equal(r.ok, true); if (!r.ok) return; assert.equal(r.info.isLinkedWorktree, true); assert.equal(fs.realpathSync(r.info.repoRoot), repo, "repoRoot 必须是主仓根,不是 .worktrees/x"); assert.equal(fs.realpathSync(r.info.commonDir), path.join(repo, ".git")); }); test("不在 git 仓库里 repoInfo 失败并说明原因", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-nogit-")); cleanup.push(() => fs.rmSync(dir, { recursive: true, force: true })); const r = repoInfo(dir); assert.equal(r.ok, false); if (!r.ok) assert.match(r.reason, /仓库|repository/); }); test("cwd 已被删除(worktree 合并后删树):repoInfo 从最近祖先探测成功并标 cwdMissing", () => { const { repo } = makeRepo(); ensureExclude(repo); const created = createWorktreeAt({ repoRoot: repo, name: "feat/gone" }); assert.equal(created.ok, true); if (!created.ok) return; const gone = created.path; const removed = removeWorktree(repo, gone); assert.equal(removed.ok, true); assert.equal(fs.existsSync(gone), false, "前置:目录要真的没了"); // 修复前这里 ENOENT(spawnSync 的 cwd 不存在,git 根本没跑)→ 误报「不在 git 仓库里」 const r = repoInfo(gone); assert.equal(r.ok, true, "cwd 消失不能挡住探测"); if (!r.ok) return; assert.equal(r.info.cwdMissing, true); assert.equal(r.info.isLinkedWorktree, false, "祖先探测看到的是主仓"); assert.equal(fs.realpathSync(r.info.repoRoot), repo, "repoRoot 仍是主仓根 —— exit 的目标"); }); test("cwd 不存在且祖先也不在任何仓库里:失败原因点明目录已不存在", () => { const r = repoInfo("/nonexistent/pi-worktree-test/deep/path"); assert.equal(r.ok, false); if (!r.ok) assert.match(r.reason, /已不存在/); }); test("空仓库(无 commit)repoInfo 失败", () => { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-empty-"))); cleanup.push(() => fs.rmSync(dir, { recursive: true, force: true })); spawnSync("git", ["init", "-q"], { cwd: dir }); const r = repoInfo(dir); assert.equal(r.ok, false); }); test("ensureExclude 首次写入、第二次幂等、文件不存在时能创建", () => { const { repo } = makeRepo(); const exclude = path.join(repo, ".git", "info", "exclude"); // 首次:文件可能不存在(git init 通常建空文件),两种情况都要能写 const first = ensureExclude(repo); assert.equal(first.changed, true); const after = fs.readFileSync(exclude, "utf8"); assert.ok(after.split("\n").includes(".worktrees/"), "exclude 里要有 .worktrees/ 这一行"); const linesAfterFirst = after.split("\n").length; const second = ensureExclude(repo); assert.equal(second.changed, false, "第二次不应再写"); assert.equal(fs.readFileSync(exclude, "utf8").split("\n").length, linesAfterFirst, "行数不能变"); }); test("createWorktreeAt 建目录 + 建分支,且主仓 git status 保持干净", () => { const { repo } = makeRepo(); ensureExclude(repo); const r = createWorktreeAt({ repoRoot: repo, name: "feat/y" }); assert.equal(r.ok, true); if (!r.ok) return; assert.equal(r.created, true); assert.equal(fs.realpathSync(r.path), fs.realpathSync(path.join(repo, ".worktrees", "feat", "y"))); const branch = spawnSync("git", ["branch", "--show-current"], { cwd: r.path, encoding: "utf8" }).stdout.trim(); assert.equal(branch, "feat/y"); assert.equal(porcelain(repo), "", "主仓必须保持干净"); assert.equal(untracked(repo), "", "未跟踪列表也必须为空(exclude 生效)"); }); test("同名分支已存在时挂上去而不是报错", () => { const { repo } = makeRepo(); ensureExclude(repo); assert.equal(branchExists(repo, "dup"), false); spawnSync("git", ["branch", "dup"], { cwd: repo, encoding: "utf8" }); assert.equal(branchExists(repo, "dup"), true); const r = createWorktreeAt({ repoRoot: repo, name: "dup" }); assert.equal(r.ok, true); if (!r.ok) return; assert.equal(r.created, false, "已有分支时 created=false"); const branch = spawnSync("git", ["branch", "--show-current"], { cwd: r.path, encoding: "utf8" }).stdout.trim(); assert.equal(branch, "dup"); }); test("名字非法时失败且不留下目录", () => { const { repo } = makeRepo(); const r = createWorktreeAt({ repoRoot: repo, name: "../escape" }); assert.equal(r.ok, false); assert.equal(fs.existsSync(path.join(repo, ".worktrees", "..", "escape")), false); assert.equal(fs.existsSync(path.join(repo, "escape")), false); }); test("目标目录已存在时失败并说明", () => { const { repo } = makeRepo(); ensureExclude(repo); const target = path.join(repo, ".worktrees", "taken"); fs.mkdirSync(target, { recursive: true }); const r = createWorktreeAt({ repoRoot: repo, name: "taken" }); assert.equal(r.ok, false); if (!r.ok) assert.match(r.reason, /已存在|exists/); }); test("listWorktrees 含主仓与新建的那个", () => { const { repo } = makeRepo(); ensureExclude(repo); const created = createWorktreeAt({ repoRoot: repo, name: "listed" }); assert.equal(created.ok, true); if (!created.ok) return; const list = listWorktrees(repo); const paths = list.map((w) => fs.realpathSync(w.path)); assert.ok(paths.includes(fs.realpathSync(repo)), "要含主仓"); assert.ok(paths.includes(fs.realpathSync(created.path)), "要含新建的 worktree"); const entry = list.find((w) => fs.realpathSync(w.path) === fs.realpathSync(created.path)); assert.equal(entry?.branch, "listed"); }); test("removeWorktree:干净树能删,脏树拒绝", () => { const { repo } = makeRepo(); ensureExclude(repo); const clean = createWorktreeAt({ repoRoot: repo, name: "clean" }); assert.equal(clean.ok, true); if (!clean.ok) return; // 目录删掉之后就不能再 realpath 它了,先把结果存下来再比 const cleanReal = fs.realpathSync(clean.path); const removed = removeWorktree(repo, clean.path); assert.equal(removed.ok, true); assert.equal(fs.existsSync(clean.path), false, "目录要真的没了"); assert.equal( listWorktrees(repo).some((w) => w.path === clean.path || w.path === cleanReal), false, ); // 删除后主仓仍然干净(.git/worktrees 的残记录已 prune) assert.equal(porcelain(repo), ""); const dirty = createWorktreeAt({ repoRoot: repo, name: "dirty" }); assert.equal(dirty.ok, true); if (!dirty.ok) return; fs.writeFileSync(path.join(dirty.path, "new.txt"), "dirty\n"); const refused = removeWorktree(repo, dirty.path); assert.equal(refused.ok, false, "带未跟踪文件的树不能静默删除"); assert.equal(fs.existsSync(dirty.path), true, "拒绝时必须保留树"); }); test("默认执行器给每条 git 命令加上 --no-optional-locks(与 statusline 同口径)", () => { // 前缀加在执行器里(调用方只传子命令),所以断言 argv 构造函数本身 assert.deepEqual(gitArgv(["rev-parse", "HEAD"]), ["--no-optional-locks", "rev-parse", "HEAD"]); assert.deepEqual(gitArgv(["worktree", "list", "--porcelain"]), [ "--no-optional-locks", "worktree", "list", "--porcelain", ]); // 而且真的跑得通(flag 拼错时 git 会直接报 unknown option) const { repo } = makeRepo(); const info = repoInfo(repo); assert.equal(info.ok, true); assert.ok(listWorktrees(repo).length >= 1); });