gitService.test.ts 33 KB

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