/** * bash-command-collapse/git-meta.ts — 会话 cwd 在 **linked worktree** 里时,把主仓的 `.git` * 也算进沙箱的可删根。 * * ## 为什么需要 * * 会话 cwd 落到 `/.worktrees/<名>` 之后,主仓的 `/.git` 就在 cwd 之外了。 * 而 `git add` / `git commit` 都要在 `.git` 里写锁文件再 rename —— **rename 按源路径计 * unlink**(seatbelt 没有 file-write-rename),于是这些操作会被判成"边界外删除"而吃 * `EPERM`,表现为 `unable to unlink '…/index.lock'` / `fatal: not a git repository`。 * 结果是「进得去 worktree、提交不了」。 * * ## 为什么不算扩大边界 * * 从主仓根开会话时,`/.git` 本来就在可删根(项目目录)之下。这里只是把同一个目录 * 补回到 worktree 会话的边界里,能力没有变宽。 * * ## 为什么只在 linked worktree 里返回 * * 主仓根会话下返回 `[]`,保证现有 profile 逐字节不变(普通会话不受这件事影响)。 */ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; /** 一次 git 调用的结果(与 worktree/git.ts 同形,但这里刻意不跨目录 import)。 */ export interface GitResult { code: number; stdout: string; stderr: string; } export type RunGit = (args: readonly string[], cwd: string) => GitResult; const defaultRunGit: RunGit = (args, cwd) => { const r = spawnSync("git", ["--no-optional-locks", ...args], { cwd, encoding: "utf8" }); return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" }; }; /** * 会话 cwd 在 linked worktree 里时返回 `[<主仓>/.git]`,否则 `[]`。 * * 任何失败(不在仓库、git 不可用、空仓库)都返回 `[]` —— 这条只做"补一个根"的增强, * 判断不出来时保持原边界,绝不因此让 bash 起不来。 */ export function gitMetaWriteRoots(cwd: string, runGit: RunGit = defaultRunGit): string[] { try { const gitDir = runGit(["rev-parse", "--path-format=absolute", "--git-dir"], cwd); const common = runGit(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd); if (gitDir.code !== 0 || common.code !== 0) return []; const resolvedGitDir = realpath(gitDir.stdout.trim()); const resolvedCommon = realpath(common.stdout.trim()); if (!resolvedGitDir || !resolvedCommon) return []; // 主仓根会话:两者相同 ⇒ 什么都不加 if (resolvedGitDir === resolvedCommon) return []; return [resolvedCommon]; } catch { return []; } } function realpath(target: string): string { if (!target) return ""; try { return fs.realpathSync(target); } catch { // 路径不存在时退回词法解析(仍然远好于返回空串把它当成"没判断出来") return path.resolve(target); } }