//! The pages a public hosted repository is read by, at `///…` //! (hub.rs `public_git`), the paths Forgejo had, so a link to the old forge //! still lands: files, the README, the log and one commit. Plain HTML from the //! server, with no login and no script but the theme's, so a reader and a search engine see the //! same thing. Private repositories never reach here. `/git///…`, //! where they were first, is sent here. //! //! - `/o/n` — the root directory and the README; //! - `/o/n/tree/?rev=` — a directory or a file; //! - `/o/n/raw/?rev=` — a file's bytes (an LFS file's own, when the hub has them); //! - `/o/n/log?rev=` — the last 50 commits; //! - `/o/n/commit/` — one commit and its diff; //! - Forgejo's `src/`, `raw/`, `media/` and `commits/` paths — sent to the above. //! //! [`front`] is the site's own front page: the public repositories, for a //! visitor who is not logged in to the hub, with the map of which uses which //! and what was built in them lately (graph.rs, its public part). use anyhow::Result; use crate::hosted; /// What a path answers with. pub enum Page { Html(String), /// Somewhere else on the site (a Forgejo path, said the new way). Moved(String), /// A file's bytes. Raw(Vec), } fn esc(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) } /// A path segment or query value as it goes into a link. fn link(s: &str) -> String { crate::hub::pct_encode(s).replace("%2F", "/") } fn is_markdown(name: &str) -> bool { let n = name.to_ascii_lowercase(); n.ends_with(".md") || n.ends_with(".markdown") } /// A Markdown file of `dir` as HTML. Raw HTML in it is shown as text, never /// passed through: the page is the hub's own origin. A relative link goes to /// the file's page, a relative image to its bytes, both at `revq`; a link with /// a scheme other than http(s) or mailto is dropped. fn markdown(key: &str, dir: &str, revq: &str, text: &str) -> String { use pulldown_cmark::{CowStr, Event, Options, Parser, Tag}; let local = |to: &str, kind: &str| -> String { let (target, frag) = to.split_once('#').map(|(t, f)| (t, format!("#{f}"))).unwrap_or((to, String::new())); if target.is_empty() { return frag; } let mut parts: Vec<&str> = if target.starts_with('/') { vec![] } else { dir.split('/').filter(|p| !p.is_empty()).collect() }; for p in target.split('/') { match p { "" | "." => {} ".." => { parts.pop(); } p => parts.push(p), } } format!("/{key}/{kind}/{}{revq}{frag}", link(&parts.join("/"))) }; let url = |to: &str, kind: &str| -> Option { let scheme = to.split_once(':').map(|(s, _)| s.to_ascii_lowercase()) .filter(|s| !s.contains('/') && !s.contains('#') && !s.contains('?')); match scheme.as_deref() { None => Some(local(to, kind)), Some("http" | "https" | "mailto") => Some(to.to_string()), Some(_) => None, } }; let events = Parser::new_ext(text, Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS) .map(|e| match e { Event::Html(h) | Event::InlineHtml(h) => Event::Text(h), Event::Start(Tag::Link { link_type, dest_url, title, id }) => Event::Start(Tag::Link { link_type, title, id, dest_url: CowStr::from(url(&dest_url, "tree").unwrap_or_default()), }), Event::Start(Tag::Image { link_type, dest_url, title, id }) => Event::Start(Tag::Image { link_type, title, id, dest_url: CowStr::from(url(&dest_url, "raw").unwrap_or_default()), }), e => e, }); let mut html = String::new(); pulldown_cmark::html::push_html(&mut html, events); format!("
{html}
") } /// A small line icon for an entry of a directory, by its kind: a folder, a /// document, code, an image, settings, a script or any other file. fn icon(name: &str, dir: bool) -> String { const FOLDER: &str = ""; const DOC: &str = ""; const CODE: &str = ""; const IMAGE: &str = ""; const CONF: &str = ""; const SHELL: &str = ""; const FILE: &str = ""; let n = name.to_ascii_lowercase(); let ext = n.rsplit_once('.').map(|(_, e)| e).unwrap_or(""); let d = if dir { FOLDER } else if n.starts_with("readme") || n.starts_with("license") || n.starts_with("licence") || n.starts_with("changelog") || matches!(ext, "md" | "markdown" | "txt" | "pdf") { DOC } else if matches!(ext, "png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "ico" | "avif") { IMAGE } else if matches!(ext, "sh" | "bash" | "zsh" | "fish") || n == "makefile" || n == "dockerfile" { SHELL } else if matches!(ext, "toml" | "json" | "yaml" | "yml" | "lock" | "conf" | "ini" | "cfg" | "env" | "service" | "timer" | "path" | "nft") || n.starts_with('.') { CONF } else if matches!(ext, "rs" | "ts" | "tsx" | "js" | "jsx" | "mjs" | "py" | "c" | "h" | "cpp" | "go" | "java" | "kt" | "swift" | "css" | "scss" | "html" | "wgsl" | "wesl" | "glsl" | "sql" | "lua" | "zig" | "frits") { CODE } else { FILE }; format!("{d}", if dir { " dir" } else { "" }) } /// A size as a person reads it: 980 B, 24.3 kB, 1.2 MB. fn size(b: u64) -> String { match b { 0..1000 => format!("{b} B"), 1000..1_000_000 => format!("{:.1} kB", b as f64 / 1e3), _ => format!("{:.1} MB", b as f64 / 1e6), } } /// The hub page's own stylesheet (`/app.css`: its palette, font and light and /// dark), and on top only what these pages lay out. A phone reads the front /// page as cards and the log as stacked rows: a three-column table squeezed a /// description into a strip a few words wide. const STYLE: &str = "body{font-size:16px;line-height:1.55}\ .pub{max-width:60rem;margin:0 auto;padding:16px}\ a{color:var(--m-accent-text);text-decoration:none}a:hover{text-decoration:underline}\ .pub-head{display:flex;gap:8px 16px;align-items:center;flex-wrap:wrap;padding-bottom:12px;margin-bottom:16px;border-bottom:1px solid var(--m-border)}\ .pub-head h1{display:flex;align-items:center;flex-wrap:wrap;gap:.4em;margin:0;font-size:1.3rem;color:var(--m-text-strong)}\ .pub-head h1 a{color:inherit}.pub-head h1 img{width:1.35em;height:1.35em}.pub-head h1 span{color:var(--m-text-dim);font-weight:400}\ .pub-head .end{margin-left:auto}.pub-head .clone{flex-basis:100%;font-size:14px}\ .pub-in{padding:6px 16px;border-radius:var(--m-radius);background:var(--m-accent);color:var(--m-on-accent);font-weight:600}\ .pub-in:hover{background:var(--m-accent-hover);text-decoration:none}\ .pub-list{display:grid;gap:12px;grid-template-columns:repeat(auto-fill,minmax(min(100%,17rem),1fr))}\ .pub-card{display:flex;flex-direction:column;gap:6px;padding:14px 16px;background:var(--m-surface);color:var(--m-text);\ border:1px solid var(--m-border);border-radius:var(--m-radius-lg);box-shadow:var(--lift-1)}\ .pub-card:hover{border-color:var(--m-accent);text-decoration:none}\ .pub-card strong{color:var(--m-accent-text);font-size:1.05rem}.pub-card time{margin-top:auto;color:var(--m-text-faint);font-size:13px}\ pre{background:var(--m-surface-sunken);border:1px solid var(--m-border);border-radius:var(--m-radius);padding:12px;overflow:auto;font-size:13px}\ code{background:var(--m-surface-sunken);border-radius:var(--m-radius-sm);padding:0 .3rem;white-space:nowrap}.clone code,.get code{white-space:normal;overflow-wrap:anywhere}\ table{border-collapse:separate;border-spacing:0;width:100%;background:var(--m-surface);border:1px solid var(--m-border);border-radius:var(--m-radius-lg);overflow:hidden}\ td{padding:8px 12px;border-bottom:1px solid var(--m-border);vertical-align:top}tr:last-child td{border-bottom:0}\ .muted{color:var(--m-text-dim)}td.muted{white-space:nowrap}h2{font-size:1.1rem;margin:24px 0 8px}\ @media (max-width:40rem){.pub{padding:12px}table.log tr{display:block;padding:8px 12px;border-bottom:1px solid var(--m-border)}\ table.log tr:last-child{border-bottom:0}table.log td{display:block;padding:1px 0;border:0}table.log td.muted{font-size:13px}}\ figure.map{margin:0 0 16px}figure.map svg{width:100%;height:auto;max-height:70vh;background:var(--m-surface);border:1px solid var(--m-border);border-radius:var(--m-radius-lg)}figcaption{font-size:13px;margin-top:4px}\ ul.files{list-style:none;margin:0;padding:0;background:var(--m-surface);border:1px solid var(--m-border);border-radius:var(--m-radius-lg);overflow:hidden}\ ul.files li+li{border-top:1px solid var(--m-border)}\ ul.files a{display:flex;align-items:center;gap:10px;padding:7px 14px;color:var(--m-text)}\ ul.files a:hover{background:var(--m-hover);text-decoration:none}ul.files a:hover .name{color:var(--m-accent-text)}\ ul.files .name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\ ul.files .size{color:var(--m-text-faint);font-size:13px;font-variant-numeric:tabular-nums;white-space:nowrap}\ svg.ico{flex:none;width:16px;height:16px;fill:none;stroke:var(--m-text-faint);stroke-width:1.2;stroke-linecap:round;stroke-linejoin:round}\ svg.ico.dir{stroke:var(--m-accent-text);fill:var(--m-accent-soft)}\ section.readme{margin-top:24px;background:var(--m-surface);border:1px solid var(--m-border);border-radius:var(--m-radius-lg);overflow:hidden}\ section.readme>h2{display:flex;align-items:center;gap:8px;margin:0;padding:8px 14px;font-size:14px;font-weight:600;border-bottom:1px solid var(--m-border);background:var(--m-surface-sunken)}\ section.readme>pre{margin:0;border:0;border-radius:0}section.readme .md{padding:4px 24px 16px}\ .md{overflow-wrap:anywhere}.md h1,.md h2,.md h3{color:var(--m-text-strong);line-height:1.25;margin:24px 0 10px}\ .md h1{font-size:1.6rem;padding-bottom:6px;border-bottom:1px solid var(--m-border)}.md h2{font-size:1.25rem;padding-bottom:4px;border-bottom:1px solid var(--m-border)}\ .md h3{font-size:1.05rem}.md p,.md ul,.md ol,.md blockquote,.md pre,.md table{margin:0 0 14px}.md li+li{margin-top:3px}\ .md code{white-space:normal;font-size:.9em}.md pre code{padding:0;background:none;white-space:pre}\ .md blockquote{padding:0 14px;color:var(--m-text-dim);border-left:3px solid var(--m-border-strong)}\ .md img{max-width:100%}.md hr{border:0;border-top:1px solid var(--m-border);margin:20px 0}\ .md table{width:auto;display:block;overflow-x:auto;background:none}.md th,.md td{padding:6px 12px;border:1px solid var(--m-border)}\ .md th{background:var(--m-surface-sunken);text-align:left}"; /// The page around a body: the hub's stylesheet and logo, and a header that /// starts with the site's name. Light or dark follows the device, or the /// choice made on the hub's page (its `m-theme`, as web/src/index.html reads /// it): the one script, and the page reads the same without it. fn page_html(title: &str, host: &str, crumbs: &str, rest: &str, body: &str) -> String { format!( "\ {title}\ \
\

