Skip to content
Myr

tree-diff.test.ts

This file

Path

packages/git/test/tree-diff.test.ts

440 lines · 12.9 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 0190ff0 point at it.

Walk every shot of the video once on the live stages, and mark the rehearsal pass or failoscabrielbefore adoption0190ff0

lines 1–440why, one step back
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];3738const countedBy = (reads: Ref.Ref<readonly string[]>) =>39 Layer.effect(40 RepoHost,41 Effect.gen(function* () {42 const host = yield* RepoHost;4344 return RepoHost.of({45 ...host,46 readTree: (name, tree) =>47 Ref.update(reads, (all) => [...all, tree]).pipe(48 Effect.andThen(host.readTree(name, tree))49 ),50 });51 })52 ).pipe(Layer.provide(RepoHostMemory));5354const withSubmodules = (links: Ref.Ref<ReadonlyMap<string, TreeEntry>>) =>55 Layer.effect(56 RepoHost,57 Effect.gen(function* () {58 const host = yield* RepoHost;5960 return RepoHost.of({61 ...host,62 readTree: (name, tree) =>63 Effect.gen(function* () {64 const entries = yield* host.readTree(name, tree);65 const link = (yield* Ref.get(links)).get(tree);6667 return link === undefined68 ? entries69 : Option.map(entries, (all) => [...all, link]);70 }),71 });72 })73 ).pipe(Layer.provide(RepoHostMemory));7475interface InFlight {76 readonly now: number;77 readonly most: number;78}7980const inFlightBy = (reads: Ref.Ref<InFlight>) =>81 Layer.effect(82 RepoHost,83 Effect.gen(function* () {84 const host = yield* RepoHost;8586 return RepoHost.of({87 ...host,88 readTree: (name, tree) =>89 Ref.update(reads, ({ most, now }) => ({90 most: Math.max(most, now + 1),91 now: now + 1,92 })).pipe(93 Effect.andThen(Effect.yieldNow),94 Effect.andThen(host.readTree(name, tree)),95 Effect.ensuring(96 Ref.update(reads, ({ most, now }) => ({ most, now: now - 1 }))97 )98 ),99 });100 })101 ).pipe(Layer.provide(RepoHostMemory));102103/**104 * Nine folders of nine folders, each file holding `content`: when every file105 * changes, a walk that reads eight at a time at each depth has far more than106 * eight reads under way.107 */108const grid = (content: string): Files =>109 Array.from({ length: 81 }, (_, at) => [110 `p${Math.floor(at / 9)}/q${at % 9}/f.txt`,111 content,112 ]);113114const pointer = (digit: string): TreeEntry => ({115 mode: "160000",116 name: "vendor",117 sha: ObjectId.make(digit.repeat(40)),118 type: "commit",119});120121const twoCommits = Effect.gen(function* () {122 const repos = yield* RepoHost;123 const client = yield* gitClient(memoryFs());124 const first = yield* client.commit("before", before);125 const second = yield* client.commit("after", after, [first]);126127 yield* repos.create(repo);128 yield* repos.push(repo, client.source, [129 { from: Option.none(), ref: main, to: second },130 ]);131132 const treeOf = (sha: CommitSha) =>133 repos.readCommit(repo, sha).pipe(134 Effect.map(Option.getOrThrow),135 Effect.map(({ tree }) => TreeSha.make(tree))136 );137138 const idAt = (root: string, path: string): Effect.Effect<string> =>139 Effect.gen(function* () {140 const [head = "", ...rest] = path.split("/");141142 const entries = yield* repos143 .readTree(repo, ObjectId.make(root))144 .pipe(Effect.orDie, Effect.map(Option.getOrThrow));145146 const entry = entries.find(({ name }) => name === head);147148 if (entry === undefined) {149 return yield* Effect.die(`no ${path}`);150 }151152 return rest.length === 0153 ? entry.sha154 : yield* idAt(entry.sha, rest.join("/"));155 });156157 const base = yield* treeOf(first);158 const head = yield* treeOf(second);159160 return {161 base,162 blob: (tree: TreeSha, path: string) =>163 idAt(tree, path).pipe(Effect.map((id) => BlobSha.make(id))),164 head,165 tree: (tree: TreeSha, path: string) => idAt(tree, path),166 };167});168169const randomFiles = (cases: number) => {170 let state = 20_261_007;171172 const next = (below: number) => {173 state = (state * 16_807) % 2_147_483_647;174175 return state % below;176 };177178 const file = () =>179 Array.from({ length: next(9) }, () => ["a", "b", "c"][next(3)] ?? "a");180181 return Array.from({ length: cases }, () => [file(), file()] as const);182};183184const lcs = (one: readonly string[], other: readonly string[]) => {185 const table = Array.from({ length: one.length + 1 }, () =>186 Array.from({ length: other.length + 1 }, () => 0)187 );188189 for (let i = 1; i <= one.length; i += 1) {190 for (let j = 1; j <= other.length; j += 1) {191 const row = table[i] ?? [];192193 row[j] =194 one[i - 1] === other[j - 1]195 ? (table[i - 1]?.[j - 1] ?? 0) + 1196 : Math.max(table[i - 1]?.[j] ?? 0, row[j - 1] ?? 0);197 }198 }199200 return table[one.length]?.[other.length] ?? 0;201};202203const text = (lines: readonly string[]) =>204 lines.map((line) => `${line}\n`).join("");205206const isSubsequence = (part: readonly string[], whole: readonly string[]) => {207 let found = 0;208209 for (const line of whole) {210 if (line === part[found]) {211 found += 1;212 }213 }214215 return found === part.length;216};217218describe("the changes between two trees", () => {219 it.effect("finds each added, modified and deleted file with its blobs", () =>220 Effect.gen(function* () {221 const { base, blob, head } = yield* twoCommits;222 const changes = yield* treeDiff(repo, base, head);223224 expect(225 changes.toSorted((one, other) => one.path.localeCompare(other.path))226 ).toStrictEqual([227 {228 after: yield* blob(head, "assets/logo.bin"),229 path: RepoPath.make("assets/logo.bin"),230 status: "added",231 },232 {233 before: yield* blob(base, "docs/x.md"),234 path: RepoPath.make("docs/x.md"),235 status: "deleted",236 },237 {238 after: yield* blob(head, "src/a.ts"),239 before: yield* blob(base, "src/a.ts"),240 path: RepoPath.make("src/a.ts"),241 status: "modified",242 },243 {244 after: yield* blob(head, "src/b/c.ts"),245 path: RepoPath.make("src/b/c.ts"),246 status: "added",247 },248 ]);249 }).pipe(Effect.provide(RepoHostMemory))250 );251252 it.effect("never reads a subtree whose id did not change", () =>253 Effect.gen(function* () {254 const reads = yield* Ref.make<readonly string[]>([]);255256 yield* Effect.gen(function* () {257 const { base, head, tree } = yield* twoCommits;258 const kept = yield* tree(head, "lib");259260 expect(yield* tree(base, "lib")).toBe(kept);261262 yield* Ref.set(reads, []);263 yield* treeDiff(repo, base, head);264265 const read = yield* Ref.get(reads);266267 expect(read).toContain(base);268 expect(read).toContain(yield* tree(head, "src"));269 expect(read).not.toContain(kept);270 }).pipe(Effect.provide(countedBy(reads)));271 })272 );273274 it.effect("reads at most eight trees from the store at once", () =>275 Effect.gen(function* () {276 const reads = yield* Ref.make<InFlight>({ most: 0, now: 0 });277278 yield* Effect.gen(function* () {279 const repos = yield* RepoHost;280 const client = yield* gitClient(memoryFs());281 const first = yield* client.commit("before", grid("1\n"));282 const second = yield* client.commit("after", grid("2\n"), [first]);283284 yield* repos.create(repo);285 yield* repos.push(repo, client.source, [286 { from: Option.none(), ref: main, to: second },287 ]);288289 const treeOf = (sha: CommitSha) =>290 repos291 .readCommit(repo, sha)292 .pipe(293 Effect.map((commit) =>294 TreeSha.make(Option.getOrThrow(commit).tree)295 )296 );297298 const changes = yield* treeDiff(299 repo,300 yield* treeOf(first),301 yield* treeOf(second)302 );303304 expect(changes).toHaveLength(81);305 }).pipe(Effect.provide(inFlightBy(reads)));306307 expect(yield* Ref.get(reads)).toStrictEqual({ most: 8, now: 0 });308 })309 );310311 it.effect(312 "counts a submodule's moved pointer as a change with no lines",313 () =>314 Effect.gen(function* () {315 const links = yield* Ref.make<ReadonlyMap<string, TreeEntry>>(316 new Map()317 );318319 yield* Effect.gen(function* () {320 const { base, head } = yield* twoCommits;321322 yield* Ref.set(323 links,324 new Map([325 [base, pointer("a")],326 [head, pointer("b")],327 ])328 );329330 const changes = yield* treeDiff(repo, base, head);331 const lines = yield* addedLines(repo, changes);332333 expect(334 changes.filter(({ path }) => path === RepoPath.make("vendor"))335 ).toStrictEqual([336 {337 after: BlobSha.make("b".repeat(40)),338 before: BlobSha.make("a".repeat(40)),339 path: RepoPath.make("vendor"),340 status: "modified",341 },342 ]);343 expect(lines.get(RepoPath.make("vendor"))).toStrictEqual([]);344 expect(lines.get(RepoPath.make("src/a.ts"))).toHaveLength(3);345 }).pipe(Effect.provide(withSubmodules(links)));346 })347 );348349 it.effect("gives a modified file's new lines, numbered in the new file", () =>350 Effect.gen(function* () {351 const { base, head } = yield* twoCommits;352 const lines = yield* addedLines(repo, yield* treeDiff(repo, base, head));353354 expect(lines.get(RepoPath.make("src/a.ts"))).toStrictEqual([355 { line: 2, text: "between" },356 { line: 5, text: "FOUR" },357 { line: 6, text: "five" },358 ]);359 expect(lines.get(RepoPath.make("src/b/c.ts"))).toStrictEqual([360 { line: 1, text: "export const c = 3;" },361 ]);362 expect(lines.get(RepoPath.make("assets/logo.bin"))).toStrictEqual([]);363 expect([...lines.keys()]).not.toContain(RepoPath.make("docs/x.md"));364 }).pipe(Effect.provide(RepoHostMemory))365 );366367 it.effect(368 "keeps a longest common run of lines and calls only the rest added",369 () =>370 Effect.gen(function* () {371 const repos = yield* RepoHost;372 const client = yield* gitClient(memoryFs());373374 const cases = yield* Effect.forEach(375 randomFiles(60),376 ([previous, next], index) =>377 Effect.gen(function* () {378 const name = RepoName.make(`case-${index}`);379380 const first = yield* client.commit("before", [381 ["f.txt", text(previous)],382 ]);383384 const second = yield* client.commit(385 "after",386 [["f.txt", text(next)]],387 [first]388 );389390 yield* repos.create(name);391 yield* repos.push(name, client.source, [392 { from: Option.none(), ref: main, to: second },393 ]);394395 const treeOf = (sha: CommitSha) =>396 repos397 .readCommit(name, sha)398 .pipe(399 Effect.map((commit) =>400 TreeSha.make(Option.getOrThrow(commit).tree)401 )402 );403404 const changes = yield* treeDiff(405 name,406 yield* treeOf(first),407 yield* treeOf(second)408 );409410 const lines = yield* addedLines(name, changes);411412 const fresh = new Set(413 (lines.get(RepoPath.make("f.txt")) ?? []).map(414 ({ line }) => line415 )416 );417418 const kept = next.filter((_, at) => !fresh.has(at + 1));419420 return {421 kept: kept.length,422 longest: lcs(previous, next),423 pair: `${previous.join("")} -> ${next.join("")}`,424 subsequence: isSubsequence(kept, previous),425 };426 })427 );428429 expect(430 cases.filter(431 ({ kept, longest, subsequence }) => !subsequence || kept !== longest432 )433 ).toStrictEqual([]);434 }).pipe(Effect.provide(RepoHostMemory)),435 // Sixty repos of real git objects: a fifth of a second alone, near four436 // while turbo runs every package's tests at once. The limit catches a437 // hang.438 30_000439 );440});