| @@ -1,8 +1,11 @@ |
| | //! Read-only web browser for GITv repositories, served on localhost behind Caddy. |
| | |
| | use std::cell::OnceCell; |
| | use std::cmp::Reverse; |
| | use std::collections::HashMap; |
| | use std::fmt::Write as _; |
| | use std::path::PathBuf; |
| | use std::sync::{Arc, LazyLock, Mutex}; |
| | use std::time::{SystemTime, UNIX_EPOCH}; |
| | |
| | use axum::extract::{Path, Query}; |
| @@ -22,7 +25,7 @@ const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3 |
| | |
| | /// The stylesheet's URL carries a hash of its contents, so browsers can cache it for good and |
| | /// still pick up every change. |
| | static STYLE_URL: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| { |
| | static STYLE_URL: LazyLock<String> = LazyLock::new(|| { |
| | use std::hash::{Hash, Hasher}; |
| | let mut hasher = std::hash::DefaultHasher::new(); |
| | STYLESHEET.hash(&mut hasher); |
| @@ -33,9 +36,40 @@ static STYLE_URL: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| { |
| | const LOGO: &str = r#"<svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>"#; |
| | |
| | const PAGE: usize = 50; |
| | /// Largest file the Raw view serves; bigger files are for `git clone`. |
| | const RAW_LIMIT: usize = 50 << 20; |
| | /// Largest file shown on a page; bigger files offer Raw instead. |
| | const SHOW_LIMIT: usize = 1 << 20; |
| | const DIFF_LIMIT: usize = 2 << 20; |
| | |
| | /// Rendered HTML and commit counts keyed by immutable object ids, so repeat views skip the |
| | /// expensive work. Emptied whenever it outgrows its budget. |
| | #[derive(Default)] |
| | struct Cache { |
| | entries: HashMap<String, Arc<str>>, |
| | bytes: usize, |
| | } |
| | |
| | static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(Default::default); |
| | const CACHE_BUDGET: usize = 32 << 20; |
| | |
| | fn cached(key: String, make: impl FnOnce() -> String) -> Arc<str> { |
| | if let Some(hit) = CACHE.lock().ok().and_then(|c| c.entries.get(&key).cloned()) { |
| | return hit; |
| | } |
| | let value: Arc<str> = make().into(); |
| | if let Ok(mut cache) = CACHE.lock() { |
| | let cost = key.len() + value.len(); |
| | if cache.bytes + cost > CACHE_BUDGET { |
| | cache.entries.clear(); |
| | cache.bytes = 0; |
| | } |
| | cache.bytes += cost; |
| | cache.entries.insert(key, Arc::clone(&value)); |
| | } |
| | value |
| | } |
| | |
| | #[derive(Parser)] |
| | #[command(about = "Read-only web browser for GITv repositories")] |
| | struct Cli { |
| @@ -56,7 +90,8 @@ type Q = HashMap<String, String>; |
| | |
| | enum View { |
| | Html(String), |
| | Raw(Vec<u8>, &'static str), |
| | /// Bytes, content type, and a download name for files the browser shouldn't display. |
| | Raw(Vec<u8>, &'static str, Option<String>), |
| | Redirect(String), |
| | Missing, |
| | } |
| @@ -74,7 +109,15 @@ impl IntoResponse for View { |
| | let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")]; |
| | match self { |
| | View::Html(body) => (SECURITY, html, body).into_response(), |
| | View::Raw(data, kind) => (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response(), |
| | View::Raw(data, kind, download) => { |
| | let mut response = (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response(); |
| | if let Some(value) = download |
| | .and_then(|name| format!("attachment; filename*=UTF-8''{}", encode(&name)).parse().ok()) |
| | { |
| | response.headers_mut().insert(header::CONTENT_DISPOSITION, value); |
| | } |
| | response |
| | } |
| | View::Redirect(to) => Redirect::to(&to).into_response(), |
| | View::Missing => (StatusCode::NOT_FOUND, SECURITY, html, view_missing()).into_response(), |
| | } |
| @@ -104,6 +147,7 @@ fn icon(name: &str) -> String { |
| | "commits" => r#"<circle cx="8" cy="8" r="2.4"/><path d="M1.5 8h4.1M10.4 8h4.1"/>"#, |
| | "chevron" => r#"<path d="M4.5 6.5 8 10l3.5-3.5"/>"#, |
| | "up" => r#"<path d="M8 13V3.5M4 7.5l4-4 4 4"/>"#, |
| | "module" => r#"<rect x="2.5" y="2.5" width="11" height="11" rx="2"/><path d="M5.5 8h5M8 5.5v5"/>"#, |
| | _ => "", |
| | }; |
| | format!(r#"<svg class="ic" viewBox="0 0 16 16" aria-hidden="true">{path}</svg>"#) |
| @@ -192,6 +236,8 @@ struct Repo { |
| | owner: String, |
| | name: String, |
| | path: PathBuf, |
| | heads: OnceCell<Vec<String>>, |
| | tags: OnceCell<Vec<String>>, |
| | } |
| | |
| | /// The newest commit on a ref: full hash, subject, author, unix time, short date. |
| @@ -209,7 +255,13 @@ impl Repo { |
| | return None; |
| | } |
| | let path = repos_root().join(owner).join(format!("{name}.git")); |
| | path.join("HEAD").is_file().then(|| Repo { owner: owner.into(), name: name.into(), path }) |
| | path.join("HEAD").is_file().then(|| Repo { |
| | owner: owner.into(), |
| | name: name.into(), |
| | path, |
| | heads: OnceCell::new(), |
| | tags: OnceCell::new(), |
| | }) |
| | } |
| | |
| | fn git(&self, args: &[&str]) -> Option<String> { |
| @@ -223,8 +275,19 @@ impl Repo { |
| | if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) } |
| | } |
| | |
| | /// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch. |
| | fn default_ref(&self) -> String { |
| | self.git(&["symbolic-ref", "--short", "HEAD"]).map_or("HEAD".into(), |s| s.trim().into()) |
| | let head = self.git(&["symbolic-ref", "--short", "HEAD"]).map(|s| s.trim().to_string()); |
| | let heads = self.heads(); |
| | if let Some(head) = head.filter(|h| heads.contains(h)) { |
| | return head; |
| | } |
| | ["main", "master"] |
| | .into_iter() |
| | .map(String::from) |
| | .find(|b| heads.contains(b)) |
| | .or_else(|| heads.first().cloned()) |
| | .unwrap_or_else(|| "HEAD".into()) |
| | } |
| | |
| | fn list_refs(&self, namespace: &str) -> Vec<String> { |
| @@ -233,6 +296,14 @@ impl Repo { |
| | .unwrap_or_default() |
| | } |
| | |
| | fn heads(&self) -> &[String] { |
| | self.heads.get_or_init(|| self.list_refs("refs/heads")) |
| | } |
| | |
| | fn tags(&self) -> &[String] { |
| | self.tags.get_or_init(|| self.list_refs("refs/tags")) |
| | } |
| | |
| | /// The commit a ref names, rejecting anything that could read as an option or range. |
| | fn resolve(&self, reference: &str) -> Option<String> { |
| | let ok = (1..=200).contains(&reference.len()) |
| @@ -246,15 +317,25 @@ impl Repo { |
| | self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into()) |
| | } |
| | |
| | fn latest(&self, rev: &str) -> Option<Head> { |
| | let out = self.git(&["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"])?; |
| | /// The newest commit on `rev` that touched `path` (the whole tree when empty). |
| | fn latest(&self, rev: &str, path: &str) -> Option<Head> { |
| | let mut args = vec!["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"]; |
| | if !path.is_empty() { |
| | args.push(path); |
| | } |
| | let out = self.git(&args)?; |
| | let f: Vec<&str> = out.trim_end().split('\x1f').collect(); |
| | let [oid, subject, author, stamp, date] = <[&str; 5]>::try_from(f).ok()?; |
| | Some(Head { oid: oid.into(), subject: subject.into(), author: author.into(), stamp: stamp.into(), date: date.into() }) |
| | } |
| | |
| | fn commit_count(&self, rev: &str) -> usize { |
| | self.git(&["rev-list", "--count", rev, "--"]).and_then(|s| s.trim().parse().ok()).unwrap_or(0) |
| | /// Commits reachable from `commit`. A commit's history never changes, so the count is cached. |
| | fn commit_count(&self, commit: &str) -> usize { |
| | let key = format!("count:{}:{commit}", self.path.display()); |
| | let count = cached(key, || { |
| | self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string()).unwrap_or_default() |
| | }); |
| | count.parse().unwrap_or(0) |
| | } |
| | |
| | /// Tag names grouped by the commit they point at, for labelling history. |
| @@ -286,7 +367,7 @@ impl Repo { |
| | /// Name, clone address and tabs, shared by every repository page. |
| | fn masthead(&self, active: &str, reference: &str) -> String { |
| | let commits = self.resolve(reference).map_or(0, |c| self.commit_count(&c)); |
| | let tags = self.list_refs("refs/tags").len(); |
| | let tags = self.tags().len(); |
| | let tab = |view: &str, glyph: &str, label: &str, count: Option<usize>| { |
| | let current = if view == active { r#" aria-current="page""# } else { "" }; |
| | let query: &[(&str, &str)] = if view == "tags" { &[] } else { &[("ref", reference)] }; |
| @@ -313,8 +394,8 @@ impl Repo { |
| | let href = self.url(view, &[("ref", name), ("path", path)]); |
| | format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name)) |
| | }; |
| | let branches: String = self.list_refs("refs/heads").iter().map(item).collect(); |
| | let tags: String = self.list_refs("refs/tags").iter().map(item).collect(); |
| | let branches: String = self.heads().iter().map(item).collect(); |
| | let tags: String = self.tags().iter().map(item).collect(); |
| | let mut menu = format!("<h2>Branches</h2>{branches}"); |
| | if !tags.is_empty() { |
| | menu += &format!("<h2>Tags</h2>{tags}"); |
| @@ -370,11 +451,11 @@ fn view_index() -> View { |
| | for entry in sorted_dir(&root.join(&owner)) { |
| | let Some(name) = entry.strip_suffix(".git") else { continue }; |
| | let Some(repo) = Repo::open(&owner, name) else { continue }; |
| | let head = repo.latest(&repo.default_ref()); |
| | let head = repo.latest(&repo.default_ref(), ""); |
| | rows.push((head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0), repo, head)); |
| | } |
| | } |
| | rows.sort_by(|a, b| b.0.cmp(&a.0)); |
| | rows.sort_by_key(|row| Reverse(row.0)); |
| | let items: String = rows |
| | .iter() |
| | .map(|(_, repo, head)| { |
| @@ -402,7 +483,7 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> { |
| | let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref()); |
| | let path = clean_path(q.get("path").map_or("", String::as_str))?; |
| | let Some(commit) = repo.resolve(&reference) else { |
| | if !repo.list_refs("refs/heads").is_empty() { |
| | if !repo.heads().is_empty() { |
| | return None; |
| | } |
| | let body = repo.masthead("tree", &reference) + &format!( |
| @@ -410,26 +491,19 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> { |
| | <code>git push git@{HOST}:{}/{}.git main</code></div>"#, esc(&repo.owner), esc(&repo.name)); |
| | return Some(View::Html(page(&format!("{}/{}", repo.owner, repo.name), &body))); |
| | }; |
| | let listing = repo.git(&["ls-tree", "-z", &format!("{commit}:{path}")])?; |
| | let mut entries: Vec<(bool, String)> = listing |
| | .split('\0') |
| | .filter_map(|line| { |
| | let (meta, name) = line.split_once('\t')?; |
| | Some((meta.split(' ').nth(1)? == "tree", name.to_string())) |
| | }) |
| | .collect(); |
| | entries.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.to_lowercase().cmp(&b.1.to_lowercase()))); |
| | let Some(listing) = repo.git(&["ls-tree", "-l", "-z", &format!("{commit}:{path}")]) else { |
| | // A file path: show it in the file view instead. |
| | return entry(repo, &commit, &path) |
| | .filter(|e| e.kind == "blob") |
| | .map(|_| View::Redirect(repo.url("blob", &[("ref", &reference), ("path", &path)]))); |
| | }; |
| | let mut entries: Vec<Entry> = listing.split('\0').filter_map(Entry::parse).collect(); |
| | // Folders first, then files and submodules, each alphabetically. |
| | entries.sort_by(|a, b| (a.kind != "tree").cmp(&(b.kind != "tree")).then(a.name.to_lowercase().cmp(&b.name.to_lowercase()))); |
| | |
| | let mut body = repo.masthead("tree", &reference) + &repo.locator("tree", &reference, &path); |
| | body += r#"<div class="panel">"#; |
| | let path_arg: Vec<&str> = if path.is_empty() { vec![] } else { vec![path.as_str()] }; |
| | let mut args = vec!["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", commit.as_str(), "--"]; |
| | args.extend(path_arg); |
| | if let Some(head) = repo.git(&args).and_then(|out| { |
| | let f: Vec<String> = out.trim_end().split('\x1f').map(String::from).collect(); |
| | let [oid, subject, author, stamp, date] = <[String; 5]>::try_from(f).ok()?; |
| | Some(Head { oid, subject, author, stamp, date }) |
| | }) { |
| | if let Some(head) = repo.latest(&commit, &path) { |
| | let _ = write!(body, |
| | r#"<div class="panel-head"><div class="lead"><b class="who">{}</b><a class="subject" href="{}">{}</a></div><div class="side">{}<span>{}</span></div></div>"#, |
| | esc(&head.author), attr(&repo.url("commit", &[("id", &head.oid)])), esc(&head.subject), |
| @@ -440,32 +514,70 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> { |
| | let up = repo.url("tree", &[("ref", &reference), ("path", parent_of(&path))]); |
| | let _ = write!(body, r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#, attr(&up), icon("up")); |
| | } |
| | for (is_dir, name) in &entries { |
| | let full = if path.is_empty() { name.clone() } else { format!("{path}/{name}") }; |
| | let (view, class, glyph) = if *is_dir { ("tree", "entry dir", "dir") } else { ("blob", "entry", "file") }; |
| | for item in &entries { |
| | let full = if path.is_empty() { item.name.clone() } else { format!("{path}/{}", item.name) }; |
| | let (view, class, glyph) = match item.kind.as_str() { |
| | "tree" => ("tree", "entry dir", "dir"), |
| | "commit" => { |
| | // A submodule: its commits live in another repository, so there's nothing to open. |
| | let _ = write!(body, r#"<li><span class="entry sub">{}<span class="name">{}</span><span class="quiet">Submodule at {}</span></span></li>"#, |
| | icon("module"), esc(&item.name), &item.oid[..item.oid.len().min(7)]); |
| | continue; |
| | } |
| | _ => ("blob", "entry", "file"), |
| | }; |
| | let href = repo.url(view, &[("ref", &reference), ("path", &full)]); |
| | let _ = write!(body, r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#, |
| | attr(&href), icon(glyph), esc(name)); |
| | attr(&href), icon(glyph), esc(&item.name)); |
| | } |
| | body += "</ul></div>"; |
| | |
| | let readme = entries.iter().find(|(d, n)| !d && n.to_ascii_lowercase().starts_with("readme")); |
| | if let Some((_, readme)) = readme { |
| | let full = if path.is_empty() { readme.clone() } else { format!("{path}/{readme}") }; |
| | if let Some(text) = repo.git(&["cat-file", "blob", &format!("{commit}:{full}")]) { |
| | let content = if render::is_markdown(readme) { |
| | let readme = entries.iter().find(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with("readme")); |
| | if let Some(readme) = readme.filter(|e| e.size <= SHOW_LIMIT) { |
| | let content = if render::is_markdown(&readme.name) { |
| | // Links in the rendered README depend on the folder and ref as well as the content. |
| | cached(format!("md:{}:{path}:{reference}", readme.oid), || { |
| | let text = repo.git(&["cat-file", "blob", &readme.oid]).unwrap_or_default(); |
| | format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, &path, &reference)) |
| | } else { |
| | code_view(readme, &text) |
| | }; |
| | let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#, |
| | icon("book"), esc(readme)); |
| | } |
| | }) |
| | } else { |
| | cached(format!("code:{}:{}", readme.oid, readme.name), || { |
| | code_view(&readme.name, &repo.git(&["cat-file", "blob", &readme.oid]).unwrap_or_default()) |
| | }) |
| | }; |
| | let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#, |
| | icon("book"), esc(&readme.name)); |
| | } |
| | let title = if path.is_empty() { format!("{}/{}", repo.owner, repo.name) } else { format!("{path} at {reference}") }; |
| | Some(View::Html(page(&title, &body))) |
| | } |
| | |
| | /// One entry of a tree listing: `blob`, `tree` or `commit` (a submodule), its object id, its |
| | /// size when it's a blob, and its name. |
| | struct Entry { |
| | kind: String, |
| | oid: String, |
| | size: usize, |
| | name: String, |
| | } |
| | |
| | impl Entry { |
| | /// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs. |
| | fn parse(record: &str) -> Option<Entry> { |
| | let (meta, name) = record.split_once('\t')?; |
| | let mut fields = meta.split_whitespace().skip(1); |
| | let (kind, oid) = (fields.next()?.to_string(), fields.next()?.to_string()); |
| | let size = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0); |
| | Some(Entry { kind, oid, size, name: name.to_string() }) |
| | } |
| | } |
| | |
| | /// The entry at `path` in `commit`, with its type, object id and size, in one git call. |
| | fn entry(repo: &Repo, commit: &str, path: &str) -> Option<Entry> { |
| | let out = repo.git(&["ls-tree", "-l", "-z", commit, "--", path])?; |
| | out.split('\0').filter_map(Entry::parse).find(|e| e.name == path) |
| | } |
| | |
| | /// Highlighted source with a line-number gutter. |
| | fn code_view(path: &str, text: &str) -> String { |
| | let lines = text.lines().count().max(1); |
| @@ -478,26 +590,38 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { |
| | let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref()); |
| | let path = clean_path(q.get("path")?)?; |
| | let commit = repo.resolve(&reference)?; |
| | let spec = format!("{commit}:{path}"); |
| | // Markdown links can't tell files from directories, so a blob link to a directory lands here. |
| | if repo.git(&["cat-file", "-t", &spec]).is_some_and(|t| t.trim() == "tree") { |
| | return Some(View::Redirect(repo.url("tree", &[("ref", &reference), ("path", &path)]))); |
| | let item = entry(repo, &commit, &path)?; |
| | match item.kind.as_str() { |
| | "blob" => {} |
| | // Markdown links can't tell files from folders, so a file link to a folder lands here. |
| | "tree" => return Some(View::Redirect(repo.url("tree", &[("ref", &reference), ("path", &path)]))), |
| | _ => return None, |
| | } |
| | let data = git(&repo.path, &["cat-file", "blob", &spec]).ok()?; |
| | let too_big = item.size > if raw { RAW_LIMIT } else { SHOW_LIMIT }; |
| | let data = if too_big { Vec::new() } else { git(&repo.path, &["cat-file", "blob", &item.oid]).ok()? }; |
| | let binary = data.iter().take(8000).any(|b| *b == 0); |
| | if raw { |
| | if too_big { |
| | return Some(View::Html(page("File too large", &format!( |
| | r#"<section class="notfound"><h1 class="title">This file is too large to download here</h1> |
| | <p class="count">{} is {}. Clone the repository to get it.</p><code>git clone git@{HOST}:{}/{}.git</code></section>"#, |
| | esc(file_name(&path)), size(item.size), esc(&repo.owner), esc(&repo.name))))); |
| | } |
| | let kind = match path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() { |
| | Some("png") => "image/png", |
| | Some("jpg" | "jpeg") => "image/jpeg", |
| | Some("gif") => "image/gif", |
| | Some("webp") => "image/webp", |
| | // Safe to serve as an image: the page's policy blocks any script inside it. |
| | Some("svg") => "image/svg+xml", |
| | _ if binary => "application/octet-stream", |
| | _ => "text/plain; charset=utf-8", |
| | }; |
| | return Some(View::Raw(data.into_iter().take(RAW_LIMIT).collect(), kind)); |
| | let download = (kind == "application/octet-stream").then(|| file_name(&path).to_string()); |
| | return Some(View::Raw(data, kind, download)); |
| | } |
| | let text = String::from_utf8_lossy(&data); |
| | let markdown = !binary && render::is_markdown(&path); |
| | let markdown = !binary && !too_big && render::is_markdown(&path); |
| | let as_code = !markdown || q.get("view").is_some_and(|v| v == "code"); |
| | |
| | let mut side = String::new(); |
| @@ -510,15 +634,20 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { |
| | let _ = write!(side, r#"<span class="segmented">{}{}</span>"#, link("Preview", "", !as_code), link("Code", "code", as_code)); |
| | } |
| | let _ = write!(side, r#"<a class="button" href="{}">Raw</a>"#, attr(&repo.url("raw", &[("ref", &reference), ("path", &path)]))); |
| | let facts = if binary { size(data.len()) } else { |
| | format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(data.len())) |
| | let facts = if binary || too_big { size(item.size) } else { |
| | format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(item.size)) |
| | }; |
| | let content = if binary { |
| | r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#.to_string() |
| | let content: Arc<str> = if too_big { |
| | r#"<p class="note">This file is too large to show here. Use Raw to open it.</p>"#.into() |
| | } else if binary { |
| | r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#.into() |
| | } else if as_code { |
| | code_view(&path, &text) |
| | // Highlighting depends only on the content and the file's type. |
| | cached(format!("code:{}:{}", item.oid, file_name(&path)), || code_view(&path, &text)) |
| | } else { |
| | format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference)) |
| | cached(format!("md:{}:{}:{reference}", item.oid, parent_of(&path)), || { |
| | format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference)) |
| | }) |
| | }; |
| | let body = repo.masthead("tree", &reference) + &repo.locator("blob", &reference, &path) + &format!( |
| | r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b><span class="quiet">{facts}</span></div><div class="side">{side}</div></div>{content}</section>"#, |
| @@ -529,9 +658,10 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { |
| | fn view_log(repo: &Repo, q: &Q) -> Option<View> { |
| | let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref()); |
| | let number: usize = q.get("page").and_then(|p| p.parse().ok()).unwrap_or(0); |
| | let skip = number.checked_mul(PAGE)?; |
| | let commit = repo.resolve(&reference)?; |
| | let out = repo.git(&[ |
| | "log", &format!("-n{}", PAGE + 1), &format!("--skip={}", number * PAGE), |
| | "log", &format!("-n{}", PAGE + 1), &format!("--skip={skip}"), |
| | "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", &commit, "--", |
| | ])?; |
| | let lines: Vec<&str> = out.lines().collect(); |
| @@ -628,7 +758,8 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> { |
| | "--format=%H%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%b", &commit])?; |
| | let f: Vec<&str> = meta.splitn(7, '\x1f').collect(); |
| | let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?; |
| | let patch = git(&repo.path, &["show", "--format=", "--no-color", "-M", "--patch", &commit]).ok()?; |
| | // A merge shows what it brought in relative to its first parent. |
| | let patch = git(&repo.path, &["show", "--format=", "--no-color", "-M", "--patch", "--diff-merges=first-parent", &commit]).ok()?; |
| | |
| | let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" "); |
| | let mut body = repo.masthead("log", &repo.default_ref()); |
| @@ -651,7 +782,9 @@ fn view_commit(repo: &Repo, q: &Q) -> Option<View> { |
| | plural(files.len(), "file", "files")); |
| | for file in &files { |
| | let status = if file.status.is_empty() { String::new() } else { format!(r#"<span class="status">{}</span>"#, file.status) }; |
| | let link = repo.url(if file.status == "Deleted" { "log" } else { "blob" }, &[("ref", oid), ("path", &file.name)]); |
| | // A deleted file still exists in the parent commit. |
| | let at = if file.status == "Deleted" { parents.split_whitespace().next().unwrap_or(oid) } else { oid }; |
| | let link = repo.url("blob", &[("ref", at), ("path", &file.name)]); |
| | let _ = write!(body, r#"<section class="panel"><div class="panel-head"><div class="lead">{}<a href="{}"><b>{}</b></a>{status}</div><div class="side"><span class="plus">+{}</span><span class="minus">−{}</span></div></div>"#, |
| | icon("file"), attr(&link), esc(&file.name), file.added, file.removed); |
| | if file.binary { |
| @@ -723,6 +856,8 @@ async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View { |
| | #[tokio::main] |
| | async fn main() { |
| | let Action::Serve { port } = Cli::parse().action; |
| | // Load the syntax definitions now rather than on the first visitor's request. |
| | tokio::task::spawn_blocking(render::warm_up); |
| | let app = Router::new() |
| | .route("/", get(|| blocking(view_index))) |
| | .route("/style.css", get(|| async { stylesheet() })) |