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