Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

diffRendering.test.ts

492 lines16.5 KB

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 ["x", "\uFEFFx", 1, 1],
110 ["\uFEFFx", "x", 1, 1],
111 ])("filters whitespace in %j to %j", (before, after, additions, deletions) => {
112 const patch = [
113 "diff --git a/example.ts b/example.ts",
114 "--- a/example.ts",
115 "+++ b/example.ts",
116 `@@ -1 +1,${after.split("\n").length} @@`,
117 `-${before}`,
118 ...after.split("\n").map((line) => `+${line}`),
119 "",
120 ].join("\n");
121 const filtered = getRenderablePatch(patch, "pr", { ignoreWhitespace: true });
122 expect(filtered?.kind).toBe("files");
123 if (filtered?.kind !== "files") return;
124 expect(getDiffLineStat(filtered.files)).toEqual({ additions, deletions });
125 });
126​
127 it.each(["+", "-"])("keeps %s blank lines without a final newline", (sign) => {
128 const parsed = getRenderablePatch(
129 [
130 "diff --git a/blank.txt b/blank.txt",
131 "--- a/blank.txt",
132 "+++ b/blank.txt",
133 sign === "+" ? "@@ -0,0 +1 @@" : "@@ -1 +0,0 @@",
134 `${sign} `,
135 "\\ No newline at end of file",
136 ].join("\n"),
137 "pr",
138 { ignoreWhitespace: true },
139 );
140 expect(parsed?.kind).toBe("files");
141 if (parsed?.kind !== "files") return;
142 expect(getDiffLineStat(parsed.files)).toEqual({
143 additions: sign === "+" ? 1 : 0,
144 deletions: sign === "-" ? 1 : 0,
145 });
146 });
147​
148 it.each([
149 ["a/example.ts", "a/example.ts", "change"],
150 ["b/example.ts", "b/example.ts", "change"],
151 ["a/before.ts", "b/after.ts", "rename-changed"],
152 ])("preserves repository paths from %s to %s", (previousPath, path, type) => {
153 const parsed = getRenderablePatch(
154 [
155 `diff --git a/${previousPath} b/${path}`,
156 ...(previousPath === path
157 ? []
158 : ["similarity index 50%", `rename from ${previousPath}`, `rename to ${path}`]),
159 `--- a/${previousPath}`,
160 `+++ b/${path}`,
161 "@@ -1 +1 @@",
162 "-before",
163 "+after",
164 ].join("\n"),
165 );
166 expect(parsed?.kind).toBe("files");
167 if (parsed?.kind !== "files") return;
168 const file = parsed.files[0];
169 expect(file).toBeDefined();
170 if (!file) return;
171 expect(resolveFileDiffPath(file)).toBe(path);
172 expect(resolveFileDiffPreviousPath(file)).toBe(previousPath);
173 expect(buildFileDiffIdentityKey(file)).toBe(`${previousPath}\0${path}\0${type}`);
174 });
175​
176 it("compacts partial hunk render offsets for virtualized review diffs", () => {
177 const patch = [
178 "diff --git a/example.ts b/example.ts",
179 "index 1111111..2222222 100644",
180 "--- a/example.ts",
181 "+++ b/example.ts",
182 "@@ -48,4 +48,4 @@",
183 " context",
184 "-before",
185 "+after",
186 " context",
187 " context",
188 "@@ -80,3 +80,4 @@",
189 " context",
190 "+added",
191 " context",
192 " context",
193 ].join("\n");
194​
195 const parsed = getRenderablePatch(patch, "review", {
196 compactPartialHunkOffsets: true,
197 });
198 expect(parsed?.kind).toBe("files");
199 if (parsed?.kind !== "files") return;
200​
201 const file = parsed.files[0];
202 expect(file?.hunks[0]?.collapsedBefore).toBe(47);
203 expect(file?.hunks[0]?.unifiedLineStart).toBe(0);
204 expect(file?.hunks[1]?.collapsedBefore).toBeGreaterThan(0);
205 expect(file?.hunks[1]?.unifiedLineStart).toBe(file?.hunks[0]?.unifiedLineCount);
206 expect(file?.unifiedLineCount).toBe(
207 file?.hunks.reduce((total, hunk) => total + hunk.unifiedLineCount, 0),
208 );
209 });
210​
211 it("retains source-file offsets for checkpoint diffs", () => {
212 const patch = [
213 "diff --git a/example.ts b/example.ts",
214 "--- a/example.ts",
215 "+++ b/example.ts",
216 "@@ -48,1 +48,1 @@",
217 "-before",
218 "+after",
219 ].join("\n");
220​
221 const parsed = getRenderablePatch(patch, "checkpoint");
222 expect(parsed?.kind).toBe("files");
223 if (parsed?.kind !== "files") return;
224 expect(parsed.files[0]?.hunks[0]?.unifiedLineStart).toBe(47);
225 });
226​
227 it("keeps whitespace at the end of the last hunk", () => {
228 const patch = (lastLines: string[]) =>
229 [
230 "diff --git a/example.ts b/example.ts",
231 "--- a/example.ts",
232 "+++ b/example.ts",
233 ...lastLines,
234 "",
235 ].join("\n");
236​
237 const trailing = getRenderablePatch(patch(["@@ -1 +1 @@", "-a", "+ b \t"]), "review");
238 expect(trailing?.kind).toBe("files");
239 if (trailing?.kind !== "files") return;
240 expect(trailing.files[0]?.additionLines).toEqual([" b \t\n"]);
241​
242 const blankContext = getRenderablePatch(patch(["@@ -1,2 +1,2 @@", "-a", "+b", " "]), "review");
243 expect(blankContext?.kind).toBe("files");
244 if (blankContext?.kind !== "files") return;
245 expect(blankContext.files[0]?.additionLines).toEqual(["b\n", "\n"]);
246 expect(blankContext.files[0]?.hunks[0]?.unifiedLineCount).toBe(3);
247​
248 expect(getRenderablePatch(" \n\t\n", "review")).toBeNull();
249 });
250​
251 it("caches patches that differ only in trailing whitespace separately", () => {
252 const patch = (added: string) =>
253 [
254 "diff --git a/example.ts b/example.ts",
255 "--- a/example.ts",
256 "+++ b/example.ts",
257 "@@ -1 +1 @@",
258 "-a",
259 `+${added}`,
260 "",
261 ].join("\n");
262​
263 const plain = getRenderablePatch(patch("b"), "review");
264 const tabbed = getRenderablePatch(patch("b\t"), "review");
265 expect(plain?.kind).toBe("files");
266 expect(tabbed?.kind).toBe("files");
267 if (plain?.kind !== "files" || tabbed?.kind !== "files") return;
268 expect(tabbed.files[0]?.cacheKey).not.toBe(plain.files[0]?.cacheKey);
269 });
270});
271​
272describe("diff file reconciliation", () => {
273 it("retains repeated blocks and their keys when content changes or other files appear", () => {
274 const parse = (blocks: [string, string][]) => {
275 const parsed = getRenderablePatch(
276 blocks
277 .map(([path, content]) =>
278 [
279 `diff --git a/${path} b/${path}`,
280 `--- a/${path}`,
281 `+++ b/${path}`,
282 "@@ -1 +1 @@",
283 "-before",
284 `+${content}`,
285 "",
286 ].join("\n"),
287 )
288 .join(""),
289 );
290 if (parsed?.kind !== "files") throw new Error("Expected file diffs");
291 return parsed.files;
292 };
293 const files = parse([
294 ["same.ts", "first"],
295 ["same.ts", "second"],
296 ]);
297 const before = buildFileDiffEntries([...files, files[1]!]);
298 expect(before.map((entry) => entry.fileDiff)).toEqual([...files, files[1]]);
299 expect(new Set(before.map((entry) => entry.fileKey)).size).toBe(3);
300 expect(before[0]?.fileKey).toBe(buildFileDiffIdentityKey(files[0]!));
301 expect(buildFileDiffEntries([...files, files[1]!])).toEqual(before);
302​
303 const after = buildFileDiffEntries(
304 parse([
305 ["unrelated.ts", "new"],
306 ["same.ts", "first"],
307 ["same.ts", "updated second"],
308 ["same.ts", "second"],
309 ]),
310 ).slice(1);
311 expect(after.map((entry) => entry.fileKey)).toEqual(before.map((entry) => entry.fileKey));
312 expect(after[0]?.fileVersion).toBe(before[0]?.fileVersion);
313 expect(after[1]?.fileVersion).not.toBe(before[1]?.fileVersion);
314 expect(after[2]?.fileVersion).toBe(before[2]?.fileVersion);
315 });
316​
317 it("keeps Pierre's render key stable when a partial diff hydrates", () => {
318 const patch = [
319 "diff --git a/example.ts b/example.ts",
320 "--- a/example.ts",
321 "+++ b/example.ts",
322 "@@ -1 +1 @@",
323 "-before",
324 "+after",
325 ].join("\n");
326 const parsed = getRenderablePatch(patch, "hydrated-key");
327 expect(parsed?.kind).toBe("files");
328 if (parsed?.kind !== "files") return;
329​
330 const file = parsed.files[0];
331 expect(file).toBeDefined();
332 if (!file) return;
333 const key = buildFileDiffRenderKey(file);
334 file.cacheKey = `${file.cacheKey}:hydrated`;
335​
336 expect(buildFileDiffRenderKey(file)).toBe(key);
337 });
338​
339 it("gives a type change its own identity per block", () => {
340 const patch = [
341 "diff --git a/AGENTS.md b/AGENTS.md",
342 "deleted file mode 100644",
343 "--- a/AGENTS.md",
344 "+++ /dev/null",
345 "@@ -1 +0,0 @@",
346 "-duplicated instructions",
347 "diff --git a/AGENTS.md b/AGENTS.md",
348 "new file mode 120000",
349 "--- /dev/null",
350 "+++ b/AGENTS.md",
351 "@@ -0,0 +1 @@",
352 "+CLAUDE.md",
353 ].join("\n");
354 const parsed = getRenderablePatch(patch, "type-change");
355 expect(parsed?.kind).toBe("files");
356 if (parsed?.kind !== "files") return;
357 const [deleted, added] = parsed.files;
358 expect(deleted?.type).toBe("deleted");
359 expect(added?.type).toBe("new");
360 if (!deleted || !added) return;
361​
362 expect(buildFileDiffIdentityKey(deleted)).not.toBe(buildFileDiffIdentityKey(added));
363 expect(new Set(parsed.files.map(buildFileDiffIdentityKey)).size).toBe(parsed.files.length);
364 });
365​
366 it("keeps identities stable and versions local to the changed file", () => {
367 const patch = (secondLine: string) =>
368 [
369 "diff --git a/unchanged.ts b/unchanged.ts",
370 "--- a/unchanged.ts",
371 "+++ b/unchanged.ts",
372 "@@ -1 +1 @@",
373 "-before",
374 "+after",
375 "diff --git a/changed.ts b/changed.ts",
376 "--- a/changed.ts",
377 "+++ b/changed.ts",
378 "@@ -1 +1 @@",
379 "-old",
380 `+${secondLine}`,
381 ].join("\n");
382 const before = getRenderablePatch(patch("new"), "before");
383 const after = getRenderablePatch(patch("newer"), "after");
384 expect(before?.kind).toBe("files");
385 expect(after?.kind).toBe("files");
386 if (before?.kind !== "files" || after?.kind !== "files") return;
387​
388 const [beforeUnchanged, beforeChanged] = before.files;
389 const [afterUnchanged, afterChanged] = after.files;
390 expect(beforeUnchanged).toBeDefined();
391 expect(beforeChanged).toBeDefined();
392 expect(afterUnchanged).toBeDefined();
393 expect(afterChanged).toBeDefined();
394 if (!beforeUnchanged || !beforeChanged || !afterUnchanged || !afterChanged) return;
395​
396 expect(buildFileDiffIdentityKey(afterUnchanged)).toBe(
397 buildFileDiffIdentityKey(beforeUnchanged),
398 );
399 expect(buildFileDiffIdentityKey(afterChanged)).toBe(buildFileDiffIdentityKey(beforeChanged));
400 expect(buildFileDiffContentVersion(afterUnchanged)).toBe(
401 buildFileDiffContentVersion(beforeUnchanged),
402 );
403 expect(buildFileDiffContentVersion(afterChanged)).not.toBe(
404 buildFileDiffContentVersion(beforeChanged),
405 );
406 });
407});
408​
409describe("a file whose name a patch header cannot carry plainly", () => {
410 const quotedPatch = (written: string) =>
411 [
412 `diff --git "a/${written}" "b/${written}"`,
413 "index 1111111..2222222 100644",
414 `--- "a/${written}"`,
415 `+++ "b/${written}"`,
416 "@@ -1 +1 @@",
417 "-before",
418 "+after",
419 "",
420 ].join("\n");
421​
422 const pathOf = (patch: string) => {
423 const parsed = getRenderablePatch(patch, "review");
424 expect(parsed?.kind).toBe("files");
425 if (parsed?.kind !== "files") throw new Error("patch did not parse as files");
426 const file = parsed.files[0];
427 expect(file).toBeDefined();
428 if (!file) throw new Error("patch carried no file");
429 return resolveFileDiffPath(file);
430 };
431​
432 it("reads the octal a host with core.quotePath on writes for a name outside ASCII", () => {
433 expect(pathOf(quotedPatch("caf\\303\\251/r\\303\\251sum\\303\\251.ts"))).toBe("café/résumé.ts");
434 });
435​
436 it("reads both sides of a rename under the names they really have", () => {
437 const patch = [
438 'diff --git "a/old\\tname.ts" "b/new\\tname.ts"',
439 "similarity index 90%",
440 'rename from "old\\tname.ts"',
441 'rename to "new\\tname.ts"',
442 "",
443 ].join("\n");
444​
445 const parsed = getRenderablePatch(patch, "review");
446 expect(parsed?.kind).toBe("files");
447 if (parsed?.kind !== "files") return;
448 const file = parsed.files[0];
449 expect(file).toBeDefined();
450 if (!file) return;
451​
452 expect(resolveFileDiffPath(file)).toBe("new\tname.ts");
453 expect(resolveFileDiffPreviousPath(file)).toBe("old\tname.ts");
454 });
455});
456​
457describe("getRenderablePatchSections", () => {
458 const patch = (path: string) =>
459 [
460 `diff --git a/${path} b/${path}`,
461 `--- a/${path}`,
462 `+++ b/${path}`,
463 "@@ -1 +1 @@",
464 "-old",
465 "+new",
466 "",
467 ].join("\n");
468​
469 it("names each repository's files from the shared folder and keeps equal paths apart", () => {
470 const parsed = getRenderablePatchSections(
471 [
472 { key: ".", relativePath: "", diff: patch("README.md") },
473 { key: "/work/api", relativePath: "api", diff: patch("README.md") },
474 { key: "/shared", relativePath: "../shared", diff: patch("src/a.ts") },
475 ],
476 "turn",
477 );
478 expect(parsed?.kind).toBe("files");
479 if (parsed?.kind !== "files") return;
480 expect(parsed.files.map(resolveFileDiffPath)).toEqual([
481 "README.md",
482 "api/README.md",
483 "../shared/src/a.ts",
484 ]);
485 expect(new Set(parsed.files.map((file) => file.cacheKey)).size).toBe(3);
486 expect(new Set(parsed.files.map(buildFileDiffIdentityKey)).size).toBe(3);
487 });
488​
489 it("gives nothing when every section is empty", () => {
490 expect(getRenderablePatchSections([{ key: ".", relativePath: "", diff: "" }])).toBeNull();
491 });
492});