// HISTORY AND DIFF: what a hosting twin's REST plane asks of the object store beyond raw reads — // the merge base of two commits, the changed-file list between two commits with GitHub's // three-dot semantics (merge-base(base, head)..head), per-file addition/deletion counts and a // unified patch from a Myers line diff. Pure functions of the store; the `git` binary is the // oracle these were proven against, never a dependency. import { GitObjectStore, decodeCommit, decodeTree, type TreeEntry } from './objects.ts'; async function parentsOf(store: GitObjectStore, sha: string): Promise { const o = await store.read(sha); return o?.type === 'commit' ? decodeCommit(o.payload).parents : []; } /** Ancestors of `sha` (inclusive), bounded. */ async function ancestors(store: GitObjectStore, sha: string, limit: number): Promise> { const seen = new Set(); const stack = [sha]; while (stack.length && seen.size < limit) { const s = stack.pop()!; if (seen.has(s)) continue; seen.add(s); stack.push(...(await parentsOf(store, s))); } return seen; } /** A best common ancestor of `a` and `b` (one that is not an ancestor of another common ancestor), or null. */ export async function mergeBase(store: GitObjectStore, a: string, b: string, limit = 20000): Promise { if (!(await store.has(a)) || !(await store.has(b))) return null; const ofA = await ancestors(store, a, limit); // BFS from b in parent order: the first commits reached that lie in A's ancestry are candidates; a // candidate reached through another candidate is dominated and dropped. const candidates: string[] = []; const seen = new Set(); const queue = [b]; while (queue.length && seen.size < limit) { const s = queue.shift()!; if (seen.has(s)) continue; seen.add(s); if (ofA.has(s)) { candidates.push(s); continue; } queue.push(...(await parentsOf(store, s))); } if (candidates.length === 0) return null; if (candidates.length === 1) return candidates[0]!; const dominated = new Set(); for (const c of candidates) { const anc = await ancestors(store, c, limit); for (const d of candidates) if (d !== c && anc.has(d)) dominated.add(d); } return candidates.find((c) => !dominated.has(c)) ?? candidates[0]!; } export type TreeChange = { path: string; status: 'added' | 'removed' | 'modified'; oldSha?: string; newSha?: string; oldMode?: string; newMode?: string }; async function treeOf(store: GitObjectStore, sha: string): Promise { const o = await store.read(sha); if (!o) return []; if (o.type === 'commit') return treeOf(store, decodeCommit(o.payload).tree); return o.type === 'tree' ? decodeTree(o.payload) : []; } const isDir = (m: string) => m === '40000' || m === '040000'; /** Recursive tree compare between two commits or trees (paths in the post-image order, no rename pairing — like `diff-tree -r` without -M). */ export async function diffTrees(store: GitObjectStore, from: string | null, to: string, prefix = ''): Promise { const a = from ? await treeOf(store, from) : []; const b = await treeOf(store, to); const byName = new Map(a.map((e) => [e.name, e])); const out: TreeChange[] = []; const seenNames = new Set(); const all = [...a.map((e) => e.name), ...b.map((e) => e.name)].filter((n) => (seenNames.has(n) ? false : (seenNames.add(n), true))).sort(); const bByName = new Map(b.map((e) => [e.name, e])); for (const name of all) { const ax = byName.get(name), by = bByName.get(name); const path = prefix + name; if (ax && by && ax.sha === by.sha && ax.mode === by.mode) continue; const xd = ax ? isDir(ax.mode) : false, yd = by ? isDir(by.mode) : false; if (xd || yd) { if (xd && yd) out.push(...(await diffTrees(store, ax!.sha, by!.sha, `${path}/`))); else { if (xd) out.push(...(await diffTrees(store, ax!.sha, '4b825dc642cb6eb9a060e54bf8d69288fbee4904', `${path}/`)).map((c) => ({ ...c }))); else if (ax) out.push({ path, status: 'removed', oldSha: ax.sha, oldMode: ax.mode }); if (yd) out.push(...(await diffTrees(store, null, by!.sha, `${path}/`))); else if (by) out.push({ path, status: 'added', newSha: by.sha, newMode: by.mode }); } continue; } if (ax && by) out.push({ path, status: 'modified', oldSha: ax.sha, newSha: by.sha, oldMode: ax.mode, newMode: by.mode }); else if (ax) out.push({ path, status: 'removed', oldSha: ax.sha, oldMode: ax.mode }); else if (by) out.push({ path, status: 'added', newSha: by.sha, newMode: by.mode }); } return out; } // ── Myers line diff ───────────────────────────────────────────────────────────────────── export type Edit = { kind: ' ' | '-' | '+'; line: string }; function splitLines(text: string): string[] { if (text === '') return []; const lines = text.split('\n'); if (lines[lines.length - 1] === '') lines.pop(); return lines; } /** A shortest edit script between two texts (Myers, O((N+M)D)). */ export function lineDiff(oldText: string, newText: string): Edit[] { const a = splitLines(oldText), b = splitLines(newText); const n = a.length, m = b.length; const max = n + m; const v = new Map([[1, 0]]); const trace: Map[] = []; outer: for (let d = 0; d <= max; d++) { trace.push(new Map(v)); for (let k = -d; k <= d; k += 2) { let ax = k === -d || (k !== d && (v.get(k - 1) ?? 0) < (v.get(k + 1) ?? 0)) ? (v.get(k + 1) ?? 0) : (v.get(k - 1) ?? 0) + 1; let by = ax - k; while (ax < n && by < m && a[ax] === b[by]) { ax++; by++; } v.set(k, ax); if (ax >= n && by >= m) break outer; } } const edits: Edit[] = []; let ax = n, by = m; for (let d = trace.length - 1; d >= 0; d--) { const vv = trace[d]!; const k = ax - by; const prevK = k === -d || (k !== d && (vv.get(k - 1) ?? 0) < (vv.get(k + 1) ?? 0)) ? k + 1 : k - 1; const prevX = vv.get(prevK) ?? 0; const prevY = prevX - prevK; while (ax > prevX && by > prevY) { edits.push({ kind: ' ', line: a[ax - 1]! }); ax--; by--; } if (d > 0) { if (ax === prevX) { edits.push({ kind: '+', line: b[by - 1]! }); by--; } else { edits.push({ kind: '-', line: a[ax - 1]! }); ax--; } } } return edits.reverse(); } /** The unified-diff hunks (the body GitHub serves as a file's `patch`), 3 lines of context. */ export function unifiedPatch(oldText: string, newText: string, context = 3): string { const edits = lineDiff(oldText, newText); if (!edits.some((e) => e.kind !== ' ')) return ''; const oldNoNl = oldText !== '' && !oldText.endsWith('\n'), newNoNl = newText !== '' && !newText.endsWith('\n'); const oldLines = splitLines(oldText).length, newLines = splitLines(newText).length; // group edits into hunks: a run of changes with up to `context` unchanged lines around it const hunks: Array<{ start: number; end: number }> = []; let i = 0; while (i < edits.length) { if (edits[i]!.kind === ' ') { i++; continue; } const start = Math.max(0, i - context); let end = i; while (end < edits.length) { if (edits[end]!.kind !== ' ') { end++; continue; } let run = end; while (run < edits.length && edits[run]!.kind === ' ') run++; if (run - end > context * 2 || run >= edits.length) { end = Math.min(edits.length, end + context); break; } end = run; } hunks.push({ start, end }); i = end; } let oldPos = 0, newPos = 0, out = ''; let cursor = 0; for (const h of hunks) { for (; cursor < h.start; cursor++) { const e = edits[cursor]!; if (e.kind !== '+') oldPos++; if (e.kind !== '-') newPos++; } let oc = 0, nc = 0, body = ''; for (let j = h.start; j < h.end; j++) { const e = edits[j]!; body += `${e.kind}${e.line}\n`; const lastOld = e.kind !== '+' && oldPos + oc === oldLines - 1, lastNew = e.kind !== '-' && newPos + nc === newLines - 1; if (e.kind !== '+') oc++; if (e.kind !== '-') nc++; if ((e.kind === '-' && lastOld && oldNoNl) || (e.kind === '+' && lastNew && newNoNl) || (e.kind === ' ' && lastOld && oldNoNl && lastNew && newNoNl)) body += '\\ No newline at end of file\n'; } const range = (p: number, c: number) => (c === 1 ? `${p + 1}` : `${c === 0 ? p : p + 1},${c}`); out += `@@ -${range(oldPos, oc)} +${range(newPos, nc)} @@\n${body}`; oldPos += oc; newPos += nc; cursor = h.end; } return out.replace(/\n$/, ''); } export type DiffFile = { filename: string; status: 'added' | 'removed' | 'modified'; additions: number; deletions: number; sha?: string; patch?: string }; const DEC = new TextDecoder(); function looksBinary(bytes: Uint8Array): boolean { const n = Math.min(bytes.length, 8000); for (let i = 0; i < n; i++) if (bytes[i] === 0) return true; return false; } /** GitHub's file list between `base` and `head` (three-dot: from merge-base(base, head), or base when histories are unrelated), with counts and patches. */ export async function diffFiles(store: GitObjectStore, baseSha: string, headSha: string, opts: { patch?: boolean } = {}): Promise { if (!(await store.has(baseSha)) || !(await store.has(headSha))) return null; const from = (await mergeBase(store, baseSha, headSha)) ?? baseSha; const out: DiffFile[] = []; for (const c of await diffTrees(store, from, headSha)) { const oldB = c.oldSha ? (await store.read(c.oldSha))?.payload ?? new Uint8Array() : new Uint8Array(); const newB = c.newSha ? (await store.read(c.newSha))?.payload ?? new Uint8Array() : new Uint8Array(); const file: DiffFile = { filename: c.path, status: c.status, additions: 0, deletions: 0, ...(c.newSha ? { sha: c.newSha } : {}) }; if (!looksBinary(oldB) && !looksBinary(newB)) { const oldT = DEC.decode(oldB), newT = DEC.decode(newB); const edits = lineDiff(oldT, newT); file.additions = edits.filter((e) => e.kind === '+').length; file.deletions = edits.filter((e) => e.kind === '-').length; if (opts.patch) { const p = unifiedPatch(oldT, newT); if (p) file.patch = p; } } out.push(file); } return out; } /** Three-way line merge. Return null for overlapping edits; preserve exact line endings. * Binary payloads belong to the caller's conflict path, never a text decoder's replacement. */ export function mergeText(base: string, ours: string, theirs: string): string | null { if (ours === theirs || theirs === base) return ours; if (ours === base) return theirs; type Hunk = { start: number; end: number; lines: string[] }; // Encode whole lines, including their terminators, before diffing. Thus changing the final // newline is a real edit and CRLF bytes survive without a separate post-merge guess. const lines = (text: string): string[] => (text.match(/[^\n]*\n|[^\n]+$/g) ?? []).map(s => JSON.stringify(s)); const original = lines(base); const changes = (text: string): Hunk[] => { const out: Hunk[] = []; let cursor = 0; let hunk: Hunk | undefined; for (const edit of lineDiff(original.join('\n'), lines(text).join('\n'))) { if (edit.kind === ' ') { hunk = undefined; cursor++; continue; } if (!hunk) { hunk = { start: cursor, end: cursor, lines: [] }; out.push(hunk); } if (edit.kind === '-') { cursor++; hunk.end++; } else hunk.lines.push(edit.line); } return out; }; const left = changes(ours), right = changes(theirs); const identical = (a: Hunk, b: Hunk) => a.start === b.start && a.end === b.end && JSON.stringify(a.lines) === JSON.stringify(b.lines); const edits = [...left]; for (const b of right) { if (left.some(a => identical(a, b))) continue; for (const a of left) { // Two insertions at one point or touching changed intervals have ambiguous order. if (a.start <= b.end && b.start <= a.end) return null; } edits.push(b); } edits.sort((a, b) => b.start - a.start); const result = [...original]; for (const h of edits) result.splice(h.start, h.end - h.start, ...h.lines); return result.map(line => JSON.parse(line) as string).join(''); } /** The blob at a path in a commit (walking its trees segment by segment), or null when the commit, a directory on the * way or the file is not there. A host that serves a file at a revision (the Hugging Face Hub's `resolve`) reads it. */ export async function blobAt(store: GitObjectStore, commit: string, path: string): Promise<{ sha: string; mode: string; bytes: Uint8Array } | null> { const c = await store.read(commit); if (!c || c.type !== 'commit') return null; let tree = decodeCommit(c.payload).tree; const parts = path.split('/').filter(Boolean); for (const [i, name] of parts.entries()) { const t = await store.read(tree); if (!t || t.type !== 'tree') return null; const e = decodeTree(t.payload).find((x) => x.name === name); if (!e) return null; if (i < parts.length - 1) { tree = e.sha; continue; } const b = await store.read(e.sha); return b && b.type === 'blob' ? { sha: e.sha, mode: e.mode, bytes: b.payload } : null; } return null; }