Skip to content
Myr

tree-diff.ts

This file

Path

packages/git/src/tree-diff.ts

347 lines · 9.7 KiB · TypeScript

Last changed by

Merge build/207-git-trailers-diff-notes: a landing commit carries its credit, a push's changes are known, and verdicts travel as git notesoscabrielbefore adoptionfd74101

History of this file

Take it

Merge build/207-git-trailers-diff-notes: a landing commit carries its credit, a push's changes are known, and verdicts travel as git notesoscabrielbefore adoptionfd74101

lines 1–347why, one step back
1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";
2import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";3import { BlobSha, RepoPath } from "@repo/protocol/ids";4import type { RepoName, TreeSha } from "@repo/protocol/ids";5import { Array, Effect, Option, Order, Semaphore } from "effect";67/**8 * One file an answer changed, with its blob ids before and after. The same9 * shape as the gate's `Change` (`@repo/gate/facts`), which git cannot import.10 */11export interface Change {12 readonly path: RepoPath;13 readonly status: "added" | "modified" | "deleted";14 readonly before?: BlobSha;15 readonly after?: BlobSha;16}1718/** A line a change added, numbered from 1 in the new file. */19export interface AddedLine {20 readonly line: number;21 readonly text: string;22}2324// Store calls under way at once, however deep the walk or long the change set.25const STORE_CALLS = 8;2627// The walk forks freely; the semaphore alone holds the store to its calls.28const ALL = { concurrency: "unbounded" } as const;2930const entriesOf = (31 calls: Semaphore.Semaphore,32 repo: RepoName,33 tree: Option.Option<string>34) =>35 Option.match(tree, {36 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),37 onSome: (id) =>38 RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(39 Semaphore.withPermit(calls),40 Effect.flatMap(41 Option.match({42 onNone: () => Effect.die(`${repo} has no tree ${id}`),43 onSome: Effect.succeed,44 })45 )46 ),47 });4849const treeIdOf = (entry: TreeEntry | undefined) =>50 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();5152// A submodule's pointer counts as a file at its path, so a change to it is seen.53const fileIdOf = (entry: TreeEntry | undefined) =>54 entry === undefined || entry.type === "tree"55 ? undefined56 : BlobSha.make(entry.sha);5758const fileChange = (59 path: string,60 before: BlobSha | undefined,61 after: BlobSha | undefined62): readonly Change[] => {63 const at = RepoPath.make(path);6465 if (before !== undefined && after !== undefined) {66 return [{ after, before, path: at, status: "modified" }];67 }6869 if (before !== undefined) {70 return [{ before, path: at, status: "deleted" }];71 }7273 return after === undefined ? [] : [{ after, path: at, status: "added" }];74};7576const walk = (77 calls: Semaphore.Semaphore,78 repo: RepoName,79 prefix: string,80 base: Option.Option<string>,81 head: Option.Option<string>82): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>83 Effect.gen(function* () {84 const [before, after] = yield* Effect.all(85 [entriesOf(calls, repo, base), entriesOf(calls, repo, head)],86 ALL87 );8889 const beforeByName = new Map(before.map((entry) => [entry.name, entry]));90 const afterByName = new Map(after.map((entry) => [entry.name, entry]));9192 // The same id and mode: nothing under it changed, so it is never read.93 const names = Array.sort(94 new Set([...beforeByName.keys(), ...afterByName.keys()]),95 Order.String96 ).filter((name) => {97 const old = beforeByName.get(name);98 const next = afterByName.get(name);99100 return old?.sha !== next?.sha || old?.mode !== next?.mode;101 });102103 const changed = yield* Effect.forEach(104 names,105 (name) => {106 const old = beforeByName.get(name);107 const next = afterByName.get(name);108 const path = `${prefix}${name}`;109 const files = fileChange(path, fileIdOf(old), fileIdOf(next));110 const inside = [treeIdOf(old), treeIdOf(next)] as const;111112 return Option.isNone(inside[0]) && Option.isNone(inside[1])113 ? Effect.succeed(files)114 : walk(calls, repo, `${path}/`, inside[0], inside[1]).pipe(115 Effect.map((nested) => [...files, ...nested])116 );117 },118 ALL119 );120121 return changed.flat();122 });123124/**125 * The files that differ between two trees of `repo`, read through the126 * `RepoHost` port alone: it walks both roots and descends only into subtrees127 * whose ids differ, since the store has no diff of its own. At most eight128 * trees are read at once.129 */130export const treeDiff = (131 repo: RepoName,132 base: TreeSha,133 head: TreeSha134): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>135 Effect.flatMap(Semaphore.make(STORE_CALLS), (calls) =>136 walk(calls, repo, "", Option.some(base), Option.some(head))137 );138139// git's own test: a NUL among the first bytes means the blob is not text.140const SNIFF = 8192;141142const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);143144const linesOf = (bytes: Uint8Array) => {145 const text = new TextDecoder().decode(bytes);146 const lines = text.split("\n");147148 if (text.endsWith("\n")) {149 lines.pop();150 }151152 return lines;153};154155// Past this many edits the diff stops looking for the shortest script.156const MAX_EDITS = 1024;157158const at = (values: Int32Array, index: number) => values[index] ?? 0;159160/**161 * Indexes in `next` that the edit script ending at `(n, m)` inserts, read162 * back from `trace`, where `trace[d]` holds diagonals `-d..d` after `d` edits.163 */164const insertsFrom = (165 trace: readonly Int32Array[],166 ends: { readonly n: number; readonly m: number }167) => {168 const inserts: number[] = [];169 let x = ends.n;170 let y = ends.m;171172 for (let edits = trace.length - 1; edits > 0; edits -= 1) {173 const previous = trace[edits - 1] ?? new Int32Array();174 const diagonal = x - y;175176 const reached = (k: number) => at(previous, k + edits - 1);177178 const down =179 diagonal === -edits ||180 (diagonal !== edits && reached(diagonal - 1) < reached(diagonal + 1));181182 const from = down ? diagonal + 1 : diagonal - 1;183184 x = reached(from);185 y = x - from;186187 if (down) {188 inserts.push(y);189 }190 }191192 return inserts.toReversed();193};194195/**196 * Lines of `next` with no partner in `previous`, matched by count: the197 * fallback for a rewrite too large for the shortest script.198 */199const unmatched = (previous: readonly string[], next: readonly string[]) => {200 const left = new Map<string, number>();201202 for (const line of previous) {203 left.set(line, (left.get(line) ?? 0) + 1);204 }205206 return next.flatMap((line, index) => {207 const count = left.get(line) ?? 0;208209 left.set(line, count - 1);210211 return count > 0 ? [] : [index];212 });213};214215/**216 * Indexes of the lines of `next` a shortest edit script from `previous`217 * inserts (Myers' O(ND) diff).218 */219const myers = (previous: readonly string[], next: readonly string[]) => {220 const n = previous.length;221 const m = next.length;222 const limit = Math.min(n + m, MAX_EDITS);223 const offset = limit + 1;224 const reach = new Int32Array(2 * limit + 3);225 const trace: Int32Array[] = [];226227 for (let edits = 0; edits <= limit; edits += 1) {228 for (let diagonal = -edits; diagonal <= edits; diagonal += 2) {229 let x =230 diagonal === -edits ||231 (diagonal !== edits &&232 at(reach, offset + diagonal - 1) < at(reach, offset + diagonal + 1))233 ? at(reach, offset + diagonal + 1)234 : at(reach, offset + diagonal - 1) + 1;235236 let y = x - diagonal;237238 while (x < n && y < m && previous[x] === next[y]) {239 x += 1;240 y += 1;241 }242243 reach[offset + diagonal] = x;244245 if (x >= n && y >= m) {246 trace.push(reach.slice(offset - edits, offset + edits + 1));247248 return insertsFrom(trace, { m, n });249 }250 }251252 trace.push(reach.slice(offset - edits, offset + edits + 1));253 }254255 return unmatched(previous, next);256};257258/** The lines of `next` that are not in `previous`, numbered from 1. */259const added = (260 previous: readonly string[],261 next: readonly string[]262): readonly AddedLine[] => {263 let start = 0;264265 while (266 start < previous.length &&267 start < next.length &&268 previous[start] === next[start]269 ) {270 start += 1;271 }272273 let end = 0;274275 while (276 end < previous.length - start &&277 end < next.length - start &&278 previous[previous.length - 1 - end] === next[next.length - 1 - end]279 ) {280 end += 1;281 }282283 const middle = myers(284 previous.slice(start, previous.length - end),285 next.slice(start, next.length - end)286 );287288 return middle.map((index) => ({289 line: start + index + 1,290 text: next[start + index] ?? "",291 }));292};293294/**295 * A file's lines; none for a binary blob, or for a submodule's pointer, whose296 * id names a commit in another repo, so the store has no blob by it.297 */298const textOf = (repo: RepoName, blob: BlobSha | undefined) =>299 blob === undefined300 ? Effect.succeedSome<readonly string[]>([])301 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(302 Effect.map(303 Option.flatMap((bytes) =>304 isBinary(bytes) ? Option.none() : Option.some(linesOf(bytes))305 )306 )307 );308309// Changes diffed at once, each reading its two blobs together: eight store310// calls, and no more than four files' text held at a time.311const CHANGES = { concurrency: STORE_CALLS / 2 } as const;312313/**314 * The lines each added or modified file gained, by a line diff of its blobs.315 * A binary blob (a NUL in its first 8 KiB) and a submodule's pointer report316 * no lines. At most eight blobs are read at once.317 */318export const addedLines = (319 repo: RepoName,320 changes: readonly Change[]321): Effect.Effect<322 ReadonlyMap<RepoPath, readonly AddedLine[]>,323 RepoNotFound,324 RepoHost325> =>326 Effect.forEach(327 changes.filter((change) => change.after !== undefined),328 (change) =>329 Effect.gen(function* () {330 const [previous, next] = yield* Effect.all(331 [textOf(repo, change.before), textOf(repo, change.after)],332 ALL333 );334335 const lines = Option.match(next, {336 onNone: () => [],337 onSome: (text) =>338 added(339 Option.getOrElse(previous, () => []),340 text341 ),342 });343344 return [change.path, lines] as const;345 }),346 CHANGES347 ).pipe(Effect.map((entries) => new Map(entries)));