save.ts

10.8 KB · raw

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	cacheFor,18	formatDate,19	notFound,20	openPublicRepo,21	type PageContext,22	page,23	pathUrl,24	plural,25	relativeTime,26} from "./layout.ts";2728// A side over the file viewer's 1 MB is not diffed; past 256 KB it is shown without highlighting.29const DIFF_MAX_BYTES = 1024 * 1024;30const HIGHLIGHT_MAX_BYTES = 256 * 1024;31// A file's diff longer than this starts collapsed; once the page has shown this many lines, the32// remaining files are listed without their diffs so one huge save can't make a huge page.33const 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	/** The lines this file's diff would show, which is what the page's limit counts. */51	length: number;52};5354export function registerSavePage(app: Hono, ctx: PageContext): void {55	app.get("/:repo/saves/:id", async (c) => {56		const repo = openPublicRepo(ctx, c.req.param("repo"));57		const id = c.req.param("id");58		const save = repo && saveByPrefix(repo.mirror, id);59		// Checkpoints never appear (§21.4), so a link to one finds nothing, like an unknown ID.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		// Past the page's line limit no file can be shown, so nothing more is diffed: a first import65		// of thousands of files costs only the files this page shows.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		// Not a year like other per-save content: a flag or a strip can arrive for this save later.74		cacheFor(c, false);75		const [title = "", ...rest] = save.message.split("\n");76		return c.html(77			page(ctx, {78				title: `${title} · ${name}`,79				description: `${save.id} · ${plural(diffs.length, "file")} changed`,80				path: `/${name}/saves/${save.id}`,81				body: html`<p class="breadcrumb mono"><a href="/${82					name83				}">${name}</a> / <a href="/${name}#history">history</a></p>84${saveHeader(repo.mirror, name, save, parent, title, rest.join("\n").trim())}85<section class="repo-section">86<details class="repo-section-toggle" open>87<summary class="section-head"><span class="section-label">files changed</span><span class="section-count">${plural(88					diffs.length,89					"file",90				)}</span></summary>91${92	diffs.length === 093		? html`<p class="muted mono save-empty">no files changed</p>`94		: diffs.map((d, i) => changeRow(d, i))95}96</details>97</section>98<section class="repo-section">${await diffSections(name, save, parent, diffs)}</section>`,99			}),100		);101	});102}103104function saveHeader(105	db: Database,106	name: string,107	save: Save,108	parent: Save | null,109	title: string,110	body: string,111): Html {112	const reason = flagReason(db, save.id);113	const facts: [string, Html | string][] = [114		["time", `${formatDate(save.created_at)} UTC · ${relativeTime(save.created_at)}`],115		["machine", save.machine],116		...(save.agent ? [["agent", save.agent] as [string, string]] : []),117		...(save.session ? [["session", save.session] as [string, string]] : []),118		[119			"parent",120			parent121				? html`<a href="/${name}/saves/${parent.id}">${parent.id}</a>`122				: "none, the first save",123		],124	];125	return html`<p class="save-id mono">${save.id}</p>126${127	reason !== null &&128	html`<p class="save-flag"><span class="save-flag-label mono">flagged</span> ${reason || "no reason given"}</p>`129}130<h1 class="save-message-head">${title}</h1>131${body && html`<p class="save-message-body">${body}</p>`}132<dl class="save-facts mono">${facts.map(133		([term, value]) => html`<dt>${term}</dt><dd>${value}</dd>`,134	)}</dl>135<p class="save-links mono"><a href="/${136		name137	}/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>`;138}139140function changes(db: Database, save: Save, parent: Save | null): Change[] {141	const before = new Map(parent ? filesAt(db, parent.id).map((f) => [f.path, f]) : []);142	const after = new Map(filesAt(db, save.id).map((f) => [f.path, f]));143	const paths = [...new Set([...before.keys(), ...after.keys()])].sort();144	return paths.flatMap((path) => {145		const old = before.get(path) ?? null;146		const now = after.get(path) ?? null;147		if (old && now && old.hash === now.hash && old.executable === now.executable) return [];148		const status = !old ? "added" : !now ? "removed" : "modified";149		return [{ path, status, before: old, after: now }];150	});151}152153function fileDiff(db: Database, change: Change, brief = false): FileDiff {154	const empty = { oldText: "", newText: "", edits: [], added: 0, removed: 0, length: 0 };155	const sides = [change.before, change.after];156	if (sides.some((f) => f && f.size > DIFF_MAX_BYTES))157		return { ...change, ...empty, kind: "large" };158	const [oldBytes, newBytes] = sides.map((f) => (f && objectBytes(db, f.hash)) ?? new Uint8Array());159	if (!isText(oldBytes as Uint8Array) || !isText(newBytes as Uint8Array)) {160		return { ...change, ...empty, kind: "binary" };161	}162	// An added or removed file's counts are its own lines, so a file past the page's limit needs no163	// diff to show them; a modified one's counts are only known from the edits, so it is diffed.164	if (brief && (!change.before || !change.after)) {165		const count = lineCount(change.before ? oldBytes : newBytes);166		const gone = change.after ? 0 : count;167		const gained = change.before ? 0 : count;168		return {169			...change,170			...empty,171			kind: "text",172			added: gained,173			removed: gone,174			length: count === 0 ? 0 : count + 1,175		};176	}177	const oldText = new TextDecoder().decode(oldBytes);178	const newText = new TextDecoder().decode(newBytes);179	const edits = diffLines(compared(oldText), compared(newText));180	const added = edits.filter((e) => e.kind === "+").length;181	const removed = edits.filter((e) => e.kind === "-").length;182	const length = hunks(edits).reduce((sum, hunk) => sum + hunk.edits.length + 1, 0);183	return { ...change, kind: "text", oldText, newText, edits, added, removed, length };184}185186/** What `lines()` would count, from the bytes: a final newline ends the last line, it adds none. */187function lineCount(bytes: Uint8Array): number {188	if (bytes.length === 0) return 0;189	let newlines = 0;190	for (const byte of bytes) if (byte === 0x0a) newlines++;191	return bytes[bytes.length - 1] === 0x0a ? newlines : newlines + 1;192}193194function lines(text: string): string[] {195	return text === "" ? [] : text.replace(/\n$/, "").split("\n");196}197198// A last line without its newline differs from the same line with one, as in GNU diff: a newline199// can never occur inside a split line, so it marks the ending for the comparison alone.200function compared(text: string): string[] {201	const split = lines(text);202	if (split.length > 0 && !text.endsWith("\n")) split[split.length - 1] += "\n";203	return split;204}205206function stat(d: FileDiff): Html {207	if (d.kind !== "text") return html`<span class="diff-note">${d.kind}</span>`;208	return html`<span class="diff-add">+${d.added}</span> <span class="diff-del">−${d.removed}</span>`;209}210211function changeRow(d: FileDiff, index: number): Html {212	return html`<a class="change-row change-${213		d.status214	}" href="#diff-${index}"><span class="change-path">${d.path}</span><span class="change-stat mono">${stat(d)}</span></a>`;215}216217async function diffSections(218	name: string,219	save: Save,220	parent: Save | null,221	diffs: FileDiff[],222): Promise<Html[]> {223	let shown = 0;224	const sections: Html[] = [];225	for (const [index, d] of diffs.entries()) {226		const at = d.status === "removed" ? parent?.id : save.id;227		const view = `/${name}/files/${pathUrl(d.path)}?at=${at}`;228		const hunkList = hunks(d.edits);229		const length = d.length;230		const mode =231			d.before && d.after && d.before.executable !== d.after.executable232				? html`<p class="diff-note mono">${233						d.after.executable ? "now executable" : "no longer executable"234					}</p>`235				: "";236		let content: Html | string = "";237		if (d.kind === "binary") content = html`<p class="diff-note mono">binary file, not shown</p>`;238		else if (d.kind === "large") content = html`<p class="diff-note mono">over 1 MB, not shown</p>`;239		else if (shown + length > PAGE_MAX_LINES) {240			content = html`<p class="diff-note mono">not shown here: too long for one page</p>`;241		} else if (length > 0) {242			shown += length;243			content = await diffBody(d, hunkList);244		}245		sections.push(html`<details class="diff-file change-${246			d.status247		}" id="diff-${index}"${length <= COLLAPSE_LINES && " open"}>248<summary class="diff-head"><span class="change-path">${249			d.path250		}</span><span class="change-stat mono">${stat(d)}</span></summary>251${mode}${content}252<p class="diff-view mono"><a href="${253			view254		}">view file${d.status === "removed" && " at the parent"}</a></p>255</details>`);256	}257	return sections;258}259260async function diffBody(d: FileDiff, hunkList: ReturnType<typeof hunks>): Promise<Html> {261	const [oldLines, newLines] = await Promise.all([262		highlighted(d.oldText, d.path),263		highlighted(d.newText, d.path),264	]);265	// The last line of a side that doesn't end in a newline, or -1 when it does.266	const unterminated = (text: string, count: number) =>267		text === "" || text.endsWith("\n") ? -1 : count - 1;268	const oldEnd = unterminated(d.oldText, oldLines.length);269	const newEnd = unterminated(d.newText, newLines.length);270	const row = (e: Edit) => {271		const code = e.kind === "-" ? oldLines[e.a] : newLines[e.b];272		const kind = e.kind === "+" ? "add" : e.kind === "-" ? "del" : "ctx";273		const bare = (e.kind !== "+" && e.a === oldEnd) || (e.kind !== "-" && e.b === newEnd);274		return html`<span class="dl dl-${275			kind276		}"><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>`}`;277	};278	return html`<div class="file-view"><pre class="code diff"><code>${hunkList.map(279		(h) => html`<span class="dh">${h.header}</span>${h.edits.map(row)}`,280	)}</code></pre></div>`;281}282283function highlighted(text: string, path: string): Promise<Html[]> | Html[] {284	if (text.length > HIGHLIGHT_MAX_BYTES) return lines(text).map((line) => html`${line}`);285	return highlightLines(text, path);286}