garage44.eu/jeroen/midas

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

cartopolis-agent · 2026-11-28T19:18:31Z

feat(codeview): a README as a page, an icon by each file, a list to read

A public repository's README showed as its raw Markdown in a <pre>. It is
now rendered (CommonMark with tables, strikethrough and task lists, by
pulldown-cmark), and so is any .md file's own page. The README's raw HTML is
shown as text, never passed through, since the page is the hub's origin; a
relative link goes to the file's page and a relative image to its bytes, at
the same revision, and a link with a scheme other than http(s) or mailto is
dropped.

The directory is a list with folders first, a small line icon by each
entry by its kind (folder, document, code, image, settings, script), a whole
row to click and sizes in kB and MB. The README sits in a card under it.
Cargo.lock      |  25 +++++++++
 Cargo.toml      |   2 +
 src/codeview.rs | 169 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
 src/tests.rs    |   4 +-
 4 files changed, 187 insertions(+), 13 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index a5de716..21ed96e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -509,6 +509,7 @@ dependencies = [
  "libc",
  "miniz_oxide",
  "p256",
+ "pulldown-cmark",
  "qrcode",
  "serde",
  "serde_json",
@@ -604,6 +605,24 @@ dependencies = [
  "unicode-ident",
 ]
 
+[[package]]
+name = "pulldown-cmark"
+version = "0.13.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b"
+dependencies = [
+ "bitflags",
+ "memchr",
+ "pulldown-cmark-escape",
+ "unicase",
+]
+
+[[package]]
+name = "pulldown-cmark-escape"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
+
 [[package]]
 name = "qrcode"
 version = "0.14.1"
@@ -827,6 +846,12 @@ version = "1.20.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
 
+[[package]]
+name = "unicase"
+version = "2.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
+
 [[package]]
 name = "unicode-ident"
 version = "1.0.26"
diff --git a/Cargo.toml b/Cargo.toml
index e96f1e8..1768e88 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -28,6 +28,8 @@ serde = { version = "1", features = ["derive"] }
 serde_json = "1"
 # The board's stream compressed (ws.rs, RFC 7692): pure Rust, the deflate std's own backtraces use.
 miniz_oxide = "0.8"
+# A public repository's README as a page (codeview.rs): CommonMark and GitHub's tables, no raw HTML.
+pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] }
 
 [dev-dependencies]
 tempfile = "3"
diff --git a/src/codeview.rs b/src/codeview.rs
index 3ca8e44..619dbcb 100644
--- a/src/codeview.rs
+++ b/src/codeview.rs
@@ -38,6 +38,99 @@ 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
@@ -63,7 +156,26 @@ const STYLE: &str = "body{font-size:16px;line-height:1.55}\
      .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}";
+     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.
@@ -204,26 +316,33 @@ pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<Page>>
             body += &format!("<p><a href=\"/{}/tree/{}{}\">..</a> <span class=\"muted\">/{}</span></p>", esc(key), link(up), revq, esc(&path));
         }
         if v["kind"] == "dir" {
-            body += "<table>";
-            for e in v["entries"].as_array().into_iter().flatten() {
+            // 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!("<tr><td><a href=\"/{}/tree/{}{}\">{}{}</a></td><td class=\"muted\">{}</td></tr>",
-                    esc(key), link(&full), revq, esc(n), if dir { "/" } else { "" },
-                    e["size"].as_u64().map(|s| format!("{s} B")).unwrap_or_default());
+                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 += "</table>";
-            // The README of the directory, as text.
-            if let Some(readme) = v["entries"].as_array().into_iter().flatten()
-                .filter_map(|e| e["name"].as_str()).find(|n| n.to_ascii_lowercase().starts_with("readme")) {
+            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!("<h2>{}</h2><pre>{}</pre>", esc(readme), esc(t));
+                    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() {
-            body += &format!("<p class=\"muted\"><a href=\"/{}/raw/{}{}\">raw</a></p><pre>{}</pre>", esc(key), link(&path), revq, esc(t));
+            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);
@@ -254,3 +373,29 @@ pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<Page>>
     }
     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()));
+    }
+}
diff --git a/src/tests.rs b/src/tests.rs
index 4a5c4ef..88e38ab 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -2989,8 +2989,10 @@ fn a_public_repository_has_pages_and_a_private_one_none() {
     assert!(home.contains("href=\"/acme/open/log\""), "links at the root, as Forgejo had them: {home}");
     assert!(html("log").contains("Start open"));
     assert!(page("nowhere", "").is_none());
+    assert!(home.contains("<article class=\"md\"><h1>open</h1>") && !home.contains("<pre># open"), "the README as a page: {home}");
+    assert!(home.contains("class=\"ico\""), "an icon by each file: {home}");
     let file = html("tree/README.md");
-    assert!(file.contains("<pre># open"), "{file}");
+    assert!(file.contains("<h1>open</h1>"), "{file}");
     assert!(matches!(page("raw/README.md", ""), Some(Page::Raw(b)) if b.starts_with(b"# open")));
     // Forgejo's paths, sent to ours.
     for (old, new) in [("src/branch/main/README.md", "/acme/open/tree/README.md?rev=main"),