GITv

Introduce Askama templates and show the latest commit for each tree entry

Browse files
Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 13:24
Commit
007725c16c63
Parent
f7a0817

12 files changed +270−98

+63−0
@@ -70,6 +70,53 @@ dependencies = [
"password-hash",
]
[[package]]
name = "askama"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4"
dependencies = [
"askama_macros",
"itoa",
"percent-encoding",
"serde",
"serde_json",
]
[[package]]
name = "askama_derive"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39"
dependencies = [
"askama_parser",
"memchr",
"proc-macro2",
"quote",
"rustc-hash",
"syn",
]
[[package]]
name = "askama_macros"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b"
dependencies = [
"askama_derive",
]
[[package]]
name = "askama_parser"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583"
dependencies = [
"rustc-hash",
"unicode-ident",
"winnow",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
@@ -385,6 +432,7 @@ name = "gitv"
version = "0.1.0"
dependencies = [
"argon2",
"askama",
"axum",
"base64",
"clap",
@@ -738,6 +786,12 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "ryu"
version = "1.0.23"
@@ -1079,6 +1133,15 @@ dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
dependencies = [
"memchr",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
@@ -5,6 +5,7 @@ edition = "2024"
[dependencies]
argon2 = "0.6.0"
askama = { version = "0.16.1", default-features = false, features = ["derive", "std"] }
axum = "0.8.9"
base64 = "0.23.1"
clap = { version = "4.6.9", features = ["derive"] }
@@ -254,3 +254,15 @@ button.button{cursor:pointer}
@media (prefers-reduced-motion:no-preference){
a.entry,.repo-row,.tabs a,.button,.segmented a,.refmenu summary,.menu a{transition:background-color .12s,border-color .12s,color .12s}
}
.tree-row{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr) max-content;align-items:center;column-gap:12px;padding-right:16px}
.tree-row:hover,.tree-row:focus-within{background:var(--sunk)}
.tree-row .entry{min-width:0}
.entry-commit{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ink-2)}
.entry-commit:hover,.entry-commit:focus-visible{color:var(--accent);text-decoration:underline}
.tree-row time{justify-self:end;white-space:nowrap;color:var(--ink-2);font-size:13px}
@media(max-width:650px){
.tree-row{grid-template-columns:minmax(0,1fr) max-content}
.tree-row time{grid-column:2;grid-row:1}
.entry-commit{grid-column:1/-1;padding:0 0 8px 42px;font-size:13px}
}
@@ -328,27 +328,9 @@ pub struct SignInForm {
}
fn sign_in_page(status: StatusCode, next: &str, message: &str) -> Response {
let message = if message.is_empty() {
String::new()
} else {
format!(r#"<p class="alert" role="alert">{}</p>"#, esc(message))
};
html(
status,
layout(
"Sign in",
&format!(
r#"<section class="signin"><h1 class="title">Sign in</h1>{message}
<form class="panel form" method="post" action="/login">
<label>Username<input name="user" autocomplete="username" autocapitalize="none" spellcheck="false" required></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required></label>
<label>Authenticator code<input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{{6}}" maxlength="6" required></label>
<input type="hidden" name="next" value="{}">
<button class="button primary" type="submit">Sign in</button></form></section>"#,
attr(safe_next(next))
),
false,
),
super::templates::SignIn { title: "Sign in", signed_in: false, next: safe_next(next), message }.to_string(),
)
}
@@ -5,6 +5,7 @@
//! for one trusted audience behind the proxy's login, not for per-owner access like SSH.
mod login;
mod templates;
use std::borrow::Cow;
use std::cell::OnceCell;
@@ -47,9 +48,6 @@ static STYLE_URL: LazyLock<String> = LazyLock::new(|| {
format!("/style.css?v={:012x}", hasher.finish() & 0xffff_ffff_ffff)
});
/// The favicon's branch glyph, coloured by the stylesheet so it follows light and dark mode.
const LOGO: &str = r#"<svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>"#;
const PAGE: usize = 50;
/// Largest file the Raw view serves; bigger files are for `git clone`.
const RAW_LIMIT: usize = 50 << 20;
@@ -315,20 +313,7 @@ fn page(title: &str, body: &str) -> String {
/// A page, with the account link in the top bar only when `signed_in`.
fn layout(title: &str, body: &str, signed_in: bool) -> String {
let account = if signed_in { r#"<a class="account" href="/account">Account</a>"# } else { "" };
format!(
r##"<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title} | GITv</title>
<link rel="stylesheet" href="{style}"><link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="preload" href="/fonts/display.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/fonts/text.woff2" as="font" type="font/woff2" crossorigin></head>
<body><a class="skip" href="#main">Skip to content</a>
<header class="top"><div class="bar"><a class="mark" href="/">{LOGO}GITv</a>{account}</div></header>
<main id="main">{body}</main></body></html>"##,
title = esc(title),
style = STYLE_URL.as_str(),
)
templates::Layout { title, body, signed_in }.to_string()
}
fn view_missing() -> String {
@@ -555,6 +540,29 @@ impl Repo {
}
}
/// 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, commit: &str, path: &[u8]) -> Option<templates::EntryCommit> {
let key = self.key("entry-commit", commit, &encode(path));
let record = cached(key, || {
let args = ["log", "-1", "--format=%H%x00%ct%x00%cI%x00%s%x00%B", commit, "--"].map(OsStr::new);
self.git(&[args.as_slice(), &[OsStr::from_bytes(path)]].concat()).filter(|out| !out.is_empty())
})?;
let mut fields = record.splitn(5, '\0');
let oid = fields.next()?;
let stamp = fields.next()?;
let datetime = 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, datetime.split('T').next().unwrap_or(datetime)),
datetime: datetime.into(),
})
}
/// Commits reachable from `commit`. A commit's history never changes, so the count is cached.
fn commit_count(&self, commit: &str) -> usize {
let key = format!("count:{}:{commit}", self.dir.path.display());
@@ -905,29 +913,21 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
);
}
for item in &entries {
let path = join(&path, &item.name);
let (view, class, glyph) = match item.kind.as_str() {
"tree" => ("tree", "entry dir", "dir"),
"commit" => {
// A submodule: its commits live in another repository, so there's nothing to open.
let _ = write!(
body,
r#"<li><span class="entry sub">{}<span class="name">{}</span><span class="quiet">Submodule at {}</span></span></li>"#,
icon("module"),
esc(&lossy(&item.name)),
&item.oid[..item.oid.len().min(7)]
);
continue;
}
_ => ("blob", "entry", "file"),
"tree" => (Some("tree"), "entry dir", "dir"),
"commit" => (None, "entry sub", "module"),
_ => (Some("blob"), "entry", "file"),
};
let href = repo.url_at(view, &reference, &join(&path, &item.name), "");
let _ = write!(
body,
r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#,
attr(&href),
icon(glyph),
esc(&lossy(&item.name))
);
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: repo.entry_commit(&commit, &path),
};
let _ = write!(body, "{row}");
}
body += "</ul></div>";
@@ -1102,51 +1102,37 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> {
])?;
let lines: Vec<&str> = out.lines().collect();
let tags = repo.tags_by_commit();
let mut rows = String::new();
for line in lines.iter().take(PAGE) {
// Subject last, split at most five ways: a subject containing 0x1f stays whole.
let Some(head) = Head::parse(line) else { continue };
let Head { oid, subject, author, stamp, date } = &head;
let chips: String = tags
.get(oid)
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(|t| {
format!(
r#"<a class="tagchip" href="{}">{}{}</a>"#,
attr(&repo.url("tree", &[("ref", &repo.tag_ref(t))])),
icon("tag"),
esc(t)
)
})
.map(|name| templates::TagLink { name, url: repo.url("tree", &[("ref", &repo.tag_ref(name))]) })
.collect();
let _ = write!(
rows,
r#"<li class="commit-row"><div class="cmain"><a class="csubj" href="{}">{}</a>{chips}<span class="cmeta">{} committed {}</span></div>{}</li>"#,
attr(&repo.url("commit", &[("id", oid)])),
esc(subject_or_placeholder(subject)),
esc(author),
ago(stamp, date),
repo.sha_link(oid)
);
}
let mut pager = String::new();
let page_link = |n: usize, label: &str| {
format!(
r#"<a class="button" href="{}">{label}</a>"#,
attr(&repo.url("log", &[("ref", &reference), ("page", &n.to_string())]))
)
};
pager += &if number > 0 { page_link(number - 1, "Newer") } else { "<span></span>".into() };
if lines.len() > PAGE {
pager += &page_link(number + 1, "Older");
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 body = repo.masthead("log", &reference, Some(&commit))
+ &repo.locator("log", &reference, b"")
+ &format!(
r#"<div class="panel"><ul class="rows">{rows}</ul></div><nav class="pager" aria-label="Pages">{pager}</nav>"#
);
Some(View::Html(page(&format!("Commits on {reference}"), &body)))
let page_url = |n: usize| repo.url("log", &[("ref", &reference), ("page", &n.to_string())]);
Some(View::Html(
templates::History {
title: format!("Commits on {reference}"),
signed_in: true,
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.
@@ -0,0 +1,66 @@
use askama::Template;
/// Wraps HTML already rendered and escaped by the existing page builders.
#[derive(Template)]
#[template(path = "layout.html")]
pub(super) struct Layout<'a> {
pub title: &'a str,
pub signed_in: bool,
pub body: &'a str,
}
#[derive(Template)]
#[template(path = "login.html")]
pub(super) struct SignIn<'a> {
pub title: &'a str,
pub signed_in: bool,
pub next: &'a str,
pub message: &'a str,
}
pub(super) struct TagLink<'a> {
pub name: &'a str,
pub url: String,
}
pub(super) struct CommitRow<'a> {
pub url: String,
pub subject: String,
pub short_id: String,
pub author: String,
pub when: String,
pub tags: Vec<TagLink<'a>>,
}
#[derive(Template)]
#[template(path = "history.html")]
pub(super) struct History<'a> {
pub title: String,
pub signed_in: bool,
// Existing HTML renderers escape repository data inside these fragments.
pub masthead: String,
pub locator: String,
pub tag_icon: String,
pub rows: Vec<CommitRow<'a>>,
pub newer: Option<String>,
pub older: Option<String>,
}
pub(super) struct EntryCommit {
pub url: String,
pub subject: String,
pub message: String,
pub when: String,
pub datetime: String,
}
#[derive(Template)]
#[template(path = "tree-row.html")]
pub(super) struct TreeRow<'a> {
pub name: std::borrow::Cow<'a, str>,
pub class: &'static str,
pub icon: String,
pub href: Option<String>,
pub short_id: &'a str,
pub commit: Option<EntryCommit>,
}
@@ -0,0 +1,9 @@
<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{ title }} | GITv</title>
<link rel="stylesheet" href="{{ super::STYLE_URL.as_str() }}"><link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="preload" href="/fonts/display.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/fonts/text.woff2" as="font" type="font/woff2" crossorigin></head>
<body><a class="skip" href="#main">Skip to content</a>
<header class="top"><div class="bar"><a class="mark" href="/"><svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>GITv</a>{% if signed_in %}<a class="account" href="/account">Account</a>{% endif %}</div></header>
<main id="main">{% block content %}{% endblock %}</main></body></html>
@@ -0,0 +1,15 @@
{% extends "base.html" %}
{% block content %}
{{ masthead|safe }}{{ locator|safe }}
<div class="panel"><ul class="rows">
{% for row in rows %}
<li class="commit-row"><div class="cmain"><a class="csubj" href="{{ row.url }}">{{ row.subject }}</a>
{% for tag in row.tags %}<a class="tagchip" href="{{ tag.url }}">{{ tag_icon|safe }}{{ tag.name }}</a>{% endfor %}
<span class="cmeta">{{ row.author }} committed {{ row.when }}</span></div><a class="sha" href="{{ row.url }}">{{ row.short_id }}</a></li>
{% endfor %}
</ul></div>
<nav class="pager" aria-label="Pages">
{% if let Some(url) = newer %}<a class="button" href="{{ url }}">Newer</a>{% else %}<span></span>{% endif %}
{% if let Some(url) = older %}<a class="button" href="{{ url }}">Older</a>{% endif %}
</nav>
{% endblock %}
@@ -0,0 +1,2 @@
{% extends "base.html" %}
{% block content %}{{ body|safe }}{% endblock %}
@@ -0,0 +1,8 @@
{% extends "base.html" %}
{% block content %}<section class="signin"><h1 class="title">Sign in</h1>{% if !message.is_empty() %}<p class="alert" role="alert">{{ message }}</p>{% endif %}
<form class="panel form" method="post" action="/login">
<label>Username<input name="user" autocomplete="username" autocapitalize="none" spellcheck="false" required></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required></label>
<label>Authenticator code<input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label>
<input type="hidden" name="next" value="{{ next }}">
<button class="button primary" type="submit">Sign in</button></form></section>{% endblock %}
@@ -0,0 +1,11 @@
<li class="tree-row">
{% if let Some(url) = href %}
<a class="{{ class }}" href="{{ url }}">{{ icon|safe }}<span class="name">{{ name }}</span></a>
{% else %}
<span class="{{ class }}">{{ icon|safe }}<span class="name">{{ name }}</span><span class="quiet">Submodule at {{ short_id }}</span></span>
{% endif %}
{% if let Some(change) = commit %}
<a class="entry-commit" href="{{ change.url }}" title="{{ change.message }}">{{ change.subject }}</a>
<time datetime="{{ change.datetime }}" title="{{ change.datetime }}">{{ change.when }}</time>
{% endif %}
</li>
@@ -348,6 +348,23 @@ fn tree_lists_folders_first_and_renders_the_readme() {
assert!(html.contains("<pre class=\"code\">") && html.contains("hl-"), "fenced code is highlighted");
}
#[test]
fn tree_rows_link_each_entry_to_its_own_change() {
let html = server().get("/ada/site/tree").text();
for (name, oid, message) in
[("README.md", &fixture().first, "With a body line."), ("src", &fixture().removal, "Remove old.txt")]
{
let row = html
.split("<li class=\"tree-row\">")
.skip(1)
.map(|row| row.split("</li>").next().unwrap())
.find(|row| row.contains(&format!(">{name}<")))
.unwrap();
assert!(row.contains(&format!("/ada/site/commit?id={oid}")), "{row}");
assert!(row.contains(message) && row.contains("<time datetime="), "{row}");
}
}
#[test]
fn tree_shows_submodules_without_links() {
let s = server();