1import assert from "node:assert/strict"
2import { spawnSync } from "node:child_process"
3import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
4import { tmpdir } from "node:os"
5import { join } from "node:path"
6import { describe, it } from "node:test"
7import { applyWorktreeDiff, readWorktreeDiff } from "../worktree-diff.mts"
8
9const git = (cwd: string, args: Array<string>) => {
10 const result = spawnSync("git", ["-c", "user.name=test", "-c", "user.email=test@example.com", ...args], {
11 cwd,
12 encoding: "utf8"
13 })
14 assert.equal(result.status, 0, result.stderr)
15}
16
17// Commits `before` in a repository, adds a second worktree at that commit,
18// writes `after` into the first one and replays its diff onto the second.
19const replay = (before: Record<string, string | Uint8Array>, after: Record<string, string | Uint8Array>) => {
20 const root = mkdtempSync(join(tmpdir(), "effect-runtimeperf-diff-"))
21 try {
22 const source = join(root, "source")
23 const target = join(root, "target")
24 git(root, ["init", "-q", source])
25 for (const [file, content] of Object.entries(before)) writeFileSync(join(source, file), content)
26 git(source, ["add", "."])
27 git(source, ["commit", "-q", "-m", "before"])
28 git(source, ["worktree", "add", "-q", "--detach", target, "HEAD"])
29 for (const [file, content] of Object.entries(after)) writeFileSync(join(source, file), content)
30
31 applyWorktreeDiff(target, readWorktreeDiff(source))
32
33 for (const file of Object.keys(after)) {
34 assert.deepEqual(readFileSync(join(target, file)), readFileSync(join(source, file)), file)
35 }
36 } finally {
37 rmSync(root, { recursive: true, force: true })
38 }
39}
40
41describe("runtimeperf worktree diff", () => {
42 it("replays a text change", () => {
43 replay({ "a.txt": "a\nb\nc\n" }, { "a.txt": "a\nB\nc\n" })
44 })
45
46 it("replays a patch whose last context line is blank", () => {
47 replay({ "a.txt": "a\nb\n\n" }, { "a.txt": "A\nb\n\n" })
48 })
49
50 it("replays an added whitespace-only last line", () => {
51 replay({ "a.txt": "a\n" }, { "a.txt": "a\n \n" })
52 })
53
54 it("replays a binary change", () => {
55 replay({ "b.bin": new Uint8Array([0, 1, 2, 3]) }, { "b.bin": new Uint8Array([0, 9, 2, 3, 4]) })
56 })
57})