import type { ChangeFile, ChangeSet, CommitDetail, CommitSummary, DiffLine } from "./contract/views.ts"; export const MAX_CHANGED_FILES = 200; export const MAX_BLOB_BYTES = 512 * 1024; export const MAX_CHANGE_SET_BYTES = 8 * 1024 * 1024; const MAX_TRACE_CELLS = 4_000_000; export const MAX_ANCESTORS = 1_000; const MAX_TREE_DEPTH = 64; const WALK_SLOP = 8; type FlatEntry = Pick; const MAX_MEMO_ENTRIES = 50_000; const memo = new Map>(); const scopes = new WeakMap(); /** Lets reads through `handle` be remembered between requests, under `repository` so no other repository can see them. */ export function rememberReads(handle: ArtifactsRepo, repository: string): ArtifactsRepo { scopes.set(handle, repository); return handle; } /** Commits and trees never change once written, so the isolate keeps them between requests, keyed by repository, kind and hash. */ function remembered(handle: ArtifactsRepo, kind: string, hash: string, load: () => Promise): Promise { const scope = scopes.get(handle); if (!scope) return load(); const key = `${scope}:${kind}:${hash}`; const known = memo.get(key); if (known) return known as Promise; if (memo.size >= MAX_MEMO_ENTRIES) memo.clear(); const loading = load().then((value) => { if (value === null) memo.delete(key); return value; }, (error) => { memo.delete(key); throw error; }); memo.set(key, loading); return loading; } export function readCommit(handle: ArtifactsRepo, hash: string): Promise { return remembered(handle, "commit", hash, () => handle.readCommit(hash)); } export function readTree(handle: ArtifactsRepo, hash: string): Promise { return remembered(handle, "tree", hash, () => handle.readTree(hash)); } type ChangedEntry = { before?: FlatEntry; after?: FlatEntry }; /** The files that differ between two trees, descending only into subtrees whose hashes differ. */ async function changedEntries(handle: ArtifactsRepo, beforeTree: string | null, afterTree: string | null, prefix = "", depth = 0, found = new Map()): Promise> { if (beforeTree === afterTree || depth > MAX_TREE_DEPTH || found.size > MAX_CHANGED_FILES) return found; const [before, after] = await Promise.all([beforeTree ? readTree(handle, beforeTree) : null, afterTree ? readTree(handle, afterTree) : null]); const old = new Map((before ?? []).map((entry) => [entry.name, entry])); const current = new Map((after ?? []).map((entry) => [entry.name, entry])); const subtrees: Promise[] = []; for (const name of new Set([...old.keys(), ...current.keys()])) { const was = old.get(name); const now = current.get(name); if (was && now && was.hash === now.hash && was.mode === now.mode) continue; const path = prefix ? `${prefix}/${name}` : name; const wasTree = was?.type === "tree" ? was.hash : null; const nowTree = now?.type === "tree" ? now.hash : null; if (wasTree || nowTree) subtrees.push(changedEntries(handle, wasTree, nowTree, path, depth + 1, found)); const wasFile = was && !wasTree ? was : undefined; const nowFile = now && !nowTree ? now : undefined; if (wasFile || nowFile) found.set(path, { before: wasFile, after: nowFile }); } await Promise.all(subtrees); return found; } function splitLines(text: string): string[] { return text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n"); } type Edit = { kind: DiffLine["kind"]; oldIndex: number; newIndex: number }; /** 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. */ function editScript(oldLines: readonly string[], newLines: readonly string[]): Edit[] | null { let start = 0; while (start < oldLines.length && start < newLines.length && oldLines[start] === newLines[start]) start++; let oldEnd = oldLines.length; let newEnd = newLines.length; while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) { oldEnd--; newEnd--; } const n = oldEnd - start; const m = newEnd - start; const max = n + m; const offset = max + 1; const maxEdits = Math.min(max, Math.floor(MAX_TRACE_CELLS / (2 * max + 3))); const v = new Int32Array(2 * max + 3); const trace: Int32Array[] = []; let found = max === 0; for (let d = 0; d <= maxEdits && !found; d++) { trace.push(v.slice()); for (let k = -d; k <= d; k += 2) { let x = k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]) ? v[offset + k + 1] : v[offset + k - 1] + 1; let y = x - k; while (x < n && y < m && oldLines[start + x] === newLines[start + y]) { x++; y++; } v[offset + k] = x; if (x >= n && y >= m) { found = true; break; } } } if (!found) return null; const middle: Edit[] = []; let x = n; let y = m; for (let d = trace.length - 1; d >= 0; d--) { const previous = trace[d]; const k = x - y; const fromK = k === -d || (k !== d && previous[offset + k - 1] < previous[offset + k + 1]) ? k + 1 : k - 1; const fromX = previous[offset + fromK]; const fromY = fromX - fromK; while (x > fromX && y > fromY) middle.push({ kind: "context", oldIndex: start + --x, newIndex: start + --y }); if (d > 0) { if (x === fromX) middle.push({ kind: "add", oldIndex: -1, newIndex: start + --y }); else middle.push({ kind: "delete", oldIndex: start + --x, newIndex: -1 }); } x = fromX; y = fromY; } while (x > 0 && y > 0) middle.push({ kind: "context", oldIndex: start + --x, newIndex: start + --y }); middle.reverse(); const edits: Edit[] = []; for (let index = 0; index < start; index++) edits.push({ kind: "context", oldIndex: index, newIndex: index }); for (let index = 0; index < middle.length; ) { if (middle[index].kind === "context") { edits.push(middle[index++]); continue; } const run: Edit[] = []; while (index < middle.length && middle[index].kind !== "context") run.push(middle[index++]); edits.push(...run.filter((edit) => edit.kind === "delete"), ...run.filter((edit) => edit.kind === "add")); } for (let index = 0; index < oldLines.length - oldEnd; index++) edits.push({ kind: "context", oldIndex: oldEnd + index, newIndex: newEnd + index }); return edits; } /** Every line of both versions in diff order, numbered on each side, or null when the edit script is too long to trace. */ export function diffRows(before: string, after: string): DiffLine[] | null { const oldLines = before ? splitLines(before) : []; const newLines = after ? splitLines(after) : []; const edits = editScript(oldLines, newLines); return ( edits?.map((edit) => ({ kind: edit.kind, text: edit.kind === "add" ? newLines[edit.newIndex] : oldLines[edit.oldIndex], oldLine: edit.kind === "add" ? null : edit.oldIndex + 1, newLine: edit.kind === "delete" ? null : edit.newIndex + 1, })) ?? null ); } export function lineDiff(before: string, after: string): { additions: number; deletions: number; truncated: boolean } { const rows = diffRows(before, after); if (!rows) return { additions: after ? splitLines(after).length : 0, deletions: before ? splitLines(before).length : 0, truncated: true }; return { additions: rows.filter((row) => row.kind === "add").length, deletions: rows.filter((row) => row.kind === "delete").length, truncated: false }; } export type LineRange = { start: number; side: "deletions" | "additions"; end: number; endSide: "deletions" | "additions" }; /** The rows a selected line range covers, in diff order: `deletions` lines count in the old file, `additions` lines in the new one. */ export function rowsInRange(before: string, after: string, range: LineRange): DiffLine[] | null { const rows = diffRows(before, after); if (!rows) return null; const at = (side: LineRange["side"], line: number) => rows.findIndex((row) => (side === "deletions" ? row.oldLine === line : row.newLine === line)); const first = at(range.side, range.start); const last = at(range.endSide, range.end); if (first < 0 || last < 0) return null; return rows.slice(Math.min(first, last), Math.max(first, last) + 1); } async function textBlob(handle: ArtifactsRepo, hash: string | null): Promise<{ kind: "text"; text: string } | { kind: "binary" | "too_large" | "missing" }> { if (!hash) return { kind: "text", text: "" }; const blob = await handle.readBlob(hash); if (!blob) return { kind: "missing" }; if (blob.size > MAX_BLOB_BYTES) return { kind: "too_large" }; const bytes = new Uint8Array(await blob.arrayBuffer()); if (bytes.subarray(0, 8_000).includes(0)) return { kind: "binary" }; return { kind: "text", text: new TextDecoder().decode(bytes) }; } async function changedFile(handle: ArtifactsRepo, path: string, before: FlatEntry | undefined, after: FlatEntry | undefined): Promise { const status = !before ? "added" : !after ? "deleted" : before.type !== after.type || before.mode !== after.mode ? "type_changed" : "modified"; if ((before && before.type !== "blob" && before.type !== "exec") || (after && after.type !== "blob" && after.type !== "exec")) { return { path, status, kind: "binary", additions: 0, deletions: 0, before: null, after: null, truncated: false }; } const [oldBlob, newBlob] = await Promise.all([textBlob(handle, before?.hash ?? null), textBlob(handle, after?.hash ?? null)]); if (oldBlob.kind !== "text" || newBlob.kind !== "text") { const kind = oldBlob.kind === "too_large" || newBlob.kind === "too_large" ? "too_large" : oldBlob.kind === "missing" || newBlob.kind === "missing" ? "missing" : "binary"; return { path, status, kind, additions: 0, deletions: 0, before: null, after: null, truncated: false }; } return { path, status, kind: "text", ...lineDiff(oldBlob.text, newBlob.text), before: before ? oldBlob.text : null, after: after ? newBlob.text : null }; } /** 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. */ function withinBudget(files: ChangeFile[]): ChangeFile[] { let used = 0; return files.map((file) => { used += (file.before?.length ?? 0) + (file.after?.length ?? 0); return used > MAX_CHANGE_SET_BYTES && file.kind === "text" ? { ...file, kind: "too_large", before: null, after: null } : file; }); } export async function ancestors(handle: ArtifactsRepo, start: string): Promise> { const distances = new Map(); const queue: { hash: string; distance: number }[] = [{ hash: start, distance: 0 }]; while (queue.length && distances.size < MAX_ANCESTORS) { const current = queue.shift()!; if (distances.has(current.hash)) continue; distances.set(current.hash, current.distance); const commit = await readCommit(handle, current.hash); for (const parent of commit?.parents ?? []) queue.push({ hash: parent, distance: current.distance + 1 }); } return distances; } function summary(commit: ArtifactsCommitMetadata): CommitSummary { return { hash: commit.hash, title: commit.message.split("\n")[0], message: commit.message, author: commit.author.name, committedAt: commit.committedAt }; } /** * Walks both histories newest first, as git's merge-base does, marking each commit with the tips that reach it, * until every commit still queued is reachable from both. Returns the newest common commit and the commits only * the head reaches, oldest first. */ async function compareHistory(handle: ArtifactsRepo, baseTip: string, headTip: string): Promise<{ mergeBase: string; onlyHead: CommitSummary[] }> { const BASE = 1; const HEAD = 2; const BOTH = BASE | HEAD; const commits = new Map(); const flags = new Map(); const queue: string[] = []; const read = async (hash: string) => { if (!commits.has(hash)) { const commit = await readCommit(handle, hash); if (commit) commits.set(hash, commit); } }; const mark = (hash: string, flag: number) => { const before = flags.get(hash) ?? 0; if ((before | flag) === before) return; flags.set(hash, before | flag); if (!queue.includes(hash)) queue.push(hash); }; await Promise.all([read(baseTip), read(headTip)]); mark(baseTip, BASE); mark(headTip, HEAD); let mergeBase: string | null = null; let slop = WALK_SLOP; for (let steps = 0; queue.length && steps < MAX_ANCESTORS; steps++) { if (queue.every((hash) => flags.get(hash) === BOTH)) { if (slop-- <= 0) break; } else slop = WALK_SLOP; queue.sort((a, b) => (commits.get(b)?.committedAt ?? 0) - (commits.get(a)?.committedAt ?? 0)); const hash = queue.shift()!; const flag = flags.get(hash)!; if (flag === BOTH) mergeBase ??= hash; const parents = commits.get(hash)?.parents ?? []; await Promise.all(parents.map(read)); for (const parent of parents) mark(parent, flag); } const onlyHead = [...flags] .reverse() .filter(([hash, flag]) => flag === HEAD && commits.has(hash)) .map(([hash]) => summary(commits.get(hash)!)) .sort((a, b) => a.committedAt - b.committedAt); return { mergeBase: mergeBase ?? baseTip, onlyHead }; } export async function mergeBase(handle: ArtifactsRepo, base: string, head: string): Promise { return (await compareHistory(handle, base, head)).mergeBase; } /** Compares `headHash` with `baseHash`, or with an empty tree when `baseHash` is null. */ export async function compareCommits(handle: ArtifactsRepo, baseHash: string | null, headHash: string, commits?: CommitSummary[]): Promise { const [base, head] = await Promise.all([baseHash ? readCommit(handle, baseHash) : null, readCommit(handle, headHash)]); if ((baseHash && !base) || !head) throw new Error("Commit not found"); const entries = await changedEntries(handle, base?.treeHash ?? null, head.treeHash); const paths = [...entries.keys()].sort(); const visible = paths.slice(0, MAX_CHANGED_FILES); const files = withinBudget(await Promise.all(visible.map((path) => changedFile(handle, path, entries.get(path)!.before, entries.get(path)!.after)))); return { base: baseHash ?? "", head: headHash, commits: commits ?? [summary(head)], files, additions: files.reduce((total, file) => total + file.additions, 0), deletions: files.reduce((total, file) => total + file.deletions, 0), truncated: paths.length > visible.length, }; } /** Paths a commit changed against its first parent. */ async function commitPaths(handle: ArtifactsRepo, hash: string): Promise { const commit = await readCommit(handle, hash); if (!commit) return []; const parent = commit.parents[0] ? await readCommit(handle, commit.parents[0]) : null; return [...(await changedEntries(handle, parent?.treeHash ?? null, commit.treeHash)).keys()].sort(); } export async function branchChanges(handle: ArtifactsRepo, baseTip: string, headTip: string): Promise { const { mergeBase, onlyHead } = await compareHistory(handle, baseTip, headTip); const commits = await Promise.all(onlyHead.map(async (commit) => ({ ...commit, files: await commitPaths(handle, commit.hash) }))); return compareCommits(handle, mergeBase, headTip, commits); } export async function commitDetail(handle: ArtifactsRepo, hash: string): Promise { const commit = await readCommit(handle, hash); if (!commit) return null; const changes = await compareCommits(handle, commit.parents[0] ?? null, hash); return { hash: commit.hash, message: commit.message, author: commit.author, committer: commit.committer, authoredAt: commit.authoredAt, committedAt: commit.committedAt, parents: commit.parents, changes, }; }