gitCliRepo.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join, resolve } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { DEFAULT_GIT_PUSH_OUTPUT_BYTES, DEFAULT_GIT_PUSH_TIMEOUT_MS } from "../src/git/config.js";
  6. import type {
  7. GitCommandExecutionOptions,
  8. GitCommandExecutionResult,
  9. GitCommandProvider,
  10. } from "../src/git/providers/gitCommandProvider.js";
  11. import { createGitService } from "../src/git/gitService.js";
  12. import { createGitCliRepo } from "../src/git/repo/gitCliRepo.js";
  13. const tempDirs: string[] = [];
  14. function createCommandResult(
  15. options: GitCommandExecutionOptions,
  16. overrides?: Partial<GitCommandExecutionResult>,
  17. ): GitCommandExecutionResult {
  18. return {
  19. binaryPath: "git",
  20. cwd: options.cwd,
  21. args: options.args,
  22. stdout: "",
  23. stderr: "",
  24. exitCode: 0,
  25. signal: null,
  26. durationMs: 1,
  27. timedOut: false,
  28. outputTruncated: false,
  29. ...overrides,
  30. };
  31. }
  32. function makeTempDir(prefix: string): string {
  33. const dir = mkdtempSync(join(tmpdir(), prefix));
  34. tempDirs.push(dir);
  35. return dir;
  36. }
  37. function createMockCommandProvider(): {
  38. commandProvider: GitCommandProvider;
  39. run: ReturnType<typeof vi.fn>;
  40. } {
  41. const run = vi.fn(
  42. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  43. const command = options.args.join(" ");
  44. switch (command) {
  45. case "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir":
  46. return createCommandResult(options, {
  47. stdout: "/repo\npackages/app/\n/repo/.git\n.git\n",
  48. });
  49. case "status --porcelain=v2 --branch --untracked-files=all -z":
  50. return createCommandResult(options, {
  51. stdout: "# branch.head main\0# branch.upstream origin/main\0# branch.ab +0 -0\0",
  52. });
  53. case "diff --cached --numstat -z --find-renames --":
  54. case "diff --numstat -z --find-renames --":
  55. return createCommandResult(options);
  56. case "config --show-scope --show-origin --get user.name":
  57. return createCommandResult(options, {
  58. stdout: "local\tfile:.git/config\tZCode Tester\n",
  59. });
  60. case "config --show-scope --show-origin --get user.email":
  61. return createCommandResult(options, {
  62. stdout: "local\tfile:.git/config\ttester@example.com\n",
  63. });
  64. case "push":
  65. return createCommandResult(options);
  66. default:
  67. throw new Error(`Unexpected git command in test: ${command}`);
  68. }
  69. },
  70. );
  71. return {
  72. commandProvider: {
  73. resolveGitBinary: vi.fn().mockResolvedValue("git"),
  74. run,
  75. },
  76. run,
  77. };
  78. }
  79. afterEach(() => {
  80. while (tempDirs.length > 0) {
  81. const dir = tempDirs.pop();
  82. if (dir) {
  83. rmSync(dir, { recursive: true, force: true });
  84. }
  85. }
  86. });
  87. describe("gitCliRepo", () => {
  88. it("reuses the in-flight status snapshot for concurrent readers", async () => {
  89. const { commandProvider, run } = createMockCommandProvider();
  90. const repo = createGitCliRepo({ commandProvider });
  91. const workspacePath = "/repo/packages/app";
  92. const [left, right] = await Promise.all([
  93. repo.getStatus(workspacePath),
  94. repo.getStatus(workspacePath),
  95. ]);
  96. expect(left.summary.repoRoot).toBe("/repo");
  97. expect(right.summary.workspaceInRepoPath).toBe("packages/app");
  98. expect(run.mock.calls.map(([options]) => options.args.join(" "))).toEqual([
  99. "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir",
  100. "status --porcelain=v2 --branch --untracked-files=all -z",
  101. "diff --cached --numstat -z --find-renames --",
  102. "diff --numstat -z --find-renames --",
  103. ]);
  104. });
  105. it("详细状态超限后应按 repoRoot 复用未跟踪目录折叠模式", async () => {
  106. const { commandProvider, run } = createMockCommandProvider();
  107. run.mockImplementation(
  108. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  109. const command = options.args.join(" ");
  110. switch (command) {
  111. case "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir":
  112. return createCommandResult(options, {
  113. stdout: "/repo\npackages/app/\n/repo/.git\n.git\n",
  114. });
  115. case "status --porcelain=v2 --branch --untracked-files=all -z":
  116. return createCommandResult(options, {
  117. stdout: "# branch.head main\0? packages/app/.npm/cache/partial-entry\0",
  118. outputTruncated: true,
  119. });
  120. case "status --porcelain=v2 --branch --untracked-files=normal -z":
  121. return createCommandResult(options, {
  122. stdout: "# branch.head main\0? packages/app/.npm/\0",
  123. });
  124. case "diff --cached --numstat -z --find-renames --":
  125. case "diff --numstat -z --find-renames --":
  126. return createCommandResult(options);
  127. default:
  128. throw new Error(`Unexpected git command in test: ${command}`);
  129. }
  130. },
  131. );
  132. const repo = createGitCliRepo({ commandProvider });
  133. const service = createGitService({ repo });
  134. const workspacePath = "/repo/packages/app";
  135. const first = await repo.getStatus(workspacePath);
  136. const second = await repo.getStatus(workspacePath);
  137. const changes = await service.getChanges({ workspacePath, sourceId: "unstaged" });
  138. expect(first.summary).toMatchObject({ branchName: "main", isDirty: true });
  139. expect(first.entries.map((entry) => entry.path)).toEqual(["packages/app/.npm/"]);
  140. expect(second.entries.map((entry) => entry.path)).toEqual(["packages/app/.npm/"]);
  141. expect(changes).toEqual([
  142. expect.objectContaining({
  143. workspaceRelativePath: ".npm/",
  144. section: "untracked",
  145. added: 0,
  146. removed: 0,
  147. }),
  148. ]);
  149. expect(
  150. run.mock.calls.filter(
  151. ([options]) =>
  152. options.args.join(" ") === "status --porcelain=v2 --branch --untracked-files=all -z",
  153. ),
  154. ).toHaveLength(1);
  155. expect(
  156. run.mock.calls.filter(
  157. ([options]) =>
  158. options.args.join(" ") === "status --porcelain=v2 --branch --untracked-files=normal -z",
  159. ),
  160. ).toHaveLength(3);
  161. });
  162. it("reuses the in-flight repository resolution across status and identity reads", async () => {
  163. const { commandProvider, run } = createMockCommandProvider();
  164. const repo = createGitCliRepo({ commandProvider });
  165. const workspacePath = "/repo/packages/app";
  166. const [status, identity] = await Promise.all([
  167. repo.getStatus(workspacePath),
  168. repo.getIdentity(workspacePath),
  169. ]);
  170. expect(status.summary.repoRoot).toBe("/repo");
  171. expect(identity.userName).toBe("ZCode Tester");
  172. expect(
  173. run.mock.calls.filter(
  174. ([options]) =>
  175. options.args.join(" ") ===
  176. "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir",
  177. ),
  178. ).toHaveLength(1);
  179. });
  180. it("identifies main-tree workspaces via repoRoot/.git directory", async () => {
  181. const repoRoot = makeTempDir("zcode-git-main-tree-");
  182. mkdirSync(join(repoRoot, ".git"));
  183. const workspacePath = join(repoRoot, "packages", "app");
  184. mkdirSync(workspacePath, { recursive: true });
  185. const { commandProvider } = createMockCommandProvider();
  186. commandProvider.run = vi.fn(
  187. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  188. const command = options.args.join(" ");
  189. if (
  190. command === "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir"
  191. ) {
  192. return createCommandResult(options, {
  193. stdout: `${repoRoot}\npackages/app/\n${join(repoRoot, ".git")}\n.git\n`,
  194. });
  195. }
  196. throw new Error(`Unexpected git command in test: ${command}`);
  197. },
  198. );
  199. const repo = createGitCliRepo({ commandProvider });
  200. await expect(repo.getWorkspaceRepositoryInfo(workspacePath)).resolves.toEqual({
  201. workspacePath,
  202. kind: "main-tree",
  203. isGitAvailable: true,
  204. });
  205. });
  206. it("identifies linked worktree workspaces via repoRoot/.git file", async () => {
  207. const mainTreeRoot = makeTempDir("zcode-git-worktree-main-");
  208. mkdirSync(join(mainTreeRoot, ".git", "worktrees", "feature"), { recursive: true });
  209. const worktreeRoot = makeTempDir("zcode-git-worktree-linked-");
  210. writeFileSync(
  211. join(worktreeRoot, ".git"),
  212. `gitdir: ${join(mainTreeRoot, ".git", "worktrees", "feature")}\n`,
  213. "utf-8",
  214. );
  215. const run = vi.fn(
  216. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  217. const command = options.args.join(" ");
  218. switch (command) {
  219. case "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir":
  220. return createCommandResult(options, {
  221. stdout: `${worktreeRoot}\n\n${join(mainTreeRoot, ".git", "worktrees", "feature")}\n${join(mainTreeRoot, ".git")}\n`,
  222. });
  223. default:
  224. throw new Error(`Unexpected git command in test: ${command}`);
  225. }
  226. },
  227. );
  228. const repo = createGitCliRepo({
  229. commandProvider: {
  230. resolveGitBinary: vi.fn().mockResolvedValue("git"),
  231. run,
  232. },
  233. });
  234. await expect(repo.getWorkspaceRepositoryInfo(worktreeRoot)).resolves.toEqual({
  235. workspacePath: worktreeRoot,
  236. kind: "linked-worktree",
  237. isGitAvailable: true,
  238. });
  239. });
  240. it("includes worktree gitdir and common gitdir in status auto-refresh watch paths", async () => {
  241. const worktreeRoot = "/repo-linked";
  242. const worktreeGitDir = "/repo-main/.git/worktrees/repo-linked";
  243. const commonGitDir = "/repo-main/.git";
  244. const run = vi.fn(
  245. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  246. const command = options.args.join(" ");
  247. switch (command) {
  248. case "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir":
  249. return createCommandResult(options, {
  250. stdout: `${worktreeRoot}\n\n${worktreeGitDir}\n${commonGitDir}\n`,
  251. });
  252. case "status --porcelain=v2 --branch --untracked-files=all -z":
  253. return createCommandResult(options, {
  254. stdout: "# branch.head feature\0",
  255. });
  256. case "diff --cached --numstat -z --find-renames --":
  257. case "diff --numstat -z --find-renames --":
  258. return createCommandResult(options);
  259. default:
  260. throw new Error(`Unexpected git command in test: ${command}`);
  261. }
  262. },
  263. );
  264. const repo = createGitCliRepo({
  265. commandProvider: {
  266. resolveGitBinary: vi.fn().mockResolvedValue("git"),
  267. run,
  268. },
  269. });
  270. const status = await repo.getStatus(worktreeRoot);
  271. expect(status.summary.autoRefreshWatchPaths).toEqual([
  272. {
  273. path: worktreeGitDir,
  274. recursive: true,
  275. },
  276. {
  277. path: commonGitDir,
  278. recursive: true,
  279. },
  280. ]);
  281. });
  282. it("resolves a relative common git dir from the workspace command cwd", async () => {
  283. // 根因:本用例是唯一走「相对 --git-common-dir + 宿主 resolve()」的分支,其它用例只做字面量
  284. // 比较。原来用 POSIX 字面量 "/root/.git" 作断言,而 resolve("/root/demo-project","../.git")
  285. // 在 win32 上得到 "C:\root\.git" —— 两者不相等,去重失败,watch 路径多出一条。
  286. // 用宿主 path 组装 fixture,让断言在三个平台上表达同一个"仓库根下的 .git"。
  287. const repoRoot = resolve("/root");
  288. const workspacePath = join(repoRoot, "demo-project");
  289. const absoluteGitDir = join(repoRoot, ".git");
  290. const run = vi.fn(
  291. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  292. const command = options.args.join(" ");
  293. if (
  294. command === "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir"
  295. ) {
  296. return createCommandResult(options, {
  297. stdout: `${repoRoot}\ndemo-project/\n${absoluteGitDir}\n../.git\n`,
  298. });
  299. }
  300. throw new Error(`Unexpected git command in test: ${command}`);
  301. },
  302. );
  303. const repo = createGitCliRepo({
  304. commandProvider: {
  305. resolveGitBinary: vi.fn().mockResolvedValue("git"),
  306. run,
  307. },
  308. });
  309. const resolution = await repo.resolveRepository(workspacePath);
  310. expect(resolution.autoRefreshWatchPaths).toEqual([
  311. {
  312. path: absoluteGitDir,
  313. recursive: true,
  314. },
  315. ]);
  316. });
  317. it("treats spawn git ENOENT during repository resolution as not-repository", async () => {
  318. const workspacePath = "/missing/worktree-path";
  319. const run = vi.fn(
  320. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  321. const command = options.args.join(" ");
  322. if (
  323. command === "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir"
  324. ) {
  325. return createCommandResult(options, {
  326. exitCode: -2,
  327. stderr: "spawn git ENOENT",
  328. });
  329. }
  330. throw new Error(`Unexpected git command in test: ${command}`);
  331. },
  332. );
  333. const repo = createGitCliRepo({
  334. commandProvider: {
  335. resolveGitBinary: vi.fn().mockResolvedValue("git"),
  336. run,
  337. },
  338. });
  339. await expect(repo.getWorkspaceRepositoryInfo(workspacePath)).resolves.toEqual({
  340. workspacePath,
  341. kind: "not-repository",
  342. isGitAvailable: true,
  343. });
  344. });
  345. it("uses the dedicated long timeout and larger output budget for push hooks", async () => {
  346. const { commandProvider, run } = createMockCommandProvider();
  347. const repo = createGitCliRepo({ commandProvider });
  348. const workspacePath = "/repo/packages/app";
  349. await repo.push(workspacePath);
  350. const pushCall = run.mock.calls.find(([options]) => options.args.join(" ") === "push");
  351. expect(pushCall?.[0].timeoutMs).toBe(DEFAULT_GIT_PUSH_TIMEOUT_MS);
  352. expect(pushCall?.[0].maxOutputBytes).toBe(DEFAULT_GIT_PUSH_OUTPUT_BYTES);
  353. });
  354. it("checks ignored paths from argv without using incompatible -z output", async () => {
  355. const { commandProvider, run } = createMockCommandProvider();
  356. const repo = createGitCliRepo({ commandProvider });
  357. const workspacePath = "/repo/packages/app";
  358. run.mockImplementation(
  359. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  360. const command = options.args.join(" ");
  361. if (
  362. command === "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir"
  363. ) {
  364. return createCommandResult(options, {
  365. stdout: "/repo\npackages/app/\n/repo/.git\n.git\n",
  366. });
  367. }
  368. if (command === "check-ignore -- packages/app/.env packages/app/src/index.ts") {
  369. return createCommandResult(options, {
  370. stdout: "packages/app/.env\n",
  371. });
  372. }
  373. throw new Error(`Unexpected git command in test: ${command}`);
  374. },
  375. );
  376. await expect(
  377. repo.getIgnoredPaths(workspacePath, [
  378. "/repo/packages/app/.env",
  379. "/repo/packages/app/src/index.ts",
  380. ]),
  381. ).resolves.toEqual(["/repo/packages/app/.env"]);
  382. });
  383. it("keeps a valid unstaged patch when the working-tree content cannot be read", async () => {
  384. const workspacePath = "/repo/packages/app";
  385. const filePath = "/repo/packages/app/index.vue";
  386. const patch = [
  387. "diff --git a/packages/app/index.vue b/packages/app/index.vue",
  388. "index 1111111..2222222 100644",
  389. "--- a/packages/app/index.vue",
  390. "+++ b/packages/app/index.vue",
  391. "@@ -1,2 +1,3 @@",
  392. " <template>",
  393. "+ <SearchSelect />",
  394. " </template>",
  395. "",
  396. ].join("\n");
  397. const run = vi.fn(
  398. async (options: GitCommandExecutionOptions): Promise<GitCommandExecutionResult> => {
  399. const command = options.args.join(" ");
  400. switch (command) {
  401. case "rev-parse --show-toplevel --show-prefix --absolute-git-dir --git-common-dir":
  402. return createCommandResult(options, {
  403. stdout: "/repo\npackages/app/\n/repo/.git\n.git\n",
  404. });
  405. case "diff --no-ext-diff --no-color --binary -- packages/app/index.vue":
  406. return createCommandResult(options, { stdout: patch });
  407. case "show :packages/app/index.vue":
  408. return createCommandResult(options, {
  409. stdout: "<template>\n</template>\n",
  410. });
  411. default:
  412. throw new Error(`Unexpected git command in test: ${command}`);
  413. }
  414. },
  415. );
  416. const repo = createGitCliRepo({
  417. commandProvider: {
  418. resolveGitBinary: vi.fn().mockResolvedValue("git"),
  419. run,
  420. },
  421. });
  422. await expect(
  423. repo.getDiff({
  424. workspacePath,
  425. path: filePath,
  426. sourceId: "unstaged",
  427. }),
  428. ).resolves.toEqual({
  429. path: filePath,
  430. availability: "patch",
  431. patch,
  432. beforeContent: null,
  433. afterContent: null,
  434. summary: null,
  435. });
  436. });
  437. });