tree-diff.ts
This file
Path
packages/git/src/tree-diff.ts
256 lines · 7.7 KiB · TypeScript
Last changed by
Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
History of this fileTake it
The walk stopped after 200 commits: lines older than 878da37 point at it.
Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 1–6why, one step back1import { 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";6Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
lines 7–8why, one step back7import { Edit, sharedEnds, shortestDiff } from "./line-diff.ts";8Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 9–177why, one step back9/**10 * One file an answer changed, with its blob ids before and after. The same11 * shape as the gate's `Change` (`@repo/gate/facts`), which git cannot import.12 */13export interface Change {14 readonly path: RepoPath;15 readonly status: "added" | "modified" | "deleted";16 readonly before?: BlobSha;17 readonly after?: BlobSha;18}1920/** A line a change added, numbered from 1 in the new file. */21export interface AddedLine {22 readonly line: number;23 readonly text: string;24}2526// Store calls under way at once, however deep the walk or long the change set.27const STORE_CALLS = 8;2829// The walk forks freely; the semaphore alone holds the store to its calls.30const ALL = { concurrency: "unbounded" } as const;3132const entriesOf = (33 calls: Semaphore.Semaphore,34 repo: RepoName,35 tree: Option.Option<string>36) =>37 Option.match(tree, {38 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),39 onSome: (id) =>40 RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(41 Semaphore.withPermit(calls),42 Effect.flatMap(43 Option.match({44 onNone: () => Effect.die(`${repo} has no tree ${id}`),45 onSome: Effect.succeed,46 })47 )48 ),49 });5051const treeIdOf = (entry: TreeEntry | undefined) =>52 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();5354// A submodule's pointer counts as a file at its path, so a change to it is seen.55const fileIdOf = (entry: TreeEntry | undefined) =>56 entry === undefined || entry.type === "tree"57 ? undefined58 : BlobSha.make(entry.sha);5960const fileChange = (61 path: string,62 before: BlobSha | undefined,63 after: BlobSha | undefined64): readonly Change[] => {65 const at = RepoPath.make(path);6667 if (before !== undefined && after !== undefined) {68 return [{ after, before, path: at, status: "modified" }];69 }7071 if (before !== undefined) {72 return [{ before, path: at, status: "deleted" }];73 }7475 return after === undefined ? [] : [{ after, path: at, status: "added" }];76};7778const walk = (79 calls: Semaphore.Semaphore,80 repo: RepoName,81 prefix: string,82 base: Option.Option<string>,83 head: Option.Option<string>84): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>85 Effect.gen(function* () {86 const [before, after] = yield* Effect.all(87 [entriesOf(calls, repo, base), entriesOf(calls, repo, head)],88 ALL89 );9091 const beforeByName = new Map(before.map((entry) => [entry.name, entry]));92 const afterByName = new Map(after.map((entry) => [entry.name, entry]));9394 // The same id and mode: nothing under it changed, so it is never read.95 const names = Array.sort(96 new Set([...beforeByName.keys(), ...afterByName.keys()]),97 Order.String98 ).filter((name) => {99 const old = beforeByName.get(name);100 const next = afterByName.get(name);101102 return old?.sha !== next?.sha || old?.mode !== next?.mode;103 });104105 const changed = yield* Effect.forEach(106 names,107 (name) => {108 const old = beforeByName.get(name);109 const next = afterByName.get(name);110 const path = `${prefix}${name}`;111 const files = fileChange(path, fileIdOf(old), fileIdOf(next));112 const inside = [treeIdOf(old), treeIdOf(next)] as const;113114 return Option.isNone(inside[0]) && Option.isNone(inside[1])115 ? Effect.succeed(files)116 : walk(calls, repo, `${path}/`, inside[0], inside[1]).pipe(117 Effect.map((nested) => [...files, ...nested])118 );119 },120 ALL121 );122123 return changed.flat();124 });125126/**127 * The files that differ between two trees of `repo`, read through the128 * `RepoHost` port alone: it walks both roots and descends only into subtrees129 * whose ids differ, since the store has no diff of its own. At most eight130 * trees are read at once.131 */132export const treeDiff = (133 repo: RepoName,134 base: TreeSha,135 head: TreeSha136): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>137 Effect.flatMap(Semaphore.make(STORE_CALLS), (calls) =>138 walk(calls, repo, "", Option.some(base), Option.some(head))139 );140141// git's own test: a NUL among the first bytes means the blob is not text.142const SNIFF = 8192;143144const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);145146const linesOf = (bytes: Uint8Array) => {147 const text = new TextDecoder().decode(bytes);148 const lines = text.split("\n");149150 if (text.endsWith("\n")) {151 lines.pop();152 }153154 return lines;155};156157/**158 * Lines of `next` with no partner in `previous`, matched by count: the159 * fallback for a rewrite too large for the shortest script.160 */161const unmatched = (previous: readonly string[], next: readonly string[]) => {162 const left = new Map<string, number>();163164 for (const line of previous) {165 left.set(line, (left.get(line) ?? 0) + 1);166 }167168 return next.flatMap((line, index) => {169 const count = left.get(line) ?? 0;170171 left.set(line, count - 1);172173 return count > 0 ? [] : [index];174 });175};176177/**Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
lines 178–180why, one step back178 * The lines of `next` that are not in `previous`, numbered from 1: the179 * insertions of the shortest edit script (`line-diff.ts`), or, for a180 * rewrite too large for it, the lines with no partner by count.Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 181–184why, one step back181 */182const added = (183 previous: readonly string[],184 next: readonly string[]Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
lines 185–188why, one step back185): readonly AddedLine[] =>186 Option.match(shortestDiff(previous, next), {187 onNone: () => {188 const { head, tail } = sharedEnds(previous, next);Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
line 189why, one step back189Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
lines 190–201why, one step back190 return unmatched(191 previous.slice(head, previous.length - tail),192 next.slice(head, next.length - tail)193 ).map((index) => head + index);194 },195 onSome: (edits) =>196 edits.flatMap((edit) =>197 Edit.$is("Insert")(edit)198 ? Array.makeBy(edit.count, (at) => edit.newStart + at)199 : []200 ),201 }).map((index) => ({ line: index + 1, text: next[index] ?? "" }));Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 202–256why, one step back202203/**204 * A file's lines; none for a binary blob, or for a submodule's pointer, whose205 * id names a commit in another repo, so the store has no blob by it.206 */207const textOf = (repo: RepoName, blob: BlobSha | undefined) =>208 blob === undefined209 ? Effect.succeedSome<readonly string[]>([])210 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(211 Effect.map(212 Option.flatMap((bytes) =>213 isBinary(bytes) ? Option.none() : Option.some(linesOf(bytes))214 )215 )216 );217218// Changes diffed at once, each reading its two blobs together: eight store219// calls, and no more than four files' text held at a time.220const CHANGES = { concurrency: STORE_CALLS / 2 } as const;221222/**223 * The lines each added or modified file gained, by a line diff of its blobs.224 * A binary blob (a NUL in its first 8 KiB) and a submodule's pointer report225 * no lines. At most eight blobs are read at once.226 */227export const addedLines = (228 repo: RepoName,229 changes: readonly Change[]230): Effect.Effect<231 ReadonlyMap<RepoPath, readonly AddedLine[]>,232 RepoNotFound,233 RepoHost234> =>235 Effect.forEach(236 changes.filter((change) => change.after !== undefined),237 (change) =>238 Effect.gen(function* () {239 const [previous, next] = yield* Effect.all(240 [textOf(repo, change.before), textOf(repo, change.after)],241 ALL242 );243244 const lines = Option.match(next, {245 onNone: () => [],246 onSome: (text) =>247 added(248 Option.getOrElse(previous, () => []),249 text250 ),251 });252253 return [change.path, lines] as const;254 }),255 CHANGES256 ).pipe(Effect.map((entries) => new Map(entries)));