/** * worktree/git.ts — git 侧的全部 IO:仓库探测、`.git/info/exclude`、建 / 列 / 删 worktree。 * * 不 import pi;`runGit` 可注入,测试用真 git 驱动(tmpdir 里 `git init`)。 * * 所有调用都带 `--no-optional-locks`:与本仓库 statusline 同口径 —— 读操作不去抢 * `index.lock`,在沙箱里也不会因为一次 `git status` 触发 unlink 而被拦。 */ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { EXCLUDE_ENTRY, branchFor, validateName, worktreePath } from "./layout.ts"; /** 一次 git 调用的结果。`code === 0` 为成功。 */ export interface GitResult { code: number; stdout: string; stderr: string; } export type RunGit = (args: readonly string[], cwd: string) => GitResult; /** 默认执行器:同步 spawn(这些调用都是几十毫秒级,且必须在下一步之前完成)。 */ export const defaultRunGit: RunGit = (args, cwd) => { const r = spawnSync("git", gitArgv(args), { cwd, encoding: "utf8" }); return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" }; }; /** * 真正传给 `git` 的 argv。 * * 单独抽出来是为了可断言:`--no-optional-locks` 是**前缀**,加在默认执行器里, * 注入的假执行器看不到它,所以测试直接对这里断言(flag 拼错时 git 会报 unknown option)。 */ export function gitArgv(args: readonly string[]): string[] { return ["--no-optional-locks", ...args]; } export interface RepoInfo { /** 主仓根(linked worktree 里也指向主仓,不是 `.worktrees/x`)。 */ repoRoot: string; /** `.git` 目录(linked worktree 里是主仓那个)。 */ commonDir: string; /** 当前 HEAD 的 sha。 */ headSha: string; /** 当前 cwd 是不是一个 linked worktree(`--git-dir` ≠ `--git-common-dir`)。 */ isLinkedWorktree: boolean; /** * 传入的 cwd 已经不存在,git 探测是从**最近的存在祖先**发出的。 * * 典型形态:worktree 里的活干完、合并进主干、树被 `git worktree remove` 删掉,而会话 cwd * 还钉在那个已消失的目录上。此时 `isLinkedWorktree` 为假(祖先探测看到的是主仓), * 但用户确实需要 exit —— 所以调用方不能只拿 `isLinkedWorktree` 当闸门。 */ cwdMissing: boolean; } export type RepoInfoResult = { ok: true; info: RepoInfo } | { ok: false; reason: string }; /** * cwd 不存在时退回**最近的存在祖先**。 * * 为什么必须退:`spawnSync` 的 `cwd` 指向不存在的目录时是 ENOENT —— git 根本没被执行, * `code` 为 null、stderr 为空,于是报错变成误导性的「不在 git 仓库里」。真实场景是 * worktree 合并后被删掉、会话 cwd 还钉在原地,用户此刻最需要的恰恰是 `/worktree exit`。 * 从 `.worktrees/<名>` 退到 `.worktrees/` 再退到主仓根,探到的正是 exit 要去的地方。 */ function nearestExistingDir(cwd: string): { dir: string; missing: boolean } { if (isDirectory(cwd)) return { dir: cwd, missing: false }; let current = path.dirname(cwd); for (;;) { if (isDirectory(current)) return { dir: current, missing: true }; const parent = path.dirname(current); // 走到文件系统根还不存在:原样交回去,让下面的 git 调用报它自己的错 if (parent === current) return { dir: cwd, missing: true }; current = parent; } } function isDirectory(target: string): boolean { try { return fs.statSync(target).isDirectory(); } catch { return false; } } /** * 从 `cwd` 探测仓库信息。 * * 空仓库(还没有 commit)返回 `{ ok: false }` —— 没有 HEAD 就没有可 fork 的基线。 * `cwd` 本身已被删除时不失败:退回最近的存在祖先探测,并在结果里标 `cwdMissing`。 */ export function repoInfo(cwd: string, runGit: RunGit = defaultRunGit): RepoInfoResult { const probe = nearestExistingDir(cwd); const probeCwd = probe.dir; const top = runGit(["rev-parse", "--show-toplevel"], probeCwd); if (top.code !== 0 || !top.stdout.trim()) { const where = probe.missing ? `${cwd}(已不存在,从 ${probeCwd} 探测)` : cwd; return { ok: false, reason: `${where} 不在 git 仓库里(git rev-parse --show-toplevel 失败)` }; } const gitDir = runGit(["rev-parse", "--path-format=absolute", "--git-dir"], probeCwd); const common = runGit(["rev-parse", "--path-format=absolute", "--git-common-dir"], probeCwd); const head = runGit(["rev-parse", "HEAD"], probeCwd); if (gitDir.code !== 0 || common.code !== 0) { return { ok: false, reason: `${cwd} 的 git 目录解析失败:${firstLine(gitDir.stderr || common.stderr)}` }; } if (head.code !== 0 || !head.stdout.trim()) { return { ok: false, reason: "仓库还没有任何 commit(HEAD 不存在),无法在其基础上建 worktree" }; } const resolvedGitDir = realpath(gitDir.stdout.trim()); const resolvedCommon = realpath(common.stdout.trim()); // `dirname(/.git)` 就是主仓根 —— linked worktree 里 `--show-toplevel` 指向 // 的是 worktree 自己,不能拿它当主仓根。 const repoRoot = realpath(path.dirname(resolvedCommon)); return { ok: true, info: { repoRoot, commonDir: resolvedCommon, headSha: head.stdout.trim(), isLinkedWorktree: resolvedGitDir !== resolvedCommon, cwdMissing: probe.missing, }, }; } /** * 确保 `/info/exclude` 里有 `.worktrees/`。 * * 幂等:已经存在(任意一行 trim 后相等)就不写。返回 `changed` 让调用方能报"第一次加"。 * 用 `info/exclude` 而不是 `.gitignore`:前者只影响本仓库、不改 tracked 文件。 */ export function ensureExclude(repoRoot: string, runGit: RunGit = defaultRunGit): { changed: boolean } { const common = runGit(["rev-parse", "--path-format=absolute", "--git-common-dir"], repoRoot); const commonDir = common.code === 0 && common.stdout.trim() ? realpath(common.stdout.trim()) : path.join(repoRoot, ".git"); const excludePath = path.join(commonDir, "info", "exclude"); let current = ""; try { current = fs.readFileSync(excludePath, "utf8"); } catch { // 文件不存在:下面按空串处理,并在写入前建目录 } const lines = current.split("\n").map((line) => line.trim()); if (lines.includes(EXCLUDE_ENTRY)) return { changed: false }; fs.mkdirSync(path.dirname(excludePath), { recursive: true }); const prefix = current === "" || current.endsWith("\n") ? current : `${current}\n`; fs.writeFileSync(excludePath, `${prefix}${EXCLUDE_ENTRY}\n`); return { changed: true }; } /** 分支是否已存在(`refs/heads/`)。 */ export function branchExists(repoRoot: string, branch: string, runGit: RunGit = defaultRunGit): boolean { return runGit(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], repoRoot).code === 0; } export type CreateWorktreeResult = | { ok: true; path: string; branch: string; created: boolean } | { ok: false; reason: string }; /** * 在 `/.worktrees/` 建 worktree。 * * - 名字非法 ⇒ 失败(不建目录)。 * - 目标已存在 ⇒ 失败并说明(不覆盖、不复用 —— 复用要走 `enter`)。 * - 同名分支已存在 ⇒ 挂上去(`created: false`);否则 `-b` 新建(`created: true`)。 */ export function createWorktreeAt( o: { repoRoot: string; name: string; runGit?: RunGit }, ): CreateWorktreeResult { const runGit = o.runGit ?? defaultRunGit; const valid = validateName(o.name); if (!valid.ok) return { ok: false, reason: valid.reason }; const target = worktreePath(o.repoRoot, valid.name); if (fs.existsSync(target)) return { ok: false, reason: `目标目录已存在:${target}` }; const branch = branchFor(valid.name); const reuse = branchExists(o.repoRoot, branch, runGit); const args = reuse ? ["worktree", "add", target, branch] : ["worktree", "add", "-b", branch, target]; const add = runGit(args, o.repoRoot); if (add.code !== 0) { // 半成品目录:git 可能已经建了一部分,清掉自己这一份,不留残骸 fs.rmSync(target, { recursive: true, force: true }); runGit(["worktree", "prune"], o.repoRoot); return { ok: false, reason: `git worktree add 失败:${firstLine(add.stderr) || `exit ${add.code}`}` }; } return { ok: true, path: target, branch, created: !reuse }; } export interface WorktreeEntry { path: string; branch?: string; } /** 解析 `git worktree list --porcelain`。分支转成短名(`refs/heads/x` → `x`)。 */ export function listWorktrees(repoRoot: string, runGit: RunGit = defaultRunGit): WorktreeEntry[] { const r = runGit(["worktree", "list", "--porcelain"], repoRoot); if (r.code !== 0) return []; const out: WorktreeEntry[] = []; let current: WorktreeEntry | undefined; for (const line of r.stdout.split("\n")) { if (line.startsWith("worktree ")) { if (current) out.push(current); current = { path: line.slice("worktree ".length).trim() }; } else if (line.startsWith("branch ") && current) { const ref = line.slice("branch ".length).trim(); current.branch = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref; } } if (current) out.push(current); return out; } /** * 删掉一个 worktree。**不带 `--force`**:带未提交改动的树删除会被 git 拒绝, * 我们原样把拒绝理由交回去(静默删掉别人的成果是比"删不掉"更糟的失败)。 */ export function removeWorktree( repoRoot: string, target: string, runGit: RunGit = defaultRunGit, ): { ok: true } | { ok: false; reason: string } { const remove = runGit(["worktree", "remove", target], repoRoot); if (remove.code !== 0) { return { ok: false, reason: `git worktree remove 失败:${firstLine(remove.stderr) || `exit ${remove.code}`}` }; } // `.git/worktrees/` 的残记录用 prune 收尾;目录已由 remove 删掉 runGit(["worktree", "prune"], repoRoot); return { ok: true }; } function realpath(target: string): string { try { return fs.realpathSync(target); } catch { return target; } } function firstLine(text: string): string { return text.split("\n").find((line) => line.trim().length > 0)?.trim() ?? ""; }