gitCheckpointService.test.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import { execFileSync, spawnSync } from "node:child_process";
  2. import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createGitCheckpointService } from "../src/git/gitCheckpointService.js";
  7. import { GitCheckpointStore } from "../src/git/repo/gitCheckpointStore.js";
  8. import { setDataBaseDir } from "../src/paths.js";
  9. const gitAvailable = spawnSync("git", ["--version"], { stdio: "ignore" }).status === 0;
  10. const describeIfGit = gitAvailable ? describe : describe.skip;
  11. const tempDirs: string[] = [];
  12. // 修复原因:这些用例会创建真实临时仓库并执行多次 Git 子进程;全量并发时磁盘与
  13. // 子进程调度会超过 15 秒,但聚焦运行时业务断言稳定通过,统一保留合理的调度余量。
  14. const GIT_INTEGRATION_TEST_TIMEOUT_MS = 30_000;
  15. const gitLocalEnvVars = gitAvailable
  16. ? execFileSync("git", ["rev-parse", "--local-env-vars"], {
  17. encoding: "utf-8",
  18. })
  19. .split("\n")
  20. .map((line) => line.trim())
  21. .filter((line) => line.length > 0)
  22. : [];
  23. function createDetachedGitEnv(): NodeJS.ProcessEnv {
  24. const env = {
  25. ...process.env,
  26. };
  27. // Bugfix: pre-push hook 会携带当前仓库的 GIT_DIR/GIT_WORK_TREE。
  28. // 这些变量会让临时仓库测试命令“串仓”,把真实工作分支误改名。
  29. // 测试 helper 在这里清理 Git local env,保证命令只作用于目标 cwd 仓库。
  30. for (const variableName of gitLocalEnvVars) {
  31. delete env[variableName];
  32. }
  33. return env;
  34. }
  35. function makeTempDir(prefix: string): string {
  36. const dir = mkdtempSync(join(tmpdir(), prefix));
  37. tempDirs.push(dir);
  38. return dir;
  39. }
  40. function runGit(cwd: string | undefined, args: string[]): string {
  41. return execFileSync("git", args, {
  42. cwd,
  43. encoding: "utf-8",
  44. env: createDetachedGitEnv(),
  45. }).trim();
  46. }
  47. function createRepo() {
  48. const repoPath = makeTempDir("zcode-git-checkpoint-repo-");
  49. const dataBaseDir = makeTempDir("zcode-git-checkpoint-data-");
  50. setDataBaseDir(dataBaseDir);
  51. const workspacePath = join(repoPath, "packages", "app");
  52. mkdirSync(workspacePath, { recursive: true });
  53. mkdirSync(join(repoPath, "packages", "other"), { recursive: true });
  54. writeFileSync(join(workspacePath, "tracked.txt"), "line 1\nline 2\n");
  55. writeFileSync(join(workspacePath, "delete-me.txt"), "delete me\n");
  56. writeFileSync(join(workspacePath, "rename-me.txt"), "rename me\n");
  57. writeFileSync(join(workspacePath, "stage-me.txt"), "stage base\n");
  58. writeFileSync(join(repoPath, "packages", "other", "skip.txt"), "skip\n");
  59. runGit(repoPath, ["init"]);
  60. runGit(repoPath, ["branch", "-M", "main"]);
  61. runGit(repoPath, ["config", "user.name", "ZCode Tester"]);
  62. runGit(repoPath, ["config", "user.email", "tester@example.com"]);
  63. runGit(repoPath, ["config", "commit.gpgsign", "false"]);
  64. runGit(repoPath, ["config", "core.autocrlf", "false"]);
  65. runGit(repoPath, ["add", "."]);
  66. runGit(repoPath, ["commit", "-m", "chore: initial"]);
  67. return { dataBaseDir, repoPath, workspacePath };
  68. }
  69. afterEach(() => {
  70. setDataBaseDir(null);
  71. while (tempDirs.length > 0) {
  72. const dir = tempDirs.pop();
  73. if (dir) {
  74. rmSync(dir, { recursive: true, force: true });
  75. }
  76. }
  77. });
  78. describeIfGit("gitCheckpointService", () => {
  79. it("creates workspace-scoped checkpoints, diffs them, and restores files without touching staged state", async () => {
  80. const { dataBaseDir, repoPath, workspacePath } = createRepo();
  81. const service = createGitCheckpointService({
  82. store: new GitCheckpointStore({ rootDir: join(repoPath, ".zcode-test-checkpoints") }),
  83. });
  84. const base = await service.createCheckpoint({ workspacePath });
  85. writeFileSync(join(workspacePath, "tracked.txt"), "line 1\nline 2 changed\n");
  86. rmSync(join(workspacePath, "delete-me.txt"));
  87. runGit(repoPath, ["mv", "packages/app/rename-me.txt", "packages/app/renamed.txt"]);
  88. writeFileSync(join(workspacePath, "new-file.txt"), "new file\n");
  89. writeFileSync(join(workspacePath, "stage-me.txt"), "stage changed\n");
  90. writeFileSync(join(repoPath, "packages", "other", "skip.txt"), "skip changed\n");
  91. runGit(repoPath, ["add", "packages/app/stage-me.txt"]);
  92. const stagedBeforeRestore = runGit(repoPath, ["diff", "--cached", "--name-only"]);
  93. const changed = await service.createCheckpoint({ workspacePath });
  94. const diff = await service.diffCheckpoints({
  95. workspacePath,
  96. fromCheckpointId: base.checkpointId,
  97. toCheckpointId: changed.checkpointId,
  98. });
  99. expect(diff.files.map((file) => `${file.kind}:${file.workspaceRelativePath}`).sort()).toEqual([
  100. "added:new-file.txt",
  101. "deleted:delete-me.txt",
  102. "modified:stage-me.txt",
  103. "modified:tracked.txt",
  104. "renamed:renamed.txt",
  105. ]);
  106. expect(diff.files.some((file) => file.repoRelativePath.includes("packages/other"))).toBe(false);
  107. const restoreResult = await service.restoreBetweenCheckpoints({
  108. workspacePath,
  109. fromCheckpointId: changed.checkpointId,
  110. toCheckpointId: base.checkpointId,
  111. });
  112. expect(restoreResult.success).toBe(true);
  113. expect(readFileSync(join(workspacePath, "tracked.txt"), "utf-8")).toBe("line 1\nline 2\n");
  114. expect(readFileSync(join(workspacePath, "delete-me.txt"), "utf-8")).toBe("delete me\n");
  115. expect(() => readFileSync(join(workspacePath, "new-file.txt"), "utf-8")).toThrow();
  116. expect(() => readFileSync(join(workspacePath, "renamed.txt"), "utf-8")).toThrow();
  117. expect(readFileSync(join(workspacePath, "rename-me.txt"), "utf-8")).toBe("rename me\n");
  118. expect(readFileSync(join(repoPath, "packages", "other", "skip.txt"), "utf-8")).toBe(
  119. "skip changed\n",
  120. );
  121. expect(runGit(repoPath, ["diff", "--cached", "--name-only"])).toBe(stagedBeforeRestore);
  122. expect(readdirSync(join(dataBaseDir, ".zcode", "git-checkpoint-index"))).toEqual([]);
  123. }, GIT_INTEGRATION_TEST_TIMEOUT_MS);
  124. it("returns conflicts when affected files drift away from the declared fromCheckpoint and supports force restore", async () => {
  125. const { repoPath, workspacePath } = createRepo();
  126. const service = createGitCheckpointService({
  127. store: new GitCheckpointStore({ rootDir: join(repoPath, ".zcode-test-checkpoints") }),
  128. });
  129. const base = await service.createCheckpoint({ workspacePath });
  130. writeFileSync(join(workspacePath, "tracked.txt"), "line 1\nline 2 changed\n");
  131. const changed = await service.createCheckpoint({ workspacePath });
  132. writeFileSync(join(workspacePath, "tracked.txt"), "line 1\nline 2 changed again\n");
  133. const conflicted = await service.restoreBetweenCheckpoints({
  134. workspacePath,
  135. fromCheckpointId: changed.checkpointId,
  136. toCheckpointId: base.checkpointId,
  137. });
  138. expect(conflicted.success).toBe(false);
  139. expect(conflicted.conflicts?.map((conflict) => conflict.workspaceRelativePath)).toEqual([
  140. "tracked.txt",
  141. ]);
  142. const forced = await service.restoreBetweenCheckpoints({
  143. workspacePath,
  144. fromCheckpointId: changed.checkpointId,
  145. toCheckpointId: base.checkpointId,
  146. force: true,
  147. });
  148. expect(forced.success).toBe(true);
  149. expect(readFileSync(join(workspacePath, "tracked.txt"), "utf-8")).toBe("line 1\nline 2\n");
  150. await service.deleteCheckpoint({ workspacePath, checkpointId: changed.checkpointId });
  151. await expect(
  152. service.diffCheckpoints({
  153. workspacePath,
  154. fromCheckpointId: base.checkpointId,
  155. toCheckpointId: changed.checkpointId,
  156. }),
  157. ).rejects.toThrow(`Checkpoint does not exist: ${changed.checkpointId}`);
  158. }, GIT_INTEGRATION_TEST_TIMEOUT_MS);
  159. });