tree-diff.ts
This file
Path
packages/git/src/tree-diff.ts
229 lines · 6.7 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake it
The walk stopped after 200 commits: lines older than 958650a point at it.
Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a
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/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 9why, one step back9/** The same shape as the gate's `Change` (`@repo/gate/facts`), which git cannot import. */Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a
lines 10–121why, one step back10export interface Change {11 readonly path: RepoPath;12 readonly status: "added" | "modified" | "deleted";13 readonly before?: BlobSha;14 readonly after?: BlobSha;15}1617export interface AddedLine {18 readonly line: number;19 readonly text: string;20}2122// Store calls under way at once, however deep the walk or long the change set.23const STORE_CALLS = 8;2425// The walk forks freely; the semaphore alone holds the store to its calls.26const ALL = { concurrency: "unbounded" } as const;2728const entriesOf = (29 calls: Semaphore.Semaphore,30 repo: RepoName,31 tree: Option.Option<string>32) =>33 Option.match(tree, {34 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),35 onSome: (id) =>36 RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(37 Semaphore.withPermit(calls),38 Effect.flatMap(39 Option.match({40 onNone: () => Effect.die(`${repo} has no tree ${id}`),41 onSome: Effect.succeed,42 })43 )44 ),45 });4647const treeIdOf = (entry: TreeEntry | undefined) =>48 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();4950// A submodule's pointer counts as a file at its path, so a change to it is seen.51const fileIdOf = (entry: TreeEntry | undefined) =>52 entry === undefined || entry.type === "tree"53 ? undefined54 : BlobSha.make(entry.sha);5556const fileChange = (57 path: string,58 before: BlobSha | undefined,59 after: BlobSha | undefined60): readonly Change[] => {61 const at = RepoPath.make(path);6263 if (before !== undefined && after !== undefined) {64 return [{ after, before, path: at, status: "modified" }];65 }6667 if (before !== undefined) {68 return [{ before, path: at, status: "deleted" }];69 }7071 return after === undefined ? [] : [{ after, path: at, status: "added" }];72};7374const walk = (75 calls: Semaphore.Semaphore,76 repo: RepoName,77 prefix: string,78 base: Option.Option<string>,79 head: Option.Option<string>80): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>81 Effect.gen(function* () {82 const [before, after] = yield* Effect.all(83 [entriesOf(calls, repo, base), entriesOf(calls, repo, head)],84 ALL85 );8687 const beforeByName = new Map(before.map((entry) => [entry.name, entry]));88 const afterByName = new Map(after.map((entry) => [entry.name, entry]));8990 // The same id and mode: nothing under it changed, so it is never read.91 const names = Array.sort(92 new Set([...beforeByName.keys(), ...afterByName.keys()]),93 Order.String94 ).filter((name) => {95 const old = beforeByName.get(name);96 const next = afterByName.get(name);9798 return old?.sha !== next?.sha || old?.mode !== next?.mode;99 });100101 const changed = yield* Effect.forEach(102 names,103 (name) => {104 const old = beforeByName.get(name);105 const next = afterByName.get(name);106 const path = `${prefix}${name}`;107 const files = fileChange(path, fileIdOf(old), fileIdOf(next));108 const inside = [treeIdOf(old), treeIdOf(next)] as const;109110 return Option.isNone(inside[0]) && Option.isNone(inside[1])111 ? Effect.succeed(files)112 : walk(calls, repo, `${path}/`, inside[0], inside[1]).pipe(113 Effect.map((nested) => [...files, ...nested])114 );115 },116 ALL117 );118119 return changed.flat();120 });121Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 122why, one step back122/** Descends only into subtrees whose ids differ: the store has no diff of its own. */Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a
lines 123–166why, one step back123export const treeDiff = (124 repo: RepoName,125 base: TreeSha,126 head: TreeSha127): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>128 Effect.flatMap(Semaphore.make(STORE_CALLS), (calls) =>129 walk(calls, repo, "", Option.some(base), Option.some(head))130 );131132// git's own test: a NUL among the first bytes means the blob is not text.133const SNIFF = 8192;134135const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);136137const linesOf = (bytes: Uint8Array) => {138 const text = new TextDecoder().decode(bytes);139 const lines = text.split("\n");140141 if (text.endsWith("\n")) {142 lines.pop();143 }144145 return lines;146};147148const unmatched = (previous: readonly string[], next: readonly string[]) => {149 const left = new Map<string, number>();150151 for (const line of previous) {152 left.set(line, (left.get(line) ?? 0) + 1);153 }154155 return next.flatMap((line, index) => {156 const count = left.get(line) ?? 0;157158 left.set(line, count - 1);159160 return count > 0 ? [] : [index];161 });162};163164const added = (165 previous: readonly string[],166 next: readonly string[]Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
lines 167–170why, one step back167): readonly AddedLine[] =>168 Option.match(shortestDiff(previous, next), {169 onNone: () => {170 const { head, tail } = sharedEnds(previous, next);Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a
line 171why, one step back171Merge branch 'build/912-why-per-line'oscabrielbefore adoption635c3c7
lines 172–183why, one step back172 return unmatched(173 previous.slice(head, previous.length - tail),174 next.slice(head, next.length - tail)175 ).map((index) => head + index);176 },177 onSome: (edits) =>178 edits.flatMap((edit) =>179 Edit.$is("Insert")(edit)180 ? Array.makeBy(edit.count, (at) => edit.newStart + at)181 : []182 ),183 }).map((index) => ({ line: index + 1, text: next[index] ?? "" }));Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a
lines 184–229why, one step back184185const textOf = (repo: RepoName, blob: BlobSha | undefined) =>186 blob === undefined187 ? Effect.succeedSome<readonly string[]>([])188 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(189 Effect.map(190 Option.flatMap((bytes) =>191 isBinary(bytes) ? Option.none() : Option.some(linesOf(bytes))192 )193 )194 );195196// Changes diffed at once, each reading its two blobs together: eight store197// calls, and no more than four files' text held at a time.198const CHANGES = { concurrency: STORE_CALLS / 2 } as const;199200export const addedLines = (201 repo: RepoName,202 changes: readonly Change[]203): Effect.Effect<204 ReadonlyMap<RepoPath, readonly AddedLine[]>,205 RepoNotFound,206 RepoHost207> =>208 Effect.forEach(209 changes.filter((change) => change.after !== undefined),210 (change) =>211 Effect.gen(function* () {212 const [previous, next] = yield* Effect.all(213 [textOf(repo, change.before), textOf(repo, change.after)],214 ALL215 );216217 const lines = Option.match(next, {218 onNone: () => [],219 onSome: (text) =>220 added(221 Option.getOrElse(previous, () => []),222 text223 ),224 });225226 return [change.path, lines] as const;227 }),228 CHANGES229 ).pipe(Effect.map((entries) => new Map(entries)));