garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/codeview.rs

raw

//! The pages a public hosted repository is read by, at `/<owner>/<name>/…`
//! (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/<owner>/<name>/…`,
//! where they were first, is sent here.
//!
//! - `/o/n` — the root directory and the README;
//! - `/o/n/tree/<path>?rev=<rev>` — a directory or a file;
//! - `/o/n/raw/<path>?rev=<rev>` — a file's bytes (an LFS file's own, when the hub has them);
//! - `/o/n/log?rev=<rev>` — the last 50 commits;
//! - `/o/n/commit/<sha>` — 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<u8>),
}

fn esc(s: &str) -> String {
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}

/// 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<String> {
        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!("<article class=\"md\">{html}</article>")
}

/// 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 = "<path d=\"M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4.5A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z\"/>";
    const DOC: &str = "<path d=\"M4 1.5h5l3 3v10H4z\"/><path d=\"M6 8h4M6 10.5h4\"/>";
    const CODE: &str = "<path d=\"M5.5 4.5 2 8l3.5 3.5M10.5 4.5 14 8l-3.5 3.5\"/>";
    const IMAGE: &str = "<rect x=\"2\" y=\"3\" width=\"12\" height=\"10\" rx=\"1.5\"/><path d=\"m2.5 12 3.5-4 3 3 2-2 2.5 3\"/><circle cx=\"10.5\" cy=\"6\" r=\"1\"/>";
    const CONF: &str = "<path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\"/><circle cx=\"5\" cy=\"4.5\" r=\"1.2\"/><circle cx=\"10.5\" cy=\"8\" r=\"1.2\"/><circle cx=\"7\" cy=\"11.5\" r=\"1.2\"/>";
    const SHELL: &str = "<rect x=\"1.5\" y=\"2.5\" width=\"13\" height=\"11\" rx=\"1.5\"/><path d=\"m4.5 6 2 2-2 2M8 10.5h3.5\"/>";
    const FILE: &str = "<path d=\"M4 1.5h5l3 3v10H4z\"/><path d=\"M9 1.5v3h3\"/>";
    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!("<svg class=\"ico{}\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">{d}</svg>", 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!(
        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
         <title>{title}</title><script>try{{const t=localStorage.getItem('m-theme');if(t==='light'||t==='dark')document.documentElement.dataset.theme=t}}catch{{}}</script>\
         <link rel=\"icon\" href=\"/icon.svg\" type=\"image/svg+xml\"><link rel=\"stylesheet\" href=\"/app.css\">\
         <style>{STYLE}</style></head><body><div class=\"pub\"><header class=\"pub-head\">\
         <h1><img src=\"/icon.svg\" alt=\"\"><a href=\"/\">{h}</a>{crumbs}</h1>{rest}</header>{body}</div></body></html>",
        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!("<span class=\"clone muted\">clone: <code>git clone https://{h}/{k}.git</code></span>") };
    page_html(
        &format!("{} · {k}", esc(title)), host,
        &format!("<span>/</span><a href=\"/{k}\">{k}</a>"),
        &format!("<a class=\"end\" href=\"/{k}/log\">log</a>{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 = "<div class=\"pub-list\">".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!("<a class=\"pub-card\" href=\"/{k}\"><strong><span class=\"muted\">{o}</span>{n}</strong>{d}<time datetime=\"{day}\">{day}</time></a>",
            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!("<span>{}</span>", esc(d)) });
    }
    body += "</div>";
    if rows.is_empty() {
        body = "<p class=\"muted\">No public projects yet.</p>".into();
    } else {
        body = map() + &body;
    }
    page_html(&esc(host), host, "", "<a class=\"end pub-in\" href=\"/login\">Log in</a>", &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!("<figure class=\"map\">{}<figcaption class=\"muted\">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.</figcaption></figure>",
                        crate::graph::svg(&g, Some("/")));
    let landed = g["landed"].as_array().cloned().unwrap_or_default();
    if !landed.is_empty() {
        s += "<h2>Built lately</h2><table class=\"log\">";
        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!("<tr><td class=\"muted\">{}</td><td><a href=\"/{r}\">{n}</a></td><td>{}</td></tr>",
                esc(&day), esc(l["name"].as_str().unwrap_or("")), r = esc(repo), n = esc(repo.rsplit('/').next().unwrap_or(repo)));
        }
        s += "</table>";
    }
    s + "<h2>Repositories</h2>"
}

