~james/core

core/web/src/lib/components/lines/diff.test.ts -rw-r--r-- 2.3 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { describe, expect, it } from "vitest";
import { parseDiffFromFile, parsePatchFiles } from "@pierre/diffs";
import { diffRows, findDiffMatches, rowLine, rowSide } from "#lib/components/lines/diff.ts";

const patch = `diff --git a/a.ts b/a.ts
--- a/a.ts
+++ b/a.ts
@@ -2,4 +2,4 @@
 two
-three
+THREE
+three and a half
 four
-five
@@ -10,2 +10,2 @@
 ten
-eleven
+ELEVEN
`;

const [file] = parsePatchFiles(patch)[0].files;
const rows = diffRows(file);

describe("diff rows", () => {
	it("walks a patch in unified order with both line numbers", () => {
		expect(rows).toEqual([
			{ deletion: 2, addition: 2, text: "two", gap: false },
			{ deletion: 3, text: "three", gap: false },
			{ addition: 3, text: "THREE", gap: false },
			{ addition: 4, text: "three and a half", gap: false },
			{ deletion: 4, addition: 5, text: "four", gap: false },
			{ deletion: 5, text: "five", gap: false },
			{ deletion: 10, addition: 10, text: "ten", gap: false },
			{ deletion: 11, text: "eleven", gap: false },
			{ addition: 11, text: "ELEVEN", gap: false }
		]);
	});

	it("fills the unchanged lines of a full-file diff", () => {
		const before = ["a", "b", "c", "d", "e"].join("\n") + "\n";
		const after = ["a", "b", "C", "d", "e"].join("\n") + "\n";
		const full = diffRows(
			parseDiffFromFile(
				{ name: "x", contents: before },
				{ name: "x", contents: after },
				{
					context: 0
				}
			)
		);
		expect(full.map((row) => [row.deletion, row.addition, row.text, row.gap])).toEqual([
			[1, 1, "a", true],
			[2, 2, "b", true],
			[3, undefined, "c", false],
			[undefined, 3, "C", false],
			[4, 4, "d", true],
			[5, 5, "e", true]
		]);
	});

	it("reads a row's line on either side", () => {
		expect(rowSide(rows[1])).toBe("deletions");
		expect(rowSide(rows[0])).toBe("additions");
		expect(rowLine(rows[4], "deletions")).toBe(4);
		expect(rowLine(rows[4], "additions")).toBe(5);
		expect(rowLine(rows[1], "additions")).toBeUndefined();
	});
});

describe("diff search", () => {
	it("finds matches on the side each row belongs to", () => {
		expect(findDiffMatches("a", rows, "three", 100)).toEqual([
			{ id: "a", row: 1, line: 3, side: "deletions", start: 0, end: 5 },
			{ id: "a", row: 2, line: 3, side: "additions", start: 0, end: 5 },
			{ id: "a", row: 3, line: 4, side: "additions", start: 0, end: 5 }
		]);
	});
});