Open History to see the last commit
1import { hydratePartialDiff } from "@pierre/diffs";
2import { describe, expect, it } from "vite-plus/test";
3import { resolveDiffReviewPosition } from "../reviewCommentContext";
4import {
5 buildFileDiffContentVersion,
6 buildFileDiffEntries,
7 buildFileDiffIdentityKey,
8 buildFileDiffRenderKey,
9 getDiffLineStat,
10 getRenderablePatch,
11 getRenderablePatchSections,
12 resolveFileDiffPath,
13 resolveFileDiffPreviousPath,
14} from "./diffRendering";
15
16describe("getRenderablePatch", () => {
17 it("hides indentation changes around inserted JSX without moving review lines", () => {
18 const patch = [
19 "diff --git a/item.tsx b/item.tsx",
20 "--- a/item.tsx",
21 "+++ b/item.tsx",
22 "@@ -40,5 +40,7 @@",
23 ' <ItemContent className="min-w-0">',
24 "- <ItemTitle>",
25 '- <h4 className="wrap-break-word">{name}</h4>',
26 "- </ItemTitle>",
27 "+ {showName && (",
28 "+ <ItemTitle>",
29 '+ <h4 className="wrap-break-word">{name}</h4>',
30 "+ </ItemTitle>",
31 "+ )}",
32 " </ItemContent>",
33 "@@ -80 +82 @@",
34 "-const value = 1;",
35 "+const value = 2;",
36 ].join("\n");
37 const shown = getRenderablePatch(patch, "pr", { compactPartialHunkOffsets: true });
38 const hidden = getRenderablePatch(patch, "pr", {
39 compactPartialHunkOffsets: true,
40 ignoreWhitespace: true,
41 });
42 expect(shown?.kind).toBe("files");
43 expect(hidden?.kind).toBe("files");
44 if (shown?.kind !== "files" || hidden?.kind !== "files") return;
45 expect(getDiffLineStat(shown.files)).toEqual({ additions: 6, deletions: 4 });
46 expect(getDiffLineStat(hidden.files)).toEqual({ additions: 3, deletions: 1 });
47 const file = hidden.files[0]!;
48 expect(file.additionLines).toEqual(shown.files[0]!.additionLines);
49 expect(file.deletionLines).toEqual(shown.files[0]!.deletionLines);
50 expect(file.cacheKey).not.toBe(shown.files[0]!.cacheKey);
51 expect(resolveDiffReviewPosition(hidden.sourceFiles[0]!, 43, "additions")).toEqual({
52 kind: "added",
53 newLine: 43,
54 });
55 expect(resolveDiffReviewPosition(hidden.sourceFiles[0]!, 42, "deletions")).toEqual({
56 kind: "deleted",
57 oldLine: 42,
58 });
59 expect(file.hunks[0]?.hunkContent).toContainEqual({
60 type: "context",
61 lines: 3,
62 additionLineIndex: 2,
63 deletionLineIndex: 1,
64 });
65 expect(resolveDiffReviewPosition(file, 41, "additions")).toEqual({
66 kind: "added",
67 newLine: 41,
68 });
69 expect(resolveDiffReviewPosition(file, 43, "additions")).toEqual({
70 kind: "context",
71 oldLine: 42,
72 newLine: 43,
73 side: "right",
74 });
75 expect(resolveDiffReviewPosition(file, 42, "deletions")).toEqual({
76 kind: "context",
77 oldLine: 42,
78 newLine: 43,
79 side: "left",
80 });
81 expect(file.hunks[1]).toMatchObject({
82 additionStart: 82,
83 deletionStart: 80,
84 splitLineStart: 7,
85 unifiedLineStart: 7,
86 });
87 const prefix = "unchanged\n".repeat(39);
88 const gap = "unchanged\n".repeat(35);
89 const hydrated = hydratePartialDiff("clone", file, {
90 oldFile: {
91 name: file.name,
92 contents: prefix + file.deletionLines.slice(0, 5).join("") + gap + "const value = 1;\n",
93 },
94 newFile: {
95 name: file.name,
96 contents: prefix + file.additionLines.slice(0, 7).join("") + gap + "const value = 2;\n",
97 },
98 });
99 expect(getDiffLineStat([hydrated])).toEqual({ additions: 3, deletions: 1 });
100 expect(resolveDiffReviewPosition(hydrated, 43, "additions")).toEqual(
101 resolveDiffReviewPosition(file, 43, "additions"),
102 );
103 });
104
105 it.each([
106 [" const x = 1;\t", "\tconst x=1;", 0, 0],
107 ["const x = 1;", "const x = 2;", 1, 1],
108 ["const x = 1;", "const x = 1;\n", 1, 0],
109 ])("filters whitespace in %j to %j", (before, after, additions, deletions) => {
110 const patch = [
111 "diff --git a/example.ts b/example.ts",
112 "--- a/example.ts",
113 "+++ b/example.ts",
114 `@@ -1 +1,${after.split("\n").length} @@`,
115 `-${before}`,
116 ...after.split("\n").map((line) => `+${line}`),
117 "",
118 ].join("\n");
119 const filtered = getRenderablePatch(patch, "pr", { ignoreWhitespace: true });
120 expect(filtered?.kind).toBe("files");
121 if (filtered?.kind !== "files") return;
122 expect(getDiffLineStat(filtered.files)).toEqual({ additions, deletions });
123 });
124
125 it.each(["+", "-"])("keeps %s blank lines without a final newline", (sign) => {
126 const parsed = getRenderablePatch(
127 [
128 "diff --git a/blank.txt b/blank.txt",
129 "--- a/blank.txt",
130 "+++ b/blank.txt",
131 sign === "+" ? "@@ -0,0 +1 @@" : "@@ -1 +0,0 @@",
132 `${sign} `,
133 "\\ No newline at end of file",
134 ].join("\n"),
135 "pr",
136 { ignoreWhitespace: true },
137 );
138 expect(parsed?.kind).toBe("files");
139 if (parsed?.kind !== "files") return;
140 expect(getDiffLineStat(parsed.files)).toEqual({
141 additions: sign === "+" ? 1 : 0,
142 deletions: sign === "-" ? 1 : 0,
143 });
144 });
145
146 it.each([
147 ["a/example.ts", "a/example.ts", "change"],
148 ["b/example.ts", "b/example.ts", "change"],
149 ["a/before.ts", "b/after.ts", "rename-changed"],
150 ])("preserves repository paths from %s to %s", (previousPath, path, type) => {
151 const parsed = getRenderablePatch(
152 [
153 `diff --git a/${previousPath} b/${path}`,
154 ...(previousPath === path
155 ? []
156 : ["similarity index 50%", `rename from ${previousPath}`, `rename to ${path}`]),
157 `--- a/${previousPath}`,
158 `+++ b/${path}`,
159 "@@ -1 +1 @@",
160 "-before",
161 "+after",
162 ].join("\n"),
163 );
164 expect(parsed?.kind).toBe("files");
165 if (parsed?.kind !== "files") return;
166 const file = parsed.files[0];
167 expect(file).toBeDefined();
168 if (!file) return;
169 expect(resolveFileDiffPath(file)).toBe(path);
170 expect(resolveFileDiffPreviousPath(file)).toBe(previousPath);
171 expect(buildFileDiffIdentityKey(file)).toBe(`${previousPath}\0${path}\0${type}`);
172 });
173
174 it("compacts partial hunk render offsets for virtualized review diffs", () => {
175 const patch = [
176 "diff --git a/example.ts b/example.ts",
177 "index 1111111..2222222 100644",
178 "--- a/example.ts",
179 "+++ b/example.ts",
180 "@@ -48,4 +48,4 @@",
181 " context",
182 "-before",
183 "+after",
184 " context",
185 " context",
186 "@@ -80,3 +80,4 @@",
187 " context",
188 "+added",
189 " context",
190 " context",
191 ].join("\n");
192
193 const parsed = getRenderablePatch(patch, "review", {
194 compactPartialHunkOffsets: true,
195 });
196 expect(parsed?.kind).toBe("files");
197 if (parsed?.kind !== "files") return;
198
199 const file = parsed.files[0];
200 expect(file?.hunks[0]?.collapsedBefore).toBe(47);
201 expect(file?.hunks[0]?.unifiedLineStart).toBe(0);
202 expect(file?.hunks[1]?.collapsedBefore).toBeGreaterThan(0);
203 expect(file?.hunks[1]?.unifiedLineStart).toBe(file?.hunks[0]?.unifiedLineCount);
204 expect(file?.unifiedLineCount).toBe(
205 file?.hunks.reduce((total, hunk) => total + hunk.unifiedLineCount, 0),
206 );
207 });
208
209 it("retains source-file offsets for checkpoint diffs", () => {
210 const patch = [
211 "diff --git a/example.ts b/example.ts",
212 "--- a/example.ts",
213 "+++ b/example.ts",
214 "@@ -48,1 +48,1 @@",
215 "-before",
216 "+after",
217 ].join("\n");
218
219 const parsed = getRenderablePatch(patch, "checkpoint");
220 expect(parsed?.kind).toBe("files");
221 if (parsed?.kind !== "files") return;
222 expect(parsed.files[0]?.hunks[0]?.unifiedLineStart).toBe(47);
223 });
224
225 it("keeps whitespace at the end of the last hunk", () => {
226 const patch = (lastLines: string[]) =>
227 [
228 "diff --git a/example.ts b/example.ts",
229 "--- a/example.ts",
230 "+++ b/example.ts",
231 ...lastLines,
232 "",
233 ].join("\n");
234
235 const trailing = getRenderablePatch(patch(["@@ -1 +1 @@", "-a", "+ b \t"]), "review");
236 expect(trailing?.kind).toBe("files");
237 if (trailing?.kind !== "files") return;
238 expect(trailing.files[0]?.additionLines).toEqual([" b \t\n"]);
239
240 const blankContext = getRenderablePatch(patch(["@@ -1,2 +1,2 @@", "-a", "+b", " "]), "review");
241 expect(blankContext?.kind).toBe("files");
242 if (blankContext?.kind !== "files") return;
243 expect(blankContext.files[0]?.additionLines).toEqual(["b\n", "\n"]);
244 expect(blankContext.files[0]?.hunks[0]?.unifiedLineCount).toBe(3);
245
246 expect(getRenderablePatch(" \n\t\n", "review")).toBeNull();
247 });
248
249 it("caches patches that differ only in trailing whitespace separately", () => {
250 const patch = (added: string) =>
251 [
252 "diff --git a/example.ts b/example.ts",
253 "--- a/example.ts",
254 "+++ b/example.ts",
255 "@@ -1 +1 @@",
256 "-a",
257 `+${added}`,
258 "",
259 ].join("\n");
260
261 const plain = getRenderablePatch(patch("b"), "review");
262 const tabbed = getRenderablePatch(patch("b\t"), "review");
263 expect(plain?.kind).toBe("files");
264 expect(tabbed?.kind).toBe("files");
265 if (plain?.kind !== "files" || tabbed?.kind !== "files") return;
266 expect(tabbed.files[0]?.cacheKey).not.toBe(plain.files[0]?.cacheKey);
267 });
268});
269
270describe("diff file reconciliation", () => {
271 it("retains repeated blocks and their keys when content changes or other files appear", () => {
272 const parse = (blocks: [string, string][]) => {
273 const parsed = getRenderablePatch(
274 blocks
275 .map(([path, content]) =>
276 [
277 `diff --git a/${path} b/${path}`,
278 `--- a/${path}`,
279 `+++ b/${path}`,
280 "@@ -1 +1 @@",
281 "-before",
282 `+${content}`,
283 "",
284 ].join("\n"),
285 )
286 .join(""),
287 );
288 if (parsed?.kind !== "files") throw new Error("Expected file diffs");
289 return parsed.files;
290 };
291 const files = parse([
292 ["same.ts", "first"],
293 ["same.ts", "second"],
294 ]);
295 const before = buildFileDiffEntries([...files, files[1]!]);
296 expect(before.map((entry) => entry.fileDiff)).toEqual([...files, files[1]]);
297 expect(new Set(before.map((entry) => entry.fileKey)).size).toBe(3);
298 expect(before[0]?.fileKey).toBe(buildFileDiffIdentityKey(files[0]!));
299 expect(buildFileDiffEntries([...files, files[1]!])).toEqual(before);
300
301 const after = buildFileDiffEntries(
302 parse([
303 ["unrelated.ts", "new"],
304 ["same.ts", "first"],
305 ["same.ts", "updated second"],
306 ["same.ts", "second"],
307 ]),
308 ).slice(1);
309 expect(after.map((entry) => entry.fileKey)).toEqual(before.map((entry) => entry.fileKey));
310 expect(after[0]?.fileVersion).toBe(before[0]?.fileVersion);
311 expect(after[1]?.fileVersion).not.toBe(before[1]?.fileVersion);
312 expect(after[2]?.fileVersion).toBe(before[2]?.fileVersion);
313 });
314
315 it("keeps Pierre's render key stable when a partial diff hydrates", () => {
316 const patch = [
317 "diff --git a/example.ts b/example.ts",
318 "--- a/example.ts",
319 "+++ b/example.ts",
320 "@@ -1 +1 @@",
321 "-before",
322 "+after",
323 ].join("\n");
324 const parsed = getRenderablePatch(patch, "hydrated-key");
325 expect(parsed?.kind).toBe("files");
326 if (parsed?.kind !== "files") return;
327
328 const file = parsed.files[0];
329 expect(file).toBeDefined();
330 if (!file) return;
331 const key = buildFileDiffRenderKey(file);
332 file.cacheKey = `${file.cacheKey}:hydrated`;
333
334 expect(buildFileDiffRenderKey(file)).toBe(key);
335 });
336
337 it("gives a type change its own identity per block", () => {
338 const patch = [
339 "diff --git a/AGENTS.md b/AGENTS.md",
340 "deleted file mode 100644",
341 "--- a/AGENTS.md",
342 "+++ /dev/null",
343 "@@ -1 +0,0 @@",
344 "-duplicated instructions",
345 "diff --git a/AGENTS.md b/AGENTS.md",
346 "new file mode 120000",
347 "--- /dev/null",
348 "+++ b/AGENTS.md",
349 "@@ -0,0 +1 @@",
350 "+CLAUDE.md",
351 ].join("\n");
352 const parsed = getRenderablePatch(patch, "type-change");
353 expect(parsed?.kind).toBe("files");
354 if (parsed?.kind !== "files") return;
355 const [deleted, added] = parsed.files;
356 expect(deleted?.type).toBe("deleted");
357 expect(added?.type).toBe("new");
358 if (!deleted || !added) return;
359
360 expect(buildFileDiffIdentityKey(deleted)).not.toBe(buildFileDiffIdentityKey(added));
361 expect(new Set(parsed.files.map(buildFileDiffIdentityKey)).size).toBe(parsed.files.length);
362 });
363
364 it("keeps identities stable and versions local to the changed file", () => {
365 const patch = (secondLine: string) =>
366 [
367 "diff --git a/unchanged.ts b/unchanged.ts",
368 "--- a/unchanged.ts",
369 "+++ b/unchanged.ts",
370 "@@ -1 +1 @@",
371 "-before",
372 "+after",
373 "diff --git a/changed.ts b/changed.ts",
374 "--- a/changed.ts",
375 "+++ b/changed.ts",
376 "@@ -1 +1 @@",
377 "-old",
378 `+${secondLine}`,
379 ].join("\n");
380 const before = getRenderablePatch(patch("new"), "before");
381 const after = getRenderablePatch(patch("newer"), "after");
382 expect(before?.kind).toBe("files");
383 expect(after?.kind).toBe("files");
384 if (before?.kind !== "files" || after?.kind !== "files") return;
385
386 const [beforeUnchanged, beforeChanged] = before.files;
387 const [afterUnchanged, afterChanged] = after.files;
388 expect(beforeUnchanged).toBeDefined();
389 expect(beforeChanged).toBeDefined();
390 expect(afterUnchanged).toBeDefined();
391 expect(afterChanged).toBeDefined();
392 if (!beforeUnchanged || !beforeChanged || !afterUnchanged || !afterChanged) return;
393
394 expect(buildFileDiffIdentityKey(afterUnchanged)).toBe(
395 buildFileDiffIdentityKey(beforeUnchanged),
396 );
397 expect(buildFileDiffIdentityKey(afterChanged)).toBe(buildFileDiffIdentityKey(beforeChanged));
398 expect(buildFileDiffContentVersion(afterUnchanged)).toBe(
399 buildFileDiffContentVersion(beforeUnchanged),
400 );
401 expect(buildFileDiffContentVersion(afterChanged)).not.toBe(
402 buildFileDiffContentVersion(beforeChanged),
403 );
404 });
405});
406
407describe("a file whose name a patch header cannot carry plainly", () => {
408 const quotedPatch = (written: string) =>
409 [
410 `diff --git "a/${written}" "b/${written}"`,
411 "index 1111111..2222222 100644",
412 `--- "a/${written}"`,
413 `+++ "b/${written}"`,
414 "@@ -1 +1 @@",
415 "-before",
416 "+after",
417 "",
418 ].join("\n");
419
420 const pathOf = (patch: string) => {
421 const parsed = getRenderablePatch(patch, "review");
422 expect(parsed?.kind).toBe("files");
423 if (parsed?.kind !== "files") throw new Error("patch did not parse as files");
424 const file = parsed.files[0];
425 expect(file).toBeDefined();
426 if (!file) throw new Error("patch carried no file");
427 return resolveFileDiffPath(file);
428 };
429
430 it("reads the octal a host with core.quotePath on writes for a name outside ASCII", () => {
431 expect(pathOf(quotedPatch("caf\\303\\251/r\\303\\251sum\\303\\251.ts"))).toBe("café/résumé.ts");
432 });
433
434 it("reads both sides of a rename under the names they really have", () => {
435 const patch = [
436 'diff --git "a/old\\tname.ts" "b/new\\tname.ts"',
437 "similarity index 90%",
438 'rename from "old\\tname.ts"',
439 'rename to "new\\tname.ts"',
440 "",
441 ].join("\n");
442
443 const parsed = getRenderablePatch(patch, "review");
444 expect(parsed?.kind).toBe("files");
445 if (parsed?.kind !== "files") return;
446 const file = parsed.files[0];
447 expect(file).toBeDefined();
448 if (!file) return;
449
450 expect(resolveFileDiffPath(file)).toBe("new\tname.ts");
451 expect(resolveFileDiffPreviousPath(file)).toBe("old\tname.ts");
452 });
453});
454
455describe("getRenderablePatchSections", () => {
456 const patch = (path: string) =>
457 [
458 `diff --git a/${path} b/${path}`,
459 `--- a/${path}`,
460 `+++ b/${path}`,
461 "@@ -1 +1 @@",
462 "-old",
463 "+new",
464 "",
465 ].join("\n");
466
467 it("names each repository's files from the shared folder and keeps equal paths apart", () => {
468 const parsed = getRenderablePatchSections(
469 [
470 { key: ".", relativePath: "", diff: patch("README.md") },
471 { key: "/work/api", relativePath: "api", diff: patch("README.md") },
472 { key: "/shared", relativePath: "../shared", diff: patch("src/a.ts") },
473 ],
474 "turn",
475 );
476 expect(parsed?.kind).toBe("files");
477 if (parsed?.kind !== "files") return;
478 expect(parsed.files.map(resolveFileDiffPath)).toEqual([
479 "README.md",
480 "api/README.md",
481 "../shared/src/a.ts",
482 ]);
483 expect(new Set(parsed.files.map((file) => file.cacheKey)).size).toBe(3);
484 expect(new Set(parsed.files.map(buildFileDiffIdentityKey)).size).toBe(3);
485 });
486
487 it("gives nothing when every section is empty", () => {
488 expect(getRenderablePatchSections([{ key: ".", relativePath: "", diff: "" }])).toBeNull();
489 });
490});