\"\"{h}{crumbs}

{rest}
{body}
", h = esc(host), ) } /// `front` is the project's front page, whose body says how to get it /// already: the header leaves its clone line out rather than say it twice. fn frame(repo: &str, host: &str, title: &str, body: &str, front: bool) -> String { let key = repo.trim_end_matches(".git"); let (k, h) = (esc(key), esc(host)); let clone = if front { String::new() } else { format!("clone: git clone https://{h}/{k}.git") }; page_html( &format!("{} · {k}", esc(title)), host, &format!("/{k}"), &format!("log{clone}"), body, ) } /// The front page: every public repository, newest change first, and the way /// in to the hub for its people. pub fn front(host: &str) -> String { let mut rows: Vec<(String, String, String)> = hosted::repos().into_iter() .filter(|(_, r)| r["visibility"] == "public") .map(|(k, r)| { let at = hosted::log(&k, None, 1).ok().and_then(|l| l.first().and_then(|c| c["at"].as_str().map(str::to_string))) .unwrap_or_default(); (k, r["description"].as_str().unwrap_or("").to_string(), at) }) .collect(); rows.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0))); let mut body = "
".to_string(); for (k, d, at) in &rows { let (owner, name) = k.split_once('/').map(|(o, n)| (format!("{o}/"), n)).unwrap_or_default(); let day = at.get(..10).unwrap_or(""); body += &format!("{o}{n}{d}", k = esc(k), o = esc(&owner), n = esc(if name.is_empty() { k } else { name }), day = esc(day), d = if d.is_empty() { String::new() } else { format!("{}", esc(d)) }); } body += "
"; if rows.is_empty() { body = "

