1import type { Database } from "bun:sqlite";2import type { Hono } from "hono";3import { isText } from "../describe/describe.ts";4import {5 type FileEntry,6 filesAt,7 flagReason,8 objectBytes,9 type Save,10 saveByPrefix,11 visibleParent,12} from "../mirror/queries.ts";13import { diffLines, type Edit, hunks } from "./diff.ts";14import { highlightLines } from "./highlight.ts";15import { type Html, html } from "./html.ts";16import {17 browserPage,18 cacheFor,19 formatDate,20 notFound,21 openBrowserRepo,22 type PageContext,23 pathUrl,24 plural,25 relativeTime,26} from "./layout.ts";272829const DIFF_MAX_BYTES = 1024 * 1024;30const HIGHLIGHT_MAX_BYTES = 256 * 1024;313233const COLLAPSE_LINES = 300;34const PAGE_MAX_LINES = 5000;3536type Change = {37 path: string;38 status: "added" | "removed" | "modified";39 before: FileEntry | null;40 after: FileEntry | null;41};4243type FileDiff = Change & {44 kind: "text" | "binary" | "large";45 oldText: string;46 newText: string;47 edits: Edit[];48 added: number;49 removed: number;50 51 length: number;52};5354export function registerSavePage(app: Hono, ctx: PageContext): void {55 app.get("/:repo/saves/:id", async (c) => {56 const repo = openBrowserRepo(ctx, c, c.req.param("repo"));57 const id = c.req.param("id");58 const save = repo && saveByPrefix(repo.mirror, id);59 60 if (!repo || !save || save.is_checkpoint) return notFound(c, ctx);61 const name = repo.settings.name;62 if (save.id !== id) return c.redirect(`/${name}/saves/${save.id}`, 302);63 const parent = visibleParent(repo.mirror, save);64 65 66 let shown = 0;67 const diffs = changes(repo.mirror, save, parent).map((change) => {68 const brief = shown >= PAGE_MAX_LINES;69 const diff = fileDiff(repo.mirror, change, brief);70 if (!brief && shown + diff.length <= PAGE_MAX_LINES) shown += diff.length;71 return diff;72 });73 74 cacheFor(c, false);75 const [title = "", ...rest] = save.message.split("\n");76 return browserPage(c, ctx, {77 title: `${title} · ${name}`,78 description: `${save.id} · ${plural(diffs.length, "file")} changed`,79 path: `/${name}/saves/${save.id}`,80 body: html`<p class="breadcrumb mono"><a href="/${81 name82 }">${name}</a> / <a href="/${name}#history">history</a></p>83${saveHeader(repo.mirror, name, save, parent, title, rest.join("\n").trim())}84<section class="repo-section">85<details class="repo-section-toggle" open>86<summary class="section-head"><span class="section-label">files changed</span><span class="section-count">${plural(87 diffs.length,88 "file",89 )}</span></summary>90${91 diffs.length === 092 ? html`<p class="muted mono save-empty">no files changed</p>`93 : diffs.map((d, i) => changeRow(d, i))94}95</details>96</section>97<section class="repo-section">${await diffSections(name, save, parent, diffs)}</section>`,98 });99 });100}101102function saveHeader(103 db: Database,104 name: string,105 save: Save,106 parent: Save | null,107 title: string,108 body: string,109): Html {110 const reason = flagReason(db, save.id);111 const facts: [string, Html | string][] = [112 ["time", `${formatDate(save.created_at)} UTC · ${relativeTime(save.created_at)}`],113 ["machine", save.machine],114 ...(save.agent ? [["agent", save.agent] as [string, string]] : []),115 ...(save.session ? [["session", save.session] as [string, string]] : []),116 [117 "parent",118 parent119 ? html`<a href="/${name}/saves/${parent.id}">${parent.id}</a>`120 : "none, the first save",121 ],122 ];123 return html`<p class="save-id mono">${save.id}</p>124${125 reason !== null &&126 html`<p class="save-flag"><span class="save-flag-label mono">flagged</span> ${reason || "no reason given"}</p>`127}128<h1 class="save-message-head">${title}</h1>129${body && html`<p class="save-message-body">${body}</p>`}130<dl class="save-facts mono">${facts.map(131 ([term, value]) => html`<dt>${term}</dt><dd>${value}</dd>`,132 )}</dl>133<p class="save-links mono"><a href="/${134 name135 }/archive/${save.id}.tar.gz">↓ ${name}-${save.id.slice(0, 8)}.tar.gz</a><a href="/${name}?at=${save.id}#atlas">atlas at this save</a></p>`;136}137138function changes(db: Database, save: Save, parent: Save | null): Change[] {139 const before = new Map(parent ? filesAt(db, parent.id).map((f) => [f.path, f]) : []);140 const after = new Map(filesAt(db, save.id).map((f) => [f.path, f]));141 const paths = [...new Set([...before.keys(), ...after.keys()])].sort();142 return paths.flatMap((path) => {143 const old = before.get(path) ?? null;144 const now = after.get(path) ?? null;145 if (old && now && old.hash === now.hash && old.executable === now.executable) return [];146 const status = !old ? "added" : !now ? "removed" : "modified";147 return [{ path, status, before: old, after: now }];148 });149}150151function fileDiff(db: Database, change: Change, brief = false): FileDiff {152 const empty = { oldText: "", newText: "", edits: [], added: 0, removed: 0, length: 0 };153 const sides = [change.before, change.after];154 if (sides.some((f) => f && f.size > DIFF_MAX_BYTES))155 return { ...change, ...empty, kind: "large" };156 const [oldBytes, newBytes] = sides.map((f) => (f && objectBytes(db, f.hash)) ?? new Uint8Array());157 if (!isText(oldBytes as Uint8Array) || !isText(newBytes as Uint8Array)) {158 return { ...change, ...empty, kind: "binary" };159 }160 161 162 if (brief && (!change.before || !change.after)) {163 const count = lineCount(change.before ? oldBytes : newBytes);164 const gone = change.after ? 0 : count;165 const gained = change.before ? 0 : count;166 return {167 ...change,168 ...empty,169 kind: "text",170 added: gained,171 removed: gone,172 length: count === 0 ? 0 : count + 1,173 };174 }175 const oldText = new TextDecoder().decode(oldBytes);176 const newText = new TextDecoder().decode(newBytes);177 const edits = diffLines(compared(oldText), compared(newText));178 const added = edits.filter((e) => e.kind === "+").length;179 const removed = edits.filter((e) => e.kind === "-").length;180 const length = hunks(edits).reduce((sum, hunk) => sum + hunk.edits.length + 1, 0);181 return { ...change, kind: "text", oldText, newText, edits, added, removed, length };182}183184185function lineCount(bytes: Uint8Array): number {186 if (bytes.length === 0) return 0;187 let newlines = 0;188 for (const byte of bytes) if (byte === 0x0a) newlines++;189 return bytes[bytes.length - 1] === 0x0a ? newlines : newlines + 1;190}191192function lines(text: string): string[] {193 return text === "" ? [] : text.replace(/\n$/, "").split("\n");194}195196197198function compared(text: string): string[] {199 const split = lines(text);200 if (split.length > 0 && !text.endsWith("\n")) split[split.length - 1] += "\n";201 return split;202}203204function stat(d: FileDiff): Html {205 if (d.kind !== "text") return html`<span class="diff-note">${d.kind}</span>`;206 return html`<span class="diff-add">+${d.added}</span> <span class="diff-del">−${d.removed}</span>`;207}208209function changeRow(d: FileDiff, index: number): Html {210 return html`<a class="change-row change-${211 d.status212 }" href="#diff-${index}"><span class="change-path">${d.path}</span><span class="change-stat mono">${stat(d)}</span></a>`;213}214215async function diffSections(216 name: string,217 save: Save,218 parent: Save | null,219 diffs: FileDiff[],220): Promise<Html[]> {221 let shown = 0;222 const sections: Html[] = [];223 for (const [index, d] of diffs.entries()) {224 const at = d.status === "removed" ? parent?.id : save.id;225 const view = `/${name}/files/${pathUrl(d.path)}?at=${at}`;226 const hunkList = hunks(d.edits);227 const length = d.length;228 const mode =229 d.before && d.after && d.before.executable !== d.after.executable230 ? html`<p class="diff-note mono">${231 d.after.executable ? "now executable" : "no longer executable"232 }</p>`233 : "";234 let content: Html | string = "";235 if (d.kind === "binary") content = html`<p class="diff-note mono">binary file, not shown</p>`;236 else if (d.kind === "large") content = html`<p class="diff-note mono">over 1 MB, not shown</p>`;237 else if (shown + length > PAGE_MAX_LINES) {238 content = html`<p class="diff-note mono">not shown here: too long for one page</p>`;239 } else if (length > 0) {240 shown += length;241 content = await diffBody(d, hunkList);242 }243 sections.push(html`<details class="diff-file change-${244 d.status245 }" id="diff-${index}"${length <= COLLAPSE_LINES && " open"}>246<summary class="diff-head"><span class="change-path">${247 d.path248 }</span><span class="change-stat mono">${stat(d)}</span></summary>249${mode}${content}250<p class="diff-view mono"><a href="${251 view252 }">view file${d.status === "removed" && " at the parent"}</a></p>253</details>`);254 }255 return sections;256}257258async function diffBody(d: FileDiff, hunkList: ReturnType<typeof hunks>): Promise<Html> {259 const [oldLines, newLines] = await Promise.all([260 highlighted(d.oldText, d.path),261 highlighted(d.newText, d.path),262 ]);263 264 const unterminated = (text: string, count: number) =>265 text === "" || text.endsWith("\n") ? -1 : count - 1;266 const oldEnd = unterminated(d.oldText, oldLines.length);267 const newEnd = unterminated(d.newText, newLines.length);268 const row = (e: Edit) => {269 const code = e.kind === "-" ? oldLines[e.a] : newLines[e.b];270 const kind = e.kind === "+" ? "add" : e.kind === "-" ? "del" : "ctx";271 const bare = (e.kind !== "+" && e.a === oldEnd) || (e.kind !== "-" && e.b === newEnd);272 return html`<span class="dl dl-${273 kind274 }"><span class="ln">${e.kind !== "+" && e.a + 1}</span><span class="ln">${e.kind !== "-" && e.b + 1}</span><span class="ds">${e.kind}</span><span class="lc">${code}</span></span>${bare && html`<span class="dh">\\ No newline at end of file</span>`}`;275 };276 return html`<div class="file-view"><pre class="code diff"><code>${hunkList.map(277 (h) => html`<span class="dh">${h.header}</span>${h.edits.map(row)}`,278 )}</code></pre></div>`;279}280281function highlighted(text: string, path: string): Promise<Html[]> | Html[] {282 if (text.length > HIGHLIGHT_MAX_BYTES) return lines(text).map((line) => html`${line}`);283 return highlightLines(text, path);284}