import { afterAll, beforeAll, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { applyAgentGitHooks } from "../src/agent_git_hooks"; /** * 对着真 git 跑:全局 hooksPath 指向一个必然失败的 pre-commit(代替卡死的 ByteSec 扫描器), * 仓库自己的 pre-commit 留一个标记文件。agent 在 worktree 里提交时,应该跑仓库的、不跑全局的。 */ let root = "", main = "", wt = "", marker = ""; let baseEnv: Record = {}; const git = (cwd: string, env: Record, ...args: string[]) => Bun.spawnSync(["git", ...args], { cwd, env }); beforeAll(() => { root = mkdtempSync(path.join(tmpdir(), "agent-hooks-")); const globalHooks = path.join(root, "bytesec"); mkdirSync(globalHooks); writeFileSync(path.join(globalHooks, "pre-commit"), "#!/bin/sh\necho scanner >&2\nexit 1\n"); chmodSync(path.join(globalHooks, "pre-commit"), 0o755); const globalConfig = path.join(root, "gitconfig"); writeFileSync(globalConfig, `[core]\n\thooksPath = ${globalHooks}\n[user]\n\tname = t\n\temail = t@x\n`); const env: Record = {}; for (const [k, v] of Object.entries(process.env)) if (v != null && !k.startsWith("GIT_")) env[k] = v; baseEnv = { ...env, GIT_CONFIG_GLOBAL: globalConfig, GIT_CONFIG_NOSYSTEM: "1" }; main = path.join(root, "main"); wt = path.join(root, "wt"); marker = path.join(root, "repo-hook-ran"); git(root, baseEnv, "init", "-b", "develop", main); writeFileSync(path.join(main, "a.txt"), "a\n"); git(main, baseEnv, "add", "."); git(main, { ...baseEnv, GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "core.hooksPath", GIT_CONFIG_VALUE_0: path.join(root, "none") }, "commit", "-m", "base"); writeFileSync(path.join(main, ".git", "hooks", "pre-commit"), `#!/bin/sh\ntouch "${marker}"\n`); chmodSync(path.join(main, ".git", "hooks", "pre-commit"), 0o755); git(main, baseEnv, "worktree", "add", "-b", "feature/x", wt); }); afterAll(() => { if (root) rmSync(root, { recursive: true, force: true }); }); test("全局 hooksPath 下提交被拦(对照)", () => { writeFileSync(path.join(wt, "b.txt"), "b\n"); git(wt, baseEnv, "add", "b.txt"); const r = git(wt, baseEnv, "commit", "-m", "plain"); expect(r.exitCode).not.toBe(0); expect(r.stderr.toString()).toContain("scanner"); }); test("agent env:worktree 里提交跑仓库自己的 hook,不跑全局扫描器", () => { const env = applyAgentGitHooks( { ...baseEnv, GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "color.ui", GIT_CONFIG_VALUE_0: "never" }, path.join(root, "agent-hooks"), ); // 已有的 GIT_CONFIG 条目保留,新条目排在后面 expect(env.GIT_CONFIG_COUNT).toBe("2"); expect(env.GIT_CONFIG_KEY_0).toBe("color.ui"); writeFileSync(path.join(wt, "c.txt"), "c\n"); git(wt, env, "add", "c.txt"); const r = git(wt, env, "commit", "-m", "agent"); expect(r.stderr.toString()).not.toContain("scanner"); expect(r.exitCode).toBe(0); expect(existsSync(marker)).toBe(true); });