tree-diff.test.ts
This file
Path
packages/git/test/tree-diff.test.ts
453 lines · 13.7 KiB · TypeScript
Last changed by
Fit W4 group A together on main: every CLI test runs signed out, the binary runs on the real client, usage errors exit 2 as typed failures, and the heaviest tests get a hang limitoscabrielbefore adoptionb08d5f6
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import {3 ObjectId,4 RefName,5 RepoHost,6 RepoName,7} from "@repo/artifacts/repo-host";8import type { TreeEntry } from "@repo/artifacts/repo-host";9import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";10import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";11import { BlobSha, RepoPath, TreeSha } from "@repo/protocol/ids";12import type { CommitSha } from "@repo/protocol/ids";13import { gitClient } from "@repo/testkit/git-client";14import type { Files } from "@repo/testkit/git-client";15import { Effect, Layer, Option, Ref } from "effect";1617import { addedLines, treeDiff } from "../src/tree-diff.ts";1819const repo = RepoName.make("demo");2021const main = RefName.make("refs/heads/main");2223const before: Files = [24 ["README.md", "demo\n"],25 ["docs/x.md", "gone soon\n"],26 ["lib/kept.ts", "export const kept = 1;\n"],27 ["src/a.ts", "one\ntwo\nthree\nfour\n"],28];2930const after: Files = [31 ["README.md", "demo\n"],32 ["assets/logo.bin", "\u0000PNG\nline\n"],33 ["lib/kept.ts", "export const kept = 1;\n"],34 ["src/a.ts", "one\nbetween\ntwo\nthree\nFOUR\nfive\n"],35 ["src/b/c.ts", "export const c = 3;\n"],36];3738/** The memory store, with each tree id `readTree` is asked for written to `reads`. */39const countedBy = (reads: Ref.Ref<readonly string[]>) =>40 Layer.effect(41 RepoHost,42 Effect.gen(function* () {43 const host = yield* RepoHost;4445 return RepoHost.of({46 ...host,47 readTree: (name, tree) =>48 Ref.update(reads, (all) => [...all, tree]).pipe(49 Effect.andThen(host.readTree(name, tree))50 ),51 });52 })53 ).pipe(Layer.provide(RepoHostMemory));5455/**56 * The memory store, with a submodule's pointer added to the trees `links`57 * names: git writes one as a `160000` entry naming a commit in another repo.58 */59const withSubmodules = (links: Ref.Ref<ReadonlyMap<string, TreeEntry>>) =>60 Layer.effect(61 RepoHost,62 Effect.gen(function* () {63 const host = yield* RepoHost;6465 return RepoHost.of({66 ...host,67 readTree: (name, tree) =>68 Effect.gen(function* () {69 const entries = yield* host.readTree(name, tree);70 const link = (yield* Ref.get(links)).get(tree);7172 return link === undefined73 ? entries74 : Option.map(entries, (all) => [...all, link]);75 }),76 });77 })78 ).pipe(Layer.provide(RepoHostMemory));7980/** Store reads under way at once: now, and the most at any moment. */81interface InFlight {82 readonly now: number;83 readonly most: number;84}8586/** The memory store, with the `readTree` calls under way at once counted in `reads`. */87const inFlightBy = (reads: Ref.Ref<InFlight>) =>88 Layer.effect(89 RepoHost,90 Effect.gen(function* () {91 const host = yield* RepoHost;9293 return RepoHost.of({94 ...host,95 readTree: (name, tree) =>96 Ref.update(reads, ({ most, now }) => ({97 most: Math.max(most, now + 1),98 now: now + 1,99 })).pipe(100 Effect.andThen(Effect.yieldNow),101 Effect.andThen(host.readTree(name, tree)),102 Effect.ensuring(103 Ref.update(reads, ({ most, now }) => ({ most, now: now - 1 }))104 )105 ),106 });107 })108 ).pipe(Layer.provide(RepoHostMemory));109110/**111 * Nine folders of nine folders, each file holding `content`: when every file112 * changes, a walk that reads eight at a time at each depth has far more than113 * eight reads under way.114 */115const grid = (content: string): Files =>116 Array.from({ length: 81 }, (_, at) => [117 `p${Math.floor(at / 9)}/q${at % 9}/f.txt`,118 content,119 ]);120121/** A submodule's pointer at `vendor`, naming commit `digit` × 40 in another repo. */122const pointer = (digit: string): TreeEntry => ({123 mode: "160000",124 name: "vendor",125 sha: ObjectId.make(digit.repeat(40)),126 type: "commit",127});128129/** Two commits in `demo`, and the ids of their trees and blobs as git wrote them. */130const twoCommits = Effect.gen(function* () {131 const repos = yield* RepoHost;132 const client = yield* gitClient(memoryFs());133 const first = yield* client.commit("before", before);134 const second = yield* client.commit("after", after, [first]);135136 yield* repos.create(repo);137 yield* repos.push(repo, client.source, [138 { from: Option.none(), ref: main, to: second },139 ]);140141 const treeOf = (sha: CommitSha) =>142 repos.readCommit(repo, sha).pipe(143 Effect.map(Option.getOrThrow),144 Effect.map(({ tree }) => TreeSha.make(tree))145 );146147 /** The id of the entry at `path` under `root`. */148 const idAt = (root: string, path: string): Effect.Effect<string> =>149 Effect.gen(function* () {150 const [head = "", ...rest] = path.split("/");151152 const entries = yield* repos153 .readTree(repo, ObjectId.make(root))154 .pipe(Effect.orDie, Effect.map(Option.getOrThrow));155156 const entry = entries.find(({ name }) => name === head);157158 if (entry === undefined) {159 return yield* Effect.die(`no ${path}`);160 }161162 return rest.length === 0163 ? entry.sha164 : yield* idAt(entry.sha, rest.join("/"));165 });166167 const base = yield* treeOf(first);168 const head = yield* treeOf(second);169170 return {171 base,172 blob: (tree: TreeSha, path: string) =>173 idAt(tree, path).pipe(Effect.map((id) => BlobSha.make(id))),174 head,175 tree: (tree: TreeSha, path: string) => idAt(tree, path),176 };177});178179/** Lines from a three-word alphabet, from a fixed seed (Park and Miller's generator). */180const randomFiles = (cases: number) => {181 let state = 20_261_007;182183 const next = (below: number) => {184 state = (state * 16_807) % 2_147_483_647;185186 return state % below;187 };188189 const file = () =>190 Array.from({ length: next(9) }, () => ["a", "b", "c"][next(3)] ?? "a");191192 return Array.from({ length: cases }, () => [file(), file()] as const);193};194195/** The length of a longest common subsequence, by the textbook table. */196const lcs = (one: readonly string[], other: readonly string[]) => {197 const table = Array.from({ length: one.length + 1 }, () =>198 Array.from({ length: other.length + 1 }, () => 0)199 );200201 for (let i = 1; i <= one.length; i += 1) {202 for (let j = 1; j <= other.length; j += 1) {203 const row = table[i] ?? [];204205 row[j] =206 one[i - 1] === other[j - 1]207 ? (table[i - 1]?.[j - 1] ?? 0) + 1208 : Math.max(table[i - 1]?.[j] ?? 0, row[j - 1] ?? 0);209 }210 }211212 return table[one.length]?.[other.length] ?? 0;213};214215const text = (lines: readonly string[]) =>216 lines.map((line) => `${line}\n`).join("");217218const isSubsequence = (part: readonly string[], whole: readonly string[]) => {219 let found = 0;220221 for (const line of whole) {222 if (line === part[found]) {223 found += 1;224 }225 }226227 return found === part.length;228};229230describe("the changes between two trees", () => {231 it.effect("finds each added, modified and deleted file with its blobs", () =>232 Effect.gen(function* () {233 const { base, blob, head } = yield* twoCommits;234 const changes = yield* treeDiff(repo, base, head);235236 expect(237 changes.toSorted((one, other) => one.path.localeCompare(other.path))238 ).toStrictEqual([239 {240 after: yield* blob(head, "assets/logo.bin"),241 path: RepoPath.make("assets/logo.bin"),242 status: "added",243 },244 {245 before: yield* blob(base, "docs/x.md"),246 path: RepoPath.make("docs/x.md"),247 status: "deleted",248 },249 {250 after: yield* blob(head, "src/a.ts"),251 before: yield* blob(base, "src/a.ts"),252 path: RepoPath.make("src/a.ts"),253 status: "modified",254 },255 {256 after: yield* blob(head, "src/b/c.ts"),257 path: RepoPath.make("src/b/c.ts"),258 status: "added",259 },260 ]);261 }).pipe(Effect.provide(RepoHostMemory))262 );263264 it.effect("never reads a subtree whose id did not change", () =>265 Effect.gen(function* () {266 const reads = yield* Ref.make<readonly string[]>([]);267268 yield* Effect.gen(function* () {269 const { base, head, tree } = yield* twoCommits;270 const kept = yield* tree(head, "lib");271272 expect(yield* tree(base, "lib")).toBe(kept);273274 yield* Ref.set(reads, []);275 yield* treeDiff(repo, base, head);276277 const read = yield* Ref.get(reads);278279 expect(read).toContain(base);280 expect(read).toContain(yield* tree(head, "src"));281 expect(read).not.toContain(kept);282 }).pipe(Effect.provide(countedBy(reads)));283 })284 );285286 it.effect("reads at most eight trees from the store at once", () =>287 Effect.gen(function* () {288 const reads = yield* Ref.make<InFlight>({ most: 0, now: 0 });289290 yield* Effect.gen(function* () {291 const repos = yield* RepoHost;292 const client = yield* gitClient(memoryFs());293 const first = yield* client.commit("before", grid("1\n"));294 const second = yield* client.commit("after", grid("2\n"), [first]);295296 yield* repos.create(repo);297 yield* repos.push(repo, client.source, [298 { from: Option.none(), ref: main, to: second },299 ]);300301 const treeOf = (sha: CommitSha) =>302 repos303 .readCommit(repo, sha)304 .pipe(305 Effect.map((commit) =>306 TreeSha.make(Option.getOrThrow(commit).tree)307 )308 );309310 const changes = yield* treeDiff(311 repo,312 yield* treeOf(first),313 yield* treeOf(second)314 );315316 expect(changes).toHaveLength(81);317 }).pipe(Effect.provide(inFlightBy(reads)));318319 expect(yield* Ref.get(reads)).toStrictEqual({ most: 8, now: 0 });320 })321 );322323 it.effect(324 "counts a submodule's moved pointer as a change with no lines",325 () =>326 Effect.gen(function* () {327 const links = yield* Ref.make<ReadonlyMap<string, TreeEntry>>(328 new Map()329 );330331 yield* Effect.gen(function* () {332 const { base, head } = yield* twoCommits;333334 yield* Ref.set(335 links,336 new Map([337 [base, pointer("a")],338 [head, pointer("b")],339 ])340 );341342 const changes = yield* treeDiff(repo, base, head);343 const lines = yield* addedLines(repo, changes);344345 expect(346 changes.filter(({ path }) => path === RepoPath.make("vendor"))347 ).toStrictEqual([348 {349 after: BlobSha.make("b".repeat(40)),350 before: BlobSha.make("a".repeat(40)),351 path: RepoPath.make("vendor"),352 status: "modified",353 },354 ]);355 expect(lines.get(RepoPath.make("vendor"))).toStrictEqual([]);356 expect(lines.get(RepoPath.make("src/a.ts"))).toHaveLength(3);357 }).pipe(Effect.provide(withSubmodules(links)));358 })359 );360361 it.effect("gives a modified file's new lines, numbered in the new file", () =>362 Effect.gen(function* () {363 const { base, head } = yield* twoCommits;364 const lines = yield* addedLines(repo, yield* treeDiff(repo, base, head));365366 expect(lines.get(RepoPath.make("src/a.ts"))).toStrictEqual([367 { line: 2, text: "between" },368 { line: 5, text: "FOUR" },369 { line: 6, text: "five" },370 ]);371 expect(lines.get(RepoPath.make("src/b/c.ts"))).toStrictEqual([372 { line: 1, text: "export const c = 3;" },373 ]);374 expect(lines.get(RepoPath.make("assets/logo.bin"))).toStrictEqual([]);375 expect([...lines.keys()]).not.toContain(RepoPath.make("docs/x.md"));376 }).pipe(Effect.provide(RepoHostMemory))377 );378379 it.effect(380 "keeps a longest common run of lines and calls only the rest added",381 () =>382 Effect.gen(function* () {383 const repos = yield* RepoHost;384 const client = yield* gitClient(memoryFs());385386 const cases = yield* Effect.forEach(387 randomFiles(60),388 ([previous, next], index) =>389 Effect.gen(function* () {390 const name = RepoName.make(`case-${index}`);391392 const first = yield* client.commit("before", [393 ["f.txt", text(previous)],394 ]);395396 const second = yield* client.commit(397 "after",398 [["f.txt", text(next)]],399 [first]400 );401402 yield* repos.create(name);403 yield* repos.push(name, client.source, [404 { from: Option.none(), ref: main, to: second },405 ]);406407 const treeOf = (sha: CommitSha) =>408 repos409 .readCommit(name, sha)410 .pipe(411 Effect.map((commit) =>412 TreeSha.make(Option.getOrThrow(commit).tree)413 )414 );415416 const changes = yield* treeDiff(417 name,418 yield* treeOf(first),419 yield* treeOf(second)420 );421422 const lines = yield* addedLines(name, changes);423424 const fresh = new Set(425 (lines.get(RepoPath.make("f.txt")) ?? []).map(426 ({ line }) => line427 )428 );429430 const kept = next.filter((_, at) => !fresh.has(at + 1));431432 return {433 kept: kept.length,434 longest: lcs(previous, next),435 pair: `${previous.join("")} -> ${next.join("")}`,436 subsequence: isSubsequence(kept, previous),437 };438 })439 );440441 // Every case keeps a common subsequence as long as any there is.442 expect(443 cases.filter(444 ({ kept, longest, subsequence }) => !subsequence || kept !== longest445 )446 ).toStrictEqual([]);447 }).pipe(Effect.provide(RepoHostMemory)),448 // Sixty repos of real git objects: a fifth of a second alone, near four449 // while turbo runs every package's tests at once. The limit catches a450 // hang.451 30_000452 );453});