No public projects yet.

".into(); } else { body = map() + &body; } page_html(&esc(host), host, "", "Log in", &body) } /// The public projects as a map, and the techs built in them lately. fn map() -> String { let g = crate::graph::public(&crate::graph::all()); let mut s = format!("
{}
An arrow runs from a project to one that uses its code, \ amber when that one uses an older commit. The ring is the share of its techs built.
", crate::graph::svg(&g, Some("/"))); let landed = g["landed"].as_array().cloned().unwrap_or_default(); if !landed.is_empty() { s += "

Built lately

"; for l in &landed { let day = l["at"].as_i64().and_then(|t| chrono::DateTime::from_timestamp(t, 0)).map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default(); let repo = l["repo"].as_str().unwrap_or(""); s += &format!("", esc(&day), esc(l["name"].as_str().unwrap_or("")), r = esc(repo), n = esc(repo.rsplit('/').next().unwrap_or(repo))); } s += "
{}{n}{}
"; } s + "

Repositories

" } fn query(q: &str, k: &str) -> Option { q.split('&').find_map(|p| p.strip_prefix(&format!("{k}="))).map(crate::hub::pct_decode) } /// Forgejo's paths, said the new way: `src/branch//

` (and `commit`, /// `tag`), `raw/…` and `media/…` likewise, and `commits/branch/`. A branch /// name with a `/` in it is read as its first segment, the rest as the path. fn forgejo(key: &str, tail: &str) -> Option { let (kind, rest) = tail.split_once('/')?; let to = match kind { "src" => "tree", "raw" | "media" => "raw", "commits" => "log", _ => return None, }; let (_, rest) = rest.split_once('/').filter(|(how, _)| matches!(*how, "branch" | "commit" | "tag"))?; let (rev, path) = rest.split_once('/').unwrap_or((rest, "")); if rev.is_empty() { return None; } let path = if to == "log" { String::new() } else { format!("/{path}") }; Some(format!("/{key}/{to}{}?rev={rev}", path.trim_end_matches('/'))) } /// A file's bytes at `rev`: an LFS pointer is answered with its object, when the /// hub's store has it. fn raw(repo: &str, rev: Option<&str>, path: &str) -> Result>> { let v = hosted::show(repo, rev, path)?; if v["kind"] != "file" { return Ok(None); } let bytes = hosted::blob(repo, rev, path)?; let oid = std::str::from_utf8(&bytes).ok().filter(|t| t.starts_with("version https://git-lfs")) .and_then(|t| t.lines().find_map(|l| l.strip_prefix("oid sha256:")).map(str::trim)); if let Some(stored) = oid.and_then(crate::mirror::cached_object) { return Ok(Some(std::fs::read(stored)?)); } Ok(Some(bytes)) } /// The page for `tail` (what follows `///`), or none for a /// path that is not one. pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result> { let key = repo.trim_end_matches(".git"); let rev = query(q, "rev"); let revq = rev.as_deref().map(|r| format!("?rev={}", link(r))).unwrap_or_default(); if let Some(to) = forgejo(key, tail) { return Ok(Some(Page::Moved(to))); } if let Some(path) = tail.strip_prefix("raw/") { return Ok(raw(repo, rev.as_deref(), &crate::hub::pct_decode(path))?.map(Page::Raw)); } if tail.is_empty() || tail == "tree" || tail.starts_with("tree/") { let path = crate::hub::pct_decode(tail.strip_prefix("tree").unwrap_or("").trim_start_matches('/')); let v = hosted::show(repo, rev.as_deref(), &path)?; let mut body = String::new(); // How to get it, on its front page: clone it, or download main without git. if path.is_empty() && rev.is_none() { body += &format!("

