336 lines · 15.7 KBRaw
| 1 | import type { ChangeFile, ChangeSet, CommitDetail, CommitSummary, DiffLine } from "./contract/views.ts"; |
| 2 | |
| 3 | export const MAX_CHANGED_FILES = 200; |
| 4 | export const MAX_BLOB_BYTES = 512 * 1024; |
| 5 | export const MAX_CHANGE_SET_BYTES = 8 * 1024 * 1024; |
| 6 | const MAX_TRACE_CELLS = 4_000_000; |
| 7 | export const MAX_ANCESTORS = 1_000; |
| 8 | const MAX_TREE_DEPTH = 64; |
| 9 | const WALK_SLOP = 8; |
| 10 | |
| 11 | type FlatEntry = Pick<ArtifactsTreeEntry, "hash" | "type" | "mode">; |
| 12 | |
| 13 | const MAX_MEMO_ENTRIES = 50_000; |
| 14 | const memo = new Map<string, Promise<ArtifactsCommitMetadata | ArtifactsTreeEntry[] | null>>(); |
| 15 | |
| 16 | const scopes = new WeakMap<ArtifactsRepo, string>(); |
| 17 | |
| 18 | /** Lets reads through `handle` be remembered between requests, under `repository` so no other repository can see them. */ |
| 19 | export function rememberReads(handle: ArtifactsRepo, repository: string): ArtifactsRepo { |
| 20 | scopes.set(handle, repository); |
| 21 | return handle; |
| 22 | } |
| 23 | |
| 24 | /** Commits and trees never change once written, so the isolate keeps them between requests, keyed by repository, kind and hash. */ |
| 25 | function remembered<T extends ArtifactsCommitMetadata | ArtifactsTreeEntry[]>(handle: ArtifactsRepo, kind: string, hash: string, load: () => Promise<T | null>): Promise<T | null> { |
| 26 | const scope = scopes.get(handle); |
| 27 | if (!scope) return load(); |
| 28 | const key = `${scope}:${kind}:${hash}`; |
| 29 | const known = memo.get(key); |
| 30 | if (known) return known as Promise<T | null>; |
| 31 | if (memo.size >= MAX_MEMO_ENTRIES) memo.clear(); |
| 32 | const loading = load().then((value) => { |
| 33 | if (value === null) memo.delete(key); |
| 34 | return value; |
| 35 | }, (error) => { |
| 36 | memo.delete(key); |
| 37 | throw error; |
| 38 | }); |
| 39 | memo.set(key, loading); |
| 40 | return loading; |
| 41 | } |
| 42 | |
| 43 | export function readCommit(handle: ArtifactsRepo, hash: string): Promise<ArtifactsCommitMetadata | null> { |
| 44 | return remembered(handle, "commit", hash, () => handle.readCommit(hash)); |
| 45 | } |
| 46 | |
| 47 | export function readTree(handle: ArtifactsRepo, hash: string): Promise<ArtifactsTreeEntry[] | null> { |
| 48 | return remembered(handle, "tree", hash, () => handle.readTree(hash)); |
| 49 | } |
| 50 | |
| 51 | type ChangedEntry = { before?: FlatEntry; after?: FlatEntry }; |
| 52 | |
| 53 | /** The files that differ between two trees, descending only into subtrees whose hashes differ. */ |
| 54 | async function changedEntries(handle: ArtifactsRepo, beforeTree: string | null, afterTree: string | null, prefix = "", depth = 0, found = new Map<string, ChangedEntry>()): Promise<Map<string, ChangedEntry>> { |
| 55 | if (beforeTree === afterTree || depth > MAX_TREE_DEPTH || found.size > MAX_CHANGED_FILES) return found; |
| 56 | const [before, after] = await Promise.all([beforeTree ? readTree(handle, beforeTree) : null, afterTree ? readTree(handle, afterTree) : null]); |
| 57 | const old = new Map((before ?? []).map((entry) => [entry.name, entry])); |
| 58 | const current = new Map((after ?? []).map((entry) => [entry.name, entry])); |
| 59 | const subtrees: Promise<unknown>[] = []; |
| 60 | for (const name of new Set([...old.keys(), ...current.keys()])) { |
| 61 | const was = old.get(name); |
| 62 | const now = current.get(name); |
| 63 | if (was && now && was.hash === now.hash && was.mode === now.mode) continue; |
| 64 | const path = prefix ? `${prefix}/${name}` : name; |
| 65 | const wasTree = was?.type === "tree" ? was.hash : null; |
| 66 | const nowTree = now?.type === "tree" ? now.hash : null; |
| 67 | if (wasTree || nowTree) subtrees.push(changedEntries(handle, wasTree, nowTree, path, depth + 1, found)); |
| 68 | const wasFile = was && !wasTree ? was : undefined; |
| 69 | const nowFile = now && !nowTree ? now : undefined; |
| 70 | if (wasFile || nowFile) found.set(path, { before: wasFile, after: nowFile }); |
| 71 | } |
| 72 | await Promise.all(subtrees); |
| 73 | return found; |
| 74 | } |
| 75 | |
| 76 | function splitLines(text: string): string[] { |
| 77 | return text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n"); |
| 78 | } |
| 79 | |
| 80 | type Edit = { kind: DiffLine["kind"]; oldIndex: number; newIndex: number }; |
| 81 | |
| 82 | /** Myers' O((N+M)D) diff over the lines between the common prefix and suffix, or null when the edit script is too long to trace. */ |
| 83 | function editScript(oldLines: readonly string[], newLines: readonly string[]): Edit[] | null { |
| 84 | let start = 0; |
| 85 | while (start < oldLines.length && start < newLines.length && oldLines[start] === newLines[start]) start++; |
| 86 | let oldEnd = oldLines.length; |
| 87 | let newEnd = newLines.length; |
| 88 | while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) { |
| 89 | oldEnd--; |
| 90 | newEnd--; |
| 91 | } |
| 92 | const n = oldEnd - start; |
| 93 | const m = newEnd - start; |
| 94 | const max = n + m; |
| 95 | const offset = max + 1; |
| 96 | const maxEdits = Math.min(max, Math.floor(MAX_TRACE_CELLS / (2 * max + 3))); |
| 97 | const v = new Int32Array(2 * max + 3); |
| 98 | const trace: Int32Array[] = []; |
| 99 | let found = max === 0; |
| 100 | for (let d = 0; d <= maxEdits && !found; d++) { |
| 101 | trace.push(v.slice()); |
| 102 | for (let k = -d; k <= d; k += 2) { |
| 103 | let x = k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]) ? v[offset + k + 1] : v[offset + k - 1] + 1; |
| 104 | let y = x - k; |
| 105 | while (x < n && y < m && oldLines[start + x] === newLines[start + y]) { |
| 106 | x++; |
| 107 | y++; |
| 108 | } |
| 109 | v[offset + k] = x; |
| 110 | if (x >= n && y >= m) { |
| 111 | found = true; |
| 112 | break; |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | if (!found) return null; |
| 117 | |
| 118 | const middle: Edit[] = []; |
| 119 | let x = n; |
| 120 | let y = m; |
| 121 | for (let d = trace.length - 1; d >= 0; d--) { |
| 122 | const previous = trace[d]; |
| 123 | const k = x - y; |
| 124 | const fromK = k === -d || (k !== d && previous[offset + k - 1] < previous[offset + k + 1]) ? k + 1 : k - 1; |
| 125 | const fromX = previous[offset + fromK]; |
| 126 | const fromY = fromX - fromK; |
| 127 | while (x > fromX && y > fromY) middle.push({ kind: "context", oldIndex: start + --x, newIndex: start + --y }); |
| 128 | if (d > 0) { |
| 129 | if (x === fromX) middle.push({ kind: "add", oldIndex: -1, newIndex: start + --y }); |
| 130 | else middle.push({ kind: "delete", oldIndex: start + --x, newIndex: -1 }); |
| 131 | } |
| 132 | x = fromX; |
| 133 | y = fromY; |
| 134 | } |
| 135 | while (x > 0 && y > 0) middle.push({ kind: "context", oldIndex: start + --x, newIndex: start + --y }); |
| 136 | middle.reverse(); |
| 137 | |
| 138 | const edits: Edit[] = []; |
| 139 | for (let index = 0; index < start; index++) edits.push({ kind: "context", oldIndex: index, newIndex: index }); |
| 140 | for (let index = 0; index < middle.length; ) { |
| 141 | if (middle[index].kind === "context") { |
| 142 | edits.push(middle[index++]); |
| 143 | continue; |
| 144 | } |
| 145 | const run: Edit[] = []; |
| 146 | while (index < middle.length && middle[index].kind !== "context") run.push(middle[index++]); |
| 147 | edits.push(...run.filter((edit) => edit.kind === "delete"), ...run.filter((edit) => edit.kind === "add")); |
| 148 | } |
| 149 | for (let index = 0; index < oldLines.length - oldEnd; index++) edits.push({ kind: "context", oldIndex: oldEnd + index, newIndex: newEnd + index }); |
| 150 | return edits; |
| 151 | } |
| 152 | |
| 153 | /** Every line of both versions in diff order, numbered on each side, or null when the edit script is too long to trace. */ |
| 154 | export function diffRows(before: string, after: string): DiffLine[] | null { |
| 155 | const oldLines = before ? splitLines(before) : []; |
| 156 | const newLines = after ? splitLines(after) : []; |
| 157 | const edits = editScript(oldLines, newLines); |
| 158 | return ( |
| 159 | edits?.map((edit) => ({ |
| 160 | kind: edit.kind, |
| 161 | text: edit.kind === "add" ? newLines[edit.newIndex] : oldLines[edit.oldIndex], |
| 162 | oldLine: edit.kind === "add" ? null : edit.oldIndex + 1, |
| 163 | newLine: edit.kind === "delete" ? null : edit.newIndex + 1, |
| 164 | })) ?? null |
| 165 | ); |
| 166 | } |
| 167 | |
| 168 | export function lineDiff(before: string, after: string): { additions: number; deletions: number; truncated: boolean } { |
| 169 | const rows = diffRows(before, after); |
| 170 | if (!rows) return { additions: after ? splitLines(after).length : 0, deletions: before ? splitLines(before).length : 0, truncated: true }; |
| 171 | return { additions: rows.filter((row) => row.kind === "add").length, deletions: rows.filter((row) => row.kind === "delete").length, truncated: false }; |
| 172 | } |
| 173 | |
| 174 | export type LineRange = { start: number; side: "deletions" | "additions"; end: number; endSide: "deletions" | "additions" }; |
| 175 | |
| 176 | /** The rows a selected line range covers, in diff order: `deletions` lines count in the old file, `additions` lines in the new one. */ |
| 177 | export function rowsInRange(before: string, after: string, range: LineRange): DiffLine[] | null { |
| 178 | const rows = diffRows(before, after); |
| 179 | if (!rows) return null; |
| 180 | const at = (side: LineRange["side"], line: number) => rows.findIndex((row) => (side === "deletions" ? row.oldLine === line : row.newLine === line)); |
| 181 | const first = at(range.side, range.start); |
| 182 | const last = at(range.endSide, range.end); |
| 183 | if (first < 0 || last < 0) return null; |
| 184 | return rows.slice(Math.min(first, last), Math.max(first, last) + 1); |
| 185 | } |
| 186 | |
| 187 | async function textBlob(handle: ArtifactsRepo, hash: string | null): Promise<{ kind: "text"; text: string } | { kind: "binary" | "too_large" | "missing" }> { |
| 188 | if (!hash) return { kind: "text", text: "" }; |
| 189 | const blob = await handle.readBlob(hash); |
| 190 | if (!blob) return { kind: "missing" }; |
| 191 | if (blob.size > MAX_BLOB_BYTES) return { kind: "too_large" }; |
| 192 | const bytes = new Uint8Array(await blob.arrayBuffer()); |
| 193 | if (bytes.subarray(0, 8_000).includes(0)) return { kind: "binary" }; |
| 194 | return { kind: "text", text: new TextDecoder().decode(bytes) }; |
| 195 | } |
| 196 | |
| 197 | async function changedFile(handle: ArtifactsRepo, path: string, before: FlatEntry | undefined, after: FlatEntry | undefined): Promise<ChangeFile> { |
| 198 | const status = !before ? "added" : !after ? "deleted" : before.type !== after.type || before.mode !== after.mode ? "type_changed" : "modified"; |
| 199 | if ((before && before.type !== "blob" && before.type !== "exec") || (after && after.type !== "blob" && after.type !== "exec")) { |
| 200 | return { path, status, kind: "binary", additions: 0, deletions: 0, before: null, after: null, truncated: false }; |
| 201 | } |
| 202 | const [oldBlob, newBlob] = await Promise.all([textBlob(handle, before?.hash ?? null), textBlob(handle, after?.hash ?? null)]); |
| 203 | if (oldBlob.kind !== "text" || newBlob.kind !== "text") { |
| 204 | const kind = oldBlob.kind === "too_large" || newBlob.kind === "too_large" ? "too_large" : oldBlob.kind === "missing" || newBlob.kind === "missing" ? "missing" : "binary"; |
| 205 | return { path, status, kind, additions: 0, deletions: 0, before: null, after: null, truncated: false }; |
| 206 | } |
| 207 | return { path, status, kind: "text", ...lineDiff(oldBlob.text, newBlob.text), before: before ? oldBlob.text : null, after: after ? newBlob.text : null }; |
| 208 | } |
| 209 | |
| 210 | /** Keeps the text of files in order until the change set's text reaches MAX_CHANGE_SET_BYTES; later files are shown as too large. */ |
| 211 | function withinBudget(files: ChangeFile[]): ChangeFile[] { |
| 212 | let used = 0; |
| 213 | return files.map((file) => { |
| 214 | used += (file.before?.length ?? 0) + (file.after?.length ?? 0); |
| 215 | return used > MAX_CHANGE_SET_BYTES && file.kind === "text" ? { ...file, kind: "too_large", before: null, after: null } : file; |
| 216 | }); |
| 217 | } |
| 218 | |
| 219 | export async function ancestors(handle: ArtifactsRepo, start: string): Promise<Map<string, number>> { |
| 220 | const distances = new Map<string, number>(); |
| 221 | const queue: { hash: string; distance: number }[] = [{ hash: start, distance: 0 }]; |
| 222 | while (queue.length && distances.size < MAX_ANCESTORS) { |
| 223 | const current = queue.shift()!; |
| 224 | if (distances.has(current.hash)) continue; |
| 225 | distances.set(current.hash, current.distance); |
| 226 | const commit = await readCommit(handle, current.hash); |
| 227 | for (const parent of commit?.parents ?? []) queue.push({ hash: parent, distance: current.distance + 1 }); |
| 228 | } |
| 229 | return distances; |
| 230 | } |
| 231 | |
| 232 | function summary(commit: ArtifactsCommitMetadata): CommitSummary { |
| 233 | return { hash: commit.hash, title: commit.message.split("\n")[0], message: commit.message, author: commit.author.name, committedAt: commit.committedAt }; |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Walks both histories newest first, as git's merge-base does, marking each commit with the tips that reach it, |
| 238 | * until every commit still queued is reachable from both. Returns the newest common commit and the commits only |
| 239 | * the head reaches, oldest first. |
| 240 | */ |
| 241 | async function compareHistory(handle: ArtifactsRepo, baseTip: string, headTip: string): Promise<{ mergeBase: string; onlyHead: CommitSummary[] }> { |
| 242 | const BASE = 1; |
| 243 | const HEAD = 2; |
| 244 | const BOTH = BASE | HEAD; |
| 245 | const commits = new Map<string, ArtifactsCommitMetadata>(); |
| 246 | const flags = new Map<string, number>(); |
| 247 | const queue: string[] = []; |
| 248 | const read = async (hash: string) => { |
| 249 | if (!commits.has(hash)) { |
| 250 | const commit = await readCommit(handle, hash); |
| 251 | if (commit) commits.set(hash, commit); |
| 252 | } |
| 253 | }; |
| 254 | const mark = (hash: string, flag: number) => { |
| 255 | const before = flags.get(hash) ?? 0; |
| 256 | if ((before | flag) === before) return; |
| 257 | flags.set(hash, before | flag); |
| 258 | if (!queue.includes(hash)) queue.push(hash); |
| 259 | }; |
| 260 | await Promise.all([read(baseTip), read(headTip)]); |
| 261 | mark(baseTip, BASE); |
| 262 | mark(headTip, HEAD); |
| 263 | let mergeBase: string | null = null; |
| 264 | let slop = WALK_SLOP; |
| 265 | for (let steps = 0; queue.length && steps < MAX_ANCESTORS; steps++) { |
| 266 | if (queue.every((hash) => flags.get(hash) === BOTH)) { |
| 267 | if (slop-- <= 0) break; |
| 268 | } else slop = WALK_SLOP; |
| 269 | queue.sort((a, b) => (commits.get(b)?.committedAt ?? 0) - (commits.get(a)?.committedAt ?? 0)); |
| 270 | const hash = queue.shift()!; |
| 271 | const flag = flags.get(hash)!; |
| 272 | if (flag === BOTH) mergeBase ??= hash; |
| 273 | const parents = commits.get(hash)?.parents ?? []; |
| 274 | await Promise.all(parents.map(read)); |
| 275 | for (const parent of parents) mark(parent, flag); |
| 276 | } |
| 277 | const onlyHead = [...flags] |
| 278 | .reverse() |
| 279 | .filter(([hash, flag]) => flag === HEAD && commits.has(hash)) |
| 280 | .map(([hash]) => summary(commits.get(hash)!)) |
| 281 | .sort((a, b) => a.committedAt - b.committedAt); |
| 282 | return { mergeBase: mergeBase ?? baseTip, onlyHead }; |
| 283 | } |
| 284 | |
| 285 | export async function mergeBase(handle: ArtifactsRepo, base: string, head: string): Promise<string> { |
| 286 | return (await compareHistory(handle, base, head)).mergeBase; |
| 287 | } |
| 288 | |
| 289 | /** Compares `headHash` with `baseHash`, or with an empty tree when `baseHash` is null. */ |
| 290 | export async function compareCommits(handle: ArtifactsRepo, baseHash: string | null, headHash: string, commits?: CommitSummary[]): Promise<ChangeSet> { |
| 291 | const [base, head] = await Promise.all([baseHash ? readCommit(handle, baseHash) : null, readCommit(handle, headHash)]); |
| 292 | if ((baseHash && !base) || !head) throw new Error("Commit not found"); |
| 293 | const entries = await changedEntries(handle, base?.treeHash ?? null, head.treeHash); |
| 294 | const paths = [...entries.keys()].sort(); |
| 295 | const visible = paths.slice(0, MAX_CHANGED_FILES); |
| 296 | const files = withinBudget(await Promise.all(visible.map((path) => changedFile(handle, path, entries.get(path)!.before, entries.get(path)!.after)))); |
| 297 | return { |
| 298 | base: baseHash ?? "", |
| 299 | head: headHash, |
| 300 | commits: commits ?? [summary(head)], |
| 301 | files, |
| 302 | additions: files.reduce((total, file) => total + file.additions, 0), |
| 303 | deletions: files.reduce((total, file) => total + file.deletions, 0), |
| 304 | truncated: paths.length > visible.length, |
| 305 | }; |
| 306 | } |
| 307 | |
| 308 | /** Paths a commit changed against its first parent. */ |
| 309 | async function commitPaths(handle: ArtifactsRepo, hash: string): Promise<string[]> { |
| 310 | const commit = await readCommit(handle, hash); |
| 311 | if (!commit) return []; |
| 312 | const parent = commit.parents[0] ? await readCommit(handle, commit.parents[0]) : null; |
| 313 | return [...(await changedEntries(handle, parent?.treeHash ?? null, commit.treeHash)).keys()].sort(); |
| 314 | } |
| 315 | |
| 316 | export async function branchChanges(handle: ArtifactsRepo, baseTip: string, headTip: string): Promise<ChangeSet> { |
| 317 | const { mergeBase, onlyHead } = await compareHistory(handle, baseTip, headTip); |
| 318 | const commits = await Promise.all(onlyHead.map(async (commit) => ({ ...commit, files: await commitPaths(handle, commit.hash) }))); |
| 319 | return compareCommits(handle, mergeBase, headTip, commits); |
| 320 | } |
| 321 | |
| 322 | export async function commitDetail(handle: ArtifactsRepo, hash: string): Promise<CommitDetail | null> { |
| 323 | const commit = await readCommit(handle, hash); |
| 324 | if (!commit) return null; |
| 325 | const changes = await compareCommits(handle, commit.parents[0] ?? null, hash); |
| 326 | return { |
| 327 | hash: commit.hash, |
| 328 | message: commit.message, |
| 329 | author: commit.author, |
| 330 | committer: commit.committer, |
| 331 | authoredAt: commit.authoredAt, |
| 332 | committedAt: commit.committedAt, |
| 333 | parents: commit.parents, |
| 334 | changes, |
| 335 | }; |
| 336 | } |