165 lines · 7.7 KBRaw
| 1 | import type { CommitSummary, File, FileBody, RefList, Tree } from "./contract/views.ts"; |
| 2 | import type { Refs } from "./git.ts"; |
| 3 | import { encodePath, isCommitHash, repoLink } from "./contract/links.ts"; |
| 4 | import { escapeHtml, renderMarkdown } from "./markdown.ts"; |
| 5 | import { COMMITS_PER_PAGE } from "./contract/limits.ts"; |
| 6 | |
| 7 | const MAX_RENDERED_BYTES = 1024 * 1024; |
| 8 | const README_PATTERN = /^readme(\.(md|markdown|txt))?$/i; |
| 9 | const MARKDOWN_PATTERN = /\.(md|markdown)$/i; |
| 10 | const IMAGE_TYPES: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", ico: "image/x-icon" }; |
| 11 | |
| 12 | export function defaultRef(refs: Refs): string | null { |
| 13 | if (refs.head && refs.branches.has(refs.head)) return refs.head; |
| 14 | return refs.branches.keys().next().value ?? null; |
| 15 | } |
| 16 | |
| 17 | export function listRefs(refs: Refs): RefList { |
| 18 | return { defaultRef: defaultRef(refs), branches: [...refs.branches.keys()], tags: [...refs.tags.keys()] }; |
| 19 | } |
| 20 | |
| 21 | function resolveRef(segments: string[], refs: Refs): { ref: string; path: string[] } | null { |
| 22 | for (let i = segments.length; i > 0; i--) { |
| 23 | const name = segments.slice(0, i).join("/"); |
| 24 | if (refs.branches.has(name) || refs.tags.has(name)) return { ref: name, path: segments.slice(i) }; |
| 25 | } |
| 26 | if (isCommitHash(segments[0] ?? "")) return { ref: segments[0], path: segments.slice(1) }; |
| 27 | return null; |
| 28 | } |
| 29 | |
| 30 | export interface Located<T> { |
| 31 | ref: string; |
| 32 | path: string[]; |
| 33 | data: T; |
| 34 | } |
| 35 | |
| 36 | /** Splits URL segments into a ref and a path. Loads speculatively with the first segment as the ref while the refs are fetched. */ |
| 37 | export async function locate<T>(refs: Promise<Refs>, segments: string[], load: (ref: string, path: string[]) => Promise<T | null>): Promise<Located<T> | null> { |
| 38 | const guess = segments[0]; |
| 39 | const speculative = guess ? load(guess, segments.slice(1)).catch(() => null) : null; |
| 40 | const resolved = resolveRef(segments, await refs); |
| 41 | if (!resolved) { |
| 42 | await speculative; |
| 43 | return null; |
| 44 | } |
| 45 | |
| 46 | const data = resolved.ref === guess ? await speculative : (await Promise.all([speculative, load(resolved.ref, resolved.path)]))[1]; |
| 47 | return data ? { ...resolved, data } : null; |
| 48 | } |
| 49 | |
| 50 | function summarize(commit: ArtifactsCommitMetadata): CommitSummary { |
| 51 | return { hash: commit.hash, title: commit.message.split("\n")[0], author: commit.author.name, committedAt: commit.committedAt }; |
| 52 | } |
| 53 | |
| 54 | export async function readTreeAt(handle: ArtifactsRepo, treeHash: string, path: string[]): Promise<ArtifactsTreeEntry[] | null> { |
| 55 | let hash = treeHash; |
| 56 | for (const segment of path) { |
| 57 | const entries = await handle.readTree(hash); |
| 58 | const next = entries?.find((entry) => entry.name === segment && entry.type === "tree"); |
| 59 | if (!next) return null; |
| 60 | hash = next.hash; |
| 61 | } |
| 62 | return handle.readTree(hash); |
| 63 | } |
| 64 | |
| 65 | function repoMarkdown(source: string, repo: string, ref: string, dir: string[]): string { |
| 66 | return renderMarkdown(source, (href, kind) => { |
| 67 | const [target, fragment] = href.split("#"); |
| 68 | const base = href.startsWith("/") ? "http://repo/" : `http://repo/${encodePath(dir)}${dir.length ? "/" : ""}`; |
| 69 | const segments = new URL(target, base).pathname.split("/").filter(Boolean).map(decodeURIComponent); |
| 70 | return repoLink(repo, kind, ref, segments) + (fragment ? `#${fragment}` : ""); |
| 71 | }); |
| 72 | } |
| 73 | |
| 74 | export async function loadTree(handle: ArtifactsRepo, repo: string, ref: string, path: string[]): Promise<Tree | null> { |
| 75 | const readmeGuess = handle.readFile({ ref, path: [...path, "README.md"].join("/") }).catch(() => null); |
| 76 | const [commit] = await handle.log({ ref, limit: 1 }); |
| 77 | const entries = commit && (await readTreeAt(handle, commit.treeHash, path)); |
| 78 | if (!commit || !entries) { |
| 79 | await readmeGuess; |
| 80 | return null; |
| 81 | } |
| 82 | |
| 83 | const sorted = [...entries].sort((a, b) => Number(b.type === "tree") - Number(a.type === "tree") || a.name.localeCompare(b.name)); |
| 84 | const readmeEntry = sorted.find((entry) => entry.type !== "tree" && README_PATTERN.test(entry.name)); |
| 85 | const blob = !readmeEntry ? (await readmeGuess, null) : readmeEntry.name === "README.md" ? await readmeGuess : await handle.readBlob(readmeEntry.hash); |
| 86 | |
| 87 | let readme: Tree["readme"] = null; |
| 88 | if (readmeEntry && blob && blob.size <= MAX_RENDERED_BYTES) { |
| 89 | const text = await blob.text(); |
| 90 | readme = { name: readmeEntry.name, html: MARKDOWN_PATTERN.test(readmeEntry.name) ? repoMarkdown(text, repo, ref, path) : `<pre>${escapeHtml(text)}</pre>` }; |
| 91 | } |
| 92 | |
| 93 | return { location: { ref, path }, commit: summarize(commit), entries: sorted.map(({ name, type }) => ({ name, type })), readme }; |
| 94 | } |
| 95 | |
| 96 | export async function tipCommit(handle: ArtifactsRepo, ref: string): Promise<CommitSummary | null> { |
| 97 | const [commit] = await handle.log({ ref, limit: 1 }); |
| 98 | return commit ? summarize(commit) : null; |
| 99 | } |
| 100 | |
| 101 | export function imageType(name: string): string | undefined { |
| 102 | return IMAGE_TYPES[name.split(".").pop()?.toLowerCase() ?? ""]; |
| 103 | } |
| 104 | |
| 105 | export function isBinary(bytes: Uint8Array): boolean { |
| 106 | return bytes.subarray(0, 8000).includes(0); |
| 107 | } |
| 108 | |
| 109 | export async function readFileAt(handle: ArtifactsRepo, ref: string, path: string[]): Promise<Blob | null> { |
| 110 | return path.length === 0 ? null : handle.readFile({ ref, path: path.join("/") }); |
| 111 | } |
| 112 | |
| 113 | export async function loadFile(handle: ArtifactsRepo, repo: string, ref: string, path: string[]): Promise<File | null> { |
| 114 | const file = await readFileAt(handle, ref, path); |
| 115 | if (!file) return null; |
| 116 | |
| 117 | const name = path[path.length - 1]; |
| 118 | const rawUrl = repoLink(repo, "raw", ref, path); |
| 119 | const result = (body: FileBody): File => ({ location: { ref, path }, name, size: file.size, body }); |
| 120 | if (imageType(name)) return result({ kind: "image", rawUrl }); |
| 121 | if (file.size > MAX_RENDERED_BYTES) return result({ kind: "too_large", rawUrl }); |
| 122 | |
| 123 | const bytes = new Uint8Array(await file.arrayBuffer()); |
| 124 | if (isBinary(bytes)) return result({ kind: "binary", rawUrl }); |
| 125 | |
| 126 | const text = new TextDecoder().decode(bytes); |
| 127 | if (MARKDOWN_PATTERN.test(name)) return result({ kind: "markdown", html: repoMarkdown(text, repo, ref, path.slice(0, -1)) }); |
| 128 | return result({ kind: "text", lines: text.replace(/\n$/, "").split("\n") }); |
| 129 | } |
| 130 | |
| 131 | export async function loadCommits(handle: ArtifactsRepo, ref: string, page: number): Promise<{ commits: CommitSummary[]; hasOlder: boolean }> { |
| 132 | const commits = await handle.log({ ref, limit: COMMITS_PER_PAGE + 1, offset: (page - 1) * COMMITS_PER_PAGE }); |
| 133 | return { commits: commits.slice(0, COMMITS_PER_PAGE).map((commit) => ({ ...summarize(commit), message: commit.message })), hasOlder: commits.length > COMMITS_PER_PAGE }; |
| 134 | } |
| 135 | |
| 136 | const HISTORY_WINDOW = 40; |
| 137 | const HISTORY_LIMIT = 400; |
| 138 | |
| 139 | export async function lastChanges(handle: ArtifactsRepo, ref: string, path: string[], window = HISTORY_WINDOW): Promise<Record<string, CommitSummary>> { |
| 140 | const changes: Record<string, CommitSummary> = {}; |
| 141 | let pending: Set<string> | null = null; |
| 142 | |
| 143 | for (let offset = 0; offset < HISTORY_LIMIT; offset += window) { |
| 144 | const commits = await handle.log({ ref, limit: window + 1, offset }); |
| 145 | const trees = await Promise.all(commits.map((commit) => readTreeAt(handle, commit.treeHash, path).catch(() => null))); |
| 146 | const hashes = trees.map((tree) => new Map((tree ?? []).map((entry) => [entry.name, entry.hash]))); |
| 147 | pending ??= new Set(hashes[0]?.keys() ?? []); |
| 148 | const endOfLog = commits.length <= window; |
| 149 | const reachedRoot = endOfLog && commits.length > 0 && commits[commits.length - 1].parents.length === 0; |
| 150 | |
| 151 | for (const name of pending) { |
| 152 | for (let i = 0; i < Math.min(window, commits.length); i++) { |
| 153 | const older = i + 1 < commits.length ? hashes[i + 1].get(name) : undefined; |
| 154 | if (i + 1 >= commits.length && !reachedRoot) break; |
| 155 | if (hashes[i].get(name) !== older) { |
| 156 | changes[name] = summarize(commits[i]); |
| 157 | pending.delete(name); |
| 158 | break; |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | if (pending.size === 0 || endOfLog) break; |
| 163 | } |
| 164 | return changes; |
| 165 | } |