gitService.test.ts 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. import { execFileSync, spawnSync } from "node:child_process";
  2. import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
  3. import { cp, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { isAbsolute, join, resolve } from "node:path";
  6. import {
  7. afterAll,
  8. beforeAll,
  9. describe,
  10. expect,
  11. it,
  12. onTestFinished,
  13. vi,
  14. } from "vitest";
  15. import { getSingularPatch } from "@pierre/diffs";
  16. import type {
  17. GitCommitMessageConversationContext,
  18. GitDiffResult,
  19. GitFileChange,
  20. GitRepositorySummary,
  21. } from "@zcode/shared";
  22. import type { GitCommitMessageGenerator } from "../src/git/gitCommitMessageGenerator.js";
  23. import { createGitService } from "../src/git/gitService.js";
  24. import type { GitCliRepo } from "../src/git/repo/gitCliRepo.js";
  25. const gitAvailable =
  26. spawnSync("git", ["--version"], { stdio: "ignore" }).status === 0;
  27. const describeIfGit = gitAvailable ? describe : describe.skip;
  28. let repoTemplatePath: string | null = null;
  29. const gitLocalEnvVars = gitAvailable
  30. ? execFileSync("git", ["rev-parse", "--local-env-vars"], {
  31. encoding: "utf-8",
  32. })
  33. .split("\n")
  34. .map((line) => line.trim())
  35. .filter((line) => line.length > 0)
  36. : [];
  37. function createSummary(
  38. overrides: Partial<GitRepositorySummary> = {},
  39. ): GitRepositorySummary {
  40. return {
  41. workspacePath: "/repo/packages/app",
  42. repoRoot: "/repo",
  43. workspaceInRepoPath: "packages/app",
  44. autoRefreshWatchPaths: [],
  45. branchName: "main",
  46. trackingBranchName: "origin/main",
  47. headRefType: "branch",
  48. ahead: 0,
  49. behind: 0,
  50. isDirty: false,
  51. isGitAvailable: true,
  52. isRepository: true,
  53. ...overrides,
  54. };
  55. }
  56. function createMockRepo(overrides: Partial<GitCliRepo>): GitCliRepo {
  57. const unexpected = (name: keyof GitCliRepo) =>
  58. vi.fn(async () => {
  59. throw new Error(`Unexpected GitCliRepo call in test: ${name}`);
  60. });
  61. return {
  62. invalidate: vi.fn(),
  63. resolveRepository: unexpected("resolveRepository"),
  64. getWorkspaceRepositoryInfo: unexpected("getWorkspaceRepositoryInfo"),
  65. getStatus: unexpected("getStatus"),
  66. getCommitGraph: unexpected("getCommitGraph"),
  67. getIgnoredPaths: unexpected("getIgnoredPaths"),
  68. listLocalBranches: unexpected("listLocalBranches"),
  69. switchBranch: unexpected("switchBranch"),
  70. createBranchAndSwitch: unexpected("createBranchAndSwitch"),
  71. getDiff: unexpected("getDiff"),
  72. getBranchComparison: unexpected("getBranchComparison"),
  73. stage: unexpected("stage"),
  74. unstage: unexpected("unstage"),
  75. discard: unexpected("discard"),
  76. commit: unexpected("commit"),
  77. push: unexpected("push"),
  78. getIdentity: unexpected("getIdentity"),
  79. ...overrides,
  80. } as GitCliRepo;
  81. }
  82. function createDetachedGitEnv(): NodeJS.ProcessEnv {
  83. const env = {
  84. ...process.env,
  85. };
  86. // Bugfix: pre-push hook 触发测试时,Git 会注入 GIT_DIR/GIT_WORK_TREE 等本地环境变量。
  87. // 如果不清理,这个 helper 即便传了临时仓库 cwd,也会误操作当前工作仓库(例如把分支重命名成 main)。
  88. // 这里统一移除 Git local env,确保测试里的每条 git 命令只作用于显式传入的仓库目录。
  89. for (const variableName of gitLocalEnvVars) {
  90. delete env[variableName];
  91. }
  92. return env;
  93. }
  94. function makeTempDir(prefix: string): string {
  95. const dir = mkdtempSync(join(tmpdir(), prefix));
  96. onTestFinished(async () => {
  97. await rm(dir, { recursive: true, force: true });
  98. });
  99. return dir;
  100. }
  101. function runGit(cwd: string | undefined, args: string[]): string {
  102. return execFileSync("git", args, {
  103. cwd,
  104. encoding: "utf-8",
  105. env: createDetachedGitEnv(),
  106. }).trim();
  107. }
  108. function runGitAllowFailure(cwd: string | undefined, args: string[]) {
  109. return spawnSync("git", args, {
  110. cwd,
  111. encoding: "utf-8",
  112. });
  113. }
  114. function resolveGitPath(repoPath: string, gitPath: string): string {
  115. return isAbsolute(gitPath) ? gitPath : resolve(repoPath, gitPath);
  116. }
  117. function createRepoTemplate(): string {
  118. const repoPath = mkdtempSync(join(tmpdir(), "zcode-git-template-"));
  119. const workspacePath = join(repoPath, "packages", "app");
  120. mkdirSync(workspacePath, { recursive: true });
  121. mkdirSync(join(repoPath, "packages", "other"), { recursive: true });
  122. writeFileSync(join(workspacePath, "tracked.txt"), "line 1\nline 2\n");
  123. writeFileSync(join(repoPath, "packages", "other", "skip.txt"), "skip\n");
  124. runGit(repoPath, ["init"]);
  125. runGit(repoPath, ["branch", "-M", "main"]);
  126. runGit(repoPath, ["config", "user.name", "ZCode Tester"]);
  127. runGit(repoPath, ["config", "user.email", "tester@example.com"]);
  128. runGit(repoPath, ["config", "commit.gpgsign", "false"]);
  129. runGit(repoPath, ["config", "core.autocrlf", "false"]);
  130. runGit(repoPath, ["config", "maintenance.auto", "false"]);
  131. runGit(repoPath, ["add", "."]);
  132. runGit(repoPath, ["commit", "-m", "chore: initial"]);
  133. return repoPath;
  134. }
  135. async function createRepo(options?: { withRemote?: boolean }) {
  136. if (!repoTemplatePath) {
  137. throw new Error("Git test repository template is not initialized");
  138. }
  139. // Bugfix: 每个 case 原本都通过 8 个同步 Git 子进程从零建库;related 测试并发时会耗尽
  140. // macOS 的进程启动队列。复用一次性模板并复制独立工作树,保留真实 Git 行为与 case 隔离。
  141. const repoContainer = makeTempDir("zcode-git-repo-");
  142. const repoPath = join(repoContainer, "repo");
  143. await cp(repoTemplatePath, repoPath, { recursive: true });
  144. const workspacePath = join(repoPath, "packages", "app");
  145. let remotePath: string | null = null;
  146. if (options?.withRemote) {
  147. remotePath = makeTempDir("zcode-git-remote-");
  148. runGit(undefined, ["init", "--bare", remotePath]);
  149. runGit(repoPath, ["remote", "add", "origin", remotePath]);
  150. runGit(repoPath, ["push", "-u", "origin", "main"]);
  151. }
  152. return { repoPath, workspacePath, remotePath };
  153. }
  154. beforeAll(() => {
  155. if (gitAvailable) {
  156. repoTemplatePath = createRepoTemplate();
  157. }
  158. });
  159. afterAll(async () => {
  160. if (repoTemplatePath) {
  161. await rm(repoTemplatePath, { recursive: true, force: true });
  162. repoTemplatePath = null;
  163. }
  164. });
  165. describeIfGit("gitService", () => {
  166. it("lists local branches and marks the current branch", async () => {
  167. const workspacePath = "/repo/packages/app";
  168. const listLocalBranches = vi.fn().mockResolvedValue({
  169. headRefType: "branch",
  170. currentBranchName: "main",
  171. branches: [
  172. {
  173. name: "main",
  174. isCurrent: true,
  175. upstreamName: "origin/main",
  176. commitHash: "a".repeat(40),
  177. commitTimestampMs: 1,
  178. },
  179. {
  180. name: "feature/list-branches",
  181. isCurrent: false,
  182. upstreamName: null,
  183. commitHash: "b".repeat(40),
  184. commitTimestampMs: 2,
  185. },
  186. ],
  187. });
  188. const service = createGitService({
  189. repo: createMockRepo({ listLocalBranches }),
  190. });
  191. const branches = await service.getLocalBranches({ workspacePath });
  192. expect(branches.headRefType).toBe("branch");
  193. expect(branches.currentBranchName).toBe("main");
  194. expect(branches.branches[0]).toMatchObject({
  195. name: "main",
  196. isCurrent: true,
  197. });
  198. expect(branches.branches.map((branch) => branch.name)).toEqual([
  199. "main",
  200. "feature/list-branches",
  201. ]);
  202. expect(
  203. branches.branches.find(
  204. (branch) => branch.name === "feature/list-branches",
  205. ),
  206. ).toMatchObject({
  207. isCurrent: false,
  208. upstreamName: null,
  209. });
  210. expect(listLocalBranches).toHaveBeenCalledWith(workspacePath);
  211. });
  212. // Bugfix: 该用例真实创建/切换/merge Git 仓库,pre-push 全量并发时偶尔超过默认 5s。
  213. // 这里仅放宽这个集成用例,避免把 Git 进程调度抖动误判成业务失败。
  214. it("returns real commit graph history with parents, refs, and max-count", async () => {
  215. const { repoPath, workspacePath } = await createRepo();
  216. const service = createGitService();
  217. runGit(repoPath, ["switch", "-c", "feature/git-graph"]);
  218. writeFileSync(join(workspacePath, "feature-graph.txt"), "feature graph\n");
  219. runGit(repoPath, ["add", "packages/app/feature-graph.txt"]);
  220. runGit(repoPath, ["commit", "-m", "feat: graph branch"]);
  221. runGit(repoPath, ["switch", "main"]);
  222. writeFileSync(join(workspacePath, "main-graph.txt"), "main graph\n");
  223. runGit(repoPath, ["add", "packages/app/main-graph.txt"]);
  224. runGit(repoPath, ["commit", "-m", "feat: graph main"]);
  225. runGit(repoPath, [
  226. "merge",
  227. "--no-ff",
  228. "feature/git-graph",
  229. "-m",
  230. "merge graph branch",
  231. ]);
  232. runGit(repoPath, ["tag", "v-graph"]);
  233. const hiddenCheckpointOid = runGit(repoPath, [
  234. "commit-tree",
  235. "HEAD^{tree}",
  236. "-m",
  237. "zcode checkpoint hidden",
  238. ]);
  239. runGit(repoPath, [
  240. "update-ref",
  241. "refs/zcode/checkpoints/test-workspace/hidden",
  242. hiddenCheckpointOid,
  243. ]);
  244. const graph = await service.getCommitGraph({ workspacePath, maxCount: 10 });
  245. expect(graph.hasMore).toBe(false);
  246. expect(graph.commits.map((commit) => commit.subject)).not.toContain(
  247. "zcode checkpoint hidden",
  248. );
  249. expect(graph.commits[0]).toMatchObject({
  250. subject: "merge graph branch",
  251. parents: expect.arrayContaining([
  252. expect.stringMatching(/^[0-9a-f]{40}$/),
  253. expect.stringMatching(/^[0-9a-f]{40}$/),
  254. ]),
  255. });
  256. expect(graph.commits[0]?.refs).toEqual(
  257. expect.arrayContaining([
  258. { name: "HEAD", kind: "head" },
  259. { name: "main", kind: "branch" },
  260. { name: "v-graph", kind: "tag" },
  261. ]),
  262. );
  263. const cappedGraph = await service.getCommitGraph({
  264. workspacePath,
  265. maxCount: 2,
  266. });
  267. expect(cappedGraph.commits).toHaveLength(2);
  268. expect(cappedGraph.hasMore).toBe(true);
  269. const secondPage = await service.getCommitGraph({
  270. workspacePath,
  271. maxCount: 2,
  272. skip: 2,
  273. });
  274. expect(secondPage.commits.map((commit) => commit.hash)).toEqual(
  275. graph.commits.slice(2, 4).map((commit) => commit.hash),
  276. );
  277. }, 15_000);
  278. it("switches branches successfully and treats switching to the current branch as a no-op", async () => {
  279. const workspacePath = "/repo/packages/app";
  280. const switchedSummary = createSummary({
  281. branchName: "feature/switch-target",
  282. });
  283. const switchBranch = vi
  284. .fn()
  285. .mockResolvedValueOnce({
  286. ok: true,
  287. action: "switch",
  288. branchName: "feature/switch-target",
  289. didChange: true,
  290. created: false,
  291. summary: switchedSummary,
  292. issues: [],
  293. })
  294. .mockResolvedValueOnce({
  295. ok: true,
  296. action: "switch",
  297. branchName: "feature/switch-target",
  298. didChange: false,
  299. created: false,
  300. summary: switchedSummary,
  301. issues: [],
  302. });
  303. const service = createGitService({
  304. repo: createMockRepo({ switchBranch }),
  305. });
  306. const switched = await service.switchBranch({
  307. workspacePath,
  308. targetBranchName: "feature/switch-target",
  309. });
  310. expect(switched).toMatchObject({
  311. ok: true,
  312. action: "switch",
  313. branchName: "feature/switch-target",
  314. didChange: true,
  315. created: false,
  316. });
  317. expect(switched.summary.branchName).toBe("feature/switch-target");
  318. const noOp = await service.switchBranch({
  319. workspacePath,
  320. targetBranchName: "feature/switch-target",
  321. });
  322. expect(noOp).toMatchObject({
  323. ok: true,
  324. didChange: false,
  325. created: false,
  326. });
  327. expect(noOp.summary.branchName).toBe("feature/switch-target");
  328. expect(switchBranch).toHaveBeenNthCalledWith(
  329. 1,
  330. workspacePath,
  331. "feature/switch-target",
  332. );
  333. expect(switchBranch).toHaveBeenNthCalledWith(
  334. 2,
  335. workspacePath,
  336. "feature/switch-target",
  337. );
  338. });
  339. it("keeps Git-native behavior and allows switching when dirty changes do not conflict", async () => {
  340. const { repoPath, workspacePath } = await createRepo();
  341. const service = createGitService();
  342. runGit(repoPath, ["switch", "-c", "feature/keep-dirty"]);
  343. runGit(repoPath, ["switch", "main"]);
  344. writeFileSync(join(workspacePath, "tracked.txt"), "line 1\nline 2 dirty\n");
  345. const result = await service.switchBranch({
  346. workspacePath,
  347. targetBranchName: "feature/keep-dirty",
  348. });
  349. expect(result).toMatchObject({
  350. ok: true,
  351. didChange: true,
  352. created: false,
  353. });
  354. expect(result.summary.branchName).toBe("feature/keep-dirty");
  355. expect(result.summary.isDirty).toBe(true);
  356. expect(readFileSync(join(workspacePath, "tracked.txt"), "utf-8")).toBe(
  357. "line 1\nline 2 dirty\n",
  358. );
  359. });
  360. it("returns structured issues when tracked changes would be overwritten", async () => {
  361. const { repoPath, workspacePath } = await createRepo();
  362. const service = createGitService();
  363. runGit(repoPath, ["switch", "-c", "feature/overwrite-tracked"]);
  364. writeFileSync(join(workspacePath, "tracked.txt"), "branch version\n");
  365. runGit(repoPath, ["commit", "-am", "feat: change tracked file"]);
  366. runGit(repoPath, ["switch", "main"]);
  367. writeFileSync(join(workspacePath, "tracked.txt"), "local dirty\n");
  368. const result = await service.switchBranch({
  369. workspacePath,
  370. targetBranchName: "feature/overwrite-tracked",
  371. });
  372. expect(result.ok).toBe(false);
  373. expect(result.summary.branchName).toBe("main");
  374. expect(result.issues).toEqual([
  375. expect.objectContaining({
  376. code: "tracked-changes-would-be-overwritten",
  377. paths: ["packages/app/tracked.txt"],
  378. }),
  379. ]);
  380. });
  381. it("returns structured issues when untracked files would be overwritten", async () => {
  382. const { repoPath, workspacePath } = await createRepo();
  383. const service = createGitService();
  384. runGit(repoPath, ["switch", "-c", "feature/overwrite-untracked"]);
  385. writeFileSync(join(workspacePath, "collide.txt"), "branch file\n");
  386. runGit(repoPath, ["add", "packages/app/collide.txt"]);
  387. runGit(repoPath, ["commit", "-m", "feat: add collide file"]);
  388. runGit(repoPath, ["switch", "main"]);
  389. writeFileSync(join(workspacePath, "collide.txt"), "local untracked\n");
  390. const result = await service.switchBranch({
  391. workspacePath,
  392. targetBranchName: "feature/overwrite-untracked",
  393. });
  394. expect(result.ok).toBe(false);
  395. expect(result.summary.branchName).toBe("main");
  396. expect(result.issues).toEqual([
  397. expect.objectContaining({
  398. code: "untracked-changes-would-be-overwritten",
  399. paths: ["packages/app/collide.txt"],
  400. }),
  401. ]);
  402. });
  403. it("returns a structured issue when the target branch does not exist", async () => {
  404. const workspacePath = "/repo/packages/app";
  405. const switchBranch = vi.fn().mockResolvedValue({
  406. ok: false,
  407. action: "switch",
  408. branchName: "main",
  409. didChange: false,
  410. created: false,
  411. summary: createSummary(),
  412. issues: [
  413. {
  414. code: "target-branch-not-found",
  415. message: "Target branch was not found",
  416. },
  417. ],
  418. });
  419. const service = createGitService({
  420. repo: createMockRepo({ switchBranch }),
  421. });
  422. const result = await service.switchBranch({
  423. workspacePath,
  424. targetBranchName: "feature/missing-branch",
  425. });
  426. expect(result.ok).toBe(false);
  427. expect(result.issues).toEqual([
  428. expect.objectContaining({ code: "target-branch-not-found" }),
  429. ]);
  430. expect(switchBranch).toHaveBeenCalledWith(
  431. workspacePath,
  432. "feature/missing-branch",
  433. );
  434. });
  435. it("returns structured issues for conflicts and in-progress operations before calling git switch", async () => {
  436. const { repoPath, workspacePath } = await createRepo();
  437. const service = createGitService();
  438. runGit(repoPath, ["switch", "-c", "feature/conflict"]);
  439. writeFileSync(join(workspacePath, "tracked.txt"), "branch version\n");
  440. runGit(repoPath, ["commit", "-am", "feat: branch conflict change"]);
  441. runGit(repoPath, ["switch", "main"]);
  442. writeFileSync(join(workspacePath, "tracked.txt"), "main version\n");
  443. runGit(repoPath, ["commit", "-am", "feat: main conflict change"]);
  444. const mergeResult = runGitAllowFailure(repoPath, [
  445. "merge",
  446. "feature/conflict",
  447. ]);
  448. expect(mergeResult.status).not.toBe(0);
  449. const conflictResult = await service.switchBranch({
  450. workspacePath,
  451. targetBranchName: "feature/conflict",
  452. });
  453. expect(conflictResult.ok).toBe(false);
  454. expect(conflictResult.issues).toEqual([
  455. expect.objectContaining({ code: "conflicts-present" }),
  456. ]);
  457. runGit(repoPath, ["merge", "--abort"]);
  458. const mergeHeadPath = resolveGitPath(
  459. repoPath,
  460. runGit(repoPath, ["rev-parse", "--git-path", "MERGE_HEAD"]),
  461. );
  462. writeFileSync(mergeHeadPath, "synthetic-merge-head\n");
  463. const inProgressResult = await service.switchBranch({
  464. workspacePath,
  465. targetBranchName: "feature/conflict",
  466. });
  467. expect(inProgressResult.ok).toBe(false);
  468. expect(inProgressResult.issues).toEqual([
  469. expect.objectContaining({ code: "operation-in-progress" }),
  470. ]);
  471. });
  472. it("creates and switches branches with structured failures for invalid or existing names", async () => {
  473. const workspacePath = "/repo/packages/app";
  474. const createBranchAndSwitch = vi
  475. .fn()
  476. .mockResolvedValueOnce({
  477. ok: true,
  478. action: "create-and-switch",
  479. branchName: "feature/new-branch",
  480. didChange: true,
  481. created: true,
  482. summary: createSummary({ branchName: "feature/new-branch" }),
  483. issues: [],
  484. })
  485. .mockResolvedValueOnce({
  486. ok: false,
  487. action: "create-and-switch",
  488. branchName: "main",
  489. didChange: false,
  490. created: false,
  491. summary: createSummary(),
  492. issues: [{ code: "invalid-branch-name", message: "Invalid branch" }],
  493. })
  494. .mockResolvedValueOnce({
  495. ok: false,
  496. action: "create-and-switch",
  497. branchName: "main",
  498. didChange: false,
  499. created: false,
  500. summary: createSummary(),
  501. issues: [{ code: "branch-already-exists", message: "Branch exists" }],
  502. });
  503. const service = createGitService({
  504. repo: createMockRepo({ createBranchAndSwitch }),
  505. });
  506. const created = await service.createBranchAndSwitch({
  507. workspacePath,
  508. branchName: "feature/new-branch",
  509. });
  510. expect(created).toMatchObject({
  511. ok: true,
  512. action: "create-and-switch",
  513. branchName: "feature/new-branch",
  514. didChange: true,
  515. created: true,
  516. });
  517. expect(created.summary.branchName).toBe("feature/new-branch");
  518. const invalid = await service.createBranchAndSwitch({
  519. workspacePath,
  520. branchName: "bad name",
  521. });
  522. expect(invalid.ok).toBe(false);
  523. expect(invalid.issues).toEqual([
  524. expect.objectContaining({ code: "invalid-branch-name" }),
  525. ]);
  526. const existing = await service.createBranchAndSwitch({
  527. workspacePath,
  528. branchName: "main",
  529. });
  530. expect(existing.ok).toBe(false);
  531. expect(existing.issues).toEqual([
  532. expect.objectContaining({ code: "branch-already-exists" }),
  533. ]);
  534. expect(createBranchAndSwitch).toHaveBeenNthCalledWith(
  535. 1,
  536. workspacePath,
  537. "feature/new-branch",
  538. undefined,
  539. );
  540. });
  541. it("filters changes to the current workspace scope and exposes summary plus identity", async () => {
  542. const { repoPath, workspacePath } = await createRepo();
  543. const service = createGitService();
  544. writeFileSync(
  545. join(workspacePath, "tracked.txt"),
  546. "line 1\nline 2 changed\n",
  547. );
  548. writeFileSync(join(workspacePath, "staged.txt"), "staged content\n");
  549. writeFileSync(join(workspacePath, "untracked.txt"), "new file\n");
  550. mkdirSync(join(workspacePath, ".build"), { recursive: true });
  551. writeFileSync(join(workspacePath, ".build", "empty-generated.h"), "");
  552. writeFileSync(
  553. join(repoPath, "packages", "other", "skip.txt"),
  554. "skip changed\n",
  555. );
  556. runGit(repoPath, ["add", "packages/app/staged.txt"]);
  557. const summary = await service.getRepositorySummary({ workspacePath });
  558. expect(summary.repoRoot).toBe(
  559. runGit(workspacePath, ["rev-parse", "--show-toplevel"]),
  560. );
  561. expect(summary.workspaceInRepoPath).toBe("packages/app");
  562. expect(summary.isDirty).toBe(true);
  563. expect(summary.isRepository).toBe(true);
  564. const identity = await service.getIdentity({ workspacePath });
  565. expect(identity.userName).toBe("ZCode Tester");
  566. expect(identity.userEmail).toBe("tester@example.com");
  567. expect(identity.nameSource).toContain(".git/config");
  568. expect(identity.scopeLabel).toBe("local");
  569. const unstagedChanges = await service.getChanges({
  570. workspacePath,
  571. sourceId: "unstaged",
  572. });
  573. expect(
  574. unstagedChanges
  575. .map((change) => `${change.section}:${change.workspaceRelativePath}`)
  576. .sort(),
  577. ).toEqual(["unstaged:tracked.txt", "untracked:untracked.txt"]);
  578. expect(
  579. unstagedChanges.some((change) =>
  580. change.repoRelativePath.includes("packages/other"),
  581. ),
  582. ).toBe(false);
  583. expect(
  584. unstagedChanges.some((change) =>
  585. change.repoRelativePath.endsWith(".build/empty-generated.h"),
  586. ),
  587. ).toBe(false);
  588. const stagedChanges = await service.getChanges({
  589. workspacePath,
  590. sourceId: "staged",
  591. });
  592. expect(stagedChanges.map((change) => change.workspaceRelativePath)).toEqual(
  593. ["staged.txt"],
  594. );
  595. const refresh = await service.refresh({
  596. workspacePath,
  597. includeIdentity: true,
  598. });
  599. expect(refresh.summary.isDirty).toBe(true);
  600. expect(refresh.identity?.userName).toBe("ZCode Tester");
  601. expect(
  602. refresh.unstagedChanges
  603. .map((change) => `${change.section}:${change.workspaceRelativePath}`)
  604. .sort(),
  605. ).toEqual(["unstaged:tracked.txt", "untracked:untracked.txt"]);
  606. expect(
  607. refresh.unstagedChanges.some((change) =>
  608. change.workspaceRelativePath.endsWith(".build/empty-generated.h"),
  609. ),
  610. ).toBe(false);
  611. expect(
  612. refresh.stagedChanges.map((change) => change.workspaceRelativePath),
  613. ).toEqual(["staged.txt"]);
  614. expect(refresh.branchComparison).toBeNull();
  615. });
  616. it("supports stage, unstage, discard and commit via the Git service", async () => {
  617. // Bugfix: 这条用例会串行执行多次真实 git CLI 调用(stage/unstage/discard/commit/status)。
  618. // 全量测试并发时,磁盘 I/O 和子进程调度偶发超过默认 5 秒,Vitest 会先超时中断,
  619. // 随后 afterEach 清理临时仓库又触发额外未处理拒绝,最终把 pre-push 挡住。
  620. // 这里放宽超时,只消除环境抖动,不改变 Git 服务行为断言。
  621. const { workspacePath } = await createRepo();
  622. const service = createGitService();
  623. const trackedPath = join(workspacePath, "tracked.txt");
  624. const commitPath = join(workspacePath, "commit.txt");
  625. writeFileSync(trackedPath, "line 1\nline 2 changed\n");
  626. await service.stagePaths({ workspacePath, paths: [trackedPath] });
  627. let stagedChanges = await service.getChanges({
  628. workspacePath,
  629. sourceId: "staged",
  630. });
  631. expect(stagedChanges.map((change) => change.workspaceRelativePath)).toEqual(
  632. ["tracked.txt"],
  633. );
  634. await service.unstagePaths({ workspacePath, paths: [trackedPath] });
  635. stagedChanges = await service.getChanges({
  636. workspacePath,
  637. sourceId: "staged",
  638. });
  639. expect(stagedChanges).toEqual([]);
  640. await service.discardPaths({ workspacePath, paths: [trackedPath] });
  641. expect(readFileSync(trackedPath, "utf-8")).toBe("line 1\nline 2\n");
  642. writeFileSync(commitPath, "commit body\n");
  643. await service.stagePaths({ workspacePath, paths: [commitPath] });
  644. const commitResult = await service.commit({
  645. workspacePath,
  646. message: "feat: add commit file",
  647. });
  648. expect(commitResult.commitHash).toMatch(/^[0-9a-f]{40}$/);
  649. expect(commitResult.summary.isDirty).toBe(false);
  650. }, 15_000);
  651. it("commits only requested paths when a path scope is provided", async () => {
  652. const workspacePath = "/repo/packages/app";
  653. const selectedPath = "/repo/packages/app/selected.txt";
  654. const commit = vi.fn().mockResolvedValue({
  655. commitHash: "a".repeat(40),
  656. });
  657. const getStatus = vi.fn().mockResolvedValue({
  658. summary: createSummary(),
  659. });
  660. const service = createGitService({
  661. repo: createMockRepo({ commit, getStatus }),
  662. });
  663. const result = await service.commit({
  664. workspacePath,
  665. message: "feat: commit selected path",
  666. paths: [selectedPath],
  667. });
  668. expect(result.commitHash).toBe("a".repeat(40));
  669. expect(commit).toHaveBeenCalledWith(
  670. workspacePath,
  671. "feat: commit selected path",
  672. [selectedPath],
  673. { stagedOnly: undefined },
  674. );
  675. expect(getStatus).toHaveBeenCalledWith(workspacePath);
  676. });
  677. it("commits only selected staged entries without pulling unstaged content", async () => {
  678. const { repoPath, workspacePath } = await createRepo();
  679. const service = createGitService();
  680. const selectedPath = join(workspacePath, "tracked.txt");
  681. const selectedNewPath = join(workspacePath, "selected-new.txt");
  682. const unrelatedPath = join(workspacePath, "unrelated.txt");
  683. writeFileSync(selectedPath, "selected staged\n");
  684. writeFileSync(selectedNewPath, "selected new staged\n");
  685. writeFileSync(unrelatedPath, "unrelated staged\n");
  686. await service.stagePaths({
  687. workspacePath,
  688. paths: [selectedPath, selectedNewPath, unrelatedPath],
  689. });
  690. writeFileSync(selectedPath, "selected unstaged\n");
  691. await service.commit({
  692. workspacePath,
  693. message: "fix: commit selected staged entry",
  694. paths: [selectedPath, selectedNewPath],
  695. stagedOnly: true,
  696. });
  697. expect(runGit(repoPath, ["show", "--name-only", "--format=", "HEAD"])).toBe(
  698. ["packages/app/selected-new.txt", "packages/app/tracked.txt"].join("\n"),
  699. );
  700. expect(runGit(repoPath, ["show", "HEAD:packages/app/tracked.txt"])).toBe(
  701. "selected staged",
  702. );
  703. expect(
  704. runGit(repoPath, ["show", "HEAD:packages/app/selected-new.txt"]),
  705. ).toBe("selected new staged");
  706. expect(readFileSync(selectedPath, "utf-8")).toBe("selected unstaged\n");
  707. expect(runGit(repoPath, ["diff", "--cached", "--name-only"])).toBe(
  708. "packages/app/unrelated.txt",
  709. );
  710. expect(runGit(repoPath, ["diff", "--name-only"])).toBe(
  711. "packages/app/tracked.txt",
  712. );
  713. });
  714. it("generates commit messages from staged changes only when unstaged changes are excluded", async () => {
  715. const { repoPath, workspacePath } = await createRepo();
  716. let capturedFiles: readonly GitFileChange[] = [];
  717. const service = createGitService({
  718. commitMessageGenerator: {
  719. async generate(params) {
  720. capturedFiles = params.files;
  721. return {
  722. message: "fix(git): test staged generation",
  723. providerId: "test",
  724. model: "test-model",
  725. };
  726. },
  727. } as unknown as GitCommitMessageGenerator,
  728. });
  729. writeFileSync(join(workspacePath, "staged.txt"), "staged\n");
  730. writeFileSync(join(workspacePath, "unstaged.txt"), "unstaged\n");
  731. runGit(repoPath, ["add", "packages/app/staged.txt"]);
  732. await service.generateCommitMessage({
  733. workspacePath,
  734. includeUnstaged: false,
  735. });
  736. expect(capturedFiles.map((file) => file.repoRelativePath)).toEqual([
  737. "packages/app/staged.txt",
  738. ]);
  739. expect(capturedFiles.every((file) => file.section === "staged")).toBe(true);
  740. });
  741. it("passes current session conversation context to commit message generation", async () => {
  742. const { repoPath, workspacePath } = await createRepo();
  743. let capturedContext: GitCommitMessageConversationContext | undefined;
  744. const service = createGitService({
  745. commitMessageGenerator: {
  746. async generate(params) {
  747. capturedContext = params.conversationContext;
  748. return {
  749. message: "fix(git): include conversation context",
  750. providerId: "test",
  751. model: "test-model",
  752. };
  753. },
  754. } as unknown as GitCommitMessageGenerator,
  755. });
  756. const conversationContext: GitCommitMessageConversationContext = {
  757. sessionId: "session-1",
  758. messages: [
  759. {
  760. role: "user",
  761. content: "生成提交信息的时候要携带当前会话的内容",
  762. },
  763. ],
  764. };
  765. writeFileSync(join(workspacePath, "staged.txt"), "staged\n");
  766. runGit(repoPath, ["add", "packages/app/staged.txt"]);
  767. await service.generateCommitMessage({
  768. workspacePath,
  769. conversationContext,
  770. });
  771. expect(capturedContext).toEqual(conversationContext);
  772. });
  773. it("filters commit message generation to current session files", async () => {
  774. const { repoPath, workspacePath } = await createRepo();
  775. let capturedFiles: readonly GitFileChange[] = [];
  776. let capturedDiffs: readonly GitDiffResult[] = [];
  777. const service = createGitService({
  778. commitMessageGenerator: {
  779. async generate(params) {
  780. capturedFiles = params.files;
  781. capturedDiffs = params.diffs;
  782. return {
  783. message: "fix(git): scope generation files",
  784. providerId: "test",
  785. model: "test-model",
  786. };
  787. },
  788. } as unknown as GitCommitMessageGenerator,
  789. });
  790. writeFileSync(join(workspacePath, "session.txt"), "session\n");
  791. writeFileSync(join(workspacePath, "unrelated.txt"), "unrelated\n");
  792. runGit(repoPath, [
  793. "add",
  794. "packages/app/session.txt",
  795. "packages/app/unrelated.txt",
  796. ]);
  797. await service.generateCommitMessage({
  798. workspacePath,
  799. currentSessionFilePaths: [join(workspacePath, "session.txt")],
  800. });
  801. expect(capturedFiles.map((file) => file.repoRelativePath)).toEqual([
  802. "packages/app/session.txt",
  803. ]);
  804. expect(capturedDiffs.map((diff) => diff.path).join("\n")).toContain(
  805. "session.txt",
  806. );
  807. expect(capturedDiffs.map((diff) => diff.path).join("\n")).not.toContain(
  808. "unrelated.txt",
  809. );
  810. });
  811. it("pushes the current branch to its tracked upstream", async () => {
  812. const workspacePath = "/repo/packages/app";
  813. const push = vi.fn().mockResolvedValue({
  814. branchName: "main",
  815. trackingBranchName: "origin/main",
  816. remoteName: "origin",
  817. setUpstream: false,
  818. summary: createSummary(),
  819. });
  820. const service = createGitService({
  821. repo: createMockRepo({ push }),
  822. });
  823. const pushResult = await service.push({ workspacePath });
  824. expect(pushResult).toMatchObject({
  825. branchName: "main",
  826. trackingBranchName: "origin/main",
  827. remoteName: "origin",
  828. setUpstream: false,
  829. });
  830. expect(pushResult.summary.ahead).toBe(0);
  831. expect(push).toHaveBeenCalledWith(workspacePath);
  832. });
  833. it("pushes a new local branch and sets upstream when tracking is missing", async () => {
  834. const workspacePath = "/repo/packages/app";
  835. const push = vi.fn().mockResolvedValue({
  836. branchName: "feature/push-upstream",
  837. trackingBranchName: "origin/feature/push-upstream",
  838. remoteName: "origin",
  839. setUpstream: true,
  840. summary: createSummary({
  841. branchName: "feature/push-upstream",
  842. trackingBranchName: "origin/feature/push-upstream",
  843. }),
  844. });
  845. const service = createGitService({
  846. repo: createMockRepo({ push }),
  847. });
  848. const pushResult = await service.push({ workspacePath });
  849. expect(pushResult).toMatchObject({
  850. branchName: "feature/push-upstream",
  851. trackingBranchName: "origin/feature/push-upstream",
  852. remoteName: "origin",
  853. setUpstream: true,
  854. });
  855. expect(pushResult.summary.ahead).toBe(0);
  856. expect(push).toHaveBeenCalledWith(workspacePath);
  857. });
  858. it("returns untracked diffs and branch comparisons against the upstream branch", async () => {
  859. const { repoPath, workspacePath } = await createRepo({ withRemote: true });
  860. const service = createGitService();
  861. const untrackedPath = join(workspacePath, "scratch.txt");
  862. writeFileSync(untrackedPath, "alpha\nbeta\n");
  863. const diff = await service.getDiff({
  864. workspacePath,
  865. path: untrackedPath,
  866. sourceId: "unstaged",
  867. });
  868. expect(diff.availability).toBe("patch");
  869. expect(diff.patch).toContain("--- /dev/null");
  870. expect(diff.patch).toContain("+++ b/packages/app/scratch.txt");
  871. expect(diff.beforeContent).toBe("");
  872. expect(diff.afterContent).toBe("alpha\nbeta\n");
  873. expect(getSingularPatch(diff.patch ?? "")).toMatchObject({
  874. name: "b/packages/app/scratch.txt",
  875. });
  876. runGit(repoPath, ["add", "packages/app/scratch.txt"]);
  877. const stagedCreatedDiff = await service.getDiff({
  878. workspacePath,
  879. path: untrackedPath,
  880. sourceId: "staged",
  881. });
  882. expect(stagedCreatedDiff.availability).toBe("patch");
  883. expect(stagedCreatedDiff.patch).toContain("--- /dev/null");
  884. expect(stagedCreatedDiff.beforeContent).toBeNull();
  885. expect(stagedCreatedDiff.afterContent).toBeNull();
  886. runGit(repoPath, ["reset", "--", "packages/app/scratch.txt"]);
  887. writeFileSync(
  888. join(workspacePath, "tracked.txt"),
  889. "line 1\nline 2\nworktree change\n",
  890. );
  891. const unstagedDiff = await service.getDiff({
  892. workspacePath,
  893. path: join(workspacePath, "tracked.txt"),
  894. sourceId: "unstaged",
  895. });
  896. expect(unstagedDiff.availability).toBe("patch");
  897. expect(unstagedDiff.beforeContent).toBe("line 1\nline 2\n");
  898. expect(unstagedDiff.afterContent).toBe("line 1\nline 2\nworktree change\n");
  899. writeFileSync(
  900. join(workspacePath, "tracked.txt"),
  901. "line 1\nline 2\nbranch change\n",
  902. );
  903. runGit(repoPath, ["add", "packages/app/tracked.txt"]);
  904. runGit(repoPath, ["commit", "-m", "feat: branch change"]);
  905. const branchComparison = await service.getBranchComparison({
  906. workspacePath,
  907. });
  908. expect(branchComparison.baseRef).toBe("origin/main");
  909. expect(branchComparison.comparisonLabel).toBe("main -> origin/main");
  910. expect(
  911. branchComparison.changes.map((change) => change.workspaceRelativePath),
  912. ).toContain("tracked.txt");
  913. expect(
  914. branchComparison.changes.some((change) =>
  915. change.repoRelativePath.includes("packages/other"),
  916. ),
  917. ).toBe(false);
  918. const branchDiff = await service.getDiff({
  919. workspacePath,
  920. path: join(workspacePath, "tracked.txt"),
  921. sourceId: "branch",
  922. });
  923. expect(branchDiff.availability).toBe("patch");
  924. expect(branchDiff.beforeContent).toBe("line 1\nline 2\n");
  925. expect(branchDiff.afterContent).toBe("line 1\nline 2\nbranch change\n");
  926. });
  927. });