Get it: git clone https://{h}/{k}.git, or download {main} as .tar.gz.

", h = esc(host), k = esc(key), main = esc(hosted::get(repo).and_then(|r| r["project"]["main"].as_str().map(str::to_string)).as_deref().unwrap_or("main"))); } if !path.is_empty() { let up = path.rsplit_once('/').map(|(u, _)| u).unwrap_or(""); body += &format!("

.. /{}

", esc(key), link(up), revq, esc(&path)); } if v["kind"] == "dir" { // Folders first, as a reader looks for them. let mut entries: Vec<&serde_json::Value> = v["entries"].as_array().into_iter().flatten().collect(); entries.sort_by_key(|e| e["kind"] != "dir"); body += "
    "; for e in entries { let n = e["name"].as_str().unwrap_or(""); let full = if path.is_empty() { n.to_string() } else { format!("{path}/{n}") }; let dir = e["kind"] == "dir"; body += &format!("
  • {}{}{}
  • ", esc(key), link(&full), revq, icon(n, dir), esc(n), e["size"].as_u64().filter(|_| !dir).map(size).unwrap_or_default()); } body += "
"; // The README of the directory, as a page when it is Markdown. let names = v["entries"].as_array().into_iter().flatten().filter_map(|e| e["name"].as_str()); let readmes: Vec<&str> = names.filter(|n| n.to_ascii_lowercase().starts_with("readme")).collect(); if let Some(readme) = readmes.iter().find(|n| is_markdown(n)).or(readmes.first()) { let p = if path.is_empty() { readme.to_string() } else { format!("{path}/{readme}") }; if let Some(t) = hosted::show(repo, rev.as_deref(), &p)?["text"].as_str() { body += &format!("