fn query(q: &str, k: &str) -> Option<String> {
    q.split('&').find_map(|p| p.strip_prefix(&format!("{k}="))).map(crate::hub::pct_decode)
}

/// Forgejo's paths, said the new way: `src/branch/<b>/<p>` (and `commit`,
/// `tag`), `raw/…` and `media/…` likewise, and `commits/branch/<b>`. 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<String> {
    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<Option<Vec<u8>>> {
    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 `/<owner>/<name>/`), or none for a
/// path that is not one.
pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<Page>> {
    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!("<p class=\"get\">Get it: <code>git clone https://{h}/{k}.git</code>, or <a href=\"/{k}/archive/{main}.tar.gz\" download>download {main} as .tar.gz</a>.</p>",
                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!("<p><a href=\"/{}/tree/{}{}\">..</a> <span class=\"muted\">/{}</span></p>", 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 += "<ul class=\"files\">";
            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!("<li><a href=\"/{}/tree/{}{}\">{}<span class=\"name\">{}</span><span class=\"size\">{}</span></a></li>",
                    esc(key), link(&full), revq, icon(n, dir), esc(n),
                    e["size"].as_u64().filter(|_| !dir).map(size).unwrap_or_default());
            }
            body += "</ul>";
            // 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!("<section class=\"readme\"><h2>{}{}</h2>{}</section>", icon(readme, false), esc(readme),
                        if is_markdown(readme) { markdown(key, &path, &revq, t) } else { format!("<pre>{}</pre>", esc(t)) });
                }
            }
        } else if let Some(t) = v["text"].as_str() {
            let dir = path.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
            body += &format!("<p class=\"muted\"><a href=\"/{}/raw/{}{}\">raw</a></p>{}", esc(key), link(&path), revq,
                if is_markdown(&path) { markdown(key, dir, &revq, t) } else { format!("<pre>{}</pre>", esc(t)) });
        } else {
            body += &format!("<p class=\"muted\">A binary file of {} bytes: <a href=\"/{}/raw/{}{}\">download</a>.</p>",
                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 = "<table class=\"log\">".to_string();
        for c in hosted::log(repo, rev.as_deref(), 50)? {
            let sha = c["sha"].as_str().unwrap_or("");
            body += &format!("<tr><td><a href=\"/{}/commit/{}\"><code>{}</code></a></td><td>{}</td><td class=\"muted\">{}</td></tr>",
                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 += "</table>";
        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!("<p class=\"muted\">{} · {}</p><pre>{}</pre><pre>{}</pre>",
            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<script>alert(1)</script>\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("<h1>Title</h1>") && h.contains("<table>"), "{h}");
        assert!(!h.contains("<script>") && h.contains("&lt;script&gt;"), "raw HTML is text: {h}");
        assert!(h.contains("href=\"/o/n/tree/sub/docs/hub.md?rev=v1#top\""), "{h}");
        assert!(h.contains("href=\"/o/n/tree/x.rs?rev=v1\""), "{h}");
        assert!(h.contains("href=\"https://example.org\"") && !h.contains("javascript:"), "{h}");
        assert!(h.contains("src=\"/o/n/raw/sub/img/a.png?rev=v1\""), "{h}");
    }

    #[test]
    fn a_file_gets_the_icon_of_its_kind() {
        assert!(icon("src", true).contains("ico dir"));
        assert_ne!(icon("main.rs", false), icon("Cargo.toml", false));
        assert_eq!(icon("README.md", false), icon("LICENSE-MIT", false));
        assert_eq!((size(980), size(24_932), size(1_200_000)), ("980 B".into(), "24.9 kB".into(), "1.2 MB".into()));
    }
}