Split the web server's main.rs into modules
Browse filesmain.rs held the CLI, routing, the cache, URL and path handling, HTML helpers, git output parsing and every page in 1,400 lines. It is now: - main.rs: CLI, router, responses, capacity and static assets - cache.rs, urls.rs, html.rs: the shared pieces - views/: the Repo type and routing, and one module per page (index, tree, blob, log, commit, tags), each with its own tests Code moved unchanged apart from visibility and imports. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 16:03
- Commit
- a58a9823c55a
- Parent
- a26d15d
14 files changed +1281−1167
+42−0
| @@ -0,0 +1,42 @@ | ||
| //! Rendered HTML and git answers kept in memory, keyed by immutable object ids. | ||
| use std::collections::HashMap; | ||
| use std::sync::{Arc, LazyLock, Mutex}; | ||
| /// 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)] | ||
| pub(crate) struct Cache { | ||
| pub(crate) entries: HashMap<String, Arc<str>>, | ||
| pub(crate) bytes: usize, | ||
| } | ||
| pub(crate) static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(Default::default); | ||
| pub(crate) const CACHE_BUDGET: usize = 32 << 20; | ||
| /// 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. | ||
| pub(crate) 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 Some(hit); | ||
| } | ||
| let value: Arc<str> = make()?.into(); | ||
| // Something this big would evict much of everything else to fit; serve it uncached. | ||
| if key.len() + value.len() > CACHE_BUDGET / 4 { | ||
| return Some(value); | ||
| } | ||
| if let Ok(mut cache) = CACHE.lock() { | ||
| let key_len = key.len(); | ||
| if cache.bytes + key_len + value.len() > CACHE_BUDGET { | ||
| cache.entries.clear(); | ||
| cache.bytes = 0; | ||
| } | ||
| // 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(); | ||
| } | ||
| Some(value) | ||
| } | ||
+78−0
| @@ -0,0 +1,78 @@ | ||
| //! Small pieces of HTML shared by every page: icons, dates, sizes and the page layout. | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
| use crate::templates; | ||
| pub(crate) 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"/>"# | ||
| } | ||
| "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"/>"# | ||
| } | ||
| "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"/>"#, | ||
| "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>"#) | ||
| } | ||
| /// "3 hours ago" for recent times, the calendar date (as git printed it) after a month. | ||
| pub(crate) fn ago(stamp: &str, date: &str) -> String { | ||
| let Ok(then) = stamp.parse::<u64>() else { return date.to_string() }; | ||
| let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); | ||
| let span = now.saturating_sub(then); | ||
| let unit = |n: u64, word: &str| format!("{n} {word}{} ago", if n == 1 { "" } else { "s" }); | ||
| match span { | ||
| 0..60 => "just now".into(), | ||
| 60..3600 => unit(span / 60, "minute"), | ||
| 3600..86400 => unit(span / 3600, "hour"), | ||
| 86400..2_592_000 => unit(span / 86400, "day"), | ||
| _ => date.to_string(), | ||
| } | ||
| } | ||
| /// A commit subject for display; an empty one would leave an invisible link. | ||
| pub(crate) fn subject_or_placeholder(subject: &str) -> &str { | ||
| if subject.trim().is_empty() { "(no message)" } else { subject } | ||
| } | ||
| pub(crate) fn plural(count: usize, one: &str, many: &str) -> String { | ||
| format!("{count} {}", if count == 1 { one } else { many }) | ||
| } | ||
| pub(crate) fn size(bytes: usize) -> String { | ||
| match bytes { | ||
| 0..1024 => plural(bytes, "byte", "bytes"), | ||
| 1024..1_048_576 => format!("{:.1} KB", bytes as f64 / 1024.0), | ||
| _ => format!("{:.1} MB", bytes as f64 / 1_048_576.0), | ||
| } | ||
| } | ||
| /// A page for someone signed in: the top bar links to their account. | ||
| pub(crate) fn page(title: &str, body: &str) -> String { | ||
| layout(title, body, true) | ||
| } | ||
| /// A page, with the account link in the top bar only when `signed_in`. | ||
| pub(crate) fn layout(title: &str, body: &str, signed_in: bool) -> String { | ||
| templates::Layout { title, body, signed_in }.to_string() | ||
| } | ||
| pub(crate) fn view_missing(signed_in: bool) -> String { | ||
| layout( | ||
| "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>"#, | ||
| signed_in, | ||
| ) | ||
| } | ||
| @@ -21,13 +21,15 @@ use data_encoding::BASE64URL_NOPAD; | ||
| use gitv::auth::{ | ||
| AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, generate_password, random_bytes, | ||
| }; | ||
| use gitv::percent_decode; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| use serde::Deserialize; | ||
| use sha2::{Digest, Sha256}; | ||
| use subtle::ConstantTimeEq; | ||
| use super::SECURITY; | ||
| use super::throttle::{Client, Throttle}; | ||
| use super::{SECURITY, layout, page, percent_decode}; | ||
| use crate::html::{layout, page}; | ||
| /// The session cookie. The `__Host-` prefix makes browsers insist on `Secure`, `Path=/` and no | ||
| /// `Domain`, so no other site or subdomain can set or overwrite it. | ||
+18−1162
| @@ -1,41 +1,34 @@ | ||
| //! Repository browser and read-only HTTP clone service. Anonymous visitors can access public repositories. | ||
| //! A session grants the shared web account access to private repositories. | ||
| mod cache; | ||
| mod capacity; | ||
| mod git_stream; | ||
| mod html; | ||
| mod login; | ||
| mod repository; | ||
| mod smart_http; | ||
| mod templates; | ||
| mod throttle; | ||
| use capacity::{Pool, Visitor}; | ||
| use throttle::Client; | ||
| mod urls; | ||
| mod views; | ||
| use std::borrow::Cow; | ||
| mod repository; | ||
| use repository::{Head, Reader}; | ||
| 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::sync::{Arc, LazyLock, Mutex}; | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
| use std::sync::{Arc, LazyLock}; | ||
| use std::time::Instant; | ||
| use axum::{Extension, Router}; | ||
| mod git_stream; | ||
| mod smart_http; | ||
| use axum::extract::DefaultBodyLimit; | ||
| use axum::extract::{Path, RawQuery}; | ||
| use axum::extract::{DefaultBodyLimit, Path, RawQuery}; | ||
| use axum::http::{StatusCode, header}; | ||
| use axum::response::{IntoResponse, Redirect, Response}; | ||
| use axum::routing::{get, post}; | ||
| use axum::{Extension, Router}; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv::render; | ||
| use gitv::{ | ||
| HOST, RepoDir, entries, git_capped, open_dir_at, open_owner, open_root, percent_decode, repo_dir, repo_in, | ||
| repos_root, try_subdirs, | ||
| }; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| use std::os::fd::{AsFd, OwnedFd}; | ||
| use std::time::Instant; | ||
| use gitv::{render, repos_root}; | ||
| use crate::html::view_missing; | ||
| use crate::urls::{encode, lossy, parse_query}; | ||
| use crate::views::{route, view_index}; | ||
| use capacity::{Pool, Visitor}; | ||
| use throttle::Client; | ||
| const STYLESHEET: &str = include_str!("../../../assets/style.css"); | ||
| const FONT_DISPLAY: &[u8] = include_bytes!("../../../assets/fonts/display.woff2"); | ||
| @@ -52,55 +45,6 @@ static STYLE_URL: LazyLock<String> = LazyLock::new(|| { | ||
| format!("/style.css?v={:012x}", hasher.finish() & 0xffff_ffff_ffff) | ||
| }); | ||
| 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; | ||
| /// Largest patch shown on a commit page; only this much is ever read. | ||
| const DIFF_LIMIT: usize = 2 << 20; | ||
| // --------------------------------------------------------------------------------------------- | ||
| // 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>>, | ||
| bytes: usize, | ||
| } | ||
| static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(Default::default); | ||
| const CACHE_BUDGET: usize = 32 << 20; | ||
| /// 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 Some(hit); | ||
| } | ||
| let value: Arc<str> = make()?.into(); | ||
| // Something this big would evict much of everything else to fit; serve it uncached. | ||
| if key.len() + value.len() > CACHE_BUDGET / 4 { | ||
| return Some(value); | ||
| } | ||
| if let Ok(mut cache) = CACHE.lock() { | ||
| let key_len = key.len(); | ||
| if cache.bytes + key_len + value.len() > CACHE_BUDGET { | ||
| cache.entries.clear(); | ||
| cache.bytes = 0; | ||
| } | ||
| // 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(); | ||
| } | ||
| Some(value) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Responses | ||
| @@ -180,1032 +124,6 @@ fn stylesheet() -> Response { | ||
| (headers, STYLESHEET).into_response() | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // 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, "")); | ||
| // In a query string `+` is a space; an encoded plus (`%2B`) stays a plus. | ||
| let (key, value) = (key.replace('+', " "), value.replace('+', " ")); | ||
| if let Ok(key) = String::from_utf8(percent_decode(&key)) { | ||
| query.entry(key).or_insert_with(|| percent_decode(&value)); | ||
| } | ||
| } | ||
| query | ||
| } | ||
| /// 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"/>"# | ||
| } | ||
| "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"/>"# | ||
| } | ||
| "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"/>"#, | ||
| "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>"#) | ||
| } | ||
| /// "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() }; | ||
| let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); | ||
| let span = now.saturating_sub(then); | ||
| let unit = |n: u64, word: &str| format!("{n} {word}{} ago", if n == 1 { "" } else { "s" }); | ||
| match span { | ||
| 0..60 => "just now".into(), | ||
| 60..3600 => unit(span / 60, "minute"), | ||
| 3600..86400 => unit(span / 3600, "hour"), | ||
| 86400..2_592_000 => unit(span / 86400, "day"), | ||
| _ => date.to_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 }) | ||
| } | ||
| fn size(bytes: usize) -> String { | ||
| match bytes { | ||
| 0..1024 => plural(bytes, "byte", "bytes"), | ||
| 1024..1_048_576 => format!("{:.1} KB", bytes as f64 / 1024.0), | ||
| _ => format!("{:.1} MB", bytes as f64 / 1_048_576.0), | ||
| } | ||
| } | ||
| /// A page for someone signed in: the top bar links to their account. | ||
| fn page(title: &str, body: &str) -> String { | ||
| layout(title, body, true) | ||
| } | ||
| /// A page, with the account link in the top bar only when `signed_in`. | ||
| fn layout(title: &str, body: &str, signed_in: bool) -> String { | ||
| templates::Layout { title, body, signed_in }.to_string() | ||
| } | ||
| fn view_missing(signed_in: bool) -> String { | ||
| layout( | ||
| "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>"#, | ||
| signed_in, | ||
| ) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Repository access | ||
| struct Repo { | ||
| signed_in: bool, | ||
| owner: String, | ||
| name: String, | ||
| reader: Reader, | ||
| } | ||
| impl Repo { | ||
| /// A repository opened through its owner and repository directories with symlinks refused; | ||
| /// every git command then runs inside that open directory. | ||
| fn open(owner: &str, name: &str) -> Option<Repo> { | ||
| let mut dir = repo_dir(owner, name)?; | ||
| dir.limit_until(Instant::now() + gitv::GIT_TIMEOUT); | ||
| Some(Repo::from_dir(owner, name, dir)) | ||
| } | ||
| fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo { | ||
| Repo { signed_in: false, reader: Reader::new(dir), owner: owner.into(), name: name.into() } | ||
| } | ||
| fn page(&self, title: &str, body: &str) -> String { | ||
| layout(title, body, self.signed_in) | ||
| } | ||
| fn clone_address(&self) -> (&'static str, String) { | ||
| if self.reader.dir.is_public() { | ||
| ("HTTPS", format!("https://{HOST}/{}/{}", self.owner, self.name)) | ||
| } else { | ||
| ("SSH", format!("git@{HOST}:{}/{}.git", self.owner, self.name)) | ||
| } | ||
| } | ||
| 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.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: &[u8], path: &[u8], extra: &str) -> String { | ||
| let mut url = self.url(view, &[]); | ||
| if !reference.is_empty() { | ||
| let _ = write!(url, "?ref={}", encode(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 | ||
| } | ||
| /// Latest change to one entry at this immutable revision. Keep the original path bytes | ||
| /// for Git and cache the timestamp itself so relative dates stay fresh. | ||
| fn entry_commit(&self, record: &str) -> Option<templates::EntryCommit> { | ||
| let mut fields = record.splitn(6, '\0'); | ||
| let oid = fields.next()?; | ||
| let stamp = fields.next()?; | ||
| let datetime = fields.next()?; | ||
| let full_date = fields.next()?; | ||
| let subject = subject_or_placeholder(fields.next()?); | ||
| let message = fields.next()?.trim_end(); | ||
| Some(templates::EntryCommit { | ||
| url: self.url("commit", &[("id", oid)]), | ||
| subject: subject.into(), | ||
| message: if message.is_empty() { subject } else { message }.into(), | ||
| when: ago(stamp, full_date.split(',').next().unwrap_or(full_date)), | ||
| full_date: full_date.into(), | ||
| datetime: datetime.into(), | ||
| }) | ||
| } | ||
| /// 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: &[u8], reference: &[u8]) -> String { | ||
| render::markdown(source, dir, &|path, image| { | ||
| if image { | ||
| self.url_at("raw", reference, path, "") | ||
| } else if path.is_empty() { | ||
| self.url_at("tree", reference, b"", "") | ||
| } else { | ||
| self.url_at("blob", reference, path, "") | ||
| } | ||
| }) | ||
| } | ||
| /// 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: &[u8], commit: Option<&str>) -> String { | ||
| let commit = commit.map(str::to_string).or_else(|| self.reader.resolve(reference)); | ||
| let commits = commit.map_or(0, |c| self.reader.commit_count(&c)); | ||
| let tags = self.reader.tags().len(); | ||
| let tab = |view: &str, glyph: &str, label: &str, count: Option<usize>| { | ||
| let current = if view == active { r#" aria-current="page""# } else { "" }; | ||
| let tab_ref = if view == "tags" { b"" } else { reference }; | ||
| let badge = count.map_or(String::new(), |n| format!(r#"<span class="n">{n}</span>"#)); | ||
| format!( | ||
| r#"<a href="{}"{current}>{}{label}{badge}</a>"#, | ||
| attr(&self.url_at(view, tab_ref, b"", "")), | ||
| icon(glyph) | ||
| ) | ||
| }; | ||
| let (protocol, address) = self.clone_address(); | ||
| format!( | ||
| r#"<div class="repohead"><h1 class="reponame"><a class="own" href="/">{owner}</a><span class="sep">/</span><a href="{home}">{name}</a></h1> | ||
| <label class="clone"><span>{protocol}</span><input readonly aria-label="Clone address" value="{address}"></label></div> | ||
| <nav class="tabs" aria-label="Repository">{}{}{}</nav>"#, | ||
| tab("tree", "code", "Code", None), | ||
| tab("log", "commits", "Commits", Some(commits)), | ||
| tab("tags", "tag", "Tags", Some(tags)), | ||
| owner = esc(&self.owner), | ||
| name = esc(&self.name), | ||
| home = attr(&self.url("tree", &[])), | ||
| ) | ||
| } | ||
| /// Branch and tag menu, then the path as breadcrumbs. | ||
| fn locator(&self, view: &str, reference: &[u8], path: &[u8]) -> String { | ||
| // `link` is what the URL carries; `name` is what people see. | ||
| let item = |link: Vec<u8>, name: &[u8]| { | ||
| let current = if link == reference { r#" aria-current="true""# } else { "" }; | ||
| let href = self.url_at(view, &link, path, ""); | ||
| format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(&lossy(name))) | ||
| }; | ||
| let branches: String = self.reader.heads().iter().map(|b| item(self.reader.branch_ref(b), b)).collect(); | ||
| let tags: String = self.reader.tags().iter().map(|t| item(self.reader.tag_ref(t), t)).collect(); | ||
| let mut menu = format!("<h2>Branches</h2>{branches}"); | ||
| if !tags.is_empty() { | ||
| menu += &format!("<h2>Tags</h2>{tags}"); | ||
| } | ||
| let mut crumbs = String::new(); | ||
| if !path.is_empty() { | ||
| let _ = write!( | ||
| crumbs, | ||
| r#"<a href="{}">{}</a>"#, | ||
| attr(&self.url_at("tree", reference, b"", "")), | ||
| 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(&lossy(part))); | ||
| } else { | ||
| 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>"#); | ||
| } | ||
| format!( | ||
| r#"<div class="locator"><details class="refmenu"><summary>{}{}{}</summary><div class="menu">{menu}</div></details> | ||
| {crumbs}</div>"#, | ||
| icon("branch"), | ||
| esc(&lossy( | ||
| reference | ||
| .strip_prefix(b"refs/heads/") | ||
| .or_else(|| reference.strip_prefix(b"refs/tags/")) | ||
| .unwrap_or(reference) | ||
| )), | ||
| icon("chevron"), | ||
| ) | ||
| } | ||
| 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)] | ||
| ) | ||
| } | ||
| } | ||
| /// 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.reader.git_bytes(&args)?; | ||
| Entry::list(&out).into_iter().find(|e| e.name == path) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Views | ||
| /// The names in an open directory, sorted, skipping hidden ones and any that aren't UTF-8 | ||
| /// (no valid owner or repository name is). | ||
| fn sorted_names(dir: &impl AsFd) -> Vec<String> { | ||
| let mut names: Vec<String> = | ||
| entries(dir).into_iter().filter_map(|n| n.into_string().ok()).filter(|n| !n.starts_with('.')).collect(); | ||
| names.sort(); | ||
| names | ||
| } | ||
| /// A fingerprint of a repository's branches, for caching its row on the index. Git updates a | ||
| /// ref by renaming a file into place (a loose ref under `refs/heads`, or `packed-refs` and | ||
| /// `HEAD` in the repository directory, or a table under `reftable`), and a rename changes the | ||
| /// directory's modification time. So the times of those directories change whenever a branch | ||
| /// or HEAD does. It reads them through the repository's open handle, the same directory git | ||
| /// reads, never through a path. The current minute is included too, which bounds staleness | ||
| /// should two pushes land within the filesystem's timestamp granularity. | ||
| fn refs_fingerprint(repo: &RepoDir) -> Option<String> { | ||
| /// Append a directory's modification time. | ||
| fn note(stamp: &mut String, dir: &impl AsFd) -> Option<()> { | ||
| let meta = nix::sys::stat::fstat(dir.as_fd()).ok()?; | ||
| let _ = write!(stamp, ":{}.{}", meta.st_mtime, meta.st_mtime_nsec); | ||
| Some(()) | ||
| } | ||
| /// Note `dir` and every directory under it, depth first, holding open only the directories | ||
| /// on the current path, never all the siblings at once. Any directory that can't be read | ||
| /// makes the whole fingerprint `None`, so a partial one is never trusted. | ||
| fn walk(stamp: &mut String, dir: &OwnedFd) -> Option<()> { | ||
| note(stamp, dir)?; | ||
| let mut names = try_subdirs(dir).ok()?; | ||
| names.sort(); | ||
| // Ref files (and entries deleted since the listing) are covered by their directory's | ||
| // time; only subdirectories need visiting. | ||
| for name in names { | ||
| stamp.push('/'); | ||
| walk(stamp, &open_dir_at(dir, &name).ok()?)?; | ||
| } | ||
| Some(()) | ||
| } | ||
| /// A directory that may legitimately be absent: absent is a fact, unreadable is not. | ||
| fn optional(parent: &impl AsFd, name: &str) -> Option<Option<OwnedFd>> { | ||
| match open_dir_at(parent, OsStr::new(name)) { | ||
| Ok(dir) => Some(Some(dir)), | ||
| Err(nix::errno::Errno::ENOENT) => Some(None), | ||
| Err(_) => None, | ||
| } | ||
| } | ||
| let minute = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() / 60; | ||
| let mut stamp = format!("{minute}"); | ||
| note(&mut stamp, &repo.handle())?; | ||
| let refs = optional(&repo.handle(), "refs")?; | ||
| for dir in [refs.as_ref(), optional(&repo.handle(), "reftable")?.as_ref()] { | ||
| match dir { | ||
| Some(dir) => note(&mut stamp, dir)?, | ||
| None => stamp.push_str(":-"), | ||
| } | ||
| } | ||
| if let Some(refs) = refs.as_ref() | ||
| && let Some(heads) = optional(refs, "heads")? | ||
| { | ||
| walk(&mut stamp, &heads)?; | ||
| } | ||
| Some(stamp) | ||
| } | ||
| /// One row of the index: everything it shows, and no open repository handle, so a large | ||
| /// installation holds one handle at a time however many repositories it lists. | ||
| struct Row { | ||
| public: bool, | ||
| owner: String, | ||
| name: String, | ||
| head: Option<Head>, | ||
| } | ||
| fn view_index(signed_in: bool) -> View { | ||
| let deadline = Instant::now() + gitv::GIT_TIMEOUT; | ||
| let mut rows = Vec::new(); | ||
| let root = open_root(); | ||
| for owner in root.as_ref().map(sorted_names).unwrap_or_default() { | ||
| // Read through the owner's open directory: a symlinked owner isn't followed or listed. | ||
| let Some(owner_dir) = open_owner(&owner) else { continue }; | ||
| for entry in sorted_names(&owner_dir) { | ||
| let Some(name) = entry.strip_suffix(".git") else { continue }; | ||
| if Instant::now() >= deadline { | ||
| return View::Busy; | ||
| } | ||
| let Some(mut dir) = repo_in(&owner_dir, &owner, name) else { continue }; | ||
| let public = dir.is_public(); | ||
| if !signed_in && !public { | ||
| continue; | ||
| } | ||
| dir.limit_until(deadline); | ||
| let repo = Repo::from_dir(&owner, name, dir); | ||
| // HEAD usually names a real branch; only look further when it doesn't. An empty | ||
| // repository caches as an empty answer. | ||
| let lookup = || { | ||
| let latest = repo.reader.latest_raw("HEAD", b"").or_else(|| { | ||
| repo.reader.resolve(&repo.reader.default_ref()).and_then(|id| repo.reader.latest_raw(&id, b"")) | ||
| }); | ||
| (Instant::now() < deadline).then(|| latest.unwrap_or_default()) | ||
| }; | ||
| let raw = match refs_fingerprint(&repo.reader.dir) { | ||
| Some(stamp) => cached(format!("index:{}:{stamp}", repo.reader.dir.path.display()), lookup), | ||
| None => lookup().map(Arc::from), | ||
| }; | ||
| let head = raw.as_deref().and_then(Head::parse); | ||
| // `repo`, and with it the directory handle, is dropped here. | ||
| rows.push(Row { public, owner: owner.clone(), name: name.to_string(), head }); | ||
| } | ||
| } | ||
| rows.sort_by_key(|row| Reverse(row.head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0))); | ||
| let count = plural(rows.len(), "repository", "repositories"); | ||
| let rows = rows | ||
| .into_iter() | ||
| .map(|row| { | ||
| let (subject, when) = row.head.map_or_else( | ||
| || ("No commits yet".into(), String::new()), | ||
| |h| (subject_or_placeholder(&h.subject).into(), ago(&h.stamp, &h.date)), | ||
| ); | ||
| templates::RepositoryRow { owner: row.owner, name: row.name, public: row.public, subject, when } | ||
| }) | ||
| .collect(); | ||
| View::Html( | ||
| templates::Repositories { title: "Repositories", signed_in, count, rows, branch: icon("branch"), host: HOST } | ||
| .to_string(), | ||
| ) | ||
| } | ||
| fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref()); | ||
| let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?; | ||
| let Some(commit) = repo.reader.resolve(&reference) else { | ||
| if !repo.reader.heads().is_empty() { | ||
| return None; | ||
| } | ||
| 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(repo.page(&format!("{}/{}", repo.owner, repo.name), &body))); | ||
| }; | ||
| let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)]; | ||
| let Some(listing) = repo.reader.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_at("blob", &reference, &path, ""))); | ||
| }; | ||
| let mut entries = Entry::list(&listing); | ||
| // Folders first, then files and submodules, each alphabetically. | ||
| entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase())); | ||
| let page: usize = param(q, "page").and_then(|n| n.parse().ok()).unwrap_or(0); | ||
| let offset = page.checked_mul(PAGE)?; | ||
| if page != 0 && offset >= entries.len() { | ||
| return None; | ||
| } | ||
| let mut rows = Vec::new(); | ||
| let visible = &entries[offset..entries.len().min(offset + PAGE)]; | ||
| let names: Vec<_> = visible.iter().map(|item| item.name.as_slice()).collect(); | ||
| let histories = repo.reader.entry_histories(&commit, &path, &names); | ||
| for (item, record) in visible.iter().zip(histories) { | ||
| let path = join(&path, &item.name); | ||
| let (view, class, glyph) = match item.kind.as_str() { | ||
| "tree" => (Some("tree"), "entry dir", "dir"), | ||
| "commit" => (None, "entry sub", "module"), | ||
| _ => (Some("blob"), "entry", "file"), | ||
| }; | ||
| let row = templates::TreeRow { | ||
| name: lossy(&item.name), | ||
| class, | ||
| icon: icon(glyph), | ||
| href: view.map(|view| repo.url_at(view, &reference, &path, "")), | ||
| short_id: &item.oid[..item.oid.len().min(7)], | ||
| commit: record.as_deref().and_then(|record| repo.entry_commit(record)), | ||
| }; | ||
| rows.push(row); | ||
| } | ||
| let page_url = |number| repo.url_at("tree", &reference, &path, &format!("page={number}")); | ||
| // 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()); | ||
| let readme = readme.filter(|e| e.size <= SHOW_LIMIT).map(|readme| { | ||
| let name = lossy(&readme.name); | ||
| let rendered = | ||
| render_file(repo, &readme.oid, readme.size, &name, &path, &reference, !render::is_markdown(&name)); | ||
| let content = rendered | ||
| .as_deref() | ||
| .and_then(|r| r.split_once('\x1f')) | ||
| .map_or(r#"<p class="note">This README couldn't be read.</p>"#, |(_, html)| html); | ||
| (name.into_owned(), content.to_string()) | ||
| }); | ||
| let title = if path.is_empty() { | ||
| format!("{}/{}", repo.owner, repo.name) | ||
| } else { | ||
| format!("{} at {}", lossy(&path), lossy(&reference)) | ||
| }; | ||
| let head = repo.reader.latest(&commit, &path).map(|head| templates::TreeHead { | ||
| url: repo.url("commit", &[("id", &head.oid)]), | ||
| sha_link: repo.sha_link(&head.oid), | ||
| subject: subject_or_placeholder(&head.subject).to_string(), | ||
| author: head.author, | ||
| when: ago(&head.stamp, &head.date), | ||
| }); | ||
| Some(View::Html( | ||
| templates::Tree { | ||
| title, | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("tree", &reference, Some(&commit)), | ||
| locator: repo.locator("tree", &reference, &path), | ||
| head, | ||
| up: (!path.is_empty()).then(|| repo.url_at("tree", &reference, parent_of(&path), "")), | ||
| rows, | ||
| previous: page.checked_sub(1).map(page_url), | ||
| next: (entries.len() - offset > PAGE).then(|| page_url(page + 1)), | ||
| readme, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// A file rendered for display, as `facts` 0x1f `html`: highlighted code, or Markdown with | ||
| /// links into this repository at `reference` (the file lives in `dir`). The file view and the | ||
| /// README panel both use this, so they share one cached value per rendering instead of | ||
| /// storing different shapes under one key. The facts and the rendering are cached together, | ||
| /// so a repeat view reads no blob at all. | ||
| fn render_file( | ||
| repo: &Repo, | ||
| oid: &str, | ||
| file_size: usize, | ||
| name: &str, | ||
| dir: &[u8], | ||
| reference: &[u8], | ||
| as_code: bool, | ||
| ) -> Option<Arc<str>> { | ||
| let key = if as_code { | ||
| // Highlighting depends only on the content and the file's type, so it's shared. | ||
| format!("code:{oid}:{name}") | ||
| } else { | ||
| // Links depend on the repository, folder and ref too. | ||
| repo.key("md", oid, &format!("{}:{}", encode(dir), encode(reference))) | ||
| }; | ||
| cached(key, || { | ||
| let data = repo.reader.git_bytes(&["cat-file", "blob", 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(file_size))); | ||
| } | ||
| let text = String::from_utf8_lossy(&data); | ||
| let facts = format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(file_size)); | ||
| let html = if as_code { | ||
| code_view(name, &text) | ||
| } else { | ||
| format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, dir, reference)) | ||
| }; | ||
| Some(format!("{facts}\x1f{html}")) | ||
| }) | ||
| } | ||
| /// 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) | ||
| ) | ||
| } | ||
| fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref()); | ||
| let path = clean_path(q.get("path")?)?; | ||
| let commit = repo.reader.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_at("tree", &reference, &path, ""))), | ||
| _ => return None, | ||
| } | ||
| let name = lossy(file_name(&path)).into_owned(); | ||
| if raw { | ||
| if item.size > RAW_LIMIT { | ||
| return Some(View::Html(repo.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 {}</code></section>"#, | ||
| esc(&name), | ||
| size(item.size), | ||
| repo.clone_address().1 | ||
| ), | ||
| ))); | ||
| } | ||
| let mut command = gitv::git_command(&repo.reader.dir); | ||
| command.args(["cat-file", "blob", &item.oid]); | ||
| return Some(View::Raw(Box::new(command), item.size, file_name(&path).to_vec())); | ||
| } | ||
| 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"); | ||
| 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 { | ||
| render_file(repo, &item.oid, item.size, &name, parent_of(&path), &reference, as_code)? | ||
| }; | ||
| 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 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#"<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(repo.page(&format!("{} at {}", lossy(&path), lossy(&reference)), &body))) | ||
| } | ||
| fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.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.reader.resolve(&reference)?; | ||
| let out = repo.reader.git(&[ | ||
| "log", | ||
| &format!("-n{}", PAGE + 1), | ||
| &format!("--skip={skip}"), | ||
| "--date=format:%-d %b %Y", | ||
| Head::FORMAT, | ||
| &commit, | ||
| "--", | ||
| ])?; | ||
| let lines: Vec<&str> = out.lines().collect(); | ||
| let tags = repo.reader.tags_by_commit(); | ||
| let mut rows = Vec::new(); | ||
| for head in lines.iter().take(PAGE).filter_map(|line| Head::parse(line)) { | ||
| let labels = tags | ||
| .get(&head.oid) | ||
| .into_iter() | ||
| .flatten() | ||
| .map(|name| templates::TagLink { | ||
| name: lossy(name), | ||
| url: repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""), | ||
| }) | ||
| .collect(); | ||
| rows.push(templates::CommitRow { | ||
| url: repo.url("commit", &[("id", &head.oid)]), | ||
| subject: subject_or_placeholder(&head.subject).to_owned(), | ||
| short_id: head.oid.chars().take(7).collect(), | ||
| author: head.author, | ||
| when: ago(&head.stamp, &head.date), | ||
| tags: labels, | ||
| }); | ||
| } | ||
| let page_url = |n: usize| repo.url_at("log", &reference, b"", &format!("page={n}")); | ||
| Some(View::Html( | ||
| templates::History { | ||
| title: format!("Commits on {}", lossy(&reference)), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("log", &reference, Some(&commit)), | ||
| locator: repo.locator("log", &reference, b""), | ||
| rows, | ||
| newer: number.checked_sub(1).map(page_url), | ||
| older: (lines.len() > PAGE).then(|| page_url(number + 1)), | ||
| tag_icon: icon("tag"), | ||
| } | ||
| .to_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 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 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("Binary files ") { | ||
| file.binary = true; | ||
| } else if line.starts_with("@@") { | ||
| let nums: Vec<usize> = line | ||
| .split_whitespace() | ||
| .skip(1) | ||
| .take(2) | ||
| .map(|r| r.trim_start_matches(['-', '+']).split(',').next().and_then(|n| n.parse().ok()).unwrap_or(0)) | ||
| .collect(); | ||
| (old, new) = (nums.first().copied().unwrap_or(0), nums.get(1).copied().unwrap_or(0)); | ||
| file.rows.push(("hunk", String::new(), String::new(), line.to_string())); | ||
| } else if !in_hunk { | ||
| continue; | ||
| } else if let Some(t) = line.strip_prefix('+') { | ||
| file.rows.push(("add", String::new(), new.to_string(), t.to_string())); | ||
| new += 1; | ||
| file.added += 1; | ||
| } else if let Some(t) = line.strip_prefix('-') { | ||
| file.rows.push(("del", old.to_string(), String::new(), t.to_string())); | ||
| old += 1; | ||
| file.removed += 1; | ||
| } else if let Some(t) = line.strip_prefix(' ') { | ||
| file.rows.push(("ctx", old.to_string(), new.to_string(), t.to_string())); | ||
| old += 1; | ||
| new += 1; | ||
| } | ||
| } | ||
| files | ||
| } | ||
| fn view_commit(repo: &Repo, q: &Q) -> Option<View> { | ||
| 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; | ||
| } | ||
| // Looked up as an object only: a branch named like this id can't redirect the page. | ||
| let commit = repo.reader.commit_object(&id)?; | ||
| // NUL between fields: a commit message can't contain one, so the subject and body can hold | ||
| // any other byte, the separator git output elsewhere uses included. | ||
| let meta = repo.reader.git(&[ | ||
| "show", | ||
| "-s", | ||
| "--date=format:%-d %b %Y, %H:%M", | ||
| "--format=%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b", | ||
| &commit, | ||
| ])?; | ||
| let f: Vec<&str> = meta.splitn(7, '\0').collect(); | ||
| let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?; | ||
| let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" "); | ||
| // 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()); | ||
| Some(View::Html( | ||
| templates::Commit { | ||
| title: subject_or_placeholder(subject), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("log", &repo.reader.default_ref(), None), | ||
| browse: repo.url("tree", &[("ref", oid)]), | ||
| message: message.trim(), | ||
| author, | ||
| email, | ||
| date, | ||
| short_id: oid.get(..12)?, | ||
| parent_links, | ||
| diff: &diff, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// 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.reader.git_bytes(&[&["show", "-z", "--name-status"][..], &options, &[oid]].concat())?; | ||
| let changes = parse_changes(&names); | ||
| let (patch, too_big) = | ||
| git_capped(&repo.reader.dir, &[&["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 { | ||
| 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.as_bytes(), &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 &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) | ||
| ); | ||
| } | ||
| } | ||
| body += "</table></div>"; | ||
| } | ||
| } | ||
| body += "</section>"; | ||
| } | ||
| Some(body) | ||
| } | ||
| fn view_tags(repo: &Repo) -> Option<View> { | ||
| let out = repo.reader.git_bytes(&[ | ||
| "for-each-ref", | ||
| "--sort=-creatordate", | ||
| "--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:format:%-d %b %Y)%1f%(objecttype)%1f%(contents:subject)", | ||
| "refs/tags", | ||
| ])?; | ||
| let mut rows = String::new(); | ||
| for line in out.split(|b| *b == b'\n') { | ||
| // The tag's message goes last, so one containing the separator stays whole. | ||
| let Ok([name, direct, peeled, stamp, date, kind, note]) = | ||
| <[&[u8]; 7]>::try_from(line.splitn(7, |b| *b == 0x1f).collect::<Vec<_>>()) | ||
| else { | ||
| continue; | ||
| }; | ||
| let target = if peeled.is_empty() { direct } else { peeled }; | ||
| let note = if kind == b"tag" && !note.is_empty() { | ||
| format!(r#"<span class="tnote">{}</span>"#, esc(&lossy(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(&lossy(name)), | ||
| repo.sha_link(&lossy(target)), | ||
| ago(&lossy(stamp), &lossy(date)), | ||
| attr(&repo.url_at("tree", &repo.reader.tag_ref(name), b"", "")) | ||
| ); | ||
| } | ||
| 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.reader.default_ref(), None) + &listing; | ||
| Some(View::Html(repo.page(&format!("Tags in {}/{}", repo.owner, repo.name), &body))) | ||
| } | ||
| fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) -> View { | ||
| let Some(mut repo) = Repo::open(owner, name) else { | ||
| return if signed_in { View::Missing(true) } else { View::LoginRequired }; | ||
| }; | ||
| if !signed_in && !repo.reader.dir.is_public() { | ||
| return View::LoginRequired; | ||
| } | ||
| repo.signed_in = signed_in; | ||
| let result = match view { | ||
| None => Some(View::Redirect(repo.url("tree", &[]))), | ||
| Some("tree") => view_tree(&repo, q), | ||
| Some("blob") => view_blob(&repo, q, false), | ||
| Some("raw") => view_blob(&repo, q, true), | ||
| Some("log") => view_log(&repo, q), | ||
| Some("commit") => view_commit(&repo, q), | ||
| Some("tags") => view_tags(&repo), | ||
| Some(_) => None, | ||
| }; | ||
| result.unwrap_or(View::Missing(signed_in)) | ||
| } | ||
| /// Pages rendering at once: 12 for anyone, 4 more kept for signed-in sessions, and at most 4 | ||
| /// for any one anonymous client. Excess requests are refused before any blocking work queues. | ||
| static RENDERS: LazyLock<Pool> = LazyLock::new(|| Pool::new(12, 4, 4)); | ||
| @@ -1371,66 +289,4 @@ mod tests { | ||
| drop(held); | ||
| assert_eq!(blocking(visitor, || View::Html(String::new())).await.status(), StatusCode::OK); | ||
| } | ||
| #[test] | ||
| fn percent_decoding_keeps_raw_bytes() { | ||
| assert_eq!(percent_decode("a%2Fb+c"), b"a/b+c", "a plus is literal outside query strings"); | ||
| assert_eq!(parse_query(Some("p=a+b%2Bc"))["p"], 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 an_incomplete_fingerprint_is_never_trusted() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; // Root reads anything, so the unreadable folder below can't be made. | ||
| } | ||
| use std::os::unix::fs::PermissionsExt; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-fingerprint-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| for folder in ["refs/heads/open", "refs/heads/locked/inner"] { | ||
| std::fs::create_dir_all(dir.join(folder)).unwrap(); | ||
| } | ||
| let repo = RepoDir::at(&dir).unwrap(); | ||
| assert!(refs_fingerprint(&repo).is_some()); | ||
| // A branch folder that can't be read: its refs could change unseen. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o000)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint missing a folder was trusted"); | ||
| // Names readable but not searchable: the folder's children can't be inspected. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o444)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint with an uninspectable folder was trusted"); | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o755)).unwrap(); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[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")] | ||
| ); | ||
| } | ||
| } | ||
| @@ -1,8 +1,12 @@ | ||
| //! Git queries on an already-open repository. Ref and path identities remain byte strings. | ||
| use super::{cached, encode, join, lossy}; | ||
| use gitv::{RepoDir, git, git_with_input}; | ||
| use std::{sync::Arc, time::Duration}; | ||
| use gitv::{RepoDir, git, git_with_input}; | ||
| use crate::cache::cached; | ||
| use crate::urls::{encode, join, lossy}; | ||
| /// Objects an abbreviated id may match before it counts as too ambiguous to look up. | ||
| const MAX_CANDIDATES: usize = 1000; | ||
| const ENTRY_FORMAT: &str = "%H%x00%ct%x00%cI%x00%cd%x00%s%x00%B"; | ||
+114−0
| @@ -0,0 +1,114 @@ | ||
| //! Query strings, repository paths and URL encoding. | ||
| use std::borrow::Cow; | ||
| use std::collections::HashMap; | ||
| use std::ffi::OsString; | ||
| use std::fmt::Write as _; | ||
| use std::os::unix::ffi::OsStringExt; | ||
| use gitv::percent_decode; | ||
| // --------------------------------------------------------------------------------------------- | ||
| // 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. | ||
| pub(crate) type Q = HashMap<String, Vec<u8>>; | ||
| pub(crate) 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, "")); | ||
| // In a query string `+` is a space; an encoded plus (`%2B`) stays a plus. | ||
| let (key, value) = (key.replace('+', " "), value.replace('+', " ")); | ||
| if let Ok(key) = String::from_utf8(percent_decode(&key)) { | ||
| query.entry(key).or_insert_with(|| percent_decode(&value)); | ||
| } | ||
| } | ||
| query | ||
| } | ||
| /// A text parameter; one that isn't valid UTF-8 counts as absent. | ||
| pub(crate) fn param(q: &Q, key: &str) -> Option<String> { | ||
| q.get(key).and_then(|v| String::from_utf8(v.clone()).ok()) | ||
| } | ||
| pub(crate) 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. | ||
| pub(crate) 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'/')) | ||
| } | ||
| pub(crate) fn parent_of(path: &[u8]) -> &[u8] { | ||
| path.iter().rposition(|b| *b == b'/').map_or(&[], |i| &path[..i]) | ||
| } | ||
| pub(crate) fn file_name(path: &[u8]) -> &[u8] { | ||
| path.iter().rposition(|b| *b == b'/').map_or(path, |i| &path[i + 1..]) | ||
| } | ||
| pub(crate) 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. | ||
| pub(crate) fn lossy(bytes: &[u8]) -> Cow<'_, str> { | ||
| String::from_utf8_lossy(bytes) | ||
| } | ||
| /// `<commit>:<path>` for git, path bytes intact. | ||
| pub(crate) fn spec(commit: &str, path: &[u8]) -> OsString { | ||
| let mut spec = format!("{commit}:").into_bytes(); | ||
| spec.extend_from_slice(path); | ||
| OsString::from_vec(spec) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn percent_decoding_keeps_raw_bytes() { | ||
| assert_eq!(percent_decode("a%2Fb+c"), b"a/b+c", "a plus is literal outside query strings"); | ||
| assert_eq!(parse_query(Some("p=a+b%2Bc"))["p"], 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/"); | ||
| } | ||
| } | ||
+83−0
| @@ -0,0 +1,83 @@ | ||
| //! A file, highlighted or rendered, and its raw download. | ||
| use std::fmt::Write as _; | ||
| use std::sync::Arc; | ||
| use gitv::render; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| use super::tree::render_file; | ||
| use super::{RAW_LIMIT, Repo, SHOW_LIMIT, entry}; | ||
| use crate::View; | ||
| use crate::html::{icon, size}; | ||
| use crate::urls::{Q, clean_path, file_name, lossy, param, parent_of}; | ||
| pub(crate) fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref()); | ||
| let path = clean_path(q.get("path")?)?; | ||
| let commit = repo.reader.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_at("tree", &reference, &path, ""))), | ||
| _ => return None, | ||
| } | ||
| let name = lossy(file_name(&path)).into_owned(); | ||
| if raw { | ||
| if item.size > RAW_LIMIT { | ||
| return Some(View::Html(repo.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 {}</code></section>"#, | ||
| esc(&name), | ||
| size(item.size), | ||
| repo.clone_address().1 | ||
| ), | ||
| ))); | ||
| } | ||
| let mut command = gitv::git_command(&repo.reader.dir); | ||
| command.args(["cat-file", "blob", &item.oid]); | ||
| return Some(View::Raw(Box::new(command), item.size, file_name(&path).to_vec())); | ||
| } | ||
| 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"); | ||
| 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 { | ||
| render_file(repo, &item.oid, item.size, &name, parent_of(&path), &reference, as_code)? | ||
| }; | ||
| 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 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#"<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(repo.page(&format!("{} at {}", lossy(&path), lossy(&reference)), &body))) | ||
| } | ||
+222−0
| @@ -0,0 +1,222 @@ | ||
| //! One commit and its changes. | ||
| use std::fmt::Write as _; | ||
| use gitv::git_capped; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| use super::{DIFF_LIMIT, Repo}; | ||
| use crate::cache::cached; | ||
| use crate::html::{icon, plural, subject_or_placeholder}; | ||
| use crate::urls::{Q, lossy, param}; | ||
| use crate::{View, templates}; | ||
| /// One changed file: how git names it (raw bytes, from NUL-delimited output) and its status. | ||
| pub(crate) struct Change { | ||
| pub(crate) status: &'static str, | ||
| pub(crate) 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. | ||
| pub(crate) 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). | ||
| pub(crate) struct FileDiff { | ||
| pub(crate) rows: Vec<(&'static str, String, String, String)>, | ||
| pub(crate) added: usize, | ||
| pub(crate) removed: usize, | ||
| pub(crate) binary: bool, | ||
| } | ||
| /// 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. | ||
| pub(crate) 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 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("Binary files ") { | ||
| file.binary = true; | ||
| } else if line.starts_with("@@") { | ||
| let nums: Vec<usize> = line | ||
| .split_whitespace() | ||
| .skip(1) | ||
| .take(2) | ||
| .map(|r| r.trim_start_matches(['-', '+']).split(',').next().and_then(|n| n.parse().ok()).unwrap_or(0)) | ||
| .collect(); | ||
| (old, new) = (nums.first().copied().unwrap_or(0), nums.get(1).copied().unwrap_or(0)); | ||
| file.rows.push(("hunk", String::new(), String::new(), line.to_string())); | ||
| } else if !in_hunk { | ||
| continue; | ||
| } else if let Some(t) = line.strip_prefix('+') { | ||
| file.rows.push(("add", String::new(), new.to_string(), t.to_string())); | ||
| new += 1; | ||
| file.added += 1; | ||
| } else if let Some(t) = line.strip_prefix('-') { | ||
| file.rows.push(("del", old.to_string(), String::new(), t.to_string())); | ||
| old += 1; | ||
| file.removed += 1; | ||
| } else if let Some(t) = line.strip_prefix(' ') { | ||
| file.rows.push(("ctx", old.to_string(), new.to_string(), t.to_string())); | ||
| old += 1; | ||
| new += 1; | ||
| } | ||
| } | ||
| files | ||
| } | ||
| pub(crate) fn view_commit(repo: &Repo, q: &Q) -> Option<View> { | ||
| 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; | ||
| } | ||
| // Looked up as an object only: a branch named like this id can't redirect the page. | ||
| let commit = repo.reader.commit_object(&id)?; | ||
| // NUL between fields: a commit message can't contain one, so the subject and body can hold | ||
| // any other byte, the separator git output elsewhere uses included. | ||
| let meta = repo.reader.git(&[ | ||
| "show", | ||
| "-s", | ||
| "--date=format:%-d %b %Y, %H:%M", | ||
| "--format=%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b", | ||
| &commit, | ||
| ])?; | ||
| let f: Vec<&str> = meta.splitn(7, '\0').collect(); | ||
| let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?; | ||
| let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" "); | ||
| // 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()); | ||
| Some(View::Html( | ||
| templates::Commit { | ||
| title: subject_or_placeholder(subject), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("log", &repo.reader.default_ref(), None), | ||
| browse: repo.url("tree", &[("ref", oid)]), | ||
| message: message.trim(), | ||
| author, | ||
| email, | ||
| date, | ||
| short_id: oid.get(..12)?, | ||
| parent_links, | ||
| diff: &diff, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// 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. | ||
| pub(crate) 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.reader.git_bytes(&[&["show", "-z", "--name-status"][..], &options, &[oid]].concat())?; | ||
| let changes = parse_changes(&names); | ||
| let (patch, too_big) = | ||
| git_capped(&repo.reader.dir, &[&["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 { | ||
| 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.as_bytes(), &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 &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) | ||
| ); | ||
| } | ||
| } | ||
| body += "</table></div>"; | ||
| } | ||
| } | ||
| body += "</section>"; | ||
| } | ||
| Some(body) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[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")] | ||
| ); | ||
| } | ||
| } | ||
+170−0
| @@ -0,0 +1,170 @@ | ||
| //! The repository index. | ||
| use std::cmp::Reverse; | ||
| use std::ffi::OsStr; | ||
| use std::fmt::Write as _; | ||
| use std::os::fd::{AsFd, OwnedFd}; | ||
| use std::sync::Arc; | ||
| use std::time::{Instant, SystemTime, UNIX_EPOCH}; | ||
| use gitv::{HOST, RepoDir, entries, open_dir_at, open_owner, open_root, repo_in, try_subdirs}; | ||
| use super::Repo; | ||
| use crate::cache::cached; | ||
| use crate::html::{ago, icon, plural, subject_or_placeholder}; | ||
| use crate::repository::Head; | ||
| use crate::{View, templates}; | ||
| /// The names in an open directory, sorted, skipping hidden ones and any that aren't UTF-8 | ||
| /// (no valid owner or repository name is). | ||
| pub(crate) fn sorted_names(dir: &impl AsFd) -> Vec<String> { | ||
| let mut names: Vec<String> = | ||
| entries(dir).into_iter().filter_map(|n| n.into_string().ok()).filter(|n| !n.starts_with('.')).collect(); | ||
| names.sort(); | ||
| names | ||
| } | ||
| /// A fingerprint of a repository's branches, for caching its row on the index. Git updates a | ||
| /// ref by renaming a file into place (a loose ref under `refs/heads`, or `packed-refs` and | ||
| /// `HEAD` in the repository directory, or a table under `reftable`), and a rename changes the | ||
| /// directory's modification time. So the times of those directories change whenever a branch | ||
| /// or HEAD does. It reads them through the repository's open handle, the same directory git | ||
| /// reads, never through a path. The current minute is included too, which bounds staleness | ||
| /// should two pushes land within the filesystem's timestamp granularity. | ||
| pub(crate) fn refs_fingerprint(repo: &RepoDir) -> Option<String> { | ||
| /// Append a directory's modification time. | ||
| pub(crate) fn note(stamp: &mut String, dir: &impl AsFd) -> Option<()> { | ||
| let meta = nix::sys::stat::fstat(dir.as_fd()).ok()?; | ||
| let _ = write!(stamp, ":{}.{}", meta.st_mtime, meta.st_mtime_nsec); | ||
| Some(()) | ||
| } | ||
| /// Note `dir` and every directory under it, depth first, holding open only the directories | ||
| /// on the current path, never all the siblings at once. Any directory that can't be read | ||
| /// makes the whole fingerprint `None`, so a partial one is never trusted. | ||
| pub(crate) fn walk(stamp: &mut String, dir: &OwnedFd) -> Option<()> { | ||
| note(stamp, dir)?; | ||
| let mut names = try_subdirs(dir).ok()?; | ||
| names.sort(); | ||
| // Ref files (and entries deleted since the listing) are covered by their directory's | ||
| // time; only subdirectories need visiting. | ||
| for name in names { | ||
| stamp.push('/'); | ||
| walk(stamp, &open_dir_at(dir, &name).ok()?)?; | ||
| } | ||
| Some(()) | ||
| } | ||
| /// A directory that may legitimately be absent: absent is a fact, unreadable is not. | ||
| pub(crate) fn optional(parent: &impl AsFd, name: &str) -> Option<Option<OwnedFd>> { | ||
| match open_dir_at(parent, OsStr::new(name)) { | ||
| Ok(dir) => Some(Some(dir)), | ||
| Err(nix::errno::Errno::ENOENT) => Some(None), | ||
| Err(_) => None, | ||
| } | ||
| } | ||
| let minute = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() / 60; | ||
| let mut stamp = format!("{minute}"); | ||
| note(&mut stamp, &repo.handle())?; | ||
| let refs = optional(&repo.handle(), "refs")?; | ||
| for dir in [refs.as_ref(), optional(&repo.handle(), "reftable")?.as_ref()] { | ||
| match dir { | ||
| Some(dir) => note(&mut stamp, dir)?, | ||
| None => stamp.push_str(":-"), | ||
| } | ||
| } | ||
| if let Some(refs) = refs.as_ref() | ||
| && let Some(heads) = optional(refs, "heads")? | ||
| { | ||
| walk(&mut stamp, &heads)?; | ||
| } | ||
| Some(stamp) | ||
| } | ||
| /// One row of the index: everything it shows, and no open repository handle, so a large | ||
| /// installation holds one handle at a time however many repositories it lists. | ||
| pub(crate) struct Row { | ||
| pub(crate) public: bool, | ||
| pub(crate) owner: String, | ||
| pub(crate) name: String, | ||
| pub(crate) head: Option<Head>, | ||
| } | ||
| pub(crate) fn view_index(signed_in: bool) -> View { | ||
| let deadline = Instant::now() + gitv::GIT_TIMEOUT; | ||
| let mut rows = Vec::new(); | ||
| let root = open_root(); | ||
| for owner in root.as_ref().map(sorted_names).unwrap_or_default() { | ||
| // Read through the owner's open directory: a symlinked owner isn't followed or listed. | ||
| let Some(owner_dir) = open_owner(&owner) else { continue }; | ||
| for entry in sorted_names(&owner_dir) { | ||
| let Some(name) = entry.strip_suffix(".git") else { continue }; | ||
| if Instant::now() >= deadline { | ||
| return View::Busy; | ||
| } | ||
| let Some(mut dir) = repo_in(&owner_dir, &owner, name) else { continue }; | ||
| let public = dir.is_public(); | ||
| if !signed_in && !public { | ||
| continue; | ||
| } | ||
| dir.limit_until(deadline); | ||
| let repo = Repo::from_dir(&owner, name, dir); | ||
| // HEAD usually names a real branch; only look further when it doesn't. An empty | ||
| // repository caches as an empty answer. | ||
| let lookup = || { | ||
| let latest = repo.reader.latest_raw("HEAD", b"").or_else(|| { | ||
| repo.reader.resolve(&repo.reader.default_ref()).and_then(|id| repo.reader.latest_raw(&id, b"")) | ||
| }); | ||
| (Instant::now() < deadline).then(|| latest.unwrap_or_default()) | ||
| }; | ||
| let raw = match refs_fingerprint(&repo.reader.dir) { | ||
| Some(stamp) => cached(format!("index:{}:{stamp}", repo.reader.dir.path.display()), lookup), | ||
| None => lookup().map(Arc::from), | ||
| }; | ||
| let head = raw.as_deref().and_then(Head::parse); | ||
| // `repo`, and with it the directory handle, is dropped here. | ||
| rows.push(Row { public, owner: owner.clone(), name: name.to_string(), head }); | ||
| } | ||
| } | ||
| rows.sort_by_key(|row| Reverse(row.head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0))); | ||
| let count = plural(rows.len(), "repository", "repositories"); | ||
| let rows = rows | ||
| .into_iter() | ||
| .map(|row| { | ||
| let (subject, when) = row.head.map_or_else( | ||
| || ("No commits yet".into(), String::new()), | ||
| |h| (subject_or_placeholder(&h.subject).into(), ago(&h.stamp, &h.date)), | ||
| ); | ||
| templates::RepositoryRow { owner: row.owner, name: row.name, public: row.public, subject, when } | ||
| }) | ||
| .collect(); | ||
| View::Html( | ||
| templates::Repositories { title: "Repositories", signed_in, count, rows, branch: icon("branch"), host: HOST } | ||
| .to_string(), | ||
| ) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn an_incomplete_fingerprint_is_never_trusted() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; // Root reads anything, so the unreadable folder below can't be made. | ||
| } | ||
| use std::os::unix::fs::PermissionsExt; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-fingerprint-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| for folder in ["refs/heads/open", "refs/heads/locked/inner"] { | ||
| std::fs::create_dir_all(dir.join(folder)).unwrap(); | ||
| } | ||
| let repo = RepoDir::at(&dir).unwrap(); | ||
| assert!(refs_fingerprint(&repo).is_some()); | ||
| // A branch folder that can't be read: its refs could change unseen. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o000)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint missing a folder was trusted"); | ||
| // Names readable but not searchable: the folder's children can't be inspected. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o444)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint with an uninspectable folder was trusted"); | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o755)).unwrap(); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
+59−0
| @@ -0,0 +1,59 @@ | ||
| //! A branch or tag's history. | ||
| use super::{PAGE, Repo}; | ||
| use crate::html::{ago, icon, subject_or_placeholder}; | ||
| use crate::repository::Head; | ||
| use crate::urls::{Q, lossy, param}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.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.reader.resolve(&reference)?; | ||
| let out = repo.reader.git(&[ | ||
| "log", | ||
| &format!("-n{}", PAGE + 1), | ||
| &format!("--skip={skip}"), | ||
| "--date=format:%-d %b %Y", | ||
| Head::FORMAT, | ||
| &commit, | ||
| "--", | ||
| ])?; | ||
| let lines: Vec<&str> = out.lines().collect(); | ||
| let tags = repo.reader.tags_by_commit(); | ||
| let mut rows = Vec::new(); | ||
| for head in lines.iter().take(PAGE).filter_map(|line| Head::parse(line)) { | ||
| let labels = tags | ||
| .get(&head.oid) | ||
| .into_iter() | ||
| .flatten() | ||
| .map(|name| templates::TagLink { | ||
| name: lossy(name), | ||
| url: repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""), | ||
| }) | ||
| .collect(); | ||
| rows.push(templates::CommitRow { | ||
| url: repo.url("commit", &[("id", &head.oid)]), | ||
| subject: subject_or_placeholder(&head.subject).to_owned(), | ||
| short_id: head.oid.chars().take(7).collect(), | ||
| author: head.author, | ||
| when: ago(&head.stamp, &head.date), | ||
| tags: labels, | ||
| }); | ||
| } | ||
| let page_url = |n: usize| repo.url_at("log", &reference, b"", &format!("page={n}")); | ||
| Some(View::Html( | ||
| templates::History { | ||
| title: format!("Commits on {}", lossy(&reference)), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("log", &reference, Some(&commit)), | ||
| locator: repo.locator("log", &reference, b""), | ||
| rows, | ||
| newer: number.checked_sub(1).map(page_url), | ||
| older: (lines.len() > PAGE).then(|| page_url(number + 1)), | ||
| tag_icon: icon("tag"), | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
+277−0
| @@ -0,0 +1,277 @@ | ||
| //! The repository pages. Each view reads one open repository and returns a [`View`]. | ||
| mod blob; | ||
| mod commit; | ||
| mod index; | ||
| mod log; | ||
| mod tags; | ||
| mod tree; | ||
| use std::ffi::OsStr; | ||
| use std::fmt::Write as _; | ||
| use std::os::unix::ffi::OsStrExt; | ||
| use std::time::Instant; | ||
| use gitv::{HOST, RepoDir, render, repo_dir}; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| use crate::html::{ago, icon, layout, subject_or_placeholder}; | ||
| use crate::repository::Reader; | ||
| use crate::urls::{Q, encode, lossy}; | ||
| use crate::{View, templates}; | ||
| use blob::view_blob; | ||
| use commit::view_commit; | ||
| use log::view_log; | ||
| use tags::view_tags; | ||
| use tree::view_tree; | ||
| pub(crate) use index::view_index; | ||
| pub(crate) const PAGE: usize = 50; | ||
| /// Largest file the Raw view serves; bigger files are for `git clone`. | ||
| pub(crate) const RAW_LIMIT: usize = 50 << 20; | ||
| /// Largest file shown on a page; bigger files offer Raw instead. | ||
| pub(crate) const SHOW_LIMIT: usize = 1 << 20; | ||
| /// Largest patch shown on a commit page; only this much is ever read. | ||
| pub(crate) const DIFF_LIMIT: usize = 2 << 20; | ||
| pub(crate) struct Repo { | ||
| pub(crate) signed_in: bool, | ||
| pub(crate) owner: String, | ||
| pub(crate) name: String, | ||
| pub(crate) reader: Reader, | ||
| } | ||
| impl Repo { | ||
| /// A repository opened through its owner and repository directories with symlinks refused; | ||
| /// every git command then runs inside that open directory. | ||
| pub(crate) fn open(owner: &str, name: &str) -> Option<Repo> { | ||
| let mut dir = repo_dir(owner, name)?; | ||
| dir.limit_until(Instant::now() + gitv::GIT_TIMEOUT); | ||
| Some(Repo::from_dir(owner, name, dir)) | ||
| } | ||
| pub(crate) fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo { | ||
| Repo { signed_in: false, reader: Reader::new(dir), owner: owner.into(), name: name.into() } | ||
| } | ||
| pub(crate) fn page(&self, title: &str, body: &str) -> String { | ||
| layout(title, body, self.signed_in) | ||
| } | ||
| pub(crate) fn clone_address(&self) -> (&'static str, String) { | ||
| if self.reader.dir.is_public() { | ||
| ("HTTPS", format!("https://{HOST}/{}/{}", self.owner, self.name)) | ||
| } else { | ||
| ("SSH", format!("git@{HOST}:{}/{}.git", self.owner, self.name)) | ||
| } | ||
| } | ||
| pub(crate) 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.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. | ||
| pub(crate) fn url_at(&self, view: &str, reference: &[u8], path: &[u8], extra: &str) -> String { | ||
| let mut url = self.url(view, &[]); | ||
| if !reference.is_empty() { | ||
| let _ = write!(url, "?ref={}", encode(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 | ||
| } | ||
| /// Latest change to one entry at this immutable revision. Keep the original path bytes | ||
| /// for Git and cache the timestamp itself so relative dates stay fresh. | ||
| pub(crate) fn entry_commit(&self, record: &str) -> Option<templates::EntryCommit> { | ||
| let mut fields = record.splitn(6, '\0'); | ||
| let oid = fields.next()?; | ||
| let stamp = fields.next()?; | ||
| let datetime = fields.next()?; | ||
| let full_date = fields.next()?; | ||
| let subject = subject_or_placeholder(fields.next()?); | ||
| let message = fields.next()?.trim_end(); | ||
| Some(templates::EntryCommit { | ||
| url: self.url("commit", &[("id", oid)]), | ||
| subject: subject.into(), | ||
| message: if message.is_empty() { subject } else { message }.into(), | ||
| when: ago(stamp, full_date.split(',').next().unwrap_or(full_date)), | ||
| full_date: full_date.into(), | ||
| datetime: datetime.into(), | ||
| }) | ||
| } | ||
| /// A cache key for rendered content of `oid` that links within this repository. | ||
| pub(crate) 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`. | ||
| pub(crate) fn markdown(&self, source: &str, dir: &[u8], reference: &[u8]) -> String { | ||
| render::markdown(source, dir, &|path, image| { | ||
| if image { | ||
| self.url_at("raw", reference, path, "") | ||
| } else if path.is_empty() { | ||
| self.url_at("tree", reference, b"", "") | ||
| } else { | ||
| self.url_at("blob", reference, path, "") | ||
| } | ||
| }) | ||
| } | ||
| /// Name, clone address and tabs, shared by every repository page. `commit` is `reference` | ||
| /// already resolved, when the caller has it. | ||
| pub(crate) fn masthead(&self, active: &str, reference: &[u8], commit: Option<&str>) -> String { | ||
| let commit = commit.map(str::to_string).or_else(|| self.reader.resolve(reference)); | ||
| let commits = commit.map_or(0, |c| self.reader.commit_count(&c)); | ||
| let tags = self.reader.tags().len(); | ||
| let tab = |view: &str, glyph: &str, label: &str, count: Option<usize>| { | ||
| let current = if view == active { r#" aria-current="page""# } else { "" }; | ||
| let tab_ref = if view == "tags" { b"" } else { reference }; | ||
| let badge = count.map_or(String::new(), |n| format!(r#"<span class="n">{n}</span>"#)); | ||
| format!( | ||
| r#"<a href="{}"{current}>{}{label}{badge}</a>"#, | ||
| attr(&self.url_at(view, tab_ref, b"", "")), | ||
| icon(glyph) | ||
| ) | ||
| }; | ||
| let (protocol, address) = self.clone_address(); | ||
| format!( | ||
| r#"<div class="repohead"><h1 class="reponame"><a class="own" href="/">{owner}</a><span class="sep">/</span><a href="{home}">{name}</a></h1> | ||
| <label class="clone"><span>{protocol}</span><input readonly aria-label="Clone address" value="{address}"></label></div> | ||
| <nav class="tabs" aria-label="Repository">{}{}{}</nav>"#, | ||
| tab("tree", "code", "Code", None), | ||
| tab("log", "commits", "Commits", Some(commits)), | ||
| tab("tags", "tag", "Tags", Some(tags)), | ||
| owner = esc(&self.owner), | ||
| name = esc(&self.name), | ||
| home = attr(&self.url("tree", &[])), | ||
| ) | ||
| } | ||
| /// Branch and tag menu, then the path as breadcrumbs. | ||
| pub(crate) fn locator(&self, view: &str, reference: &[u8], path: &[u8]) -> String { | ||
| // `link` is what the URL carries; `name` is what people see. | ||
| let item = |link: Vec<u8>, name: &[u8]| { | ||
| let current = if link == reference { r#" aria-current="true""# } else { "" }; | ||
| let href = self.url_at(view, &link, path, ""); | ||
| format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(&lossy(name))) | ||
| }; | ||
| let branches: String = self.reader.heads().iter().map(|b| item(self.reader.branch_ref(b), b)).collect(); | ||
| let tags: String = self.reader.tags().iter().map(|t| item(self.reader.tag_ref(t), t)).collect(); | ||
| let mut menu = format!("<h2>Branches</h2>{branches}"); | ||
| if !tags.is_empty() { | ||
| menu += &format!("<h2>Tags</h2>{tags}"); | ||
| } | ||
| let mut crumbs = String::new(); | ||
| if !path.is_empty() { | ||
| let _ = write!( | ||
| crumbs, | ||
| r#"<a href="{}">{}</a>"#, | ||
| attr(&self.url_at("tree", reference, b"", "")), | ||
| 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(&lossy(part))); | ||
| } else { | ||
| 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>"#); | ||
| } | ||
| format!( | ||
| r#"<div class="locator"><details class="refmenu"><summary>{}{}{}</summary><div class="menu">{menu}</div></details> | ||
| {crumbs}</div>"#, | ||
| icon("branch"), | ||
| esc(&lossy( | ||
| reference | ||
| .strip_prefix(b"refs/heads/") | ||
| .or_else(|| reference.strip_prefix(b"refs/tags/")) | ||
| .unwrap_or(reference) | ||
| )), | ||
| icon("chevron"), | ||
| ) | ||
| } | ||
| pub(crate) 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)] | ||
| ) | ||
| } | ||
| } | ||
| /// 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. | ||
| pub(crate) struct Entry { | ||
| pub(crate) kind: String, | ||
| pub(crate) oid: String, | ||
| pub(crate) size: usize, | ||
| pub(crate) name: Vec<u8>, | ||
| } | ||
| impl Entry { | ||
| /// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs. | ||
| pub(crate) 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() }) | ||
| } | ||
| pub(crate) 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. | ||
| pub(crate) 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.reader.git_bytes(&args)?; | ||
| Entry::list(&out).into_iter().find(|e| e.name == path) | ||
| } | ||
| pub(crate) fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) -> View { | ||
| let Some(mut repo) = Repo::open(owner, name) else { | ||
| return if signed_in { View::Missing(true) } else { View::LoginRequired }; | ||
| }; | ||
| if !signed_in && !repo.reader.dir.is_public() { | ||
| return View::LoginRequired; | ||
| } | ||
| repo.signed_in = signed_in; | ||
| let result = match view { | ||
| None => Some(View::Redirect(repo.url("tree", &[]))), | ||
| Some("tree") => view_tree(&repo, q), | ||
| Some("blob") => view_blob(&repo, q, false), | ||
| Some("raw") => view_blob(&repo, q, true), | ||
| Some("log") => view_log(&repo, q), | ||
| Some("commit") => view_commit(&repo, q), | ||
| Some("tags") => view_tags(&repo), | ||
| Some(_) => None, | ||
| }; | ||
| result.unwrap_or(View::Missing(signed_in)) | ||
| } | ||
+50−0
| @@ -0,0 +1,50 @@ | ||
| //! The tags in a repository. | ||
| use std::fmt::Write as _; | ||
| use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc}; | ||
| use super::Repo; | ||
| use crate::View; | ||
| use crate::html::ago; | ||
| use crate::urls::lossy; | ||
| pub(crate) fn view_tags(repo: &Repo) -> Option<View> { | ||
| let out = repo.reader.git_bytes(&[ | ||
| "for-each-ref", | ||
| "--sort=-creatordate", | ||
| "--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:format:%-d %b %Y)%1f%(objecttype)%1f%(contents:subject)", | ||
| "refs/tags", | ||
| ])?; | ||
| let mut rows = String::new(); | ||
| for line in out.split(|b| *b == b'\n') { | ||
| // The tag's message goes last, so one containing the separator stays whole. | ||
| let Ok([name, direct, peeled, stamp, date, kind, note]) = | ||
| <[&[u8]; 7]>::try_from(line.splitn(7, |b| *b == 0x1f).collect::<Vec<_>>()) | ||
| else { | ||
| continue; | ||
| }; | ||
| let target = if peeled.is_empty() { direct } else { peeled }; | ||
| let note = if kind == b"tag" && !note.is_empty() { | ||
| format!(r#"<span class="tnote">{}</span>"#, esc(&lossy(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(&lossy(name)), | ||
| repo.sha_link(&lossy(target)), | ||
| ago(&lossy(stamp), &lossy(date)), | ||
| attr(&repo.url_at("tree", &repo.reader.tag_ref(name), b"", "")) | ||
| ); | ||
| } | ||
| 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.reader.default_ref(), None) + &listing; | ||
| Some(View::Html(repo.page(&format!("Tags in {}/{}", repo.owner, repo.name), &body))) | ||
| } | ||
+157−0
| @@ -0,0 +1,157 @@ | ||
| //! Folder listings, with the latest change to each entry and the README. | ||
| use std::ffi::OsStr; | ||
| use std::sync::Arc; | ||
| use gitv::{HOST, render}; | ||
| use html_escape::encode_text as esc; | ||
| use super::{Entry, PAGE, Repo, SHOW_LIMIT, entry}; | ||
| use crate::cache::cached; | ||
| use crate::html::{ago, icon, plural, size, subject_or_placeholder}; | ||
| use crate::urls::{Q, clean_path, encode, join, lossy, param, parent_of, spec}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref()); | ||
| let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?; | ||
| let Some(commit) = repo.reader.resolve(&reference) else { | ||
| if !repo.reader.heads().is_empty() { | ||
| return None; | ||
| } | ||
| 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(repo.page(&format!("{}/{}", repo.owner, repo.name), &body))); | ||
| }; | ||
| let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)]; | ||
| let Some(listing) = repo.reader.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_at("blob", &reference, &path, ""))); | ||
| }; | ||
| let mut entries = Entry::list(&listing); | ||
| // Folders first, then files and submodules, each alphabetically. | ||
| entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase())); | ||
| let page: usize = param(q, "page").and_then(|n| n.parse().ok()).unwrap_or(0); | ||
| let offset = page.checked_mul(PAGE)?; | ||
| if page != 0 && offset >= entries.len() { | ||
| return None; | ||
| } | ||
| let mut rows = Vec::new(); | ||
| let visible = &entries[offset..entries.len().min(offset + PAGE)]; | ||
| let names: Vec<_> = visible.iter().map(|item| item.name.as_slice()).collect(); | ||
| let histories = repo.reader.entry_histories(&commit, &path, &names); | ||
| for (item, record) in visible.iter().zip(histories) { | ||
| let path = join(&path, &item.name); | ||
| let (view, class, glyph) = match item.kind.as_str() { | ||
| "tree" => (Some("tree"), "entry dir", "dir"), | ||
| "commit" => (None, "entry sub", "module"), | ||
| _ => (Some("blob"), "entry", "file"), | ||
| }; | ||
| let row = templates::TreeRow { | ||
| name: lossy(&item.name), | ||
| class, | ||
| icon: icon(glyph), | ||
| href: view.map(|view| repo.url_at(view, &reference, &path, "")), | ||
| short_id: &item.oid[..item.oid.len().min(7)], | ||
| commit: record.as_deref().and_then(|record| repo.entry_commit(record)), | ||
| }; | ||
| rows.push(row); | ||
| } | ||
| let page_url = |number| repo.url_at("tree", &reference, &path, &format!("page={number}")); | ||
| // 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()); | ||
| let readme = readme.filter(|e| e.size <= SHOW_LIMIT).map(|readme| { | ||
| let name = lossy(&readme.name); | ||
| let rendered = | ||
| render_file(repo, &readme.oid, readme.size, &name, &path, &reference, !render::is_markdown(&name)); | ||
| let content = rendered | ||
| .as_deref() | ||
| .and_then(|r| r.split_once('\x1f')) | ||
| .map_or(r#"<p class="note">This README couldn't be read.</p>"#, |(_, html)| html); | ||
| (name.into_owned(), content.to_string()) | ||
| }); | ||
| let title = if path.is_empty() { | ||
| format!("{}/{}", repo.owner, repo.name) | ||
| } else { | ||
| format!("{} at {}", lossy(&path), lossy(&reference)) | ||
| }; | ||
| let head = repo.reader.latest(&commit, &path).map(|head| templates::TreeHead { | ||
| url: repo.url("commit", &[("id", &head.oid)]), | ||
| sha_link: repo.sha_link(&head.oid), | ||
| subject: subject_or_placeholder(&head.subject).to_string(), | ||
| author: head.author, | ||
| when: ago(&head.stamp, &head.date), | ||
| }); | ||
| Some(View::Html( | ||
| templates::Tree { | ||
| title, | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("tree", &reference, Some(&commit)), | ||
| locator: repo.locator("tree", &reference, &path), | ||
| head, | ||
| up: (!path.is_empty()).then(|| repo.url_at("tree", &reference, parent_of(&path), "")), | ||
| rows, | ||
| previous: page.checked_sub(1).map(page_url), | ||
| next: (entries.len() - offset > PAGE).then(|| page_url(page + 1)), | ||
| readme, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// A file rendered for display, as `facts` 0x1f `html`: highlighted code, or Markdown with | ||
| /// links into this repository at `reference` (the file lives in `dir`). The file view and the | ||
| /// README panel both use this, so they share one cached value per rendering instead of | ||
| /// storing different shapes under one key. The facts and the rendering are cached together, | ||
| /// so a repeat view reads no blob at all. | ||
| pub(crate) fn render_file( | ||
| repo: &Repo, | ||
| oid: &str, | ||
| file_size: usize, | ||
| name: &str, | ||
| dir: &[u8], | ||
| reference: &[u8], | ||
| as_code: bool, | ||
| ) -> Option<Arc<str>> { | ||
| let key = if as_code { | ||
| // Highlighting depends only on the content and the file's type, so it's shared. | ||
| format!("code:{oid}:{name}") | ||
| } else { | ||
| // Links depend on the repository, folder and ref too. | ||
| repo.key("md", oid, &format!("{}:{}", encode(dir), encode(reference))) | ||
| }; | ||
| cached(key, || { | ||
| let data = repo.reader.git_bytes(&["cat-file", "blob", 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(file_size))); | ||
| } | ||
| let text = String::from_utf8_lossy(&data); | ||
| let facts = format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(file_size)); | ||
| let html = if as_code { | ||
| code_view(name, &text) | ||
| } else { | ||
| format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, dir, reference)) | ||
| }; | ||
| Some(format!("{facts}\x1f{html}")) | ||
| }) | ||
| } | ||
| /// Highlighted source with a line-number gutter. | ||
| pub(crate) 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) | ||
| ) | ||
| } | ||
| @@ -6,7 +6,7 @@ | ||
| <div class="panel-head"><div class="lead"><b class="who">{{ h.author }}</b><a class="subject" href="{{ h.url }}">{{ h.subject }}</a></div><div class="side">{{ h.sha_link|safe }}<span>{{ h.when }}</span></div></div> | ||
| {% endif %} | ||
| <ul class="rows tree-list"> | ||
| {% if let Some(url) = up %}<li><a class="entry" href="{{ url }}">{{ super::icon("up")|safe }}<span class="name">..</span></a></li>{% endif %} | ||
| {% if let Some(url) = up %}<li><a class="entry" href="{{ url }}">{{ crate::html::icon("up")|safe }}<span class="name">..</span></a></li>{% endif %} | ||
| {% for row in rows %}{{ row|safe }}{% endfor %} | ||
| </ul></div> | ||
| {% if previous.is_some() || next.is_some() %} | ||
| @@ -15,5 +15,5 @@ | ||
| {% if let Some(url) = next %}<a class="button" href="{{ url }}">Next</a>{% endif %} | ||
| </nav> | ||
| {% endif %} | ||
| {% if let Some((name, content)) = readme %}<section class="panel"><div class="panel-head"><div class="lead">{{ super::icon("book")|safe }}<b>{{ name }}</b></div></div>{{ content|safe }}</section>{% endif %} | ||
| {% if let Some((name, content)) = readme %}<section class="panel"><div class="panel-head"><div class="lead">{{ crate::html::icon("book")|safe }}<b>{{ name }}</b></div></div>{{ content|safe }}</section>{% endif %} | ||
| {% endblock %} | ||