| @@ -1,20 +1,26 @@ |
| | //! Read-only web browser for GITv repositories, served on localhost behind Caddy. |
| | //! |
| | //! Every repository on the server is visible to anyone who can reach this service: it is meant |
| | //! for one trusted audience behind the proxy's login, not for per-owner access like SSH. |
| | |
| | use std::borrow::Cow; |
| | use std::cell::OnceCell; |
| | use std::cmp::Reverse; |
| | use std::collections::HashMap; |
| | use std::ffi::{OsStr, OsString}; |
| | use std::fmt::Write as _; |
| | use std::os::unix::ffi::{OsStrExt, OsStringExt}; |
| | use std::path::PathBuf; |
| | use std::sync::{Arc, LazyLock, Mutex}; |
| | use std::time::{SystemTime, UNIX_EPOCH}; |
| | |
| | use axum::extract::{Path, Query}; |
| | use axum::extract::{Path, RawQuery}; |
| | use axum::http::{StatusCode, header}; |
| | use axum::response::{IntoResponse, Redirect, Response}; |
| | use axum::{Router, routing::get}; |
| | use clap::{Parser, Subcommand}; |
| | use gitv::render; |
| | use gitv::{HOST, git, repos_root, valid_name}; |
| | use gitv::{HOST, git, git_capped, repo_dir, repos_root}; |
| | use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; |
| | |
| | const STYLESHEET: &str = include_str!("../../assets/style.css"); |
| @@ -40,10 +46,15 @@ const PAGE: usize = 50; |
| | const RAW_LIMIT: usize = 50 << 20; |
| | /// Largest file shown on a page; bigger files offer Raw instead. |
| | const SHOW_LIMIT: usize = 1 << 20; |
| | /// Largest patch shown on a commit page; only this much is ever read. |
| | 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. |
| | // --------------------------------------------------------------------------------------------- |
| | // Cache |
| | |
| | /// Rendered HTML and git answers keyed by immutable object ids, so repeat views skip the |
| | /// expensive work. Keys for anything that contains links include the repository, since the |
| | /// same content in two repositories links differently. Emptied whenever it outgrows its budget. |
| | #[derive(Default)] |
| | struct Cache { |
| | entries: HashMap<String, Arc<str>>, |
| @@ -53,23 +64,31 @@ struct Cache { |
| | 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> { |
| | /// The cached value for `key`, or `make`'s. A failure (`None`) is never cached, so a git |
| | /// command that timed out is retried next time instead of leaving a blank forever. |
| | fn cached(key: String, make: impl FnOnce() -> Option<String>) -> Option<Arc<str>> { |
| | if let Some(hit) = CACHE.lock().ok().and_then(|c| c.entries.get(&key).cloned()) { |
| | return hit; |
| | return Some(hit); |
| | } |
| | let value: Arc<str> = make().into(); |
| | 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 { |
| | let key_len = key.len(); |
| | if cache.bytes + key_len + value.len() > CACHE_BUDGET { |
| | cache.entries.clear(); |
| | cache.bytes = 0; |
| | } |
| | cache.bytes += cost; |
| | cache.entries.insert(key, Arc::clone(&value)); |
| | // Two requests can render the same key at once; count only the entry that stays. |
| | if let Some(old) = cache.entries.insert(key, Arc::clone(&value)) { |
| | cache.bytes -= key_len + old.len(); |
| | } |
| | cache.bytes += key_len + value.len(); |
| | } |
| | value |
| | Some(value) |
| | } |
| | |
| | // --------------------------------------------------------------------------------------------- |
| | // Responses |
| | |
| | #[derive(Parser)] |
| | #[command(about = "Read-only web browser for GITv repositories")] |
| | struct Cli { |
| @@ -86,19 +105,19 @@ enum Action { |
| | }, |
| | } |
| | |
| | type Q = HashMap<String, String>; |
| | |
| | enum View { |
| | Html(String), |
| | /// Bytes, content type, and a download name for files the browser shouldn't display. |
| | Raw(Vec<u8>, &'static str, Option<String>), |
| | Raw(Vec<u8>, &'static str, Option<Vec<u8>>), |
| | Redirect(String), |
| | Missing, |
| | } |
| | |
| | const SECURITY: [(header::HeaderName, &str); 4] = [ |
| | (header::CONTENT_SECURITY_POLICY, |
| | "default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'"), |
| | ( |
| | header::CONTENT_SECURITY_POLICY, |
| | "default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'", |
| | ), |
| | (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), |
| | (header::REFERRER_POLICY, "no-referrer"), |
| | (header::CACHE_CONTROL, "no-store"), |
| @@ -111,8 +130,8 @@ impl IntoResponse for View { |
| | View::Html(body) => (SECURITY, html, body).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()) |
| | 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); |
| | } |
| @@ -129,20 +148,120 @@ fn static_file(kind: &'static str, data: &'static [u8]) -> Response { |
| | } |
| | |
| | fn stylesheet() -> Response { |
| | let headers = [(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=31536000, immutable")]; |
| | let headers = |
| | [(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=31536000, immutable")]; |
| | (headers, STYLESHEET).into_response() |
| | } |
| | |
| | // --------------------------------------------------------------------------------------------- |
| | // Helpers |
| | // Query strings and paths |
| | // |
| | // File paths are bytes, not text: git allows any bytes but `/` and NUL in a name, so a path |
| | // is decoded from the URL, checked and handed to git without ever passing through UTF-8. |
| | |
| | /// Query parameters with their values percent-decoded to raw bytes. The first of a repeated |
| | /// key wins. |
| | type Q = HashMap<String, Vec<u8>>; |
| | |
| | fn parse_query(raw: Option<&str>) -> Q { |
| | let mut query = Q::new(); |
| | for pair in raw.unwrap_or("").split('&').filter(|p| !p.is_empty()) { |
| | let (key, value) = pair.split_once('=').unwrap_or((pair, "")); |
| | if let Ok(key) = String::from_utf8(percent_decode(key)) { |
| | query.entry(key).or_insert_with(|| percent_decode(value)); |
| | } |
| | } |
| | query |
| | } |
| | |
| | fn percent_decode(text: &str) -> Vec<u8> { |
| | let bytes = text.as_bytes(); |
| | let mut out = Vec::with_capacity(bytes.len()); |
| | let mut i = 0; |
| | while i < bytes.len() { |
| | let hex = |b: u8| (b as char).to_digit(16); |
| | match bytes[i] { |
| | b'+' => out.push(b' '), |
| | b'%' if i + 2 < bytes.len() => match (hex(bytes[i + 1]), hex(bytes[i + 2])) { |
| | (Some(high), Some(low)) => { |
| | out.push((high * 16 + low) as u8); |
| | i += 2; |
| | } |
| | _ => out.push(b'%'), |
| | }, |
| | byte => out.push(byte), |
| | } |
| | i += 1; |
| | } |
| | out |
| | } |
| | |
| | /// A text parameter; one that isn't valid UTF-8 counts as absent. |
| | fn param(q: &Q, key: &str) -> Option<String> { |
| | q.get(key).and_then(|v| String::from_utf8(v.clone()).ok()) |
| | } |
| | |
| | fn encode(value: &[u8]) -> String { |
| | let mut out = String::with_capacity(value.len()); |
| | for &b in value { |
| | match b { |
| | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char), |
| | _ => { |
| | let _ = write!(out, "%{b:02X}"); |
| | } |
| | } |
| | } |
| | out |
| | } |
| | |
| | /// A repository-relative path with no `.`, `..`, empty or absolute parts and no NUL. |
| | fn clean_path(value: &[u8]) -> Option<Vec<u8>> { |
| | let parts: Vec<&[u8]> = value.split(|b| *b == b'/').filter(|p| !p.is_empty()).collect(); |
| | if parts.iter().any(|p| *p == b"." || *p == b".." || p.contains(&0)) { |
| | return None; |
| | } |
| | Some(parts.join(&b'/')) |
| | } |
| | |
| | fn parent_of(path: &[u8]) -> &[u8] { |
| | path.iter().rposition(|b| *b == b'/').map_or(&[], |i| &path[..i]) |
| | } |
| | |
| | fn file_name(path: &[u8]) -> &[u8] { |
| | path.iter().rposition(|b| *b == b'/').map_or(path, |i| &path[i + 1..]) |
| | } |
| | |
| | fn join(dir: &[u8], name: &[u8]) -> Vec<u8> { |
| | if dir.is_empty() { name.to_vec() } else { [dir, b"/", name].concat() } |
| | } |
| | |
| | /// Bytes for display. Names that aren't UTF-8 show replacement characters, but links keep |
| | /// the real bytes. |
| | fn lossy(bytes: &[u8]) -> Cow<'_, str> { |
| | String::from_utf8_lossy(bytes) |
| | } |
| | |
| | /// `<commit>:<path>` for git, path bytes intact. |
| | fn spec(commit: &str, path: &[u8]) -> OsString { |
| | let mut spec = format!("{commit}:").into_bytes(); |
| | spec.extend_from_slice(path); |
| | OsString::from_vec(spec) |
| | } |
| | |
| | // --------------------------------------------------------------------------------------------- |
| | // Formatting |
| | |
| | fn icon(name: &str) -> String { |
| | let path = match name { |
| | "dir" => r#"<path d="M2 4.5c0-.6.4-1 1-1h3.2l1.4 1.5H13c.6 0 1 .4 1 1v6.5c0 .6-.4 1-1 1H3c-.6 0-1-.4-1-1z"/>"#, |
| | "file" => r#"<path d="M4 1.8h5.3L12.5 5v9.2H4z"/><path d="M9 1.8v3.5h3.5"/>"#, |
| | "branch" => r#"<circle cx="4.5" cy="3.5" r="1.6"/><circle cx="4.5" cy="12.5" r="1.6"/><circle cx="11.5" cy="5" r="1.6"/><path d="M4.5 5.1v5.8M11.5 6.6c0 2.6-2.2 3.3-7 4.3"/>"#, |
| | "branch" => { |
| | r#"<circle cx="4.5" cy="3.5" r="1.6"/><circle cx="4.5" cy="12.5" r="1.6"/><circle cx="11.5" cy="5" r="1.6"/><path d="M4.5 5.1v5.8M11.5 6.6c0 2.6-2.2 3.3-7 4.3"/>"# |
| | } |
| | "tag" => r#"<path d="M2 2.5h5.3l6.2 6.2-4.8 4.8-6.7-6.7z"/><circle cx="5" cy="5.5" r="1"/>"#, |
| | "book" => r#"<path d="M2.5 3h4c.8 0 1.5.7 1.5 1.5V13c0-.6-.5-1-1-1h-4.5zM13.5 3h-4c-.8 0-1.5.7-1.5 1.5V13c0-.6.5-1 1-1h4.5z"/>"#, |
| | "book" => { |
| | r#"<path d="M2.5 3h4c.8 0 1.5.7 1.5 1.5V13c0-.6-.5-1-1-1h-4.5zM13.5 3h-4c-.8 0-1.5.7-1.5 1.5V13c0-.6.5-1 1-1h4.5z"/>"# |
| | } |
| | "code" => r#"<path d="M5.5 4.5 2 8l3.5 3.5M10.5 4.5 14 8l-3.5 3.5"/>"#, |
| | "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"/>"#, |
| @@ -153,33 +272,6 @@ fn icon(name: &str) -> String { |
| | format!(r#"<svg class="ic" viewBox="0 0 16 16" aria-hidden="true">{path}</svg>"#) |
| | } |
| | |
| | fn encode(value: &str) -> String { |
| | value |
| | .bytes() |
| | .map(|b| match b { |
| | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => (b as char).to_string(), |
| | _ => format!("%{b:02X}"), |
| | }) |
| | .collect() |
| | } |
| | |
| | /// A repository-relative path with no `..`, empty or absolute parts. |
| | fn clean_path(value: &str) -> Option<String> { |
| | let parts: Vec<&str> = value.split('/').filter(|p| !p.is_empty()).collect(); |
| | if parts.iter().any(|p| *p == "." || *p == ".." || p.contains('\0')) { |
| | return None; |
| | } |
| | Some(parts.join("/")) |
| | } |
| | |
| | fn parent_of(path: &str) -> &str { |
| | path.rsplit_once('/').map_or("", |(p, _)| p) |
| | } |
| | |
| | fn file_name(path: &str) -> &str { |
| | path.rsplit('/').next().unwrap_or(path) |
| | } |
| | |
| | /// "3 hours ago" for recent times, the calendar date (as git printed it) after a month. |
| | fn ago(stamp: &str, date: &str) -> String { |
| | let Ok(then) = stamp.parse::<u64>() else { return date.to_string() }; |
| @@ -195,6 +287,11 @@ fn ago(stamp: &str, date: &str) -> String { |
| | } |
| | } |
| | |
| | /// A commit subject for display; an empty one would leave an invisible link. |
| | fn subject_or_placeholder(subject: &str) -> &str { |
| | if subject.trim().is_empty() { "(no message)" } else { subject } |
| | } |
| | |
| | fn plural(count: usize, one: &str, many: &str) -> String { |
| | format!("{count} {}", if count == 1 { one } else { many }) |
| | } |
| @@ -224,9 +321,12 @@ fn page(title: &str, body: &str) -> String { |
| | } |
| | |
| | fn view_missing() -> String { |
| | page("Not found", r#"<section class="notfound"><h1 class="title">Nothing here</h1> |
| | page( |
| | "Not found", |
| | r#"<section class="notfound"><h1 class="title">Nothing here</h1> |
| | <p class="count">That repository, branch, file or commit doesn’t exist, or the link is malformed.</p> |
| | <a class="button" href="/">Back to repositories</a></section>"#) |
| | <a class="button" href="/">Back to repositories</a></section>"#, |
| | ) |
| | } |
| | |
| | // --------------------------------------------------------------------------------------------- |
| @@ -250,37 +350,54 @@ struct Head { |
| | } |
| | |
| | impl Repo { |
| | /// A repository whose owner and repository directories are real directories, never |
| | /// symlinks that could lead outside the tree. |
| | fn open(owner: &str, name: &str) -> Option<Repo> { |
| | if !(valid_name(owner) && valid_name(name)) { |
| | return None; |
| | } |
| | let path = repos_root().join(owner).join(format!("{name}.git")); |
| | path.join("HEAD").is_file().then(|| Repo { |
| | Some(Repo { |
| | path: repo_dir(owner, name)?, |
| | owner: owner.into(), |
| | name: name.into(), |
| | path, |
| | heads: OnceCell::new(), |
| | tags: OnceCell::new(), |
| | }) |
| | } |
| | |
| | fn git(&self, args: &[&str]) -> Option<String> { |
| | git(&self.path, args).ok().map(|out| String::from_utf8_lossy(&out).into_owned()) |
| | fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> { |
| | git(&self.path, args).ok() |
| | } |
| | |
| | fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> { |
| | self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned()) |
| | } |
| | |
| | fn url(&self, view: &str, query: &[(&str, &str)]) -> String { |
| | let query: Vec<String> = |
| | query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v))).collect(); |
| | query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v.as_bytes()))).collect(); |
| | let base = format!("/{}/{}/{view}", self.owner, self.name); |
| | if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) } |
| | } |
| | |
| | /// A tree, blob or raw link for a path, which may not be UTF-8. |
| | fn url_at(&self, view: &str, reference: &str, path: &[u8], extra: &str) -> String { |
| | let mut url = self.url(view, &[("ref", reference)]); |
| | if !path.is_empty() { |
| | url.push(if url.contains('?') { '&' } else { '?' }); |
| | let _ = write!(url, "path={}", encode(path)); |
| | } |
| | if !extra.is_empty() { |
| | url.push(if url.contains('?') { '&' } else { '?' }); |
| | url.push_str(extra); |
| | } |
| | url |
| | } |
| | |
| | /// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch. |
| | fn default_ref(&self) -> String { |
| | let head = self.git(&["symbolic-ref", "--short", "HEAD"]).map(|s| s.trim().to_string()); |
| | let head = self.git(&["symbolic-ref", "HEAD"]); |
| | let head = head.as_deref().map(str::trim).and_then(|h| h.strip_prefix("refs/heads/")); |
| | let heads = self.heads(); |
| | if let Some(head) = head.filter(|h| heads.contains(h)) { |
| | return head; |
| | if let Some(head) = head.filter(|h| heads.iter().any(|b| b == h)) { |
| | return head.to_string(); |
| | } |
| | ["main", "master"] |
| | .into_iter() |
| @@ -290,8 +407,10 @@ impl Repo { |
| | .unwrap_or_else(|| "HEAD".into()) |
| | } |
| | |
| | /// Names under a namespace exactly as git stores them (not `refname:short`, which can |
| | /// add `heads/` or `tags/` to tell apart a branch and tag of the same name). |
| | fn list_refs(&self, namespace: &str) -> Vec<String> { |
| | self.git(&["for-each-ref", "--format=%(refname:short)", namespace]) |
| | self.git(&["for-each-ref", "--format=%(refname:lstrip=2)", namespace]) |
| | .map(|s| s.lines().map(str::to_string).collect()) |
| | .unwrap_or_default() |
| | } |
| @@ -304,69 +423,99 @@ impl Repo { |
| | 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. |
| | /// The commit a reference names. Branches and tags are looked up by their exact full ref, |
| | /// so any name git allows works and none is read as revision syntax; anything else must be |
| | /// a (possibly abbreviated) commit id. |
| | fn resolve(&self, reference: &str) -> Option<String> { |
| | let ok = (1..=200).contains(&reference.len()) |
| | && !reference.starts_with('-') |
| | && !reference.contains("..") |
| | && reference.bytes().all(|b| b.is_ascii_alphanumeric() || b"._/-".contains(&b)); |
| | if !ok { |
| | let full = if self.heads().iter().any(|h| h == reference) { |
| | format!("refs/heads/{reference}") |
| | } else if self.tags().iter().any(|t| t == reference) { |
| | format!("refs/tags/{reference}") |
| | } else if reference == "HEAD" |
| | || (4..=64).contains(&reference.len()) && reference.bytes().all(|b| b.is_ascii_hexdigit()) |
| | { |
| | reference.to_string() |
| | } else { |
| | return None; |
| | } |
| | let spec = format!("{reference}^{{commit}}"); |
| | }; |
| | let spec = format!("{full}^{{commit}}"); |
| | self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into()) |
| | } |
| | |
| | /// 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)?; |
| | /// The newest commit on `rev` that touched `path` (the whole tree when empty). Walking |
| | /// history for a path can be slow, so answers for a fixed commit are cached. |
| | fn latest(&self, rev: &str, path: &[u8]) -> Option<Head> { |
| | let lookup = || { |
| | let mut args: Vec<&OsStr> = |
| | ["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", rev, "--"].map(OsStr::new).to_vec(); |
| | if !path.is_empty() { |
| | args.push(OsStr::from_bytes(path)); |
| | } |
| | self.git(&args).filter(|out| !out.trim().is_empty()) |
| | }; |
| | let is_oid = rev.len() >= 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()); |
| | let out = if is_oid { |
| | cached(format!("latest:{}:{rev}:{}", self.path.display(), encode(path)), lookup)?.to_string() |
| | } else { |
| | lookup()? |
| | }; |
| | 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() }) |
| | Some(Head { |
| | oid: oid.into(), |
| | subject: subject.into(), |
| | author: author.into(), |
| | stamp: stamp.into(), |
| | date: date.into(), |
| | }) |
| | } |
| | |
| | /// 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) |
| | cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string())) |
| | .and_then(|count| count.parse().ok()) |
| | .unwrap_or(0) |
| | } |
| | |
| | /// Tag names grouped by the commit they point at, for labelling history. |
| | fn tags_by_commit(&self) -> HashMap<String, Vec<String>> { |
| | let mut found: HashMap<String, Vec<String>> = HashMap::new(); |
| | let out = self.git(&["for-each-ref", "--format=%(refname:short) %(objectname) %(*objectname)", "refs/tags"]); |
| | let out = self.git(&["for-each-ref", "--format=%(objectname) %(*objectname) %(refname:lstrip=2)", "refs/tags"]); |
| | for line in out.unwrap_or_default().lines() { |
| | let parts: Vec<&str> = line.split_whitespace().collect(); |
| | if let [name, direct, rest @ ..] = parts.as_slice() { |
| | found.entry(rest.first().unwrap_or(direct).to_string()).or_default().push(name.to_string()); |
| | // Tag names can't contain spaces, but an unpeeled tag leaves the middle field empty. |
| | let mut fields = line.splitn(3, ' '); |
| | if let (Some(direct), Some(peeled), Some(name)) = (fields.next(), fields.next(), fields.next()) { |
| | let commit = if peeled.is_empty() { direct } else { peeled }; |
| | found.entry(commit.to_string()).or_default().push(name.to_string()); |
| | } |
| | } |
| | found |
| | } |
| | |
| | /// A cache key for rendered content of `oid` that links within this repository. |
| | fn key(&self, kind: &str, oid: &str, extra: &str) -> String { |
| | format!("{kind}:{}/{}:{oid}:{extra}", self.owner, self.name) |
| | } |
| | |
| | /// Render a Markdown file from directory `dir`, linking repository paths at `reference`. |
| | fn markdown(&self, source: &str, dir: &str, reference: &str) -> String { |
| | render::markdown(source, dir, &|path, image| { |
| | fn markdown(&self, source: &str, dir: &[u8], reference: &str) -> String { |
| | render::markdown(source, &lossy(dir), &|path, image| { |
| | if image { |
| | self.url("raw", &[("ref", reference), ("path", path)]) |
| | self.url_at("raw", reference, path.as_bytes(), "") |
| | } else if path.is_empty() { |
| | self.url("tree", &[("ref", reference)]) |
| | } else { |
| | self.url("blob", &[("ref", reference), ("path", path)]) |
| | self.url_at("blob", reference, path.as_bytes(), "") |
| | } |
| | }) |
| | } |
| | |
| | /// 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)); |
| | /// Name, clone address and tabs, shared by every repository page. `commit` is `reference` |
| | /// already resolved, when the caller has it. |
| | fn masthead(&self, active: &str, reference: &str, commit: Option<&str>) -> String { |
| | let commit = commit.map(str::to_string).or_else(|| self.resolve(reference)); |
| | let commits = commit.map_or(0, |c| self.commit_count(&c)); |
| | 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 { "" }; |
| @@ -388,10 +537,10 @@ impl Repo { |
| | } |
| | |
| | /// Branch and tag menu, then the path as breadcrumbs. |
| | fn locator(&self, view: &str, reference: &str, path: &str) -> String { |
| | fn locator(&self, view: &str, reference: &str, path: &[u8]) -> String { |
| | let item = |name: &String| { |
| | let current = if name == reference { r#" aria-current="true""# } else { "" }; |
| | let href = self.url(view, &[("ref", name), ("path", path)]); |
| | let href = self.url_at(view, name, path, ""); |
| | format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name)) |
| | }; |
| | let branches: String = self.heads().iter().map(item).collect(); |
| @@ -402,15 +551,20 @@ impl Repo { |
| | } |
| | let mut crumbs = String::new(); |
| | if !path.is_empty() { |
| | let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&self.url("tree", &[("ref", reference)])), esc(&self.name)); |
| | let parts: Vec<&str> = path.split('/').collect(); |
| | let _ = write!( |
| | crumbs, |
| | r#"<a href="{}">{}</a>"#, |
| | attr(&self.url("tree", &[("ref", reference)])), |
| | esc(&self.name) |
| | ); |
| | let parts: Vec<&[u8]> = path.split(|b| *b == b'/').collect(); |
| | for (i, part) in parts.iter().enumerate() { |
| | crumbs += r#"<span class="sep">/</span>"#; |
| | if i + 1 == parts.len() { |
| | let _ = write!(crumbs, "<b>{}</b>", esc(part)); |
| | let _ = write!(crumbs, "<b>{}</b>", esc(&lossy(part))); |
| | } else { |
| | let href = self.url("tree", &[("ref", reference), ("path", &parts[..=i].join("/"))]); |
| | let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&href), esc(part)); |
| | let href = self.url_at("tree", reference, &parts[..=i].join(&b'/'), ""); |
| | let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&href), esc(&lossy(part))); |
| | } |
| | } |
| | crumbs = format!(r#"<nav class="crumbs" aria-label="Path">{crumbs}</nav>"#); |
| @@ -425,8 +579,51 @@ impl Repo { |
| | } |
| | |
| | fn sha_link(&self, oid: &str) -> String { |
| | format!(r#"<a class="sha" href="{}">{}</a>"#, attr(&self.url("commit", &[("id", oid)])), &oid[..oid.len().min(7)]) |
| | format!( |
| | r#"<a class="sha" href="{}">{}</a>"#, |
| | attr(&self.url("commit", &[("id", oid)])), |
| | &oid[..oid.len().min(7)] |
| | ) |
| | } |
| | } |
| | |
| | /// 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 as git stores it. |
| | struct Entry { |
| | kind: String, |
| | oid: String, |
| | size: usize, |
| | name: Vec<u8>, |
| | } |
| | |
| | impl Entry { |
| | /// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs. |
| | fn parse(record: &[u8]) -> Option<Entry> { |
| | let tab = record.iter().position(|b| *b == b'\t')?; |
| | let meta = std::str::from_utf8(&record[..tab]).ok()?; |
| | 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: record[tab + 1..].to_vec() }) |
| | } |
| | |
| | fn list(out: &[u8]) -> Vec<Entry> { |
| | out.split(|b| *b == 0).filter_map(Entry::parse).collect() |
| | } |
| | } |
| | |
| | /// The entry at `path` in `commit`, with its type, object id and size, in one git call. |
| | fn entry(repo: &Repo, commit: &str, path: &[u8]) -> Option<Entry> { |
| | let args = [ |
| | OsStr::new("ls-tree"), |
| | OsStr::new("-l"), |
| | OsStr::new("-z"), |
| | OsStr::new(commit), |
| | OsStr::new("--"), |
| | OsStr::from_bytes(path), |
| | ]; |
| | let out = repo.git_bytes(&args)?; |
| | Entry::list(&out).into_iter().find(|e| e.name == path) |
| | } |
| | |
| | // --------------------------------------------------------------------------------------------- |
| @@ -451,7 +648,8 @@ 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(), ""); |
| | // HEAD usually names a real branch; only look further when it doesn't. |
| | let head = repo.latest("HEAD", b"").or_else(|| repo.latest(&repo.default_ref(), b"")); |
| | rows.push((head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0), repo, head)); |
| | } |
| | } |
| @@ -460,154 +658,182 @@ fn view_index() -> View { |
| | .iter() |
| | .map(|(_, repo, head)| { |
| | let (last, when) = head.as_ref().map_or(("No commits yet".into(), String::new()), |h| { |
| | (esc(&h.subject).into_owned(), ago(&h.stamp, &h.date)) |
| | (esc(subject_or_placeholder(&h.subject)).into_owned(), ago(&h.stamp, &h.date)) |
| | }); |
| | format!( |
| | r#"<li><a class="repo-row" href="{}"><span class="rname"><span>{}/</span>{}</span><span class="rlast">{last}</span><span class="rwhen">{when}</span></a></li>"#, |
| | attr(&repo.url("tree", &[])), esc(&repo.owner), esc(&repo.name) |
| | attr(&repo.url("tree", &[])), |
| | esc(&repo.owner), |
| | esc(&repo.name) |
| | ) |
| | }) |
| | .collect(); |
| | let listing = if items.is_empty() { |
| | format!(r#"<div class="panel empty"><h2>No repositories yet</h2><p>Push to a new name and GITv creates the repository.</p> |
| | <code>git push git@{HOST}:um9i/my-project.git main</code></div>"#) |
| | format!( |
| | r#"<div class="panel empty"><h2>No repositories yet</h2><p>Push to a new name and GITv creates the repository.</p> |
| | <code>git push git@{HOST}:um9i/my-project.git main</code></div>"# |
| | ) |
| | } else { |
| | format!(r#"<div class="panel"><ul class="rows">{items}</ul></div>"#) |
| | }; |
| | let count = plural(rows.len(), "repository", "repositories"); |
| | View::Html(page("Repositories", &format!( |
| | r#"<div class="pagehead"><h1 class="title">Repositories</h1><p class="count">{count}</p></div>{listing}"#))) |
| | View::Html(page( |
| | "Repositories", |
| | &format!( |
| | r#"<div class="pagehead"><h1 class="title">Repositories</h1><p class="count">{count}</p></div>{listing}"# |
| | ), |
| | )) |
| | } |
| | |
| | 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 reference = param(q, "ref").unwrap_or_else(|| repo.default_ref()); |
| | let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?; |
| | let Some(commit) = repo.resolve(&reference) else { |
| | if !repo.heads().is_empty() { |
| | return None; |
| | } |
| | let body = repo.masthead("tree", &reference) + &format!( |
| | r#"<div class="panel empty"><h2>This repository is empty</h2><p>Push a branch to get started.</p> |
| | <code>git push git@{HOST}:{}/{}.git main</code></div>"#, esc(&repo.owner), esc(&repo.name)); |
| | let body = repo.masthead("tree", &reference, None) |
| | + &format!( |
| | r#"<div class="panel empty"><h2>This repository is empty</h2><p>Push a branch to get started.</p> |
| | <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 Some(listing) = repo.git(&["ls-tree", "-l", "-z", &format!("{commit}:{path}")]) else { |
| | let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)]; |
| | let Some(listing) = repo.git_bytes(&listing) 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)]))); |
| | .map(|_| View::Redirect(repo.url_at("blob", &reference, &path, ""))); |
| | }; |
| | let mut entries: Vec<Entry> = listing.split('\0').filter_map(Entry::parse).collect(); |
| | let mut entries = Entry::list(&listing); |
| | // 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()))); |
| | entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase())); |
| | |
| | let mut body = repo.masthead("tree", &reference) + &repo.locator("tree", &reference, &path); |
| | let mut body = repo.masthead("tree", &reference, Some(&commit)) + &repo.locator("tree", &reference, &path); |
| | body += r#"<div class="panel">"#; |
| | if let Some(head) = repo.latest(&commit, &path) { |
| | let _ = write!(body, |
| | 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), |
| | repo.sha_link(&head.oid), ago(&head.stamp, &head.date)); |
| | esc(&head.author), |
| | attr(&repo.url("commit", &[("id", &head.oid)])), |
| | esc(subject_or_placeholder(&head.subject)), |
| | repo.sha_link(&head.oid), |
| | ago(&head.stamp, &head.date) |
| | ); |
| | } |
| | body += r#"<ul class="rows">"#; |
| | if !path.is_empty() { |
| | 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")); |
| | let up = repo.url_at("tree", &reference, parent_of(&path), ""); |
| | let _ = write!( |
| | body, |
| | r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#, |
| | attr(&up), |
| | icon("up") |
| | ); |
| | } |
| | 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)]); |
| | let _ = write!( |
| | body, |
| | r#"<li><span class="entry sub">{}<span class="name">{}</span><span class="quiet">Submodule at {}</span></span></li>"#, |
| | icon("module"), |
| | esc(&lossy(&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(&item.name)); |
| | let href = repo.url_at(view, &reference, &join(&path, &item.name), ""); |
| | let _ = write!( |
| | body, |
| | r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#, |
| | attr(&href), |
| | icon(glyph), |
| | esc(&lossy(&item.name)) |
| | ); |
| | } |
| | body += "</ul></div>"; |
| | |
| | let readme = entries.iter().find(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with("readme")); |
| | // README.md over README or README.txt, as people expect. |
| | let readmes = entries.iter().filter(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with(b"readme")); |
| | let readme = readmes.clone().find(|e| render::is_markdown(&lossy(&e.name))).or_else(|| readmes.clone().next()); |
| | 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)) |
| | let name = lossy(&readme.name); |
| | let content = if render::is_markdown(&name) { |
| | // Links in the rendered README depend on the repository, folder and ref too. |
| | cached(repo.key("md", &readme.oid, &format!("{}:{reference}", encode(&path))), || { |
| | let text = repo.git(&["cat-file", "blob", &readme.oid])?; |
| | Some(format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, &path, &reference))) |
| | }) |
| | } else { |
| | cached(format!("code:{}:{}", readme.oid, readme.name), || { |
| | code_view(&readme.name, &repo.git(&["cat-file", "blob", &readme.oid]).unwrap_or_default()) |
| | // Highlighted code has no links, so any repository can share it. |
| | cached(format!("code:{}:{name}", readme.oid), || { |
| | Some(code_view(&name, &repo.git(&["cat-file", "blob", &readme.oid])?)) |
| | }) |
| | }; |
| | 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 content = content.unwrap_or_else(|| r#"<p class="note">This README couldn't be read.</p>"#.into()); |
| | let _ = write!( |
| | body, |
| | r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#, |
| | icon("book"), |
| | esc(&name) |
| | ); |
| | } |
| | let title = if path.is_empty() { format!("{}/{}", repo.owner, repo.name) } else { format!("{path} at {reference}") }; |
| | let title = if path.is_empty() { |
| | format!("{}/{}", repo.owner, repo.name) |
| | } else { |
| | format!("{} at {reference}", lossy(&path)) |
| | }; |
| | 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); |
| | let gutter: String = (1..=lines).map(|n| format!("{n}\n")).collect(); |
| | format!(r#"<div class="code-view"><pre class="gutter" aria-hidden="true">{gutter}</pre><pre class="code">{}</pre></div>"#, |
| | render::highlight(path, text)) |
| | format!( |
| | r#"<div class="code-view"><pre class="gutter" aria-hidden="true">{gutter}</pre><pre class="code">{}</pre></div>"#, |
| | render::highlight(path, text) |
| | ) |
| | } |
| | |
| | fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { |
| | let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref()); |
| | let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref()); |
| | let path = clean_path(q.get("path")?)?; |
| | let commit = repo.resolve(&reference)?; |
| | 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)]))), |
| | "tree" => return Some(View::Redirect(repo.url_at("tree", &reference, &path, ""))), |
| | _ => return None, |
| | } |
| | 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); |
| | let name = lossy(file_name(&path)).into_owned(); |
| | 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> |
| | if item.size > RAW_LIMIT { |
| | 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))))); |
| | esc(&name), |
| | size(item.size), |
| | esc(&repo.owner), |
| | esc(&repo.name) |
| | ), |
| | ))); |
| | } |
| | let kind = match path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() { |
| | let data = repo.git_bytes(&["cat-file", "blob", &item.oid])?; |
| | let binary = data.iter().take(8000).any(|b| *b == 0); |
| | let kind = match name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() { |
| | Some("png") => "image/png", |
| | Some("jpg" | "jpeg") => "image/jpeg", |
| | Some("gif") => "image/gif", |
| @@ -617,108 +843,184 @@ fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { |
| | _ if binary => "application/octet-stream", |
| | _ => "text/plain; charset=utf-8", |
| | }; |
| | let download = (kind == "application/octet-stream").then(|| file_name(&path).to_string()); |
| | let download = (kind == "application/octet-stream").then(|| file_name(&path).to_vec()); |
| | return Some(View::Raw(data, kind, download)); |
| | } |
| | let text = String::from_utf8_lossy(&data); |
| | let markdown = !binary && !too_big && render::is_markdown(&path); |
| | let as_code = !markdown || q.get("view").is_some_and(|v| v == "code"); |
| | |
| | let too_big = item.size > SHOW_LIMIT; |
| | let markdown = !too_big && render::is_markdown(&name); |
| | let as_code = !markdown || param(q, "view").as_deref() == Some("code"); |
| | // The facts and the rendering are cached together, so a repeat view reads no blob at all. |
| | let rendered: Arc<str> = if too_big { |
| | format!( |
| | "{}\x1f{}", |
| | size(item.size), |
| | r#"<p class="note">This file is too large to show here. Use Raw to open it.</p>"# |
| | ) |
| | .into() |
| | } else { |
| | let key = if as_code { |
| | // Highlighting depends only on the content and the file's type, so it's shared. |
| | format!("code:{}:{name}", item.oid) |
| | } else { |
| | repo.key("md", &item.oid, &format!("{}:{reference}", encode(parent_of(&path)))) |
| | }; |
| | cached(key, || { |
| | let data = repo.git_bytes(&["cat-file", "blob", &item.oid])?; |
| | if data.iter().take(8000).any(|b| *b == 0) { |
| | let note = r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#; |
| | return Some(format!("{}\x1f{note}", size(item.size))); |
| | } |
| | let text = String::from_utf8_lossy(&data); |
| | let facts = format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(item.size)); |
| | let html = if as_code { |
| | code_view(&name, &text) |
| | } else { |
| | format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, parent_of(&path), &reference)) |
| | }; |
| | Some(format!("{facts}\x1f{html}")) |
| | })? |
| | }; |
| | let (facts, content) = rendered.split_once('\x1f').unwrap_or(("", &rendered)); |
| | |
| | let mut side = String::new(); |
| | if markdown { |
| | let link = |label: &str, view: &str, on: bool| { |
| | let current = if on { r#" aria-current="true""# } else { "" }; |
| | let href = repo.url("blob", &[("ref", &reference), ("path", &path), ("view", view)]); |
| | format!(r#"<a href="{}"{current}>{label}</a>"#, attr(&href)) |
| | let extra = if view.is_empty() { String::new() } else { format!("view={view}") }; |
| | format!(r#"<a href="{}"{current}>{label}</a>"#, attr(&repo.url_at("blob", &reference, &path, &extra))) |
| | }; |
| | let _ = write!(side, r#"<span class="segmented">{}{}</span>"#, link("Preview", "", !as_code), link("Code", "code", as_code)); |
| | 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 || too_big { size(item.size) } else { |
| | format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(item.size)) |
| | }; |
| | 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 { |
| | // Highlighting depends only on the content and the file's type. |
| | cached(format!("code:{}:{}", item.oid, file_name(&path)), || code_view(&path, &text)) |
| | } else { |
| | 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>"#, |
| | icon("file"), esc(file_name(&path))); |
| | Some(View::Html(page(&format!("{path} at {reference}"), &body))) |
| | let _ = write!(side, r#"<a class="button" href="{}">Raw</a>"#, attr(&repo.url_at("raw", &reference, &path, ""))); |
| | let body = repo.masthead("tree", &reference, Some(&commit)) |
| | + &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>"#, |
| | icon("file"), |
| | esc(&name) |
| | ); |
| | Some(View::Html(page(&format!("{} at {reference}", lossy(&path)), &body))) |
| | } |
| | |
| | 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 reference = param(q, "ref").unwrap_or_else(|| repo.default_ref()); |
| | let number: usize = param(q, "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={skip}"), |
| | "--format=%H%x1f%s%x1f%an%x1f%ct%x1f%cs", &commit, "--", |
| | "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(); |
| | let tags = repo.tags_by_commit(); |
| | let mut rows = String::new(); |
| | for line in lines.iter().take(PAGE) { |
| | let Ok([oid, subject, author, stamp, date]) = <[&str; 5]>::try_from(line.split('\x1f').collect::<Vec<_>>()) else { |
| | let Ok([oid, subject, author, stamp, date]) = <[&str; 5]>::try_from(line.split('\x1f').collect::<Vec<_>>()) |
| | else { |
| | continue; |
| | }; |
| | let chips: String = tags.get(oid).into_iter().flatten().map(|t| { |
| | format!(r#"<a class="tagchip" href="{}">{}{}</a>"#, attr(&repo.url("tree", &[("ref", t)])), icon("tag"), esc(t)) |
| | }).collect(); |
| | let _ = write!(rows, |
| | let chips: String = tags |
| | .get(oid) |
| | .into_iter() |
| | .flatten() |
| | .map(|t| { |
| | format!( |
| | r#"<a class="tagchip" href="{}">{}{}</a>"#, |
| | attr(&repo.url("tree", &[("ref", t)])), |
| | icon("tag"), |
| | esc(t) |
| | ) |
| | }) |
| | .collect(); |
| | let _ = write!( |
| | rows, |
| | r#"<li class="commit-row"><div class="cmain"><a class="csubj" href="{}">{}</a>{chips}<span class="cmeta">{} committed {}</span></div>{}</li>"#, |
| | attr(&repo.url("commit", &[("id", oid)])), esc(subject), esc(author), ago(stamp, date), repo.sha_link(oid)); |
| | attr(&repo.url("commit", &[("id", oid)])), |
| | esc(subject_or_placeholder(subject)), |
| | esc(author), |
| | ago(stamp, date), |
| | repo.sha_link(oid) |
| | ); |
| | } |
| | let mut pager = String::new(); |
| | let page_link = |n: usize, label: &str| { |
| | format!(r#"<a class="button" href="{}">{label}</a>"#, attr(&repo.url("log", &[("ref", &reference), ("page", &n.to_string())]))) |
| | format!( |
| | r#"<a class="button" href="{}">{label}</a>"#, |
| | attr(&repo.url("log", &[("ref", &reference), ("page", &n.to_string())])) |
| | ) |
| | }; |
| | pager += &if number > 0 { page_link(number - 1, "Newer") } else { "<span></span>".into() }; |
| | if lines.len() > PAGE { |
| | pager += &page_link(number + 1, "Older"); |
| | } |
| | let body = repo.masthead("log", &reference) + &repo.locator("log", &reference, "") + &format!( |
| | r#"<div class="panel"><ul class="rows">{rows}</ul></div><nav class="pager" aria-label="Pages">{pager}</nav>"#); |
| | let body = repo.masthead("log", &reference, Some(&commit)) |
| | + &repo.locator("log", &reference, b"") |
| | + &format!( |
| | r#"<div class="panel"><ul class="rows">{rows}</ul></div><nav class="pager" aria-label="Pages">{pager}</nav>"# |
| | ); |
| | Some(View::Html(page(&format!("Commits on {reference}"), &body))) |
| | } |
| | |
| | struct FileDiff { |
| | name: String, |
| | /// One changed file: how git names it (raw bytes, from NUL-delimited output) and its status. |
| | struct Change { |
| | status: &'static str, |
| | path: Vec<u8>, |
| | } |
| | |
| | /// Parse `git show -z --name-status`: a status (`M`, `A`, `D`, `R100`, ...) then one path, or |
| | /// two (old and new) for renames and copies. |
| | fn parse_changes(out: &[u8]) -> Vec<Change> { |
| | let mut fields = out.split(|b| *b == 0).filter(|f| !f.is_empty()); |
| | let mut changes = Vec::new(); |
| | while let Some(code) = fields.next() { |
| | let (status, paths) = match code.first() { |
| | Some(b'A') => ("Added", 1), |
| | Some(b'D') => ("Deleted", 1), |
| | Some(b'R') => ("Renamed", 2), |
| | Some(b'C') => ("Copied", 2), |
| | _ => ("", 1), |
| | }; |
| | let mut path = None; |
| | for _ in 0..paths { |
| | path = fields.next(); |
| | } |
| | let Some(path) = path else { break }; |
| | changes.push(Change { status, path: path.to_vec() }); |
| | } |
| | changes |
| | } |
| | |
| | /// The lines of one file's diff: (class, old number, new number, text). |
| | struct FileDiff { |
| | rows: Vec<(&'static str, String, String, String)>, |
| | added: usize, |
| | removed: usize, |
| | binary: bool, |
| | } |
| | |
| | /// Split `git show` patch output into files of (class, old number, new number, text) rows. |
| | /// Split `git show` patch output into one entry per `diff --git` section, in order. Names come |
| | /// from [`parse_changes`], not from these human-readable headers, which quote or misplace odd names. |
| | fn parse_diff(text: &str) -> Vec<FileDiff> { |
| | let mut files: Vec<FileDiff> = Vec::new(); |
| | let (mut old, mut new) = (0usize, 0usize); |
| | for line in text.lines() { |
| | if let Some(rest) = line.strip_prefix("diff --git ") { |
| | let name = rest.rsplit_once(" b/").map_or(rest, |(_, b)| b).to_string(); |
| | files.push(FileDiff { name, status: "", rows: Vec::new(), added: 0, removed: 0, binary: false }); |
| | if line.starts_with("diff --git ") { |
| | files.push(FileDiff { rows: Vec::new(), added: 0, removed: 0, binary: false }); |
| | continue; |
| | } |
| | let Some(file) = files.last_mut() else { continue }; |
| | let in_hunk = !file.rows.is_empty(); |
| | if !in_hunk && line.starts_with("new file mode") { |
| | file.status = "Added"; |
| | } else if !in_hunk && line.starts_with("deleted file mode") { |
| | file.status = "Deleted"; |
| | } else if !in_hunk && line.starts_with("rename from ") { |
| | file.status = "Renamed"; |
| | } else if !in_hunk && line.starts_with("Binary files ") { |
| | if !in_hunk && line.starts_with("Binary files ") { |
| | file.binary = true; |
| | } else if line.starts_with("@@") { |
| | let nums: Vec<usize> = line |
| @@ -749,87 +1051,160 @@ fn parse_diff(text: &str) -> Vec<FileDiff> { |
| | } |
| | |
| | fn view_commit(repo: &Repo, q: &Q) -> Option<View> { |
| | let id = q.get("id")?; |
| | let id = param(q, "id")?; |
| | if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { |
| | return None; |
| | } |
| | let commit = repo.resolve(id)?; |
| | let meta = repo.git(&["show", "-s", "--date=format:%-d %b %Y, %H:%M", |
| | "--format=%H%x1f%P%x1f%an%x1f%ae%x1f%ad%x1f%s%x1f%b", &commit])?; |
| | let commit = repo.resolve(&id)?; |
| | let meta = repo.git(&[ |
| | "show", |
| | "-s", |
| | "--date=format:%-d %b %Y, %H:%M", |
| | "--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()?; |
| | // 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()); |
| | let mut body = repo.masthead("log", &repo.default_ref(), None); |
| | let message = message.trim(); |
| | let _ = write!(body, r#"<section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{}</h2><a class="button" href="{}">Browse files</a></div>{}</div><dl class="facts"> |
| | let _ = write!( |
| | body, |
| | r#"<section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{}</h2><a class="button" href="{}">Browse files</a></div>{}</div><dl class="facts"> |
| | <div><dt>Author</dt><dd>{} <span class="quiet">{}</span></dd></div><div><dt>Date</dt><dd>{}</dd></div> |
| | <div><dt>Commit</dt><dd><span class="sha">{}</span></dd></div>{}</dl></section>"#, |
| | esc(subject), |
| | esc(subject_or_placeholder(subject)), |
| | attr(&repo.url("tree", &[("ref", oid)])), |
| | if message.is_empty() { String::new() } else { format!(r#"<p class="cbody">{}</p>"#, esc(message)) }, |
| | esc(author), esc(email), esc(date), &oid[..12], |
| | if parent_links.is_empty() { String::new() } else { format!("<div><dt>Parent</dt><dd>{parent_links}</dd></div>") }); |
| | esc(author), |
| | esc(email), |
| | esc(date), |
| | &oid[..12], |
| | if parent_links.is_empty() { |
| | String::new() |
| | } else { |
| | format!("<div><dt>Parent</dt><dd>{parent_links}</dd></div>") |
| | } |
| | ); |
| | // A commit's diff never changes, so its rendering is cached. If git can't produce it, the |
| | // page still shows the commit, with a note. |
| | let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents)) |
| | .unwrap_or_else(|| r#"<p class="note">This commit’s changes couldn’t be read.</p>"#.into()); |
| | body += &diff; |
| | Some(View::Html(page(subject_or_placeholder(subject), &body))) |
| | } |
| | |
| | if patch.len() > DIFF_LIMIT { |
| | body += r#"<p class="note">This commit’s changes are too large to show here.</p>"#; |
| | /// A commit's changes as one panel per file. Only [`DIFF_LIMIT`] bytes of patch are read; past |
| | /// that the files are listed without their lines. |
| | fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> { |
| | // A merge shows what it brought in relative to its first parent. |
| | let options = ["--format=", "--no-color", "-M", "--diff-merges=first-parent"]; |
| | let names = repo.git_bytes(&[&["show", "-z", "--name-status"][..], &options, &[oid]].concat())?; |
| | let changes = parse_changes(&names); |
| | let (patch, too_big) = |
| | git_capped(&repo.path, &[&["show", "--patch"][..], &options, &[oid]].concat(), DIFF_LIMIT).ok()?; |
| | let files = if too_big { Vec::new() } else { parse_diff(&String::from_utf8_lossy(&patch)) }; |
| | // The two listings come from the same diff, in the same order; if they ever disagree, show |
| | // names only rather than pair lines with the wrong file. |
| | let paired = files.len() == changes.len(); |
| | |
| | let mut body = String::new(); |
| | let (added, removed) = files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed)); |
| | let totals = if paired { |
| | format!(r#" <span class="plus">+{added}</span><span class="minus">−{removed}</span>"#) |
| | } else { |
| | let files = parse_diff(&String::from_utf8_lossy(&patch)); |
| | let (added, removed) = files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed)); |
| | let _ = write!(body, r#"<h2 class="changes">{} changed <span class="plus">+{added}</span><span class="minus">−{removed}</span></h2>"#, |
| | 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) }; |
| | // 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 { |
| | body += r#"<p class="note">Binary file changed.</p>"#; |
| | } else if file.rows.is_empty() { |
| | body += r#"<p class="note">No content changes.</p>"#; |
| | } else { |
| | String::new() |
| | }; |
| | let _ = write!(body, r#"<h2 class="changes">{} changed{totals}</h2>"#, plural(changes.len(), "file", "files")); |
| | if too_big { |
| | body += r#"<p class="note">This commit’s changes are too large to show line by line.</p>"#; |
| | } |
| | for (i, change) in changes.iter().enumerate() { |
| | let file = files.get(i).filter(|_| paired); |
| | let status = if change.status.is_empty() { |
| | String::new() |
| | } else { |
| | format!(r#"<span class="status">{}</span>"#, change.status) |
| | }; |
| | // A deleted file still exists in the parent commit. |
| | let at = if change.status == "Deleted" { parents.split_whitespace().next().unwrap_or(oid) } else { oid }; |
| | let link = repo.url_at("blob", at, &change.path, ""); |
| | let counts = file.map_or(String::new(), |f| { |
| | format!(r#"<span class="plus">+{}</span><span class="minus">−{}</span>"#, f.added, f.removed) |
| | }); |
| | let _ = write!( |
| | body, |
| | r#"<section class="panel"><div class="panel-head"><div class="lead">{}<a href="{}"><b>{}</b></a>{status}</div><div class="side">{counts}</div></div>"#, |
| | icon("file"), |
| | attr(&link), |
| | esc(&lossy(&change.path)) |
| | ); |
| | match file { |
| | None => {} |
| | Some(f) if f.binary => body += r#"<p class="note">Binary file changed.</p>"#, |
| | Some(f) if f.rows.is_empty() => body += r#"<p class="note">No content changes.</p>"#, |
| | Some(f) => { |
| | body += r#"<div class="diff-wrap"><table class="diff">"#; |
| | for (class, o, n, text) in &file.rows { |
| | for (class, o, n, text) in &f.rows { |
| | if *class == "hunk" { |
| | let _ = write!(body, r#"<tr class="hunk"><td colspan="3">{}</td></tr>"#, esc(text)); |
| | } else { |
| | let sign = match *class { "add" => "+", "del" => "-", _ => " " }; |
| | let _ = write!(body, r#"<tr class="{class}"><td class="num" data-n="{o}"></td><td class="num" data-n="{n}"></td><td class="line" data-s="{sign}">{}</td></tr>"#, esc(text)); |
| | let sign = match *class { |
| | "add" => "+", |
| | "del" => "-", |
| | _ => " ", |
| | }; |
| | let _ = write!( |
| | body, |
| | r#"<tr class="{class}"><td class="num" data-n="{o}"></td><td class="num" data-n="{n}"></td><td class="line" data-s="{sign}">{}</td></tr>"#, |
| | esc(text) |
| | ); |
| | } |
| | } |
| | body += "</table></div>"; |
| | } |
| | body += "</section>"; |
| | } |
| | body += "</section>"; |
| | } |
| | Some(View::Html(page(subject, &body))) |
| | Some(body) |
| | } |
| | |
| | fn view_tags(repo: &Repo) -> Option<View> { |
| | let out = repo.git(&["for-each-ref", "--sort=-creatordate", |
| | "--format=%(refname:short)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:short)%1f%(contents:subject)%1f%(objecttype)", |
| | "refs/tags"])?; |
| | let out = repo.git(&[ |
| | "for-each-ref", |
| | "--sort=-creatordate", |
| | "--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:short)%1f%(contents:subject)%1f%(objecttype)", |
| | "refs/tags", |
| | ])?; |
| | let mut rows = String::new(); |
| | for line in out.lines() { |
| | let Ok([name, direct, peeled, stamp, date, note, kind]) = <[&str; 7]>::try_from(line.split('\x1f').collect::<Vec<_>>()) else { |
| | let Ok([name, direct, peeled, stamp, date, note, kind]) = |
| | <[&str; 7]>::try_from(line.split('\x1f').collect::<Vec<_>>()) |
| | else { |
| | continue; |
| | }; |
| | let target = if peeled.is_empty() { direct } else { peeled }; |
| | let note = if kind == "tag" && !note.is_empty() { format!(r#"<span class="tnote">{}</span>"#, esc(note)) } else { String::new() }; |
| | let _ = write!(rows, r#"<li class="tag-row"><span class="tname">{}</span>{note}<span class="tmeta">{}{}</span> |
| | let note = if kind == "tag" && !note.is_empty() { |
| | format!(r#"<span class="tnote">{}</span>"#, esc(note)) |
| | } else { |
| | String::new() |
| | }; |
| | let _ = write!( |
| | rows, |
| | r#"<li class="tag-row"><span class="tname">{}</span>{note}<span class="tmeta">{}{}</span> |
| | <span class="tacts"><a class="button" href="{}">Browse files</a></span></li>"#, |
| | esc(name), repo.sha_link(target), ago(stamp, date), attr(&repo.url("tree", &[("ref", name)]))); |
| | esc(name), |
| | repo.sha_link(target), |
| | ago(stamp, date), |
| | attr(&repo.url("tree", &[("ref", name)])) |
| | ); |
| | } |
| | let listing = if rows.is_empty() { |
| | r#"<div class="panel empty"><h2>No tags yet</h2><p>Tag a release and push it to see it here.</p><code>git tag -a v1.0.0 -m "v1.0.0" && git push origin v1.0.0</code></div>"#.to_string() |
| | } else { |
| | format!(r#"<div class="panel"><ul class="rows">{rows}</ul></div>"#) |
| | }; |
| | let body = repo.masthead("tags", &repo.default_ref()) + &listing; |
| | let body = repo.masthead("tags", &repo.default_ref(), None) + &listing; |
| | Some(View::Html(page(&format!("Tags in {}/{}", repo.owner, repo.name), &body))) |
| | } |
| | |
| @@ -848,9 +1223,17 @@ fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View { |
| | result.unwrap_or(View::Missing) |
| | } |
| | |
| | /// Pages rendered at once. Each runs several git processes, so a burst of requests queues |
| | /// here instead of starting hundreds of them. |
| | static RENDERS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(16); |
| | |
| | /// Git calls block, so every page renders on the blocking pool. |
| | async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View { |
| | tokio::task::spawn_blocking(f).await.unwrap_or(View::Missing) |
| | let Ok(_permit) = RENDERS.acquire().await else { return View::Missing }; |
| | tokio::task::spawn_blocking(f).await.unwrap_or_else(|error| { |
| | eprintln!("gitv-web: a page failed to render: {error}"); |
| | View::Missing |
| | }) |
| | } |
| | |
| | #[tokio::main] |
| @@ -865,10 +1248,18 @@ async fn main() { |
| | .route("/fonts/display.woff2", get(|| async { static_file("font/woff2", FONT_DISPLAY) })) |
| | .route("/fonts/text.woff2", get(|| async { static_file("font/woff2", FONT_TEXT) })) |
| | .route("/fonts/mono.woff2", get(|| async { static_file("font/woff2", FONT_MONO) })) |
| | .route("/{owner}/{name}", get(|Path((o, n)): Path<(String, String)>, Query(q): Query<Q>| |
| | blocking(move || route(&o, &n, None, &q)))) |
| | .route("/{owner}/{name}/{view}", get(|Path((o, n, v)): Path<(String, String, String)>, Query(q): Query<Q>| |
| | blocking(move || route(&o, &n, Some(&v), &q)))) |
| | .route( |
| | "/{owner}/{name}", |
| | get(|Path((o, n)): Path<(String, String)>, RawQuery(q): RawQuery| { |
| | blocking(move || route(&o, &n, None, &parse_query(q.as_deref()))) |
| | }), |
| | ) |
| | .route( |
| | "/{owner}/{name}/{view}", |
| | get(|Path((o, n, v)): Path<(String, String, String)>, RawQuery(q): RawQuery| { |
| | blocking(move || route(&o, &n, Some(&v), &parse_query(q.as_deref()))) |
| | }), |
| | ) |
| | .fallback(|| async { View::Missing }); |
| | let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.expect("bind port"); |
| | // Print the bound address (not the requested port), so `--port 0` works for tests. |
| @@ -876,3 +1267,46 @@ async fn main() { |
| | println!("gitv-web listening on http://{address} (repos: {})", repos_root().display()); |
| | axum::serve(listener, app).await.expect("server"); |
| | } |
| | |
| | #[cfg(test)] |
| | mod tests { |
| | use super::*; |
| | |
| | #[test] |
| | fn percent_decoding_keeps_raw_bytes() { |
| | assert_eq!(percent_decode("a%2Fb+c"), b"a/b c"); |
| | assert_eq!(percent_decode("caf%C3%A9"), "café".as_bytes()); |
| | assert_eq!(percent_decode("%FF%00"), [0xff, 0]); |
| | assert_eq!(percent_decode("100%"), b"100%"); |
| | assert_eq!(percent_decode("%zz%4"), b"%zz%4"); |
| | } |
| | |
| | #[test] |
| | fn query_first_value_wins() { |
| | let q = parse_query(Some("path=a&path=b&ref=main&flag")); |
| | assert_eq!(q["path"], b"a"); |
| | assert_eq!(param(&q, "ref").as_deref(), Some("main")); |
| | assert_eq!(q["flag"], b""); |
| | } |
| | |
| | #[test] |
| | fn paths_are_cleaned_as_bytes() { |
| | assert_eq!(clean_path(b"/a//b/"), Some(b"a/b".to_vec())); |
| | assert_eq!(clean_path(b"a/../b"), None); |
| | assert_eq!(clean_path(b"./a"), None); |
| | assert_eq!(clean_path(b"a\0b"), None); |
| | assert_eq!(clean_path(&[0xff, b'/', b'x']), Some(vec![0xff, b'/', b'x'])); |
| | assert_eq!(encode(&[b'a', b' ', 0xff, b'/']), "a%20%FF/"); |
| | } |
| | |
| | #[test] |
| | fn name_status_parsing() { |
| | let out = b"M\0src/a b.rs\0R100\0old name\0new\tname\0D\0gone\0A\0\xffbin\0"; |
| | let changes = parse_changes(out); |
| | let got: Vec<(&str, &[u8])> = changes.iter().map(|c| (c.status, c.path.as_slice())).collect(); |
| | assert_eq!( |
| | got, |
| | [("", &b"src/a b.rs"[..]), ("Renamed", b"new\tname"), ("Deleted", b"gone"), ("Added", b"\xffbin")] |
| | ); |
| | } |
| | } |