gitUntrackedStats.test.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import { mkdtemp, mkdir, open, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { buildUntrackedStats } from "#src/git/repo/gitCliHelpers.js";
  6. import type { GitStatusEntry } from "#src/git/repo/gitCliTypes.js";
  7. const io = vi.hoisted(() => ({
  8. readFile: vi.fn(),
  9. open: vi.fn(),
  10. }));
  11. vi.mock("node:fs/promises", async (importOriginal) => {
  12. const actual = await importOriginal<typeof import("node:fs/promises")>();
  13. io.readFile.mockImplementation(actual.readFile);
  14. io.open.mockImplementation(actual.open);
  15. return { ...actual, readFile: io.readFile, open: io.open };
  16. });
  17. const actualFs = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  18. const dirs: string[] = [];
  19. const LIMIT = 1024 * 1024;
  20. const CHUNK = 64 * 1024;
  21. function entry(path: string): GitStatusEntry {
  22. return {
  23. path,
  24. originalPath: null,
  25. kind: "added",
  26. x: "?",
  27. y: "?",
  28. isUntracked: true,
  29. isConflicted: false,
  30. };
  31. }
  32. async function fixture() {
  33. const dir = await mkdtemp(join(tmpdir(), "zcode-untracked-stats-"));
  34. dirs.push(dir);
  35. return dir;
  36. }
  37. afterEach(async () => {
  38. io.open.mockReset().mockImplementation(actualFs.open);
  39. io.readFile.mockClear();
  40. await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
  41. });
  42. describe("未跟踪文件统计读取预算", () => {
  43. it("保留空文件、CRLF、末尾换行和跨块文本的精确行数", async () => {
  44. const dir = await fixture();
  45. const cases = [
  46. ["empty", "", 0],
  47. ["lf", "\n", 1],
  48. ["crlf", "中文\r\n第二行\r\n", 2],
  49. ["tail", "a\nb", 2],
  50. ["blank", "a\n\n", 2],
  51. ["boundary", "a".repeat(CHUNK - 1) + "\n末行", 2],
  52. ["limit", "a".repeat(LIMIT - 1) + "\n", 1],
  53. ] as const;
  54. for (const [path, text] of cases) await writeFile(join(dir, path), text);
  55. const stats = await buildUntrackedStats(
  56. dir,
  57. cases.map(([path]) => entry(path)),
  58. );
  59. for (const [path, , added] of cases) expect(stats.get(path)).toEqual({ added, removed: 0 });
  60. });
  61. it("跳过超限文本、二进制、目录和已删除文件,同时保留条目", async () => {
  62. const dir = await fixture();
  63. await writeFile(join(dir, "large-text"), "a".repeat(LIMIT + 1));
  64. const binary = await open(join(dir, "large-binary"), "w");
  65. await binary.truncate(32 * LIMIT);
  66. await binary.close();
  67. await mkdir(join(dir, "directory"));
  68. io.readFile.mockClear();
  69. io.open.mockClear();
  70. const stats = await buildUntrackedStats(
  71. dir,
  72. ["large-text", "large-binary", "directory", "missing"].map(entry),
  73. );
  74. expect([...stats.values()]).toEqual(
  75. Array.from({ length: 4 }, () => ({ added: 0, removed: 0 })),
  76. );
  77. expect(io.readFile).not.toHaveBeenCalled();
  78. expect(io.open).not.toHaveBeenCalled();
  79. });
  80. it("首块发现二进制就停止读取并关闭句柄", async () => {
  81. const dir = await fixture();
  82. await writeFile(join(dir, "binary"), Buffer.alloc(LIMIT));
  83. let bytesRead = 0;
  84. let closed = 0;
  85. io.open.mockImplementation(async (...args: Parameters<typeof actualFs.open>) => {
  86. const handle = await actualFs.open(...args);
  87. const read = handle.read.bind(handle);
  88. vi.spyOn(handle, "read").mockImplementation(async (...readArgs: Parameters<typeof read>) => {
  89. const result = await read(...readArgs);
  90. bytesRead += result.bytesRead;
  91. return result;
  92. });
  93. const close = handle.close.bind(handle);
  94. vi.spyOn(handle, "close").mockImplementation(async () => {
  95. closed++;
  96. await close();
  97. });
  98. return handle;
  99. });
  100. expect((await buildUntrackedStats(dir, [entry("binary")])).get("binary")?.added).toBe(0);
  101. expect(bytesRead).toBeGreaterThan(0);
  102. expect(bytesRead).toBeLessThanOrEqual(CHUNK);
  103. expect(closed).toBe(1);
  104. });
  105. it("最多同时打开四个文件,读取异常也释放句柄", async () => {
  106. const dir = await fixture();
  107. const entries = Array.from({ length: 12 }, (_, i) => entry(`file-${i}`));
  108. for (const file of entries) await writeFile(join(dir, file.path), "line\n");
  109. let active = 0;
  110. let peak = 0;
  111. io.open.mockImplementation(async (...args: Parameters<typeof actualFs.open>) => {
  112. const handle = await actualFs.open(...args);
  113. peak = Math.max(peak, ++active);
  114. if (String(args[0]).endsWith("file-0"))
  115. vi.spyOn(handle, "read").mockRejectedValue(new Error("read failed"));
  116. const close = handle.close.bind(handle);
  117. vi.spyOn(handle, "close").mockImplementation(async () => {
  118. try {
  119. await close();
  120. } finally {
  121. active--;
  122. }
  123. });
  124. return handle;
  125. });
  126. const stats = await buildUntrackedStats(dir, entries);
  127. expect(stats.get("file-0")?.added).toBe(0);
  128. expect(stats.get("file-11")?.added).toBe(1);
  129. expect(peak).toBeGreaterThan(0);
  130. expect(peak).toBeLessThanOrEqual(4);
  131. expect(active).toBe(0);
  132. });
  133. it("文件在检查后增长仍只读预算加一个字节,不返回部分行数", async () => {
  134. const dir = await fixture();
  135. const path = join(dir, "growing");
  136. await writeFile(path, "small\n");
  137. let bytesRead = 0;
  138. let closed = false;
  139. io.open.mockImplementation(async (...args: Parameters<typeof actualFs.open>) => {
  140. const handle = await actualFs.open(...args);
  141. const read = handle.read.bind(handle);
  142. vi.spyOn(handle, "read").mockImplementation(async (...readArgs: Parameters<typeof read>) => {
  143. if (bytesRead === 0) await writeFile(path, "x\n".repeat(LIMIT));
  144. const result = await read(...readArgs);
  145. bytesRead += result.bytesRead;
  146. return result;
  147. });
  148. const close = handle.close.bind(handle);
  149. vi.spyOn(handle, "close").mockImplementation(async () => {
  150. closed = true;
  151. await close();
  152. });
  153. return handle;
  154. });
  155. expect((await buildUntrackedStats(dir, [entry("growing")])).get("growing")?.added).toBe(0);
  156. expect(bytesRead).toBe(LIMIT + 1);
  157. expect(closed).toBe(true);
  158. });
  159. });