git-snapshot.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. import { existsSync } from "node:fs";
  2. import { chmod, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { delimiter, dirname, join } from "node:path";
  5. import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
  6. import { createNodeContextSourceAdapter } from "../src/context/index.js";
  7. interface GitResponse {
  8. code: number;
  9. // 没有 git 退出码的失败:timeout 被 kill、signal 取消、git 无法启动。
  10. failure?: "timeout" | "abort" | "spawn";
  11. stdout?: string;
  12. stderr?: string;
  13. }
  14. interface GitCall {
  15. // 去掉开头的 `-c` 加固参数后的命令;rawArgs 是实际传给 git 的完整参数。
  16. args: string[];
  17. command: string;
  18. rawArgs: string[];
  19. options: {
  20. cwd?: string;
  21. env?: NodeJS.ProcessEnv;
  22. maxBuffer?: number;
  23. signal?: AbortSignal;
  24. timeout?: number;
  25. windowsHide?: boolean;
  26. };
  27. }
  28. const { execFileMock, gitCalls, heldGitArgs, holdGitCommands, resetGitMock, setGitResponse } =
  29. vi.hoisted(() => {
  30. const calls: GitCall[] = [];
  31. const responses = new Map<string, GitResponse>();
  32. // 设置后,git 命令先记进 held,等放行后才执行,用来证明快照命令是并行发出的。
  33. let gate: Promise<void> | undefined;
  34. const held: string[][] = [];
  35. const commandKey = (args: string[]) => args.join("\0");
  36. const withoutLeadingConfig = (args: string[]) => {
  37. let index = 0;
  38. while (args[index] === "-c" && index + 1 < args.length) index += 2;
  39. return args.slice(index);
  40. };
  41. const runGitMock = (command: string, rawArgs: string[], options: GitCall["options"]) => {
  42. const args = withoutLeadingConfig(rawArgs);
  43. calls.push({ args, command, options, rawArgs: [...rawArgs] });
  44. const response = responses.get(commandKey(args)) ?? { code: 1, stdout: "", stderr: "" };
  45. const stdout = response.stdout ?? "";
  46. const stderr = response.stderr ?? "";
  47. if (response.failure) {
  48. throw execFailure(response.failure);
  49. }
  50. if (response.code === 0) {
  51. return { stdout, stderr };
  52. }
  53. const error = new Error(`git exited with ${response.code}`) as Error & {
  54. code?: number;
  55. stderr?: string;
  56. stdout?: string;
  57. };
  58. error.code = response.code;
  59. error.stdout = stdout;
  60. error.stderr = stderr;
  61. throw error;
  62. };
  63. const mock = vi.fn(
  64. (
  65. command: string,
  66. args: string[],
  67. options: GitCall["options"],
  68. callback: (error: Error | null, stdout: string, stderr: string) => void,
  69. ) => {
  70. try {
  71. const result = runGitMock(command, args, options);
  72. callback(null, result.stdout, result.stderr);
  73. } catch (error) {
  74. const execError = error as Error & { stderr?: string; stdout?: string };
  75. callback(execError, execError.stdout ?? "", execError.stderr ?? "");
  76. }
  77. },
  78. );
  79. // 与 Node execFile 的失败形状一致:timeout 时 killed 且 code 为 null;取消时是 AbortError;
  80. // 无法启动时 code 是字符串。
  81. const execFailure = (failure: NonNullable<GitResponse["failure"]>) => {
  82. if (failure === "abort") {
  83. return Object.assign(new Error("The operation was aborted"), {
  84. code: "ABORT_ERR",
  85. name: "AbortError",
  86. });
  87. }
  88. if (failure === "spawn") {
  89. return Object.assign(new Error("spawn git ENOENT"), { code: "ENOENT" });
  90. }
  91. return Object.assign(new Error("Command failed: git"), {
  92. code: null,
  93. killed: true,
  94. signal: "SIGTERM",
  95. });
  96. };
  97. const customPromisify = Symbol.for("nodejs.util.promisify.custom");
  98. Object.defineProperty(mock, customPromisify, {
  99. value: async (command: string, args: string[], options: GitCall["options"]) => {
  100. if (gate) {
  101. held.push(withoutLeadingConfig(args));
  102. await gate;
  103. }
  104. return runGitMock(command, args, options);
  105. },
  106. });
  107. return {
  108. execFileMock: mock,
  109. gitCalls: calls,
  110. heldGitArgs: held,
  111. holdGitCommands: () => {
  112. let release!: () => void;
  113. gate = new Promise<void>((resolveGate) => {
  114. release = resolveGate;
  115. });
  116. return () => {
  117. gate = undefined;
  118. release();
  119. };
  120. },
  121. resetGitMock: () => {
  122. calls.length = 0;
  123. mock.mockClear();
  124. responses.clear();
  125. gate = undefined;
  126. held.length = 0;
  127. },
  128. setGitResponse: (args: string[], response: GitResponse) => {
  129. responses.set(commandKey(args), response);
  130. },
  131. };
  132. });
  133. vi.mock("node:child_process", () => ({
  134. execFile: execFileMock,
  135. }));
  136. // 记录对 `.git` 的 stat,用来证明一次 context 解析只向上查找一遍。
  137. const { gitEntryStats } = vi.hoisted(() => ({ gitEntryStats: [] as string[] }));
  138. vi.mock("node:fs/promises", async (importOriginal) => {
  139. const actual = await importOriginal<typeof import("node:fs/promises")>();
  140. const stat = ((path: Parameters<typeof actual.stat>[0], options?: { bigint?: false }) => {
  141. if (String(path).endsWith(".git")) gitEntryStats.push(String(path));
  142. return actual.stat(path, options);
  143. }) as typeof actual.stat;
  144. return { ...actual, stat };
  145. });
  146. const SNAPSHOT_COMMANDS = [
  147. ["symbolic-ref", "--short", "-q", "HEAD"],
  148. ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
  149. ["config", "user.name"],
  150. ["--no-optional-locks", "status", "--short", "--ignore-submodules=dirty"],
  151. ["--no-optional-locks", "log", "--oneline", "-n", "5"],
  152. ];
  153. const STATUS_COMMAND = SNAPSHOT_COMMANDS[3]!;
  154. const GIT_EXECUTABLE_NAME = process.platform === "win32" ? "git.exe" : "git";
  155. let root: string;
  156. let repoDirectory: string;
  157. let nestedDirectory: string;
  158. let worktreeDirectory: string;
  159. let outsideDirectory: string;
  160. // PATH 上的假 git;execFile 已被替换,它不会真的运行。
  161. let gitBinDirectory: string;
  162. let gitOnPath: string;
  163. let originalPath: string | undefined;
  164. // 临时目录的上级里有 .git 时(例如 TMPDIR 指向某个仓库内部),"不在仓库"的结论不成立。
  165. let outsideIsReliable: boolean;
  166. function hasGitAncestor(directory: string): boolean {
  167. for (let current = directory; ; current = dirname(current)) {
  168. if (existsSync(join(current, ".git"))) return true;
  169. if (dirname(current) === current) return false;
  170. }
  171. }
  172. beforeAll(async () => {
  173. root = await realpath(await mkdtemp(join(tmpdir(), "zcode-git-snapshot-")));
  174. repoDirectory = join(root, "repo");
  175. nestedDirectory = join(repoDirectory, "src", "deep");
  176. worktreeDirectory = join(root, "worktree");
  177. outsideDirectory = join(root, "outside");
  178. await mkdir(join(repoDirectory, ".git"), { recursive: true });
  179. await mkdir(nestedDirectory, { recursive: true });
  180. await mkdir(worktreeDirectory, { recursive: true });
  181. // worktree / submodule 的 .git 是指向 gitdir 的文件。
  182. await writeFile(join(worktreeDirectory, ".git"), "gitdir: /elsewhere/.git/worktrees/wt\n");
  183. await mkdir(outsideDirectory, { recursive: true });
  184. outsideIsReliable = !hasGitAncestor(root);
  185. gitBinDirectory = join(root, "bin");
  186. await mkdir(gitBinDirectory, { recursive: true });
  187. gitOnPath = join(gitBinDirectory, GIT_EXECUTABLE_NAME);
  188. // 工作目录里也放一个同名程序:Windows 对裸名会先找 cwd,自动 git 不能用到它。
  189. for (const path of [gitOnPath, join(repoDirectory, GIT_EXECUTABLE_NAME)]) {
  190. await writeFile(path, "#!/bin/sh\nexit 0\n");
  191. await chmod(path, 0o755);
  192. }
  193. originalPath = process.env.PATH;
  194. process.env.PATH = gitBinDirectory;
  195. });
  196. afterAll(async () => {
  197. // 原来没有 PATH 时删掉,不能赋 undefined:process.env 会把它存成字符串 "undefined"。
  198. if (originalPath === undefined) delete process.env.PATH;
  199. else process.env.PATH = originalPath;
  200. await rm(root, { recursive: true, force: true });
  201. });
  202. describe("resolveGitSnapshot command semantics", () => {
  203. beforeEach(() => {
  204. resetGitMock();
  205. });
  206. it("falls back to HEAD when HEAD is detached", async () => {
  207. setGitResponse(["symbolic-ref", "--short", "-q", "HEAD"], { code: 1 });
  208. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  209. expect((await resolveGitSnapshot(repoDirectory)).gitBranch).toBe("HEAD");
  210. });
  211. it("decides repository membership from .git without starting git", async () => {
  212. const adapter = createNodeContextSourceAdapter({ env: { SHELL: "/bin/zsh" } });
  213. for (const directory of [repoDirectory, nestedDirectory, worktreeDirectory]) {
  214. expect(await adapter.resolveEnvironment({ workingDirectory: directory })).toMatchObject({
  215. cwd: directory,
  216. shell: "zsh",
  217. isGitRepository: true,
  218. });
  219. }
  220. if (outsideIsReliable) {
  221. expect(
  222. await adapter.resolveEnvironment({
  223. workingDirectory: outsideDirectory,
  224. effectiveShellDisplayName: "bash",
  225. }),
  226. ).toMatchObject({ cwd: outsideDirectory, shell: "bash", isGitRepository: false });
  227. }
  228. // 修复原因:原来用 git rev-parse 判定,超时、取消、没装 git 都没有结论;现在只看文件系统。
  229. expect(gitCalls).toEqual([]);
  230. });
  231. it.skipIf(process.platform === "win32")(
  232. "follows a symlinked directory and ignores a dangling .git link",
  233. async () => {
  234. const linked = join(root, "repo-link");
  235. const dangling = join(root, "dangling");
  236. await symlink(repoDirectory, linked, "dir");
  237. await mkdir(dangling, { recursive: true });
  238. await symlink(join(root, "missing-git-dir"), join(dangling, ".git"));
  239. const { resolveIsGitRepository } = await import("../src/context/git-snapshot.js");
  240. expect(await resolveIsGitRepository(linked)).toBe(true);
  241. if (outsideIsReliable) expect(await resolveIsGitRepository(dangling)).toBe(false);
  242. },
  243. );
  244. // 修复原因:原来从打开时的路径(链接本身的位置)逐级向上找 .git,git 却在链接指向的真实位置运行,
  245. // 两边结论相反:指向仓库子目录的链接被判为"不是仓库";仓库里指向外部的链接被判为仓库,
  246. // git 命令全部失败,模型看到默认值拼成的假快照。现在是否仓库按真实路径判断,与 git 一致;
  247. // 项目根、AGENTS.md 查找和给模型看的路径仍用打开时的路径。junction 在 Windows 上不需要权限。
  248. it("decides membership from the real path of a link while paths keep the opened form", async (context) => {
  249. // 临时目录的上级里有 .git 时,"不是仓库"的两种结论都不成立。
  250. if (!outsideIsReliable) context.skip();
  251. const home = join(root, "link-home");
  252. const mono = join(root, "link-mono");
  253. const intoRepo = join(home, "pkg");
  254. const outOfRepo = join(mono, "data-link");
  255. await mkdir(join(mono, ".git"), { recursive: true });
  256. await mkdir(join(mono, "packages", "pkg"), { recursive: true });
  257. await mkdir(home, { recursive: true });
  258. await writeFile(join(mono, "AGENTS.md"), "mono rule\n");
  259. await symlink(join(mono, "packages", "pkg"), intoRepo, "junction");
  260. await symlink(outsideDirectory, outOfRepo, "junction");
  261. const adapter = createNodeContextSourceAdapter({
  262. env: { SHELL: "/bin/zsh", HOME: home, USERPROFILE: home },
  263. });
  264. const { resolveIsGitRepository } = await import("../src/context/git-snapshot.js");
  265. // 链接指向仓库子目录:是仓库;git 命令在打开时的路径下运行,cwd 也保持原样。
  266. expect(await resolveIsGitRepository(intoRepo)).toBe(true);
  267. expect(await adapter.resolveEnvironment({ workingDirectory: intoRepo })).toMatchObject({
  268. cwd: intoRepo,
  269. isGitRepository: true,
  270. });
  271. expect(await adapter.resolveGitContext({ workingDirectory: intoRepo })).toMatchObject({
  272. isGitRepository: true,
  273. });
  274. expect(gitCalls.length).toBeGreaterThan(0);
  275. expect(new Set(gitCalls.map((call) => call.options.cwd))).toEqual(new Set([intoRepo]));
  276. const intoSnapshot = await adapter.resolveContextSources({ workingDirectory: intoRepo });
  277. expect(intoSnapshot.workingDirectory).toBe(intoRepo);
  278. expect(intoSnapshot.envInfo).toMatchObject({ cwd: intoRepo, isGitRepository: true });
  279. // 仓库里指向外部的链接:不是仓库,不启动 git;项目根仍按打开时的路径找到 mono 的 AGENTS.md。
  280. resetGitMock();
  281. expect(await resolveIsGitRepository(outOfRepo)).toBe(false);
  282. expect(await adapter.resolveEnvironment({ workingDirectory: outOfRepo })).toMatchObject({
  283. cwd: outOfRepo,
  284. isGitRepository: false,
  285. });
  286. expect(await adapter.resolveGitContext({ workingDirectory: outOfRepo })).toEqual({
  287. isGitRepository: false,
  288. gitStatus: "not_repo",
  289. });
  290. const outSnapshot = await adapter.resolveContextSources({
  291. workingDirectory: outOfRepo,
  292. userInstructions: { workingDirectory: outOfRepo },
  293. });
  294. expect(outSnapshot.envInfo).toMatchObject({
  295. cwd: outOfRepo,
  296. isGitRepository: false,
  297. gitStatus: "not_repo",
  298. });
  299. expect(outSnapshot.userInstructions?.filePath).toBe(join(mono, "AGENTS.md"));
  300. expect(gitCalls).toEqual([]);
  301. // 真实路径读不到(目录已删除)时按打开时的路径判断,不抛错。
  302. expect(await resolveIsGitRepository(join(mono, "deleted"))).toBe(true);
  303. });
  304. it("reads a fresh Git context for the working directory without host facts", async () => {
  305. const adapter = createNodeContextSourceAdapter({ env: { SHELL: "/bin/zsh" } });
  306. setGitResponse(["symbolic-ref", "--short", "-q", "HEAD"], { code: 0, stdout: "feature\n" });
  307. setGitResponse(STATUS_COMMAND, { code: 0, stdout: " M a.ts\n" });
  308. const context = await adapter.resolveGitContext({ workingDirectory: repoDirectory });
  309. expect(context).toMatchObject({
  310. isGitRepository: true,
  311. gitBranch: "feature",
  312. gitStatus: "dirty",
  313. gitStatusLines: ["M a.ts"],
  314. });
  315. expect(context).not.toHaveProperty("shell");
  316. expect(gitCalls.every(({ options }) => options.cwd === repoDirectory)).toBe(true);
  317. });
  318. it("keeps the local three second timeout for every git snapshot command", async () => {
  319. setGitResponse(["symbolic-ref", "--short", "-q", "HEAD"], { code: 0, stdout: "feature\n" });
  320. setGitResponse(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
  321. code: 0,
  322. stdout: "origin/main\n",
  323. });
  324. setGitResponse(["show-ref", "--verify", "--quiet", "refs/remotes/origin/main"], {
  325. code: 0,
  326. });
  327. setGitResponse(["config", "user.name"], { code: 0, stdout: "ZCode Tester\n" });
  328. setGitResponse(STATUS_COMMAND, {
  329. code: 0,
  330. stdout: " M tracked.txt\n",
  331. });
  332. setGitResponse(["--no-optional-locks", "log", "--oneline", "-n", "5"], {
  333. code: 0,
  334. stdout: "abc123 first commit\n",
  335. });
  336. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  337. const snapshot = await resolveGitSnapshot(repoDirectory);
  338. expect(snapshot.isGitRepository).toBe(true);
  339. expect(gitCalls).not.toHaveLength(0);
  340. expect(gitCalls.every((call) => call.command === gitOnPath)).toBe(true);
  341. expect(gitCalls.every((call) => call.options.cwd === repoDirectory)).toBe(true);
  342. expect(gitCalls.every((call) => call.options.maxBuffer === 1024 * 1024)).toBe(true);
  343. expect(gitCalls.every((call) => call.options.timeout === 3000)).toBe(true);
  344. expect(gitCalls.every((call) => call.options.windowsHide === true)).toBe(true);
  345. });
  346. it("starts the snapshot commands in parallel and keeps the result unchanged", async () => {
  347. setGitResponse(["symbolic-ref", "--short", "-q", "HEAD"], { code: 0, stdout: "feature\n" });
  348. setGitResponse(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
  349. code: 0,
  350. stdout: "origin/trunk\n",
  351. });
  352. setGitResponse(["show-ref", "--verify", "--quiet", "refs/remotes/origin/trunk"], { code: 0 });
  353. setGitResponse(["config", "user.name"], { code: 0, stdout: "ZCode Tester\n" });
  354. setGitResponse(STATUS_COMMAND, { code: 0, stdout: " M a.ts\n" });
  355. setGitResponse(["--no-optional-locks", "log", "--oneline", "-n", "5"], {
  356. code: 0,
  357. stdout: "abc123 first\ndef456 second\n",
  358. });
  359. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  360. const release = holdGitCommands();
  361. const pending = resolveGitSnapshot(repoDirectory);
  362. // 修复原因:串行执行时,git 卡住的仓库每条命令都要等满 3 秒。
  363. await vi.waitFor(() => expect(heldGitArgs).toHaveLength(SNAPSHOT_COMMANDS.length));
  364. expect(heldGitArgs).toEqual(expect.arrayContaining(SNAPSHOT_COMMANDS));
  365. release();
  366. expect(await pending).toEqual({
  367. isGitRepository: true,
  368. gitBranch: "feature",
  369. gitMainBranch: "trunk",
  370. gitUser: "ZCode Tester",
  371. gitStatus: "dirty",
  372. gitStatusLines: ["M a.ts"],
  373. recentCommits: ["abc123 first", "def456 second"],
  374. });
  375. });
  376. it("drops stdout from failed optional git commands and keeps the snapshot usable", async () => {
  377. setGitResponse(["symbolic-ref", "--short", "-q", "HEAD"], { code: 0, stdout: "feature\n" });
  378. setGitResponse(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
  379. code: 1,
  380. stdout: "origin/should-not-leak\n",
  381. });
  382. setGitResponse(["show-ref", "--verify", "--quiet", "refs/remotes/origin/main"], {
  383. code: 1,
  384. });
  385. setGitResponse(["show-ref", "--verify", "--quiet", "refs/remotes/origin/master"], {
  386. code: 1,
  387. });
  388. setGitResponse(["config", "user.name"], { code: 1, stdout: "Leaked User\n" });
  389. setGitResponse(STATUS_COMMAND, {
  390. code: 128,
  391. stdout: " M leaked.txt\n",
  392. });
  393. setGitResponse(["--no-optional-locks", "log", "--oneline", "-n", "5"], {
  394. code: 128,
  395. stdout: "abc123 leaked commit\n",
  396. });
  397. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  398. const snapshot = await resolveGitSnapshot(repoDirectory);
  399. expect(snapshot).toMatchObject({
  400. isGitRepository: true,
  401. gitBranch: "feature",
  402. gitMainBranch: "main",
  403. gitStatus: "clean",
  404. gitStatusLines: [],
  405. recentCommits: [],
  406. });
  407. expect(snapshot.gitUser).toBeUndefined();
  408. });
  409. it("walks up for .git once when resolving context sources", async () => {
  410. const adapter = createNodeContextSourceAdapter({ env: {} });
  411. gitEntryStats.length = 0;
  412. const snapshot = await adapter.resolveContextSources({ workingDirectory: nestedDirectory });
  413. expect(snapshot.envInfo).toMatchObject({ isGitRepository: true });
  414. // 项目根与是否在仓库用同一次查找:deep → src → repo,各 stat 一次。
  415. expect(gitEntryStats).toEqual([
  416. join(nestedDirectory, ".git"),
  417. join(repoDirectory, "src", ".git"),
  418. join(repoDirectory, ".git"),
  419. ]);
  420. });
  421. it("reports a directory without .git as a non-repository and starts no git", async () => {
  422. if (!outsideIsReliable) return;
  423. const adapter = createNodeContextSourceAdapter({ env: {} });
  424. expect(await adapter.resolveGitContext({ workingDirectory: outsideDirectory })).toEqual({
  425. isGitRepository: false,
  426. gitStatus: "not_repo",
  427. });
  428. expect(gitCalls).toEqual([]);
  429. });
  430. it.each([
  431. ["a timeout", { code: 0, failure: "timeout" }],
  432. ["an abort", { code: 0, failure: "abort" }],
  433. ["a missing git", { code: 0, failure: "spawn" }],
  434. ] as const)(
  435. "still reports a repository when every git command fails with %s",
  436. async (_label, response) => {
  437. const adapter = createNodeContextSourceAdapter({ env: {} });
  438. for (const args of SNAPSHOT_COMMANDS) setGitResponse(args, response);
  439. // 修复原因:git 卡住或没装时原来被记成"不是仓库",Environment 与之后的 gitStatus 互相矛盾。
  440. expect(await adapter.resolveGitContext({ workingDirectory: repoDirectory })).toEqual({
  441. isGitRepository: true,
  442. gitBranch: "HEAD",
  443. gitMainBranch: "main",
  444. gitStatus: "clean",
  445. gitStatusLines: [],
  446. recentCommits: [],
  447. });
  448. const snapshot = await adapter.resolveContextSources({ workingDirectory: repoDirectory });
  449. expect(snapshot.envInfo).toMatchObject({ isGitRepository: true, gitStatus: "clean" });
  450. },
  451. );
  452. // 修复原因:自动 git 用裸名 `git` 执行,Windows 对裸名先查 cwd,工作区里的 git.exe 会被运行。
  453. // 现在先按 PATH 找到绝对路径再执行,查找不加工作目录。
  454. it("runs git by the absolute path found on PATH, never a git in the working directory", async () => {
  455. setGitResponse(["symbolic-ref", "--short", "-q", "HEAD"], { code: 0, stdout: "feature\n" });
  456. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  457. await resolveGitSnapshot(repoDirectory);
  458. expect(gitCalls.length).toBeGreaterThan(0);
  459. expect(new Set(gitCalls.map((call) => call.command))).toEqual(new Set([gitOnPath]));
  460. });
  461. // 修复原因:自动 git 不是工具调用,不经过权限判定;仓库 `.git/config` 里的 fsmonitor、hooks 等
  462. // 会让 ZCode 自己执行仓库里的程序。每条命令都带同一组覆盖,并镜像到 GIT_CONFIG_COUNT。
  463. it("starts every automatic git command with the hardening overrides", async () => {
  464. const nullDevice = process.platform === "win32" ? "\\\\.\\NUL" : "/dev/null";
  465. const hooks = [
  466. "applypatch-msg",
  467. "pre-applypatch",
  468. "post-applypatch",
  469. "pre-commit",
  470. "pre-merge-commit",
  471. "prepare-commit-msg",
  472. "commit-msg",
  473. "post-commit",
  474. "pre-rebase",
  475. "post-checkout",
  476. "post-merge",
  477. "pre-push",
  478. "pre-receive",
  479. "update",
  480. "proc-receive",
  481. "post-receive",
  482. "post-update",
  483. "reference-transaction",
  484. "push-to-checkout",
  485. "pre-auto-gc",
  486. "post-rewrite",
  487. "sendemail-validate",
  488. "fsmonitor-watchman",
  489. "p4-changelist",
  490. "p4-prepare-changelist",
  491. "p4-post-changelist",
  492. "p4-pre-submit",
  493. "post-index-change",
  494. ];
  495. const pairs = [
  496. ["core.fsmonitor", ""],
  497. ["core.hooksPath", nullDevice],
  498. ["core.askPass", ""],
  499. ["protocol.ext.allow", "never"],
  500. ["submodule.recurse", "false"],
  501. ["log.showSignature", "false"],
  502. ["format.pretty", "medium"],
  503. ["gc.auto", "0"],
  504. ["maintenance.auto", "false"],
  505. ...hooks.map((hook) => [`hook.${hook}.enabled`, "false"]),
  506. ];
  507. const prefix = pairs.flatMap(([key, value]) => ["-c", `${key}=${value}`]);
  508. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  509. await resolveGitSnapshot(repoDirectory);
  510. expect(gitCalls.length).toBeGreaterThan(0);
  511. for (const call of gitCalls) {
  512. expect(call.rawArgs).toEqual([...prefix, ...call.args]);
  513. const env = call.options.env ?? {};
  514. expect(env.GIT_CONFIG_COUNT).toBe(String(pairs.length));
  515. pairs.forEach(([key, value], index) => {
  516. expect(env[`GIT_CONFIG_KEY_${index}`]).toBe(key);
  517. expect(env[`GIT_CONFIG_VALUE_${index}`]).toBe(value);
  518. });
  519. }
  520. expect(gitCalls.map((call) => call.args)).toContainEqual(STATUS_COMMAND);
  521. });
  522. it("drops inherited repository selectors and sets the automatic git environment", async () => {
  523. const saved = { ...process.env };
  524. // 继承来的 GIT_DIR 等会让 git 读另一个仓库;大小写不同的写法也要去掉。
  525. process.env.GIT_DIR = join(outsideDirectory, ".git");
  526. process.env.GIT_WORK_TREE = outsideDirectory;
  527. process.env.git_index_file = join(outsideDirectory, "index");
  528. process.env.GIT_CONFIG_COUNT = "1";
  529. process.env.GIT_CONFIG_KEY_0 = "core.pager";
  530. process.env.GIT_CONFIG_VALUE_0 = "evil";
  531. process.env.GIT_CONFIG_PARAMETERS = "'core.fsmonitor=evil'";
  532. process.env.ZCODE_GIT_SNAPSHOT_KEEP = "kept";
  533. delete process.env.GIT_PROXY_COMMAND;
  534. process.env.PATH = [gitBinDirectory, "relative-bin", ""].join(delimiter);
  535. try {
  536. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  537. await resolveGitSnapshot(repoDirectory);
  538. } finally {
  539. for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
  540. Object.assign(process.env, saved);
  541. }
  542. expect(gitCalls.length).toBeGreaterThan(0);
  543. for (const { options } of gitCalls) {
  544. const env = options.env ?? {};
  545. for (const key of ["GIT_DIR", "GIT_WORK_TREE", "git_index_file"]) {
  546. expect(env).not.toHaveProperty(key);
  547. }
  548. expect(env).toMatchObject({
  549. GIT_ALLOW_PROTOCOL: "/",
  550. GIT_CONFIG_PARAMETERS:
  551. "'alias.remote-none=version' 'alias.remote-none.command=version' 'alias.remote-/.command=version' 'fetch.bundleURI=' 'help.autocorrect=0'",
  552. GIT_LFS_SKIP_SMUDGE: "1",
  553. GIT_NO_LAZY_FETCH: "1",
  554. GIT_NO_REPLACE_OBJECTS: "1",
  555. GIT_PROXY_COMMAND: "",
  556. GIT_SSH_COMMAND: "false",
  557. GIT_TERMINAL_PROMPT: "0",
  558. ZCODE_GIT_SNAPSHOT_KEEP: "kept",
  559. });
  560. // 继承的 GIT_CONFIG_KEY_0 被换成加固的第一项,计数从 0 开始。
  561. expect(env.GIT_CONFIG_KEY_0).toBe("core.fsmonitor");
  562. if (process.platform !== "win32") {
  563. // 名为 PATH 的变量只留以 `/` 开头的条目。
  564. expect(env.PATH).toBe(gitBinDirectory);
  565. }
  566. }
  567. });
  568. it("passes the request signal to every git command", async () => {
  569. const adapter = createNodeContextSourceAdapter({ env: {} });
  570. const controller = new AbortController();
  571. setGitResponse(["symbolic-ref", "--short", "-q", "HEAD"], { code: 0, stdout: "feature\n" });
  572. await adapter.resolveGitContext(
  573. { workingDirectory: repoDirectory },
  574. { signal: controller.signal },
  575. );
  576. expect(gitCalls.length).toBeGreaterThan(2);
  577. expect(gitCalls.every(({ options }) => options.signal === controller.signal)).toBe(true);
  578. });
  579. });
  580. // 自动 git 的 PATH 只留绝对路径条目,按平台拆分。
  581. describe("automatic git PATH", () => {
  582. // 修复原因:桌面 host 在 Windows 上以大写 PATH 启动 Agent,原来按 ":" 拆、只留 "/" 开头,
  583. // Windows 条目全部被丢掉,git 找不到 git-lfs 等外部程序。
  584. it("keeps drive and UNC entries on Windows for a key of any letter case", async () => {
  585. const { automaticGitEnv } = await import("../src/context/git-snapshot.js");
  586. const windowsPath =
  587. 'C:\\Windows\\system32;.;tools;\\rooted;"C:\\Program Files\\Git LFS";\\\\server\\share\\bin;;D:';
  588. const kept = "C:\\Windows\\system32;C:\\Program Files\\Git LFS;\\\\server\\share\\bin";
  589. expect(automaticGitEnv({ PATH: windowsPath }, "win32").PATH).toBe(kept);
  590. const lowerCase = automaticGitEnv({ Path: windowsPath }, "win32");
  591. expect(lowerCase.Path).toBe(kept);
  592. expect(lowerCase).not.toHaveProperty("PATH");
  593. expect(automaticGitEnv({ PATH: ".;tools" }, "win32").PATH).toBe("\\\\.\\NUL");
  594. });
  595. it("keeps the POSIX rule for the variable named exactly PATH", async () => {
  596. const { automaticGitEnv } = await import("../src/context/git-snapshot.js");
  597. expect(automaticGitEnv({ PATH: "/usr/bin:relative::/opt/x" }, "linux").PATH).toBe(
  598. "/usr/bin:/opt/x",
  599. );
  600. expect(automaticGitEnv({ PATH: "relative" }, "darwin").PATH).toBe("/dev/null");
  601. expect(automaticGitEnv({ Path: "relative" }, "linux").Path).toBe("relative");
  602. });
  603. });
  604. describe("automatic git executable lookup", () => {
  605. beforeEach(() => {
  606. resetGitMock();
  607. });
  608. it("searches only PATH entries on Windows and skips scripts Node cannot start", async () => {
  609. const { findExecutableOnPath } = await import("../src/context/git-snapshot.js");
  610. const executables = new Set([
  611. "C:\\proj\\git.exe",
  612. "C:\\tools\\git.cmd",
  613. "C:\\Git\\cmd\\git.exe",
  614. ]);
  615. expect(
  616. await findExecutableOnPath(
  617. "git",
  618. { Path: "C:\\tools;;C:\\Git\\cmd", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
  619. {
  620. cwd: "C:\\proj",
  621. platform: "win32",
  622. isExecutableFile: async (path) => executables.has(path),
  623. },
  624. ),
  625. ).toBe("C:\\Git\\cmd\\git.exe");
  626. });
  627. it("removes the quotes of a Windows entry and tries .com then .exe without PATHEXT", async () => {
  628. const { findExecutableOnPath } = await import("../src/context/git-snapshot.js");
  629. const executables = new Set([
  630. "C:\\Program Files\\Git\\cmd\\git.exe",
  631. "C:\\both\\git.com",
  632. "C:\\both\\git.exe",
  633. ]);
  634. const lookup = (Path: string) =>
  635. findExecutableOnPath(
  636. "git",
  637. // PATHEXT 里没有 .EXE / .COM 也照样找到,与 Node 按裸名启动时相同。
  638. { Path, PATHEXT: ".CMD" },
  639. {
  640. cwd: "C:\\proj",
  641. platform: "win32",
  642. isExecutableFile: async (path) => executables.has(path),
  643. },
  644. );
  645. expect(await lookup('"C:\\Program Files\\Git\\cmd";C:\\both')).toBe(
  646. "C:\\Program Files\\Git\\cmd\\git.exe",
  647. );
  648. expect(await lookup("C:\\both")).toBe("C:\\both\\git.com");
  649. });
  650. it("skips empty PATH entries on POSIX and returns undefined when nothing is found", async () => {
  651. const { findExecutableOnPath } = await import("../src/context/git-snapshot.js");
  652. const executables = new Set(["/work/git", "/usr/bin/git"]);
  653. const lookup = (PATH: string) =>
  654. findExecutableOnPath(
  655. "git",
  656. { PATH },
  657. {
  658. cwd: "/work",
  659. platform: "linux",
  660. isExecutableFile: async (path) => executables.has(path),
  661. },
  662. );
  663. expect(await lookup(":/opt/empty:/usr/bin")).toBe("/usr/bin/git");
  664. expect(await lookup("/opt/empty")).toBeUndefined();
  665. });
  666. it("starts no git when PATH has none and looks again on the next read", async () => {
  667. vi.resetModules();
  668. const { resolveGitSnapshot } = await import("../src/context/git-snapshot.js");
  669. process.env.PATH = outsideDirectory;
  670. try {
  671. expect(await resolveGitSnapshot(repoDirectory)).toEqual({
  672. isGitRepository: true,
  673. gitBranch: "HEAD",
  674. gitMainBranch: "main",
  675. gitStatus: "clean",
  676. gitStatusLines: [],
  677. recentCommits: [],
  678. });
  679. expect(gitCalls).toEqual([]);
  680. } finally {
  681. process.env.PATH = gitBinDirectory;
  682. }
  683. await resolveGitSnapshot(repoDirectory);
  684. expect(new Set(gitCalls.map((call) => call.command))).toEqual(new Set([gitOnPath]));
  685. });
  686. // 进程目录读不到(例如已被删除)时只跳过相对条目,绝对条目上的 git 照常找到并运行。
  687. it("still finds git on an absolute entry when the process directory cannot be read", async () => {
  688. vi.resetModules();
  689. const { findExecutableOnPath, resolveGitSnapshot } =
  690. await import("../src/context/git-snapshot.js");
  691. const cwd = vi.spyOn(process, "cwd").mockImplementation(() => {
  692. throw Object.assign(new Error("ENOENT: no such file or directory, uv_cwd"), {
  693. code: "ENOENT",
  694. });
  695. });
  696. const checked: string[] = [];
  697. try {
  698. expect(
  699. await findExecutableOnPath(
  700. "git",
  701. { PATH: "relbin:/usr/bin" },
  702. {
  703. platform: "linux",
  704. isExecutableFile: async (path) => {
  705. checked.push(path);
  706. return path === "/usr/bin/git";
  707. },
  708. },
  709. ),
  710. ).toBe("/usr/bin/git");
  711. await resolveGitSnapshot(repoDirectory);
  712. } finally {
  713. cwd.mockRestore();
  714. }
  715. expect(checked).toEqual(["/usr/bin/git"]);
  716. expect(new Set(gitCalls.map((call) => call.command))).toEqual(new Set([gitOnPath]));
  717. });
  718. });