import type { CommitSummary, File, FileBody, RefList, Tree } from "./contract/views.ts"; import type { Refs } from "./git.ts"; import { encodePath, isCommitHash, repoLink } from "./contract/links.ts"; import { escapeHtml, renderMarkdown } from "./markdown.ts"; import { COMMITS_PER_PAGE } from "./contract/limits.ts"; const MAX_RENDERED_BYTES = 1024 * 1024; const README_PATTERN = /^readme(\.(md|markdown|txt))?$/i; const MARKDOWN_PATTERN = /\.(md|markdown)$/i; const IMAGE_TYPES: Record = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", ico: "image/x-icon" }; export function defaultRef(refs: Refs): string | null { if (refs.head && refs.branches.has(refs.head)) return refs.head; return refs.branches.keys().next().value ?? null; } export function listRefs(refs: Refs): RefList { return { defaultRef: defaultRef(refs), branches: [...refs.branches.keys()], tags: [...refs.tags.keys()] }; } function resolveRef(segments: string[], refs: Refs): { ref: string; path: string[] } | null { for (let i = segments.length; i > 0; i--) { const name = segments.slice(0, i).join("/"); if (refs.branches.has(name) || refs.tags.has(name)) return { ref: name, path: segments.slice(i) }; } if (isCommitHash(segments[0] ?? "")) return { ref: segments[0], path: segments.slice(1) }; return null; } export interface Located { ref: string; path: string[]; data: T; } /** Splits URL segments into a ref and a path. Loads speculatively with the first segment as the ref while the refs are fetched. */ export async function locate(refs: Promise, segments: string[], load: (ref: string, path: string[]) => Promise): Promise | null> { const guess = segments[0]; const speculative = guess ? load(guess, segments.slice(1)).catch(() => null) : null; const resolved = resolveRef(segments, await refs); if (!resolved) { await speculative; return null; } const data = resolved.ref === guess ? await speculative : (await Promise.all([speculative, load(resolved.ref, resolved.path)]))[1]; return data ? { ...resolved, data } : null; } function summarize(commit: ArtifactsCommitMetadata): CommitSummary { return { hash: commit.hash, title: commit.message.split("\n")[0], author: commit.author.name, committedAt: commit.committedAt }; } export async function readTreeAt(handle: ArtifactsRepo, treeHash: string, path: string[]): Promise { let hash = treeHash; for (const segment of path) { const entries = await handle.readTree(hash); const next = entries?.find((entry) => entry.name === segment && entry.type === "tree"); if (!next) return null; hash = next.hash; } return handle.readTree(hash); } function repoMarkdown(source: string, repo: string, ref: string, dir: string[]): string { return renderMarkdown(source, (href, kind) => { const [target, fragment] = href.split("#"); const base = href.startsWith("/") ? "http://repo/" : `http://repo/${encodePath(dir)}${dir.length ? "/" : ""}`; const segments = new URL(target, base).pathname.split("/").filter(Boolean).map(decodeURIComponent); return repoLink(repo, kind, ref, segments) + (fragment ? `#${fragment}` : ""); }); } export async function loadTree(handle: ArtifactsRepo, repo: string, ref: string, path: string[]): Promise { const readmeGuess = handle.readFile({ ref, path: [...path, "README.md"].join("/") }).catch(() => null); const [commit] = await handle.log({ ref, limit: 1 }); const entries = commit && (await readTreeAt(handle, commit.treeHash, path)); if (!commit || !entries) { await readmeGuess; return null; } const sorted = [...entries].sort((a, b) => Number(b.type === "tree") - Number(a.type === "tree") || a.name.localeCompare(b.name)); const readmeEntry = sorted.find((entry) => entry.type !== "tree" && README_PATTERN.test(entry.name)); const blob = !readmeEntry ? (await readmeGuess, null) : readmeEntry.name === "README.md" ? await readmeGuess : await handle.readBlob(readmeEntry.hash); let readme: Tree["readme"] = null; if (readmeEntry && blob && blob.size <= MAX_RENDERED_BYTES) { const text = await blob.text(); readme = { name: readmeEntry.name, html: MARKDOWN_PATTERN.test(readmeEntry.name) ? repoMarkdown(text, repo, ref, path) : `
${escapeHtml(text)}
` }; } return { location: { ref, path }, commit: summarize(commit), entries: sorted.map(({ name, type }) => ({ name, type })), readme }; } export async function tipCommit(handle: ArtifactsRepo, ref: string): Promise { const [commit] = await handle.log({ ref, limit: 1 }); return commit ? summarize(commit) : null; } export function imageType(name: string): string | undefined { return IMAGE_TYPES[name.split(".").pop()?.toLowerCase() ?? ""]; } export function isBinary(bytes: Uint8Array): boolean { return bytes.subarray(0, 8000).includes(0); } export async function readFileAt(handle: ArtifactsRepo, ref: string, path: string[]): Promise { return path.length === 0 ? null : handle.readFile({ ref, path: path.join("/") }); } export async function loadFile(handle: ArtifactsRepo, repo: string, ref: string, path: string[]): Promise { const file = await readFileAt(handle, ref, path); if (!file) return null; const name = path[path.length - 1]; const rawUrl = repoLink(repo, "raw", ref, path); const result = (body: FileBody): File => ({ location: { ref, path }, name, size: file.size, body }); if (imageType(name)) return result({ kind: "image", rawUrl }); if (file.size > MAX_RENDERED_BYTES) return result({ kind: "too_large", rawUrl }); const bytes = new Uint8Array(await file.arrayBuffer()); if (isBinary(bytes)) return result({ kind: "binary", rawUrl }); const text = new TextDecoder().decode(bytes); if (MARKDOWN_PATTERN.test(name)) return result({ kind: "markdown", html: repoMarkdown(text, repo, ref, path.slice(0, -1)) }); return result({ kind: "text", lines: text.replace(/\n$/, "").split("\n") }); } export async function loadCommits(handle: ArtifactsRepo, ref: string, page: number): Promise<{ commits: CommitSummary[]; hasOlder: boolean }> { const commits = await handle.log({ ref, limit: COMMITS_PER_PAGE + 1, offset: (page - 1) * COMMITS_PER_PAGE }); return { commits: commits.slice(0, COMMITS_PER_PAGE).map((commit) => ({ ...summarize(commit), message: commit.message })), hasOlder: commits.length > COMMITS_PER_PAGE }; } const HISTORY_WINDOW = 40; const HISTORY_LIMIT = 400; export async function lastChanges(handle: ArtifactsRepo, ref: string, path: string[], window = HISTORY_WINDOW): Promise> { const changes: Record = {}; let pending: Set | null = null; for (let offset = 0; offset < HISTORY_LIMIT; offset += window) { const commits = await handle.log({ ref, limit: window + 1, offset }); const trees = await Promise.all(commits.map((commit) => readTreeAt(handle, commit.treeHash, path).catch(() => null))); const hashes = trees.map((tree) => new Map((tree ?? []).map((entry) => [entry.name, entry.hash]))); pending ??= new Set(hashes[0]?.keys() ?? []); const endOfLog = commits.length <= window; const reachedRoot = endOfLog && commits.length > 0 && commits[commits.length - 1].parents.length === 0; for (const name of pending) { for (let i = 0; i < Math.min(window, commits.length); i++) { const older = i + 1 < commits.length ? hashes[i + 1].get(name) : undefined; if (i + 1 >= commits.length && !reachedRoot) break; if (hashes[i].get(name) !== older) { changes[name] = summarize(commits[i]); pending.delete(name); break; } } } if (pending.size === 0 || endOfLog) break; } return changes; }