anvilsign in

collin/anvil

1//! Server-rendered web UI (Maud): repo list, repo overview, tree browsing, and
2//! blob viewing. Pages are plain SSR and work without JavaScript; htmx-based
3//! progressive enhancement is a follow-up.
4
5use std::{
6 collections::{
7 BTreeMap,
8 HashMap,
9 },
10 path::PathBuf,
11 sync::{
12 Arc,
13 Mutex,
14 OnceLock,
15 },
16};
17
18use anvil_core::{
19 App,
20 CiRun,
21 Repository,
22 SshKey,
23 User,
24 access,
25 ci,
26 repos,
27 ssh_keys,
28 users,
29};
30use anvil_git::browse::{
31 self,
32 ChangeKind,
33 FileChange,
34};
35use axum::{
36 Form,
37 Router,
38 extract::{
39 Path,
40 Query,
41 State,
42 },
43 http::{
44 StatusCode,
45 header,
46 },
47 response::{
48 IntoResponse,
49 Redirect,
50 Response,
51 },
52 routing::{
53 get,
54 post,
55 },
56};
57use maud::{
58 DOCTYPE,
59 Markup,
60 PreEscaped,
61 html,
62};
63use similar::{
64 ChangeTag,
65 TextDiff,
66};
67use syntect::{
68 easy::HighlightLines,
69 highlighting::{
70 Theme,
71 ThemeSet,
72 },
73 html::{
74 IncludeBackground,
75 styled_line_to_highlighted_html,
76 },
77 parsing::SyntaxSet,
78};
79use time::OffsetDateTime;
80
81use crate::{
82 auth::{
83 CSRF_FIELD,
84 Csrf,
85 CurrentUser,
86 verify_csrf,
87 },
88 todomd,
89};
90
91const STYLE: &str = r#"
92:root { --fg:#1f2328; --muted:#656d76; --bg:#fff; --border:#d0d7de; --accent:#0969da; --code-bg:#f6f8fa; }
93* { box-sizing:border-box; }
94body { margin:0; font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif; color:var(--fg); background:var(--bg); }
95a { color:var(--accent); text-decoration:none; } a:hover { text-decoration:underline; }
96header.top { border-bottom:1px solid var(--border); padding:12px 0; background:var(--code-bg); }
97.container { max-width:980px; margin:0 auto; padding:0 16px; }
98header.top .container { display:flex; align-items:center; gap:12px; }
99.brand { font-weight:700; font-size:16px; color:var(--fg); }
100main { padding:24px 0; }
101h1,h2 { font-weight:600; } h1 { font-size:20px; } h2 { font-size:15px; margin:20px 0 8px; }
102.muted { color:var(--muted); }
103.repo-list { list-style:none; padding:0; margin:0; }
104.repo-list li { padding:12px 0; border-bottom:1px solid var(--border); }
105.repo-list .name { font-size:16px; font-weight:600; }
106.box { border:1px solid var(--border); border-radius:6px; overflow:hidden; }
107.box .row { display:flex; justify-content:space-between; padding:8px 16px; border-top:1px solid var(--border); }
108.box .row:first-child { border-top:0; }
109.box .row a.entry { display:flex; gap:8px; align-items:center; white-space:nowrap; }
110.box .row a.fc-msg { flex:1; margin-left:24px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; text-align:left; color:var(--muted); font-size:13px; }
111.box .row a.fc-msg:hover { color:var(--accent); }
112.box .row .fc-time { margin-left:16px; white-space:nowrap; color:var(--muted); font-size:13px; }
113.icon { width:16px; flex:none; display:inline-flex; align-items:center; justify-content:center; color:var(--muted); }
114.icon.dir { color:#54aeff; }
115table.code { border-collapse:collapse; width:100%; font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
116table.code td { padding:0 10px; vertical-align:top; white-space:pre; }
117table.code td.ln { text-align:right; color:var(--muted); user-select:none; width:1%; border-right:1px solid var(--border); background:var(--code-bg); }
118.clone { border:1px solid var(--border); border-radius:6px; padding:12px 16px; margin:16px 0; }
119.clone-head { display:flex; align-items:center; gap:12px; margin-bottom:8px; }
120.clone-tabs { display:flex; margin-left:auto; }
121.clone-tab { font-size:12px; padding:2px 10px; border:1px solid var(--border); border-radius:0; margin-left:-1px; position:relative; background:var(--bg); color:var(--muted); cursor:pointer; }
122.clone-tab:first-child { border-radius:2em 0 0 2em; margin-left:0; }
123.clone-tab:last-child { border-radius:0 2em 2em 0; }
124.clone-tab:first-child:last-child { border-radius:2em; }
125.clone-tab.active { background:var(--accent); color:#fff; border-color:var(--accent); z-index:1; }
126.clone-cmd { display:flex; align-items:center; gap:8px; background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:6px 10px; }
127.clone-cmd code { flex:1; font:12px ui-monospace,monospace; user-select:all; overflow-x:auto; white-space:nowrap; }
128.copy-btn { display:inline-flex; align-items:center; background:none; border:0; color:var(--muted); cursor:pointer; padding:2px; }
129.copy-btn:hover { color:var(--fg); }
130.copied-msg { display:none; color:#1a7f37; font-size:12px; }
131.clone.copied .copied-msg { display:inline; }
132.clone.copied .copy-btn { color:#1a7f37; }
133.crumbs { margin:12px 0; font:13px ui-monospace,monospace; }
134.pill { display:inline-block; background:var(--code-bg); border:1px solid var(--border); border-radius:2em; padding:1px 8px; font-size:12px; color:var(--muted); }
135.pill.active { background:var(--accent); border-color:var(--accent); color:#fff; }
136.view-toggle { margin:8px 0; }
137a.pill:hover { text-decoration:none; border-color:var(--accent); color:var(--accent); }
138.md-body { padding:8px 24px 16px; line-height:1.6; overflow-wrap:break-word; }
139.md-body h1, .md-body h2 { border-bottom:1px solid var(--border); padding-bottom:6px; }
140.md-body pre { background:var(--code-bg); border-radius:6px; padding:12px 14px; overflow-x:auto; font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
141.md-body code { background:var(--code-bg); border-radius:4px; padding:1px 4px; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:0.9em; }
142.md-body pre code { background:none; padding:0; font-size:inherit; }
143.md-body blockquote { border-left:4px solid var(--border); margin:0 0 12px; padding:0 14px; color:var(--muted); }
144.md-body table { border-collapse:collapse; margin:12px 0; } .md-body th, .md-body td { border:1px solid var(--border); padding:5px 10px; }
145.md-body img { max-width:100%; }
146.linkbtn { background:none; border:0; color:var(--accent); cursor:pointer; font:inherit; padding:0; }
147.linkbtn:hover { text-decoration:underline; }
148.btn { display:inline-block; background:var(--accent); color:#fff; border:1px solid var(--accent); border-radius:6px; padding:5px 12px; font-size:13px; cursor:pointer; }
149.btn:hover { text-decoration:none; opacity:.92; }
150.repo-nav { font-size:13px; }
151.repo-nav a { color:var(--muted); }
152.repo-nav a:hover { color:var(--accent); text-decoration:none; }
153.pill-group { display:inline-flex; }
154.pill-group > .pill { border-radius:0; margin-left:-1px; position:relative; }
155.pill-group > .pill:first-child { border-radius:2em 0 0 2em; margin-left:0; }
156.pill-group > .pill:last-child { border-radius:0 2em 2em 0; }
157form.stack p { margin:10px 0; } form.stack label { font-size:13px; color:var(--muted); }
158form.stack input[type=text], form.stack textarea { width:100%; max-width:480px; padding:6px 8px; border:1px solid var(--border); border-radius:6px; font:inherit; }
159form.stack .check { display:flex; gap:8px; align-items:flex-start; max-width:480px; }
160.issue-dot { width:10px; height:10px; border-radius:50%; flex:none; }
161.issue-dot.open { background:#1a7f37; }
162.issue-dot.closed { background:#8250df; }
163.st.issue-open { background:#dafbe1; color:#1a7f37; }
164.st.issue-closed { background:#fbefff; color:#8250df; }
165.issue-post { margin:12px 0; }
166.issue-head { padding:8px 16px; border-bottom:1px solid var(--border); background:var(--code-bg); font-size:13px; color:var(--muted); }
167.btn.btn-secondary { background:var(--bg); color:var(--fg); border-color:var(--border); }
168.readme { margin-top:16px; }
169.readme-head { padding:8px 16px; border-bottom:1px solid var(--border); background:var(--code-bg); font-size:13px; font-weight:600; }
170.kanban { display:flex; gap:12px; align-items:flex-start; overflow-x:auto; padding:12px; }
171.kanban .col { flex:1 1 0; min-width:230px; background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:8px; }
172.kanban .col h3 { margin:2px 4px 8px; font-size:13px; display:flex; align-items:baseline; gap:8px; }
173.kanban .col h3 .count { font-weight:400; font-size:12px; color:var(--muted); margin-left:auto; }
174.kanban .card { background:var(--bg); border:1px solid var(--border); border-radius:6px; padding:6px 10px; margin-bottom:8px; font-size:13px; }
175.kanban .card:last-child { margin-bottom:0; }
176.kanban .card .title { display:flex; gap:6px; align-items:baseline; }
177.kanban .card .title p { margin:0; display:inline; }
178.kanban .card.done .title { color:var(--muted); text-decoration:line-through; }
179.kanban .card details { margin-top:4px; }
180.kanban .card summary { cursor:pointer; font-size:12px; color:var(--muted); }
181.kanban .card .card-details { padding:4px 0 0 6px; font-size:12px; }
182.kanban .card .card-details p { margin:0 0 4px; }
183.todo-notes { margin:0 12px 12px; }
184.todo-notes > summary { cursor:pointer; font-size:13px; color:var(--muted); }
185.latest-commit { display:flex; gap:10px; align-items:baseline; background:var(--code-bg); border:1px solid var(--border); border-radius:6px 6px 0 0; border-bottom:0; padding:8px 16px; }
186.latest-commit + .box { border-radius:0 0 6px 6px; }
187.commit-list { list-style:none; padding:0; margin:0; }
188.commit-list li { padding:8px 0; border-top:1px solid var(--border); display:flex; gap:12px; align-items:baseline; }
189.commit-list li:first-child { border-top:0; }
190.sha { font:12px ui-monospace,monospace; color:var(--muted); }
191.file-diff { margin:16px 0; }
192.file-diff summary.head { background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:6px 12px; font:12px ui-monospace,monospace; cursor:pointer; display:flex; align-items:center; gap:8px; list-style:none; }
193.file-diff summary.head::-webkit-details-marker { display:none; }
194.file-diff summary.head::before { content:"\25B8"; color:var(--muted); }
195.file-diff[open] summary.head::before { content:"\25BE"; }
196.file-diff[open] summary.head { border-bottom:0; border-radius:6px 6px 0 0; }
197.file-diff .stat { margin-left:auto; white-space:nowrap; }
198.stat .plus { color:#1a7f37; } .stat .minus { color:#cf222e; }
199table.diff { border:1px solid var(--border); border-radius:0 0 6px 6px; }
200table.diff td.sign { width:1%; text-align:center; color:var(--muted); user-select:none; }
201table.diff tr.ins { background:#e6ffec; } table.diff tr.ins td.sign { color:#1a7f37; }
202table.diff tr.del { background:#ffebe9; } table.diff tr.del td.sign { color:#cf222e; }
203table.diff tr.gap td { background:var(--code-bg); color:var(--muted); text-align:center; padding:3px 10px; user-select:none; font-size:11px; }
204.badge { font-size:11px; border-radius:3px; padding:1px 6px; }
205.badge.add { background:#dafbe1; color:#1a7f37; } .badge.del { background:#ffebe9; color:#cf222e; } .badge.mod { background:#fff8c5; color:#7d4e00; }
206.st { font-size:11px; border-radius:2em; padding:1px 9px; font-weight:600; text-transform:capitalize; }
207.st.queued { background:#eaeef2; color:#656d76; } .st.running { background:#fff8c5; color:#7d4e00; }
208.st.success { background:#dafbe1; color:#1a7f37; } .st.failure, .st.error { background:#ffebe9; color:#cf222e; }
209.log { background:#0d1117; color:#e6edf3; border-radius:6px; padding:14px 16px; overflow-x:auto; font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; white-space:pre-wrap; word-break:break-word; margin:0; }
210footer { color:var(--muted); font-size:12px; padding:24px 0; border-top:1px solid var(--border); margin-top:32px; }
211details.nav-menu { position:relative; }
212details.nav-menu > summary { list-style:none; cursor:pointer; color:var(--accent); font-size:14px; }
213details.nav-menu > summary::-webkit-details-marker { display:none; }
214details.nav-menu > summary::after { content:" ▾"; font-size:10px; color:var(--muted); }
215.nav-dropdown { position:absolute; right:0; top:calc(100% + 6px); background:var(--bg); border:1px solid var(--border); border-radius:6px; min-width:130px; box-shadow:0 4px 14px rgba(0,0,0,.1); z-index:200; padding:4px 0; }
216.nav-dropdown a, .nav-dropdown button { display:block; width:100%; padding:6px 14px; font-size:13px; color:var(--fg); text-align:left; background:none; border:0; cursor:pointer; font:inherit; text-decoration:none; }
217.nav-dropdown a:hover, .nav-dropdown button:hover { background:var(--code-bg); color:var(--fg); }
218.nav-dropdown.left { left:0; right:auto; max-height:320px; overflow-y:auto; }
219.nav-dropdown .dd-head { padding:6px 14px 2px; font-size:11px; text-transform:uppercase; letter-spacing:.03em; color:var(--muted); }
220.nav-dropdown a.current { font-weight:600; }
221details.rev-menu { display:inline-block; }
222details.rev-menu > summary .pill { cursor:pointer; }
223"#;
224
225/// Clipboard icon for the clone "copy" button.
226const CLIPBOARD_SVG: &str = r#"<svg viewBox="0 0 16 16" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M10 1.5H6a.5.5 0 0 0-.5.5v1H4A1.5 1.5 0 0 0 2.5 4.5v9A1.5 1.5 0 0 0 4 15h8a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 12 3h-1.5V2a.5.5 0 0 0-.5-.5zm-3.5 1h3v1h-3v-1zM4 4.5h8v9H4v-9z"/></svg>"#;
227
228/// Filled folder icon for directory entries in the tree view.
229const FOLDER_SVG: &str = r#"<svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden="true"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"/></svg>"#;
230
231/// Outline file icon for blob entries in the tree view.
232const FILE_SVG: &str = r#"<svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden="true"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"/></svg>"#;
233
234/// Delegated handlers for the clone widget: protocol toggle + copy-to-clipboard.
235/// Registered once on `document`, so it survives htmx body swaps.
236const CLONE_JS: &str = r#"
237(function(){
238 function copyText(t){
239 if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(t);
240 var ta=document.createElement('textarea'); ta.value=t; ta.style.position='fixed'; ta.style.opacity='0';
241 document.body.appendChild(ta); ta.focus(); ta.select();
242 try{document.execCommand('copy')}catch(e){}
243 document.body.removeChild(ta); return Promise.resolve();
244 }
245 document.addEventListener('click', function(e){
246 var nm=e.target.closest('details.nav-menu');
247 document.querySelectorAll('details.nav-menu').forEach(function(d){ if(d!==nm) d.removeAttribute('open'); });
248 var tab=e.target.closest('.clone-tab');
249 if(tab){
250 var box=tab.closest('.clone'), cmd=box.dataset[tab.dataset.proto];
251 if(cmd){ box.querySelector('.clone-cmd code').textContent=cmd; }
252 box.querySelectorAll('.clone-tab').forEach(function(t){ t.classList.toggle('active', t===tab); });
253 return;
254 }
255 var copy=e.target.closest('.copy-btn');
256 if(copy){
257 var box=copy.closest('.clone');
258 copyText(box.querySelector('.clone-cmd code').textContent).then(function(){
259 box.classList.add('copied');
260 setTimeout(function(){ box.classList.remove('copied'); }, 1300);
261 });
262 }
263 });
264})();
265"#;
266
267/// Mount the web UI routes.
268pub fn routes(router: Router<App>) -> Router<App> {
269 router
270 .route("/", get(home))
271 .route("/-/settings", get(account_settings))
272 .route("/-/settings/keys", post(add_ssh_key))
273 .route("/-/settings/keys/{id}/delete", post(delete_ssh_key))
274 .route("/-/new", get(new_repo_form).post(new_repo_submit))
275 .route("/{username}", get(user_profile))
276 .route(
277 "/{owner}/{repo}/settings",
278 get(repo_settings).post(repo_settings_submit),
279 )
280 .route("/{owner}/{repo}", get(repo_index))
281 .route("/{owner}/{repo}/tree/{rev}", get(tree_root))
282 .route("/{owner}/{repo}/tree/{rev}/{*path}", get(tree_path))
283 .route("/{owner}/{repo}/blob/{rev}/{*path}", get(blob))
284 .route("/{owner}/{repo}/commits/{rev}", get(commits))
285 .route("/{owner}/{repo}/commit/{id}", get(commit))
286 .route("/{owner}/{repo}/ci", get(ci_runs))
287 .route("/{owner}/{repo}/ci/{id}", get(ci_run))
288 .route("/-/static/htmx.min.js", get(htmx_js))
289}
290
291/// Serve the vendored htmx script (embedded in the binary).
292async fn htmx_js() -> Response {
293 (
294 [(
295 header::CONTENT_TYPE,
296 "application/javascript; charset=utf-8",
297 )],
298 include_str!("../assets/htmx.min.js"),
299 )
300 .into_response()
301}
302
303pub(crate) fn layout(title: &str, user: Option<&User>, body: Markup) -> Markup {
304 // Attach the session's CSRF token to every htmx request as a header, so any
305 // JS-driven action carries it without a hidden field. Omitted (no attribute)
306 // when unauthenticated. The token is hex, so it needs no JSON escaping.
307 let csrf = crate::auth::current_csrf();
308 let hx_headers = (!csrf.is_empty()).then(|| format!(r#"{{"{CSRF_FIELD}": "{csrf}"}}"#));
309 html! {
310 (DOCTYPE)
311 html lang="en" {
312 head {
313 meta charset="utf-8";
314 meta name="viewport" content="width=device-width, initial-scale=1";
315 title { (title) " · anvil" }
316 style { (PreEscaped(STYLE)) }
317 }
318 body hx-boost="true" hx-headers=[hx_headers] {
319 header.top { div.container {
320 a.brand href="/" { "anvil" }
321 span style="margin-left:auto" {
322 @match user {
323 Some(u) => {
324 details.nav-menu {
325 summary { (u.username) }
326 div.nav-dropdown {
327 a href="/-/settings" { "Settings" }
328 form method="post" action="/-/logout" {
329 button type="submit" { "Sign out" }
330 }
331 }
332 }
333 }
334 None => { a href="/-/login" { "sign in" } }
335 }
336 }
337 } }
338 main { div.container { (body) } }
339 footer { div.container { "anvil — a git forge" } }
340 script src="/-/static/htmx.min.js" {}
341 script { (PreEscaped(CLONE_JS)) }
342 }
343 }
344 }
345}
346
347/// Hidden CSRF token field for embedding inside a mutating `<form>`.
348pub(crate) fn csrf_input(token: &str) -> Markup {
349 html! { input type="hidden" name=(CSRF_FIELD) value=(token); }
350}
351
352pub(crate) fn not_found(message: &str) -> Response {
353 (
354 StatusCode::NOT_FOUND,
355 layout(
356 "Not found",
357 None,
358 html! { h1 { "Not found" } p.muted { (message) } },
359 ),
360 )
361 .into_response()
362}
363
364pub(crate) fn server_error(err: impl std::fmt::Display) -> Response {
365 tracing::error!("ui error: {err}");
366 (
367 StatusCode::INTERNAL_SERVER_ERROR,
368 layout("Error", None, html! { h1 { "Something went wrong" } }),
369 )
370 .into_response()
371}
372
373/// Resolve `<owner>/<repo>` to its on-disk path and metadata row, enforcing read
374/// access for `viewer`. Private repos 404 for non-owners (no existence leak).
375pub(crate) async fn resolve_repo(
376 app: &App,
377 viewer: Option<&User>,
378 owner: &str,
379 name: &str,
380) -> Result<(PathBuf, Repository), Response> {
381 let owner_user = users::find_by_username(&app.db, owner)
382 .await
383 .map_err(server_error)?
384 .ok_or_else(|| not_found("no such user"))?;
385 let repo = repos::find(&app.db, owner_user.id, name)
386 .await
387 .map_err(server_error)?
388 .ok_or_else(|| not_found("no such repository"))?;
389 if !access::can_read(&repo, viewer) {
390 return Err(not_found("no such repository"));
391 }
392 let path = anvil_core::storage::repo_path(&app.config.repositories_dir(), owner, name);
393 if !path.exists() {
394 return Err(not_found("repository not found on disk"));
395 }
396 Ok((path, repo))
397}
398
399/// `GET /` — list repositories visible to the current user.
400async fn home(State(app): State<App>, CurrentUser(user): CurrentUser) -> Result<Markup, Response> {
401 let all = repos::list_all_with_owner(&app.db)
402 .await
403 .map_err(server_error)?;
404 let repos: Vec<_> = all
405 .into_iter()
406 .filter(|r| {
407 !r.is_private
408 || user
409 .as_ref()
410 .is_some_and(|u| u.id == r.owner_id || u.is_admin)
411 })
412 .collect();
413 Ok(layout(
414 "Repositories",
415 user.as_ref(),
416 html! {
417 div style="display:flex;align-items:center" {
418 h1 style="margin-right:auto" { "Repositories" }
419 @if user.is_some() { a.btn href="/-/new" { "New repository" } }
420 }
421 @if repos.is_empty() {
422 p.muted {
423 "No repositories yet. "
424 @if user.is_some() { a href="/-/new" { "Create one" } "." }
425 @else { "Sign in to create one." }
426 }
427 } @else {
428 ul.repo-list {
429 @for r in &repos {
430 li {
431 div.name {
432 a href=(format!("/{}", r.owner)) { (r.owner) }
433 "/"
434 a href=(format!("/{}/{}", r.owner, r.name)) { (r.name) }
435 @if r.is_private { " " span.pill { "private" } }
436 }
437 @if !r.description.is_empty() { div.muted { (r.description) } }
438 }
439 }
440 }
441 }
442 },
443 ))
444}
445
446/// `GET /{username}` — a user's profile: their repositories (public to all;
447/// private only to themselves or an admin).
448async fn user_profile(
449 State(app): State<App>,
450 CurrentUser(viewer): CurrentUser,
451 Path(username): Path<String>,
452) -> Result<Markup, Response> {
453 let owner = users::find_by_username(&app.db, &username)
454 .await
455 .map_err(server_error)?
456 .ok_or_else(|| not_found("no such user"))?;
457 let visible: Vec<_> = repos::list_by_owner(&app.db, owner.id)
458 .await
459 .map_err(server_error)?
460 .into_iter()
461 .filter(|r| access::can_read(r, viewer.as_ref()))
462 .collect();
463 let is_self = viewer.as_ref().is_some_and(|u| u.id == owner.id);
464
465 Ok(layout(
466 &owner.username,
467 viewer.as_ref(),
468 html! {
469 div style="display:flex;align-items:center" {
470 h1 style="margin-right:auto" { (owner.username) }
471 @if is_self { a.btn href="/-/new" { "New repository" } }
472 }
473 h2 { "Repositories" }
474 @if visible.is_empty() {
475 p.muted { "No repositories." }
476 } @else {
477 ul.repo-list {
478 @for r in &visible {
479 li {
480 div.name {
481 a href=(format!("/{}/{}", owner.username, r.name)) { (r.name) }
482 @if r.is_private { " " span.pill { "private" } }
483 }
484 @if !r.description.is_empty() { div.muted { (r.description) } }
485 }
486 }
487 }
488 }
489 },
490 ))
491}
492
493#[derive(serde::Deserialize)]
494struct AddKeyForm {
495 #[serde(default)]
496 title: String,
497 key: String,
498 #[serde(default)]
499 csrf: String,
500}
501
502/// `GET /settings` — account settings: profile + SSH keys.
503async fn account_settings(
504 State(app): State<App>,
505 CurrentUser(user): CurrentUser,
506 csrf: Csrf,
507) -> Response {
508 let Some(user) = user else {
509 return Redirect::to("/-/login").into_response();
510 };
511 let keys = match ssh_keys::list_by_user(&app.db, user.id).await {
512 Ok(keys) => keys,
513 Err(e) => return server_error(e),
514 };
515 account_page(&user, &keys, None, &csrf.0).into_response()
516}
517
518/// `POST /settings/keys` — register an SSH public key for the current user.
519async fn add_ssh_key(
520 State(app): State<App>,
521 CurrentUser(user): CurrentUser,
522 csrf: Csrf,
523 Form(form): Form<AddKeyForm>,
524) -> Response {
525 let Some(user) = user else {
526 return Redirect::to("/-/login").into_response();
527 };
528 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
529 return resp;
530 }
531 let result = match ssh_keys::parse_public_key(&form.key) {
532 Ok((fingerprint, content)) => {
533 ssh_keys::add(&app.db, user.id, &form.title, &fingerprint, &content)
534 .await
535 .map(|_| ())
536 }
537 Err(e) => Err(e),
538 };
539 match result {
540 Ok(()) => Redirect::to("/-/settings").into_response(),
541 Err(e) => {
542 let keys = ssh_keys::list_by_user(&app.db, user.id)
543 .await
544 .unwrap_or_default();
545 (
546 StatusCode::BAD_REQUEST,
547 account_page(&user, &keys, Some(&e.to_string()), &csrf.0),
548 )
549 .into_response()
550 }
551 }
552}
553
554/// `POST /settings/keys/{id}/delete` — remove one of the current user's keys.
555async fn delete_ssh_key(
556 State(app): State<App>,
557 CurrentUser(user): CurrentUser,
558 csrf: Csrf,
559 Path(id): Path<i64>,
560 Form(form): Form<crate::auth::CsrfForm>,
561) -> Response {
562 let Some(user) = user else {
563 return Redirect::to("/-/login").into_response();
564 };
565 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
566 return resp;
567 }
568 if let Err(e) = ssh_keys::delete(&app.db, id, user.id).await {
569 return server_error(e);
570 }
571 Redirect::to("/-/settings").into_response()
572}
573
574fn account_page(user: &User, keys: &[SshKey], error: Option<&str>, csrf: &str) -> Markup {
575 layout(
576 "Account settings",
577 Some(user),
578 html! {
579 h1 { "Account settings" }
580 p.muted {
581 "Signed in as " strong { (user.username) }
582 @if !user.email.is_empty() { " · " (user.email) }
583 }
584
585 h2 { "SSH keys" }
586 p.muted { "Add a public key to clone and push over SSH." }
587 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
588 @if keys.is_empty() {
589 p.muted { "No SSH keys yet." }
590 } @else {
591 div.box {
592 @for k in keys {
593 div.row {
594 div {
595 @if !k.title.is_empty() { strong { (k.title) } " " }
596 span.sha { (k.fingerprint) }
597 div.muted style="font-size:12px" { "added " (fmt_time(k.created_at)) }
598 }
599 form method="post" action=(format!("/-/settings/keys/{}/delete", k.id)) {
600 (csrf_input(csrf))
601 button.linkbtn type="submit" { "delete" }
602 }
603 }
604 }
605 }
606 }
607
608 form.stack method="post" action="/-/settings/keys" style="margin-top:16px" {
609 (csrf_input(csrf))
610 p { label { "Title" br; input type="text" name="title" placeholder="laptop"; } }
611 p { label { "Public key" br; textarea name="key" rows="4" placeholder="ssh-ed25519 AAAA…" {} } }
612 p { button.btn type="submit" { "Add SSH key" } }
613 }
614 },
615 )
616}
617
618fn forbidden() -> Response {
619 (
620 StatusCode::FORBIDDEN,
621 layout(
622 "Forbidden",
623 None,
624 html! { h1 { "Forbidden" } p.muted { "You don't have access to this." } },
625 ),
626 )
627 .into_response()
628}
629
630#[derive(serde::Deserialize)]
631struct NewRepoForm {
632 name: String,
633 #[serde(default)]
634 description: String,
635 private: Option<String>,
636 #[serde(default)]
637 csrf: String,
638}
639
640#[derive(serde::Deserialize)]
641struct SettingsForm {
642 #[serde(default)]
643 description: String,
644 private: Option<String>,
645 #[serde(default)]
646 mirror_url: String,
647 #[serde(default)]
648 csrf: String,
649}
650
651/// `GET /new` — new-repository form (requires login).
652async fn new_repo_form(CurrentUser(user): CurrentUser, csrf: Csrf) -> Response {
653 let Some(user) = user else {
654 return Redirect::to("/-/login").into_response();
655 };
656 new_repo_page(&user, None, "", "", false, &csrf.0).into_response()
657}
658
659/// `POST /new` — create a repository owned by the current user.
660async fn new_repo_submit(
661 State(app): State<App>,
662 CurrentUser(user): CurrentUser,
663 csrf: Csrf,
664 Form(form): Form<NewRepoForm>,
665) -> Response {
666 let Some(user) = user else {
667 return Redirect::to("/-/login").into_response();
668 };
669 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
670 return resp;
671 }
672 let private = form.private.is_some();
673 match repos::create(
674 &app.db,
675 &app.config.repositories_dir(),
676 &user,
677 &form.name,
678 &form.description,
679 private,
680 )
681 .await
682 {
683 Ok(repo) => Redirect::to(&format!("/{}/{}", user.username, repo.name)).into_response(),
684 Err(e) => (
685 StatusCode::BAD_REQUEST,
686 new_repo_page(
687 &user,
688 Some(&e.to_string()),
689 &form.name,
690 &form.description,
691 private,
692 &csrf.0,
693 ),
694 )
695 .into_response(),
696 }
697}
698
699fn new_repo_page(
700 user: &User,
701 error: Option<&str>,
702 name: &str,
703 description: &str,
704 private: bool,
705 csrf: &str,
706) -> Markup {
707 layout(
708 "New repository",
709 Some(user),
710 html! {
711 h1 { "New repository" }
712 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
713 form.stack method="post" action="/-/new" {
714 (csrf_input(csrf))
715 p { label { "Name" br; input type="text" name="name" value=(name) placeholder="my-project" autofocus; } }
716 p { label { "Description" br; input type="text" name="description" value=(description); } }
717 p { label.check { input type="checkbox" name="private" value="on" checked[private]; span { "Private — only you can see and push to it" } } }
718 p { button.btn type="submit" { "Create repository" } }
719 }
720 p.muted { "It will be created at " code { (user.username) "/" (if name.is_empty() { "<name>" } else { name }) } "." }
721 },
722 )
723}
724
725/// Load a repo for an owner-only settings action, enforcing write access.
726async fn resolve_for_settings(
727 app: &App,
728 viewer: Option<&User>,
729 owner: &str,
730 name: &str,
731) -> Result<Repository, Response> {
732 let owner_user = users::find_by_username(&app.db, owner)
733 .await
734 .map_err(server_error)?
735 .ok_or_else(|| not_found("no such repository"))?;
736 let repo = repos::find(&app.db, owner_user.id, name)
737 .await
738 .map_err(server_error)?
739 .ok_or_else(|| not_found("no such repository"))?;
740 if !access::can_read(&repo, viewer) {
741 return Err(not_found("no such repository"));
742 }
743 if !access::can_write(&repo, viewer) {
744 return Err(forbidden());
745 }
746 Ok(repo)
747}
748
749/// `GET /{owner}/{repo}/settings` — owner-only repository settings.
750async fn repo_settings(
751 State(app): State<App>,
752 CurrentUser(user): CurrentUser,
753 csrf: Csrf,
754 Path((owner, repo)): Path<(String, String)>,
755) -> Response {
756 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
757 Ok(m) => m,
758 Err(resp) => return resp,
759 };
760 settings_page(user.as_ref(), &owner, &repo, &meta, None, &csrf.0).into_response()
761}
762
763/// `POST /{owner}/{repo}/settings` — update description / visibility.
764async fn repo_settings_submit(
765 State(app): State<App>,
766 CurrentUser(user): CurrentUser,
767 csrf: Csrf,
768 Path((owner, repo)): Path<(String, String)>,
769 Form(form): Form<SettingsForm>,
770) -> Response {
771 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
772 Ok(m) => m,
773 Err(resp) => return resp,
774 };
775 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
776 return resp;
777 }
778 if let Err(e) = repos::update_settings(
779 &app.db,
780 meta.id,
781 &form.description,
782 form.private.is_some(),
783 &form.mirror_url,
784 )
785 .await
786 {
787 return server_error(e);
788 }
789 Redirect::to(&format!("/{owner}/{repo}")).into_response()
790}
791
792fn settings_page(
793 user: Option<&User>,
794 owner: &str,
795 repo: &str,
796 meta: &Repository,
797 error: Option<&str>,
798 csrf: &str,
799) -> Markup {
800 layout(
801 &format!("{owner}/{repo}: settings"),
802 user,
803 html! {
804 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · settings" }
805 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
806 form.stack method="post" action=(format!("/{owner}/{repo}/settings")) {
807 (csrf_input(csrf))
808 p { label { "Description" br; input type="text" name="description" value=(meta.description); } }
809 p { label.check { input type="checkbox" name="private" value="on" checked[meta.is_private]; span { "Private — only you can see and push to it" } } }
810 p {
811 label {
812 "Mirror push URL" br;
813 input type="text" name="mirror_url" value=(meta.mirror_url)
814 placeholder="https://x-access-token:<token>@github.com/you/repo.git";
815 }
816 br;
817 span.muted style="font-size:12px" {
818 "After every push here, all refs are mirrored to this remote ("
819 code { "git push --mirror" }
820 "). Stored as-is — use a scoped token. Empty disables it."
821 }
822 }
823 p { button.btn type="submit" { "Save changes" } }
824 }
825 },
826 )
827}
828
829fn clone_box(app: &App, owner: &str, name: &str) -> Markup {
830 let http = app.config.http_clone_url(owner, name);
831 let ssh = app
832 .config
833 .ssh
834 .enabled
835 .then(|| app.config.ssh_clone_url(owner, name));
836 // SSH first and preselected when available — it's the protocol that can
837 // push without a credential prompt.
838 let default_cmd = format!("git clone {}", ssh.as_deref().unwrap_or(&http));
839 html! {
840 div.clone data-http=(format!("git clone {http}")) data-ssh=[ssh.as_ref().map(|s| format!("git clone {s}"))] {
841 div.clone-head {
842 span.muted { "Clone" }
843 div.clone-tabs {
844 @if ssh.is_some() {
845 button.clone-tab.active type="button" data-proto="ssh" { "SSH" }
846 button.clone-tab type="button" data-proto="http" { "HTTP" }
847 } @else {
848 button.clone-tab.active type="button" data-proto="http" { "HTTP" }
849 }
850 }
851 }
852 div.clone-cmd {
853 code { (default_cmd) }
854 button.copy-btn type="button" title="Copy to clipboard" aria-label="Copy" {
855 (PreEscaped(CLIPBOARD_SVG))
856 }
857 span.copied-msg { "Copied!" }
858 }
859 }
860 }
861}
862
863/// `GET /{owner}/{repo}` — repository overview with the root tree.
864async fn repo_index(
865 State(app): State<App>,
866 CurrentUser(user): CurrentUser,
867 Path((owner, repo)): Path<(String, String)>,
868) -> Result<Markup, Response> {
869 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
870 let overview = browse::overview(&path).map_err(server_error)?;
871
872 let can_write = access::can_write(&meta, user.as_ref());
873 let header = html! {
874 div style="display:flex;align-items:center;gap:8px" {
875 h1 style="margin-right:auto" {
876 a href=(format!("/{owner}")) { (owner) } " / " (repo)
877 @if meta.is_private { " " span.pill { "private" } }
878 }
879 span.repo-nav {
880 a href=(format!("/{owner}/{repo}/issues")) { "Issues" }
881 " · "
882 a href=(format!("/{owner}/{repo}/ci")) { "CI" }
883 " · "
884 a href=(format!("/{owner}/{repo}/pages")) { "Pages" }
885 @if can_write {
886 " · "
887 a href=(format!("/{owner}/{repo}/settings")) { "Settings" }
888 }
889 }
890 }
891 @if !meta.description.is_empty() { p.muted { (meta.description) } }
892 p {
893 span.pill { (overview.branches.len()) " branches" }
894 " "
895 span.pill { (overview.tags.len()) " tags" }
896 }
897 (clone_box(&app, &owner, &repo))
898 };
899
900 if overview.is_empty {
901 return Ok(layout(
902 &format!("{owner}/{repo}"),
903 user.as_ref(),
904 html! {
905 (header)
906 p.muted { "This repository is empty. Push to it to get started." }
907 },
908 ));
909 }
910
911 let rev = overview
912 .default_branch
913 .clone()
914 .unwrap_or_else(|| "HEAD".to_string());
915 let entries = browse::list_tree(&path, &rev, "").map_err(server_error)?;
916 let latest = browse::commit_log(&path, &rev, 1)
917 .map_err(server_error)?
918 .into_iter()
919 .next();
920 // Best-effort: a failed walk only costs the per-entry annotations.
921 let entry_commits =
922 browse::latest_entry_commits(&path, &rev, "", ENTRY_LOG_WALK).unwrap_or_default();
923
924 // A root README renders below the tree, GitHub-style. Best-effort: a
925 // missing or unreadable file just omits the section.
926 let readme = entries
927 .iter()
928 .find(|e| !e.is_dir && e.name.eq_ignore_ascii_case("readme.md"))
929 .and_then(|e| {
930 let bytes = browse::read_blob(&path, &rev, &e.name).ok().flatten()?;
931 Some((
932 render_markdown(&String::from_utf8_lossy(&bytes)),
933 e.name.clone(),
934 ))
935 });
936
937 // A root TODO.md with tasks renders as a kanban board below the README.
938 let todo_board = entries
939 .iter()
940 .find(|e| !e.is_dir && e.name.eq_ignore_ascii_case("todo.md"))
941 .and_then(|e| {
942 let bytes = browse::read_blob(&path, &rev, &e.name).ok().flatten()?;
943 let board = todomd::render_board(&String::from_utf8_lossy(&bytes))?;
944 Some((board, e.name.clone()))
945 });
946
947 Ok(layout(
948 &format!("{owner}/{repo}"),
949 user.as_ref(),
950 html! {
951 (header)
952 p {
953 (rev_switcher(&owner, &repo, &rev, &overview))
954 " · "
955 a href=(format!("/{owner}/{repo}/commits/{}", enc_ref(&rev))) { "commits" }
956 }
957 @if let Some(c) = &latest {
958 div.latest-commit {
959 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
960 a href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.summary) }
961 span.muted style="margin-left:auto" {
962 (c.author) " · "
963 span title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
964 }
965 }
966 }
967 (tree_table(&owner, &repo, &rev, "", &entries, &entry_commits))
968 @if let Some((rendered, name)) = &readme {
969 div.box.readme {
970 div.readme-head {
971 a href=(format!("/{owner}/{repo}/blob/{}/{name}", enc_ref(&rev))) { (name) }
972 }
973 div.md-body { (rendered) }
974 }
975 }
976 @if let Some((board, name)) = &todo_board {
977 div.box.readme {
978 div.readme-head {
979 a href=(format!("/{owner}/{repo}/blob/{}/{name}", enc_ref(&rev))) { (name) }
980 }
981 (board)
982 }
983 }
984 },
985 ))
986}
987
988async fn tree_root(
989 State(app): State<App>,
990 user: CurrentUser,
991 Path((owner, repo, rev)): Path<(String, String, String)>,
992) -> Result<Markup, Response> {
993 render_tree(&app, user, &owner, &repo, &rev, "").await
994}
995
996async fn tree_path(
997 State(app): State<App>,
998 user: CurrentUser,
999 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1000) -> Result<Markup, Response> {
1001 render_tree(&app, user, &owner, &repo, &rev, &path).await
1002}
1003
1004async fn render_tree(
1005 app: &App,
1006 CurrentUser(user): CurrentUser,
1007 owner: &str,
1008 repo: &str,
1009 rev: &str,
1010 path: &str,
1011) -> Result<Markup, Response> {
1012 let (repo_path, _) = resolve_repo(app, user.as_ref(), owner, repo).await?;
1013 let overview = browse::overview(&repo_path).map_err(server_error)?;
1014 let entries = browse::list_tree(&repo_path, rev, path).map_err(server_error)?;
1015 // Best-effort: a failed walk only costs the per-entry annotations.
1016 let entry_commits =
1017 browse::latest_entry_commits(&repo_path, rev, path, ENTRY_LOG_WALK).unwrap_or_default();
1018 Ok(layout(
1019 &format!("{owner}/{repo}: {path}"),
1020 user.as_ref(),
1021 html! {
1022 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1023 p { (rev_switcher(owner, repo, rev, &overview)) }
1024 (breadcrumbs(owner, repo, rev, path, false))
1025 (tree_table(owner, repo, rev, path, &entries, &entry_commits))
1026 },
1027 ))
1028}
1029
1030/// `GET /{owner}/{repo}/blob/{rev}/{*path}` — view a file. Markdown renders
1031/// by default; `?plain=1` shows the raw source (toggle links on the page).
1032async fn blob(
1033 State(app): State<App>,
1034 CurrentUser(user): CurrentUser,
1035 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1036 Query(query): Query<HashMap<String, String>>,
1037) -> Result<Markup, Response> {
1038 let (repo_path, _) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1039 let (oid, bytes) = browse::read_blob_with_id(&repo_path, &rev, &path)
1040 .map_err(server_error)?
1041 .ok_or_else(|| not_found("file not found"))?;
1042
1043 let markdown = is_markdown(&path) && !is_binary(&bytes);
1044 // Custom renderers for well-known filenames (the plugin point — add new
1045 // filename → renderer pairs here). TODO.md defaults to a kanban board.
1046 let is_todo = todomd::is_todo_md(&path) && !is_binary(&bytes);
1047 let board = (is_todo && !query.contains_key("plain") && !query.contains_key("md"))
1048 .then(|| todomd::render_board(&String::from_utf8_lossy(&bytes)))
1049 .flatten();
1050 let rendered = markdown && !query.contains_key("plain") && board.is_none();
1051
1052 let body = if let Some(board) = &board {
1053 board.clone()
1054 } else if is_binary(&bytes) {
1055 html! { p.muted { "Binary file (" (bytes.len()) " bytes)" } }
1056 } else if rendered {
1057 let text = String::from_utf8_lossy(&bytes);
1058 html! { div.md-body { (render_markdown(&text)) } }
1059 } else {
1060 let text = String::from_utf8_lossy(&bytes);
1061 let budget = app.config.http.highlight_cache_mb.saturating_mul(1 << 20);
1062 let lines = cached_highlight(budget, &oid, &path, &text);
1063 html! {
1064 table.code {
1065 @for (i, line) in lines.iter().enumerate() {
1066 tr {
1067 td.ln { (i + 1) }
1068 td { (PreEscaped(line)) }
1069 }
1070 }
1071 }
1072 }
1073 };
1074
1075 let blob_url = format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev));
1076 Ok(layout(
1077 &format!("{owner}/{repo}: {path}"),
1078 user.as_ref(),
1079 html! {
1080 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1081 (breadcrumbs(&owner, &repo, &rev, &path, true))
1082 @if markdown {
1083 p.view-toggle {
1084 span.pill-group {
1085 @if is_todo {
1086 @if board.is_some() { span.pill.active { "Board" } }
1087 @else { a.pill href=(&blob_url) { "Board" } }
1088 @if rendered { span.pill.active { "Rendered" } }
1089 @else { a.pill href=(format!("{blob_url}?md=1")) { "Rendered" } }
1090 } @else if rendered {
1091 span.pill.active { "Rendered" }
1092 } @else {
1093 a.pill href=(&blob_url) { "Rendered" }
1094 }
1095 @if rendered || board.is_some() {
1096 a.pill href=(format!("{blob_url}?plain=1")) { "Source" }
1097 } @else {
1098 span.pill.active { "Source" }
1099 }
1100 }
1101 }
1102 }
1103 div.box style="overflow-x:auto" { (body) }
1104 },
1105 ))
1106}
1107
1108/// Whether a path should be treated as markdown (by extension).
1109fn is_markdown(path: &str) -> bool {
1110 std::path::Path::new(path)
1111 .extension()
1112 .and_then(|e| e.to_str())
1113 .is_some_and(|e| e.eq_ignore_ascii_case("md") || e.eq_ignore_ascii_case("markdown"))
1114}
1115
1116/// Render markdown to HTML (tables, strikethrough, task lists, footnotes).
1117///
1118/// Repo content is untrusted, so this is a stored-XSS surface: raw HTML in the
1119/// source is emitted as escaped literal text, and `javascript:`/`data:`-style
1120/// link and image destinations are dropped.
1121pub(crate) fn render_markdown(text: &str) -> Markup {
1122 use pulldown_cmark::{
1123 Event,
1124 Options,
1125 Parser,
1126 Tag,
1127 html,
1128 };
1129
1130 fn safe_url(dest: &str) -> bool {
1131 let d = dest.trim().to_ascii_lowercase();
1132 !(d.starts_with("javascript:") || d.starts_with("data:") || d.starts_with("vbscript:"))
1133 }
1134
1135 let opts = Options::ENABLE_TABLES
1136 | Options::ENABLE_STRIKETHROUGH
1137 | Options::ENABLE_TASKLISTS
1138 | Options::ENABLE_FOOTNOTES;
1139 let events = Parser::new_ext(text, opts).map(|ev| match ev {
1140 Event::Html(h) => Event::Text(h),
1141 Event::InlineHtml(h) => Event::Text(h),
1142 Event::Start(Tag::Link {
1143 link_type,
1144 dest_url,
1145 title,
1146 id,
1147 }) if !safe_url(&dest_url) => Event::Start(Tag::Link {
1148 link_type,
1149 dest_url: "".into(),
1150 title,
1151 id,
1152 }),
1153 Event::Start(Tag::Image {
1154 link_type,
1155 dest_url,
1156 title,
1157 id,
1158 }) if !safe_url(&dest_url) => Event::Start(Tag::Image {
1159 link_type,
1160 dest_url: "".into(),
1161 title,
1162 id,
1163 }),
1164 e => e,
1165 });
1166 let mut out = String::new();
1167 html::push_html(&mut out, events);
1168 PreEscaped(out)
1169}
1170
1171/// How far back the per-entry "latest commit" walk looks. Entries last touched
1172/// beyond this many commits just lose the annotation.
1173const ENTRY_LOG_WALK: usize = 400;
1174
1175/// Folder or file icon for an entry row (tree listings, pages, artifacts).
1176pub(crate) fn entry_icon(is_dir: bool) -> Markup {
1177 html! {
1178 @if is_dir {
1179 span.icon.dir { (PreEscaped(FOLDER_SVG)) }
1180 } @else {
1181 span.icon { (PreEscaped(FILE_SVG)) }
1182 }
1183 }
1184}
1185
1186/// Human-readable byte size (`482 B`, `1.2 KiB`, `34.0 MiB`).
1187pub(crate) fn fmt_size(bytes: i64) -> String {
1188 let b = bytes.max(0) as f64;
1189 match b {
1190 b if b < 1024.0 => format!("{bytes} B"),
1191 b if b < 1024.0 * 1024.0 => format!("{:.1} KiB", b / 1024.0),
1192 b if b < 1024.0 * 1024.0 * 1024.0 => format!("{:.1} MiB", b / (1024.0 * 1024.0)),
1193 b => format!("{:.1} GiB", b / (1024.0 * 1024.0 * 1024.0)),
1194 }
1195}
1196
1197/// Percent-encode a ref name for use as one path segment in a URL. Axum
1198/// matches routes before decoding, so an encoded `/` keeps a branch like
1199/// `feat/x` inside the single `{rev}` segment.
1200pub(crate) fn enc_ref(name: &str) -> String {
1201 name.replace('%', "%25")
1202 .replace('/', "%2F")
1203 .replace('?', "%3F")
1204 .replace('#', "%23")
1205}
1206
1207/// Branch/tag switcher: a dropdown over the current rev linking each ref to
1208/// its tree view. Branch names, tag names, and commit ids all work as `rev`.
1209fn rev_switcher(owner: &str, repo: &str, rev: &str, overview: &browse::Overview) -> Markup {
1210 html! {
1211 details.nav-menu.rev-menu {
1212 summary { span.pill { (rev) } }
1213 div.nav-dropdown.left {
1214 @if !overview.branches.is_empty() {
1215 div.dd-head { "Branches" }
1216 @for b in &overview.branches {
1217 a.current[b == rev] href=(format!("/{owner}/{repo}/tree/{}", enc_ref(b))) { (b) }
1218 }
1219 }
1220 @if !overview.tags.is_empty() {
1221 div.dd-head { "Tags" }
1222 @for t in &overview.tags {
1223 a.current[t == rev] href=(format!("/{owner}/{repo}/tree/{}", enc_ref(t))) { (t) }
1224 }
1225 }
1226 }
1227 }
1228 }
1229}
1230
1231/// Render a tree listing as a box of rows; directories link to `tree`, files to
1232/// `blob`. Each entry also shows the subject of (and links to) the latest
1233/// commit that touched it, when `latest` has one for it.
1234fn tree_table(
1235 owner: &str,
1236 repo: &str,
1237 rev: &str,
1238 path: &str,
1239 entries: &[browse::TreeEntry],
1240 latest: &BTreeMap<String, browse::CommitInfo>,
1241) -> Markup {
1242 let join = |name: &str| {
1243 if path.is_empty() {
1244 name.to_string()
1245 } else {
1246 format!("{path}/{name}")
1247 }
1248 };
1249 html! {
1250 div.box {
1251 @if !path.is_empty() {
1252 div.row {
1253 a.entry href=(parent_link(owner, repo, rev, path)) { span.icon { ".." } "up" }
1254 }
1255 }
1256 @for e in entries {
1257 @let child = join(&e.name);
1258 @let kind = if e.is_dir { "tree" } else { "blob" };
1259 div.row {
1260 a.entry href=(format!("/{owner}/{repo}/{kind}/{}/{child}", enc_ref(rev))) {
1261 (entry_icon(e.is_dir))
1262 (e.name) @if e.is_dir { "/" }
1263 }
1264 @if let Some(c) = latest.get(&e.name) {
1265 a.fc-msg href=(format!("/{owner}/{repo}/commit/{}", c.id)) title=(c.summary) { (c.summary) }
1266 span.fc-time title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
1267 }
1268 }
1269 }
1270 }
1271 }
1272}
1273
1274fn parent_link(owner: &str, repo: &str, rev: &str, path: &str) -> String {
1275 match path.rsplit_once('/') {
1276 Some((parent, _)) => format!("/{owner}/{repo}/tree/{}/{parent}", enc_ref(rev)),
1277 None => format!("/{owner}/{repo}/tree/{}", enc_ref(rev)),
1278 }
1279}
1280
1281/// Path breadcrumbs. `is_blob` marks the final component as a file.
1282fn breadcrumbs(owner: &str, repo: &str, rev: &str, path: &str, is_blob: bool) -> Markup {
1283 // Precompute (label, cumulative_path) for each path component.
1284 let mut crumbs: Vec<(String, String)> = Vec::new();
1285 let mut acc = String::new();
1286 for part in path.split('/').filter(|p| !p.is_empty()) {
1287 if !acc.is_empty() {
1288 acc.push('/');
1289 }
1290 acc.push_str(part);
1291 crumbs.push((part.to_string(), acc.clone()));
1292 }
1293 let last = crumbs.len();
1294 html! {
1295 div.crumbs {
1296 a href=(format!("/{owner}/{repo}/tree/{}", enc_ref(rev))) { (rev) }
1297 @for (i, (label, cum)) in crumbs.iter().enumerate() {
1298 " / "
1299 @if i + 1 == last && is_blob {
1300 span { (label) }
1301 } @else {
1302 a href=(format!("/{owner}/{repo}/tree/{}/{cum}", enc_ref(rev))) { (label) }
1303 }
1304 }
1305 }
1306 }
1307}
1308
1309/// `GET /{owner}/{repo}/commits/{rev}` — commit history.
1310async fn commits(
1311 State(app): State<App>,
1312 CurrentUser(user): CurrentUser,
1313 Path((owner, repo, rev)): Path<(String, String, String)>,
1314) -> Result<Markup, Response> {
1315 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1316 let log = browse::commit_log(&path, &rev, 100).map_err(server_error)?;
1317
1318 // Map each commit oid to its latest run status, for inline badges. One query
1319 // for the repo's recent runs; first match wins (list is newest-first).
1320 let runs = ci::list_by_repo(&app.db, meta.id, 200)
1321 .await
1322 .unwrap_or_default();
1323 let mut status_of: HashMap<&str, &str> = HashMap::new();
1324 for r in &runs {
1325 status_of
1326 .entry(r.commit.as_str())
1327 .or_insert(r.status.as_str());
1328 }
1329
1330 Ok(layout(
1331 &format!("{owner}/{repo}: commits"),
1332 user.as_ref(),
1333 html! {
1334 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · commits" }
1335 ul.commit-list {
1336 @for c in &log {
1337 li {
1338 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
1339 @if let Some(st) = status_of.get(c.id.as_str()) {
1340 a href=(format!("/{owner}/{repo}/ci")) { (status_badge(st)) }
1341 }
1342 span { (c.summary) }
1343 span.muted style="margin-left:auto" {
1344 (c.author) " · "
1345 span title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
1346 }
1347 }
1348 }
1349 }
1350 },
1351 ))
1352}
1353
1354/// `GET /{owner}/{repo}/commit/{id}` — a commit with its diff.
1355async fn commit(
1356 State(app): State<App>,
1357 CurrentUser(user): CurrentUser,
1358 Path((owner, repo, id)): Path<(String, String, String)>,
1359) -> Result<Markup, Response> {
1360 let (path, _) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1361 let detail = browse::commit_detail(&path, &id).map_err(server_error)?;
1362 Ok(layout(
1363 &format!("{owner}/{repo}: {}", detail.info.short),
1364 user.as_ref(),
1365 html! {
1366 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · " span.sha { (detail.info.short) } }
1367 p { (detail.info.summary) }
1368 p.muted {
1369 (detail.info.author) " · " (fmt_time(detail.info.time)) " · "
1370 span.sha { (detail.info.id) }
1371 @if let Some(parent) = &detail.parent {
1372 " · parent " a.sha href=(format!("/{owner}/{repo}/commit/{parent}")) { (&parent[..parent.len().min(8)]) }
1373 }
1374 " · "
1375 a href=(format!("/{owner}/{repo}/tree/{}", detail.info.id)) { "browse files" }
1376 }
1377 @if detail.changes.is_empty() {
1378 p.muted { "No file changes." }
1379 }
1380 @for change in &detail.changes {
1381 (render_file_diff(change))
1382 }
1383 },
1384 ))
1385}
1386
1387/// `GET /{owner}/{repo}/ci` — recent CI runs for the repository.
1388async fn ci_runs(
1389 State(app): State<App>,
1390 CurrentUser(user): CurrentUser,
1391 Path((owner, repo)): Path<(String, String)>,
1392) -> Result<Markup, Response> {
1393 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1394 let runs = ci::list_by_repo(&app.db, meta.id, 100)
1395 .await
1396 .map_err(server_error)?;
1397 Ok(layout(
1398 &format!("{owner}/{repo}: CI"),
1399 user.as_ref(),
1400 html! {
1401 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · CI" }
1402 @if runs.is_empty() {
1403 p.muted {
1404 "No CI runs yet. Add a " code { ".anvil/ci.yml" }
1405 " pipeline and push to trigger one."
1406 }
1407 } @else {
1408 div.box {
1409 @for r in &runs {
1410 div.row {
1411 a.entry href=(format!("/{owner}/{repo}/ci/{}", r.id)) {
1412 (status_badge(&r.status))
1413 span.sha { (short_commit(&r.commit)) }
1414 span { (r.ref_name) }
1415 }
1416 span.muted { (fmt_time(r.created_at)) }
1417 }
1418 }
1419 }
1420 }
1421 },
1422 ))
1423}
1424
1425/// `GET /{owner}/{repo}/ci/{id}` — one run's status, timing, and log output.
1426async fn ci_run(
1427 State(app): State<App>,
1428 CurrentUser(user): CurrentUser,
1429 Path((owner, repo, id)): Path<(String, String, i64)>,
1430) -> Result<Markup, Response> {
1431 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1432 let run = ci::get(&app.db, id)
1433 .await
1434 .map_err(server_error)?
1435 .filter(|r| r.repo_id == meta.id)
1436 .ok_or_else(|| not_found("no such CI run"))?;
1437 let artifacts = ci::artifacts_for_run(&app.db, run.id)
1438 .await
1439 .map_err(server_error)?;
1440 Ok(layout(
1441 &format!("{owner}/{repo}: CI #{}", run.id),
1442 user.as_ref(),
1443 html! {
1444 h1 {
1445 a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) }
1446 " · " a href=(format!("/{owner}/{repo}/ci")) { "CI" }
1447 " · #" (run.id)
1448 }
1449 p {
1450 (status_badge(&run.status))
1451 " "
1452 a.sha href=(format!("/{owner}/{repo}/commit/{}", run.commit)) { (short_commit(&run.commit)) }
1453 " " span.muted { (run.ref_name) }
1454 }
1455 p.muted {
1456 "queued " (fmt_time(run.created_at))
1457 @if run.started_at > 0 { " · started " (fmt_time(run.started_at)) }
1458 @if run.finished_at > 0 { " · finished " (fmt_time(run.finished_at)) }
1459 @if let Some(d) = run_duration(&run) { " · took " (d) }
1460 }
1461 @if !artifacts.is_empty() {
1462 h2 { "Artifacts" }
1463 div.box {
1464 @for a in &artifacts {
1465 div.row {
1466 a.entry href=(format!("/{owner}/{repo}/ci/{}/artifacts/{}", run.id, a.name)) {
1467 (entry_icon(a.is_dir))
1468 (a.name)
1469 @if a.browse { " " span.pill { "site" } }
1470 @else if a.is_dir { ".tar.gz" }
1471 }
1472 span.muted {
1473 (artifact_meta_chips(&a.meta))
1474 (fmt_size(a.size))
1475 }
1476 }
1477 }
1478 }
1479 }
1480 @if run.log.is_empty() {
1481 p.muted { "No output yet." }
1482 } @else {
1483 pre.log { (run.log) }
1484 }
1485 },
1486 ))
1487}
1488
1489/// Render an artifact's extractor metadata (a JSON object of key → value) as
1490/// inline `key: value` chips before the size.
1491fn artifact_meta_chips(meta: &str) -> Markup {
1492 let map: BTreeMap<String, String> = serde_json::from_str(meta).unwrap_or_default();
1493 html! {
1494 @for (k, v) in &map {
1495 span.pill title=(k) { (k) ": " (v) }
1496 " "
1497 }
1498 }
1499}
1500
1501/// A coloured status pill for a CI run status string.
1502fn status_badge(status: &str) -> Markup {
1503 html! { span class=(format!("st {status}")) { (status) } }
1504}
1505
1506/// First 8 hex chars of a commit oid (for compact display).
1507fn short_commit(commit: &str) -> &str {
1508 &commit[..commit.len().min(8)]
1509}
1510
1511/// Wall-clock run duration (`started`→`finished`) as a short string, if known.
1512fn run_duration(run: &CiRun) -> Option<String> {
1513 if run.started_at > 0 && run.finished_at >= run.started_at {
1514 Some(format!("{}s", run.finished_at - run.started_at))
1515 } else {
1516 None
1517 }
1518}
1519
1520/// Render one file's diff (added/deleted/modified) as a unified line diff.
1521/// A file diff bigger than this many rows starts collapsed (its header still
1522/// shows the +/− counts; clicking expands it — native `details`, no JS).
1523const DIFF_COLLAPSE_ROWS: usize = 400;
1524
1525fn render_file_diff(change: &FileChange) -> Markup {
1526 let (badge_cls, badge) = match change.kind {
1527 ChangeKind::Added => ("add", "added"),
1528 ChangeKind::Deleted => ("del", "deleted"),
1529 ChangeKind::Modified => ("mod", "modified"),
1530 };
1531 let head = |stat: Markup| {
1532 html! {
1533 summary.head {
1534 span class=(format!("badge {badge_cls}")) { (badge) }
1535 span { (change.path) }
1536 span.stat { (stat) }
1537 }
1538 }
1539 };
1540
1541 let binary = change.old.as_deref().is_some_and(is_binary)
1542 || change.new.as_deref().is_some_and(is_binary);
1543 if binary {
1544 return html! {
1545 details.file-diff open {
1546 (head(html! { span.muted { "binary" } }))
1547 div.box { div.row { span.muted { "Binary file" } } }
1548 }
1549 };
1550 }
1551
1552 let old = change
1553 .old
1554 .as_deref()
1555 .map(|b| String::from_utf8_lossy(b).into_owned())
1556 .unwrap_or_default();
1557 let new = change
1558 .new
1559 .as_deref()
1560 .map(|b| String::from_utf8_lossy(b).into_owned())
1561 .unwrap_or_default();
1562 let diff = TextDiff::from_lines(&old, &new);
1563 let (mut adds, mut dels) = (0usize, 0usize);
1564 for c in diff.iter_all_changes() {
1565 match c.tag() {
1566 ChangeTag::Insert => adds += 1,
1567 ChangeTag::Delete => dels += 1,
1568 ChangeTag::Equal => {}
1569 }
1570 }
1571 // Hunks: changed lines plus 3 lines of context, not the whole file.
1572 let groups = diff.grouped_ops(3);
1573 let rendered_rows: usize = groups
1574 .iter()
1575 .flatten()
1576 .map(|op| diff.iter_changes(op).count())
1577 .sum();
1578
1579 html! {
1580 details.file-diff open[rendered_rows <= DIFF_COLLAPSE_ROWS] {
1581 (head(html! { span.plus { "+" (adds) } " " span.minus { "−" (dels) } }))
1582 (diff_table(&diff, &groups, old.lines().count()))
1583 }
1584 }
1585}
1586
1587/// Render grouped diff hunks as a table: old/new line numbers, a +/- sign
1588/// column, and the line. Elided stretches show a "⋯ N unchanged lines" row
1589/// (including before the first hunk and after the last).
1590fn diff_table<'a>(
1591 diff: &TextDiff<'a, 'a, '_, str>,
1592 groups: &[Vec<similar::DiffOp>],
1593 old_total: usize,
1594) -> Markup {
1595 let gap_row = |n: usize| {
1596 html! {
1597 @if n > 0 {
1598 tr.gap { td colspan="4" { "⋯ " (n) " unchanged line" @if n != 1 { "s" } } }
1599 }
1600 }
1601 };
1602 // Unchanged-line gap before each group, and after the last one.
1603 let mut prev_end = 0usize; // end of the previous group, in old-file lines
1604 let mut with_gaps = Vec::with_capacity(groups.len());
1605 for group in groups {
1606 let start = group.first().map_or(prev_end, |op| op.old_range().start);
1607 with_gaps.push((start.saturating_sub(prev_end), group));
1608 prev_end = group.last().map_or(prev_end, |op| op.old_range().end);
1609 }
1610 let trailing = old_total.saturating_sub(prev_end);
1611
1612 html! {
1613 table.code.diff {
1614 @for (gap, group) in &with_gaps {
1615 (gap_row(*gap))
1616 @for op in group.iter() {
1617 @for change in diff.iter_changes(op) {
1618 @let (sign, cls) = match change.tag() {
1619 ChangeTag::Delete => ("-", "del"),
1620 ChangeTag::Insert => ("+", "ins"),
1621 ChangeTag::Equal => (" ", ""),
1622 };
1623 tr class=(cls) {
1624 td.ln { @if let Some(i) = change.old_index() { (i + 1) } }
1625 td.ln { @if let Some(i) = change.new_index() { (i + 1) } }
1626 td.sign { (sign) }
1627 td { (change.value().trim_end_matches('\n')) }
1628 }
1629 }
1630 }
1631 }
1632 (gap_row(trailing))
1633 }
1634 }
1635}
1636
1637/// Lazily-loaded syntax set and theme (pure-Rust fancy-regex backend).
1638fn highlighter() -> &'static (SyntaxSet, Theme) {
1639 static HL: OnceLock<(SyntaxSet, Theme)> = OnceLock::new();
1640 HL.get_or_init(|| {
1641 let syntaxes = SyntaxSet::load_defaults_newlines();
1642 let themes = ThemeSet::load_defaults();
1643 let theme = themes
1644 .themes
1645 .get("InspiredGitHub")
1646 .or_else(|| themes.themes.values().next())
1647 .cloned()
1648 .expect("at least one default theme");
1649 (syntaxes, theme)
1650 })
1651}
1652
1653/// [`highlight`] through a byte-budgeted LRU keyed by blob oid + extension: a
1654/// blob's rendered HTML is immutable for its object id (the extension is part
1655/// of the key because it picks the syntax), so each file is highlighted once
1656/// rather than once per request — highlighting large files is by far the most
1657/// expensive thing a page view can do. The budget is
1658/// `http.highlight_cache_mb`; `0` bypasses the cache entirely (for
1659/// RAM-constrained hosts). Concurrent misses may both compute and the last
1660/// insert wins; that's benign.
1661fn cached_highlight(budget_bytes: usize, oid: &str, path: &str, text: &str) -> Arc<Vec<String>> {
1662 if budget_bytes == 0 {
1663 return Arc::new(highlight(path, text));
1664 }
1665 struct Cache {
1666 lru: lru::LruCache<String, Arc<Vec<String>>>,
1667 bytes: usize,
1668 }
1669 fn cost(key: &str, lines: &[String]) -> usize {
1670 key.len() + lines.iter().map(String::len).sum::<usize>()
1671 }
1672 static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
1673 let cache = CACHE.get_or_init(|| {
1674 Mutex::new(Cache {
1675 lru: lru::LruCache::unbounded(),
1676 bytes: 0,
1677 })
1678 });
1679
1680 let ext = std::path::Path::new(path)
1681 .extension()
1682 .and_then(|e| e.to_str())
1683 .unwrap_or("");
1684 let key = format!("{oid}\x00{ext}");
1685 if let Some(hit) = cache.lock().expect("cache lock").lru.get(&key) {
1686 return hit.clone();
1687 }
1688
1689 let lines = Arc::new(highlight(path, text));
1690 let mut c = cache.lock().expect("cache lock");
1691 c.bytes += cost(&key, &lines);
1692 if let Some(old) = c.lru.put(key.clone(), Arc::clone(&lines)) {
1693 c.bytes -= cost(&key, &old); // concurrent miss inserted it first
1694 }
1695 // Evict oldest entries until we're back under budget. An entry larger than
1696 // the whole budget evicts itself — memory stays bounded, it just never caches.
1697 while c.bytes > budget_bytes {
1698 let Some((k, v)) = c.lru.pop_lru() else { break };
1699 c.bytes -= cost(&k, &v);
1700 }
1701 lines
1702}
1703
1704/// Syntax-highlight `text` (chosen by file extension), returning per-line HTML.
1705/// Falls back to escaped plain text for large files or on any failure.
1706fn highlight(path: &str, text: &str) -> Vec<String> {
1707 if text.len() > 512 * 1024 {
1708 return text.lines().map(escape).collect();
1709 }
1710 let (syntaxes, theme) = highlighter();
1711 let syntax = std::path::Path::new(path)
1712 .extension()
1713 .and_then(|e| e.to_str())
1714 .and_then(|ext| syntaxes.find_syntax_by_extension(ext))
1715 .or_else(|| syntaxes.find_syntax_by_first_line(text.lines().next().unwrap_or("")))
1716 .unwrap_or_else(|| syntaxes.find_syntax_plain_text());
1717
1718 let mut h = HighlightLines::new(syntax, theme);
1719 text.lines()
1720 .map(|line| match h.highlight_line(line, syntaxes) {
1721 Ok(ranges) => styled_line_to_highlighted_html(&ranges, IncludeBackground::No)
1722 .unwrap_or_else(|_| escape(line)),
1723 Err(_) => escape(line),
1724 })
1725 .collect()
1726}
1727
1728fn escape(s: &str) -> String {
1729 s.replace('&', "&amp;")
1730 .replace('<', "&lt;")
1731 .replace('>', "&gt;")
1732}
1733
1734/// Format a Unix timestamp as `YYYY-MM-DD HH:MM UTC`.
1735pub(crate) fn fmt_time(secs: i64) -> String {
1736 match OffsetDateTime::from_unix_timestamp(secs) {
1737 Ok(t) => format!(
1738 "{:04}-{:02}-{:02} {:02}:{:02} UTC",
1739 t.year(),
1740 u8::from(t.month()),
1741 t.day(),
1742 t.hour(),
1743 t.minute()
1744 ),
1745 Err(_) => secs.to_string(),
1746 }
1747}
1748
1749/// Format a Unix timestamp relative to now (`2 hours ago`, `last month`).
1750pub(crate) fn fmt_relative(secs: i64) -> String {
1751 relative_to(secs, OffsetDateTime::now_utc().unix_timestamp())
1752}
1753
1754fn relative_to(secs: i64, now: i64) -> String {
1755 fn ago(n: i64, one: &str, unit: &str) -> String {
1756 if n == 1 {
1757 one.to_string()
1758 } else {
1759 format!("{n} {unit}s ago")
1760 }
1761 }
1762 let delta = now - secs;
1763 if delta < 60 {
1764 return "just now".to_string();
1765 }
1766 let minutes = delta / 60;
1767 if minutes < 60 {
1768 return ago(minutes, "1 minute ago", "minute");
1769 }
1770 let hours = delta / 3600;
1771 if hours < 24 {
1772 return ago(hours, "1 hour ago", "hour");
1773 }
1774 let days = delta / 86_400;
1775 if days < 7 {
1776 return ago(days, "yesterday", "day");
1777 }
1778 let weeks = days / 7;
1779 if weeks < 5 {
1780 return ago(weeks, "last week", "week");
1781 }
1782 let months = days / 30;
1783 if months < 12 {
1784 return ago(months, "last month", "month");
1785 }
1786 ago(days / 365, "last year", "year")
1787}
1788
1789/// Heuristic: treat content with a NUL in the first 8 KiB as binary.
1790fn is_binary(bytes: &[u8]) -> bool {
1791 bytes.iter().take(8192).any(|&b| b == 0)
1792}
1793
1794#[cfg(test)]
1795mod tests {
1796 use super::*;
1797
1798 #[test]
1799 fn markdown_by_extension_only() {
1800 assert!(is_markdown("README.md"));
1801 assert!(is_markdown("docs/guide.MarkDown"));
1802 assert!(!is_markdown("main.rs"));
1803 assert!(!is_markdown("md")); // no extension
1804 }
1805
1806 // Repo content is untrusted; rendered markdown must not become stored XSS.
1807 #[test]
1808 fn rendered_markdown_neutralizes_html_and_script_urls() {
1809 let out = render_markdown(
1810 "# title\n\n<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n![y](data:text/html,evil)\n\n[ok](https://example.com)\n",
1811 )
1812 .into_string();
1813 assert!(out.contains("<h1>title</h1>"), "markdown renders: {out}");
1814 assert!(!out.contains("<script>"), "raw HTML escaped: {out}");
1815 assert!(
1816 out.contains("&lt;script&gt;"),
1817 "raw HTML kept as text: {out}"
1818 );
1819 assert!(!out.contains("javascript:"), "script URL dropped: {out}");
1820 assert!(!out.contains("data:"), "data URL dropped: {out}");
1821 assert!(
1822 out.contains(r#"href="https://example.com""#),
1823 "normal links survive: {out}"
1824 );
1825 }
1826
1827 #[test]
1828 fn relative_time_buckets() {
1829 const NOW: i64 = 1_000_000_000;
1830 let at = |delta: i64| relative_to(NOW - delta, NOW);
1831 assert_eq!(at(0), "just now");
1832 assert_eq!(at(59), "just now");
1833 assert_eq!(at(60), "1 minute ago");
1834 assert_eq!(at(45 * 60), "45 minutes ago");
1835 assert_eq!(at(3600), "1 hour ago");
1836 assert_eq!(at(23 * 3600), "23 hours ago");
1837 assert_eq!(at(86_400), "yesterday");
1838 assert_eq!(at(3 * 86_400), "3 days ago");
1839 assert_eq!(at(8 * 86_400), "last week");
1840 assert_eq!(at(20 * 86_400), "2 weeks ago");
1841 assert_eq!(at(40 * 86_400), "last month");
1842 assert_eq!(at(200 * 86_400), "6 months ago");
1843 assert_eq!(at(400 * 86_400), "last year");
1844 assert_eq!(at(900 * 86_400), "2 years ago");
1845 }
1846}