{}{}

{}
", icon(readme, false), esc(readme), if is_markdown(readme) { markdown(key, &path, &revq, t) } else { format!("
{}
", esc(t)) }); } } } else if let Some(t) = v["text"].as_str() { let dir = path.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); body += &format!("

raw

{}", esc(key), link(&path), revq, if is_markdown(&path) { markdown(key, dir, &revq, t) } else { format!("
{}
", esc(t)) }); } else { body += &format!("

A binary file of {} bytes: download.

", v["size"], esc(key), link(&path), revq); } let title = if path.is_empty() { key.to_string() } else { path.clone() }; return Ok(Some(Page::Html(frame(repo, host, &title, &body, path.is_empty() && rev.is_none())))); } if tail == "log" { let mut body = "".to_string(); for c in hosted::log(repo, rev.as_deref(), 50)? { let sha = c["sha"].as_str().unwrap_or(""); body += &format!("", esc(key), esc(sha), esc(sha.get(..10).unwrap_or(sha)), esc(c["subject"].as_str().unwrap_or("")), esc(c["at"].as_str().unwrap_or("").get(..10).unwrap_or(""))); } body += "
{}{}{}
"; return Ok(Some(Page::Html(frame(repo, host, "log", &body, false)))); } if let Some(sha) = tail.strip_prefix("commit/") { if !sha.chars().all(|c| c.is_ascii_hexdigit()) { return Ok(None); } let c = hosted::commit(repo, sha)?; let body = format!("

{} · {}

{}
{}
", esc(c["author"].as_str().unwrap_or("")), esc(c["at"].as_str().unwrap_or("")), esc(c["message"].as_str().unwrap_or("")), esc(c["diff"].as_str().unwrap_or(""))); return Ok(Some(Page::Html(frame(repo, host, sha, &body, false)))); } Ok(None) } #[cfg(test)] mod tests { use super::*; #[test] fn a_readme_is_markdown_with_no_html_or_scripts_of_its_own() { let md = "# Title\n\n\n\nSee [the docs](docs/hub.md#top), [up](../x.rs), \ [site](https://example.org), [bad](javascript:alert(1)) and ![logo](img/a.png).\n\n| a | b |\n|---|---|\n| 1 | 2 |\n"; let h = markdown("o/n", "sub", "?rev=v1", md); assert!(h.contains("

Title

") && h.contains(""), "{h}"); assert!(!h.contains("