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 ApiToken,
20 App,
21 CiRun,
22 Repository,
23 SshKey,
24 User,
25 access,
26 api_tokens,
27 ci,
28 repos,
29 ssh_keys,
30 users,
31};
32use anvil_git::browse::{
33 self,
34 ChangeKind,
35 FileChange,
36};
37use axum::{
38 Form,
39 Router,
40 extract::{
41 Path,
42 Query,
43 State,
44 },
45 http::{
46 StatusCode,
47 header,
48 },
49 response::{
50 IntoResponse,
51 Redirect,
52 Response,
53 },
54 routing::{
55 get,
56 post,
57 },
58};
59use maud::{
60 DOCTYPE,
61 Markup,
62 PreEscaped,
63 html,
64};
65use similar::{
66 ChangeTag,
67 TextDiff,
68};
69use syntect::{
70 easy::HighlightLines,
71 highlighting::{
72 Theme,
73 ThemeSet,
74 },
75 html::{
76 IncludeBackground,
77 styled_line_to_highlighted_html,
78 },
79 parsing::SyntaxSet,
80};
81use time::OffsetDateTime;
82
83use crate::{
84 auth::{
85 CSRF_FIELD,
86 Csrf,
87 CurrentUser,
88 verify_csrf,
89 },
90 todomd,
91};
92
93const STYLE: &str = r#"
94:root { --fg:#1f2328; --muted:#656d76; --bg:#fff; --border:#d0d7de; --accent:#0969da; --code-bg:#f6f8fa; }
95* { box-sizing:border-box; }
96body { margin:0; font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif; color:var(--fg); background:var(--bg); }
97a { color:var(--accent); text-decoration:none; } a:hover { text-decoration:underline; }
98header.top { border-bottom:1px solid var(--border); padding:12px 0; background:var(--code-bg); }
99.container { max-width:980px; margin:0 auto; padding:0 16px; }
100header.top .container { display:flex; align-items:center; gap:12px; }
101.brand { font-weight:700; font-size:16px; color:var(--fg); }
102main { padding:12px 0 24px; }
103h1,h2 { font-weight:600; } h1 { font-size:20px; } h2 { font-size:15px; margin:20px 0 8px; }
104.muted { color:var(--muted); }
105.repo-list { list-style:none; padding:0; margin:0; }
106.repo-list li { padding:12px 0; border-bottom:1px solid var(--border); }
107.repo-list .name { font-size:16px; font-weight:600; }
108.box { border:1px solid var(--border); border-radius:6px; overflow:hidden; }
109.box .row { display:flex; justify-content:space-between; padding:8px 16px; border-top:1px solid var(--border); }
110.box .row:first-child { border-top:0; }
111.box .row a.entry { display:flex; gap:8px; align-items:center; white-space:nowrap; }
112.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; }
113.box .row a.fc-msg:hover { color:var(--accent); }
114.box .row .fc-time { margin-left:16px; white-space:nowrap; color:var(--muted); font-size:13px; }
115.icon { width:1em; height:1em; flex:none; fill:currentColor; color:var(--muted); vertical-align:-0.125em; }
116.icon.dir { color:#54aeff; }
117.file-actions .btn .icon { color:inherit; }
118table.code { border-collapse:collapse; width:100%; font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
119table.code td { padding:0 10px; vertical-align:top; white-space:pre; }
120table.code td.ln { text-align:right; color:var(--muted); user-select:none; width:1%; border-right:1px solid var(--border); background:var(--code-bg); }
121.cmds { background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:12px 14px; margin:8px 0; font:12px/1.7 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; overflow-x:auto; }
122.clone { border:1px solid var(--border); border-radius:6px; padding:12px 16px; margin:16px 0; }
123.clone-head { display:flex; align-items:center; gap:12px; margin-bottom:8px; }
124.clone-tabs { display:flex; margin-left:auto; }
125.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; }
126.clone-tab:first-child { border-radius:2em 0 0 2em; margin-left:0; }
127.clone-tab:last-child { border-radius:0 2em 2em 0; }
128.clone-tab:first-child:last-child { border-radius:2em; }
129.clone-tab.active { background:var(--accent); color:#fff; border-color:var(--accent); z-index:1; }
130.clone-cmd { display:flex; align-items:center; gap:8px; background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:6px 10px; }
131.clone-cmd code { flex:1; font:12px ui-monospace,monospace; user-select:all; overflow-x:auto; white-space:nowrap; }
132.copy-btn { display:inline-flex; align-items:center; background:none; border:0; color:var(--muted); cursor:pointer; padding:2px; }
133.copy-btn:hover { color:var(--fg); }
134.copied-msg { display:none; color:#1a7f37; font-size:12px; }
135.clone.copied .copied-msg { display:inline; }
136.clone.copied .copy-btn { color:#1a7f37; }
137.crumbs { margin:12px 0; font:13px ui-monospace,monospace; }
138.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); }
139.pill.active { background:var(--accent); border-color:var(--accent); color:#fff; }
140.view-toggle { margin:8px 0; }
141a.pill:hover { text-decoration:none; border-color:var(--accent); color:var(--accent); }
142.md-body { padding:8px 24px 16px; line-height:1.6; overflow-wrap:break-word; }
143.md-body h1, .md-body h2 { border-bottom:1px solid var(--border); padding-bottom:6px; }
144.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; }
145.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; }
146.md-body pre code { background:none; padding:0; font-size:inherit; }
147.md-body blockquote { border-left:4px solid var(--border); margin:0 0 12px; padding:0 14px; color:var(--muted); }
148.md-body table { border-collapse:collapse; margin:12px 0; } .md-body th, .md-body td { border:1px solid var(--border); padding:5px 10px; }
149.md-body img { max-width:100%; }
150.linkbtn { background:none; border:0; color:var(--accent); cursor:pointer; font:inherit; padding:0; }
151.linkbtn:hover { text-decoration:underline; }
152.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; }
153.btn:hover { text-decoration:none; opacity:.92; }
154/* Repo header: title (+ visibility badge) on the left, quick-nav on the right;
155 wraps cleanly to its own line on narrow viewports instead of floating. */
156.repo-head { display:flex; flex-wrap:wrap; align-items:baseline; justify-content:space-between; gap:6px 16px; margin:24px 0 4px; }
157.repo-title { display:flex; align-items:baseline; flex-wrap:wrap; gap:8px; min-width:0; }
158.repo-title h1 { margin:0; }
159.repo-title .pill { font-size:11px; text-transform:uppercase; letter-spacing:.04em; align-self:center; }
160.repo-nav { font-size:13px; display:flex; align-items:baseline; gap:8px; color:var(--muted); }
161.repo-nav a { color:var(--muted); }
162.repo-nav a:hover { color:var(--accent); text-decoration:none; }
163.repo-nav .sep { color:var(--border); }
164.repo-meta { display:flex; gap:8px; margin:8px 0; color:var(--muted); font-size:13px; }
165.repo-meta b { font-weight:600; color:var(--fg); }
166.pill-group { display:inline-flex; }
167.pill-group > .pill { border-radius:0; margin-left:-1px; position:relative; }
168.pill-group > .pill:first-child { border-radius:2em 0 0 2em; margin-left:0; }
169.pill-group > .pill:last-child { border-radius:0 2em 2em 0; }
170form.stack p { margin:10px 0; } form.stack label { font-size:13px; color:var(--muted); }
171form.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; }
172form.stack .check { display:flex; gap:8px; align-items:flex-start; max-width:480px; }
173form.stack select { padding:6px 8px; border:1px solid var(--border); border-radius:6px; font:inherit; }
174form.stack textarea.editor { max-width:none; font:13px/1.5 ui-monospace,monospace; tab-size:4; resize:vertical; }
175p.file-actions { margin:10px 0; display:flex; gap:6px; align-items:center; }
176.file-actions .btn { padding:3px 11px; font-size:12px; font-weight:500; border-radius:6px; display:inline-flex; align-items:center; gap:5px; }
177table.usage { border-collapse:collapse; width:100%; max-width:680px; margin-top:12px; }
178table.usage th, table.usage td { padding:6px 10px; border-bottom:1px solid var(--border); text-align:left; }
179table.usage .num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
180table.usage tfoot td { font-weight:600; border-top:2px solid var(--border); border-bottom:none; }
181.issue-dot { width:10px; height:10px; border-radius:50%; flex:none; }
182.issue-dot.open { background:#1a7f37; }
183.issue-dot.closed { background:#8250df; }
184.st.issue-open { background:#dafbe1; color:#1a7f37; }
185.st.issue-closed { background:#fbefff; color:#8250df; }
186.issue-post { margin:12px 0; }
187.issue-head { padding:8px 16px; border-bottom:1px solid var(--border); background:var(--code-bg); font-size:13px; color:var(--muted); }
188.btn.btn-secondary { background:var(--bg); color:var(--fg); border-color:var(--border); }
189.readme { margin-top:16px; }
190.readme-head { padding:8px 16px; border-bottom:1px solid var(--border); background:var(--code-bg); font-size:13px; font-weight:600; }
191/* Kanban: cards are the only boxes. Columns are headers + whitespace, no
192 nested frames. */
193.kanban { display:flex; gap:20px; align-items:flex-start; overflow-x:auto; padding:4px 2px 8px; }
194.kanban .col { flex:1 1 0; min-width:240px; }
195.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); }
196.kanban .col h3 .count { font-weight:400; letter-spacing:0; text-transform:none; font-size:12px; margin-left:auto; }
197.kanban .card { position:relative; 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); }
198.kanban .card-del { position:absolute; top:3px; right:4px; margin:0; }
199.kanban .card-del-btn { border:0; background:none; color:var(--muted); cursor:pointer; font-size:16px; line-height:1; padding:1px 5px; border-radius:4px; opacity:0; transition:opacity .1s,background .1s; }
200.kanban .card:hover .card-del-btn, .card-del-btn:focus { opacity:1; }
201.kanban .card-del-btn:hover { color:#cf222e; background:var(--code-bg); }
202.kanban .card .title { padding-right:14px; }
203.kanban .card[draggable="true"] { cursor:grab; }
204.kanban .card.dragging { opacity:.4; cursor:grabbing; }
205.kanban .card .title p { margin:0; font-weight:500; }
206.kanban .card.done .title { color:var(--muted); text-decoration:line-through; font-weight:400; }
207.kanban .card details { margin-top:7px; }
208.kanban .card summary { cursor:pointer; font-size:11px; font-weight:500; letter-spacing:.03em; text-transform:uppercase; color:var(--muted); list-style:none; display:inline-flex; align-items:center; gap:5px; user-select:none; }
209.kanban .card summary:hover { color:var(--accent); }
210.kanban .card summary::-webkit-details-marker { display:none; }
211.kanban .card summary::before { content:"\25B8"; font-size:9px; transition:transform .15s ease; }
212.kanban .card details[open] summary { margin-bottom:5px; }
213.kanban .card details[open] summary::before { transform:rotate(90deg); }
214.kanban .card .card-details { font-size:13px; color:var(--fg); line-height:1.5; }
215.kanban .card .card-details p { margin:0 0 6px; }
216.kanban .card .card-details ul { margin:4px 0; padding-left:16px; }
217.kanban .card .card-details img { max-width:100%; height:auto; border-radius:4px; margin:2px 0; }
218.kanban .card .card-details > :last-child { margin-bottom:0; }
219.kanban .card .title img { max-width:100%; height:auto; border-radius:4px; }
220.todo-board-head { font-size:13px; font-weight:600; margin:20px 0 10px; }
221.todo-notes { margin:8px 2px; }
222.todo-notes > summary { cursor:pointer; font-size:13px; color:var(--muted); }
223.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; }
224.latest-commit + .box { border-radius:0 0 6px 6px; }
225.commit-list { list-style:none; padding:0; margin:0; }
226.commit-list li { padding:8px 0; border-top:1px solid var(--border); display:flex; gap:12px; align-items:baseline; }
227.commit-list li:first-child { border-top:0; }
228.sha { font:12px ui-monospace,monospace; color:var(--muted); }
229.file-diff { margin:16px 0; }
230.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; }
231.file-diff summary.head::-webkit-details-marker { display:none; }
232.file-diff summary.head::before { content:"\25B8"; color:var(--muted); }
233.file-diff[open] summary.head::before { content:"\25BE"; }
234.file-diff[open] summary.head { border-bottom:0; border-radius:6px 6px 0 0; }
235.file-diff .stat { margin-left:auto; white-space:nowrap; }
236.stat .plus { color:#1a7f37; } .stat .minus { color:#cf222e; }
237table.diff { border:1px solid var(--border); border-radius:0 0 6px 6px; }
238table.diff td.sign { width:1%; text-align:center; color:var(--muted); user-select:none; }
239table.diff tr.ins { background:#e6ffec; } table.diff tr.ins td.sign { color:#1a7f37; }
240table.diff tr.del { background:#ffebe9; } table.diff tr.del td.sign { color:#cf222e; }
241table.diff tr.gap td { background:var(--code-bg); color:var(--muted); text-align:center; padding:3px 10px; user-select:none; font-size:11px; }
242.badge { font-size:11px; border-radius:3px; padding:1px 6px; }
243.badge.add { background:#dafbe1; color:#1a7f37; } .badge.del { background:#ffebe9; color:#cf222e; } .badge.mod { background:#fff8c5; color:#7d4e00; }
244.st { font-size:11px; border-radius:2em; padding:1px 9px; font-weight:600; text-transform:capitalize; }
245.st.queued { background:#eaeef2; color:#656d76; } .st.running { background:#fff8c5; color:#7d4e00; }
246.st.success { background:#dafbe1; color:#1a7f37; } .st.failure, .st.error { background:#ffebe9; color:#cf222e; }
247.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; }
248footer { color:var(--muted); font-size:12px; padding:24px 0; border-top:1px solid var(--border); margin-top:32px; }
249details.nav-menu { position:relative; }
250details.nav-menu > summary { list-style:none; cursor:pointer; color:var(--accent); font-size:14px; }
251details.nav-menu > summary::-webkit-details-marker { display:none; }
252details.nav-menu > summary::after { content:""; display:inline-block; width:0; height:0; margin-left:6px; vertical-align:middle; border:4px solid transparent; border-top:5px solid var(--muted); border-bottom:0; transition:transform .15s ease; }
253details.nav-menu > summary:hover::after { border-top-color:var(--accent); }
254details.nav-menu[open] > summary::after { transform:rotate(180deg); }
255.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; }
256.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; }
257.nav-dropdown a:hover, .nav-dropdown button:hover { background:var(--code-bg); color:var(--fg); }
258.nav-dropdown.left { left:0; right:auto; max-height:320px; overflow-y:auto; }
259.nav-dropdown .dd-head { padding:6px 14px 2px; font-size:11px; text-transform:uppercase; letter-spacing:.03em; color:var(--muted); }
260.nav-dropdown a.current { font-weight:600; }
261details.rev-menu { display:inline-block; }
262details.rev-menu > summary .pill { cursor:pointer; }
263"#;
264
265/// Icon set as an SVG sprite (a hidden `<svg>` of `<symbol id="i-…">`s),
266/// authored in `assets/icons.svg` and embedded at compile time. The layout
267/// emits it once per page; [`icon`] references a symbol via `<use>`, so the
268/// path data is never duplicated in the rendered HTML.
269const ICON_SPRITE: &str = include_str!("../assets/icons.svg");
270
271/// The icons defined in the sprite. Each maps to a `<symbol id="i-…">` in
272/// `assets/icons.svg` — keep the two in sync.
273#[derive(Clone, Copy)]
274pub(crate) enum Icon {
275 Clipboard,
276 Pencil,
277 Plus,
278 Folder,
279 File,
280}
281
282impl Icon {
283 /// The sprite symbol id (`<symbol id="…">`).
284 fn id(self) -> &'static str {
285 match self {
286 Icon::Clipboard => "i-clipboard",
287 Icon::Pencil => "i-pencil",
288 Icon::Plus => "i-plus",
289 Icon::Folder => "i-folder",
290 Icon::File => "i-file",
291 }
292 }
293}
294
295/// Reference a sprite symbol as an inline `<svg>`, sized/colored by the `.icon`
296/// CSS (1em, `currentColor`).
297fn icon(i: Icon) -> Markup {
298 icon_with(i, "icon")
299}
300
301/// Like [`icon`] but with custom classes (e.g. `"icon dir"` to tint a folder).
302fn icon_with(i: Icon, class: &str) -> Markup {
303 PreEscaped(format!(
304 r##"<svg class="{class}" aria-hidden="true"><use href="#{}"></use></svg>"##,
305 i.id()
306 ))
307}
308
309/// Delegated handlers for the clone widget: protocol toggle + copy-to-clipboard.
310/// Registered once on `document`, so it survives htmx body swaps.
311const CLONE_JS: &str = r#"
312(function(){
313 function copyText(t){
314 if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(t);
315 var ta=document.createElement('textarea'); ta.value=t; ta.style.position='fixed'; ta.style.opacity='0';
316 document.body.appendChild(ta); ta.focus(); ta.select();
317 try{document.execCommand('copy')}catch(e){}
318 document.body.removeChild(ta); return Promise.resolve();
319 }
320 document.addEventListener('click', function(e){
321 var nm=e.target.closest('details.nav-menu');
322 document.querySelectorAll('details.nav-menu').forEach(function(d){ if(d!==nm) d.removeAttribute('open'); });
323 var tab=e.target.closest('.clone-tab');
324 if(tab){
325 var box=tab.closest('.clone'), cmd=box.dataset[tab.dataset.proto];
326 if(cmd){ box.querySelector('.clone-cmd code').textContent=cmd; }
327 box.querySelectorAll('.clone-tab').forEach(function(t){ t.classList.toggle('active', t===tab); });
328 return;
329 }
330 var copy=e.target.closest('.copy-btn');
331 if(copy){
332 var box=copy.closest('.clone');
333 copyText(box.querySelector('.clone-cmd code').textContent).then(function(){
334 box.classList.add('copied');
335 setTimeout(function(){ box.classList.remove('copied'); }, 1300);
336 });
337 }
338 });
339})();
340"#;
341
342/// Mount the web UI routes.
343pub fn routes(router: Router<App>) -> Router<App> {
344 router
345 .route("/", get(home))
346 .route("/-/settings", get(account_settings))
347 .route("/-/settings/keys", post(add_ssh_key))
348 .route("/-/settings/keys/{id}/delete", post(delete_ssh_key))
349 .route("/-/settings/tokens", post(create_token))
350 .route("/-/settings/tokens/{id}/delete", post(revoke_token))
351 .route("/-/new", get(new_repo_form).post(new_repo_submit))
352 .route("/{username}", get(user_profile))
353 .route(
354 "/{owner}/{repo}/settings",
355 get(repo_settings).post(repo_settings_submit),
356 )
357 .route("/{owner}/{repo}", get(repo_index))
358 .route("/{owner}/{repo}/tree/{rev}", get(tree_root))
359 .route("/{owner}/{repo}/tree/{rev}/{*path}", get(tree_path))
360 .route("/{owner}/{repo}/blob/{rev}/{*path}", get(blob))
361 .route(
362 "/{owner}/{repo}/edit/{rev}/{*path}",
363 get(edit_form).post(edit_submit),
364 )
365 .route(
366 "/{owner}/{repo}/add-task/{rev}/{*path}",
367 get(add_task_form).post(add_task_submit),
368 )
369 .route(
370 "/{owner}/{repo}/delete-task/{rev}/{*path}",
371 post(delete_task),
372 )
373 .route("/{owner}/{repo}/move-task/{rev}/{*path}", post(move_task))
374 .route("/{owner}/{repo}/commits/{rev}", get(commits))
375 .route("/{owner}/{repo}/commit/{id}", get(commit))
376 .route("/{owner}/{repo}/ci", get(ci_runs))
377 .route("/{owner}/{repo}/ci/{id}", get(ci_run))
378 .route("/-/static/htmx.min.js", get(htmx_js))
379}
380
381/// Serve the vendored htmx script (embedded in the binary).
382async fn htmx_js() -> Response {
383 (
384 [(
385 header::CONTENT_TYPE,
386 "application/javascript; charset=utf-8",
387 )],
388 include_str!("../assets/htmx.min.js"),
389 )
390 .into_response()
391}
392
393pub(crate) fn layout(title: &str, user: Option<&User>, body: Markup) -> Markup {
394 // Attach the session's CSRF token to every htmx request as a header, so any
395 // JS-driven action carries it without a hidden field. Omitted (no attribute)
396 // when unauthenticated. The token is hex, so it needs no JSON escaping.
397 let csrf = crate::auth::current_csrf();
398 let hx_headers = (!csrf.is_empty()).then(|| format!(r#"{{"{CSRF_FIELD}": "{csrf}"}}"#));
399 html! {
400 (DOCTYPE)
401 html lang="en" {
402 head {
403 meta charset="utf-8";
404 meta name="viewport" content="width=device-width, initial-scale=1";
405 title { (title) " · anvil" }
406 style { (PreEscaped(STYLE)) }
407 }
408 body hx-boost="true" hx-headers=[hx_headers] {
409 (PreEscaped(ICON_SPRITE))
410 header.top { div.container {
411 a.brand href="/" { "anvil" }
412 span style="margin-left:auto" {
413 @match user {
414 Some(u) => {
415 details.nav-menu {
416 summary { (u.username) }
417 div.nav-dropdown {
418 a href="/-/settings" { "Settings" }
419 @if u.is_admin { a href="/-/admin/usage" { "Disk usage" } }
420 form method="post" action="/-/logout" {
421 button type="submit" { "Sign out" }
422 }
423 }
424 }
425 }
426 None => { a href="/-/login" { "sign in" } }
427 }
428 }
429 } }
430 main { div.container { (body) } }
431 footer { div.container { "anvil — a git forge" } }
432 script src="/-/static/htmx.min.js" {}
433 script { (PreEscaped(CLONE_JS)) }
434 }
435 }
436 }
437}
438
439/// Hidden CSRF token field for embedding inside a mutating `<form>`.
440pub(crate) fn csrf_input(token: &str) -> Markup {
441 html! { input type="hidden" name=(CSRF_FIELD) value=(token); }
442}
443
444pub(crate) fn not_found(message: &str) -> Response {
445 (
446 StatusCode::NOT_FOUND,
447 layout(
448 "Not found",
449 None,
450 html! { h1 { "Not found" } p.muted { (message) } },
451 ),
452 )
453 .into_response()
454}
455
456pub(crate) fn server_error(err: impl std::fmt::Display) -> Response {
457 tracing::error!("ui error: {err}");
458 (
459 StatusCode::INTERNAL_SERVER_ERROR,
460 layout("Error", None, html! { h1 { "Something went wrong" } }),
461 )
462 .into_response()
463}
464
465/// Resolve `<owner>/<repo>` to its on-disk path and metadata row, enforcing read
466/// access for `viewer`. Private repos 404 for non-owners (no existence leak).
467pub(crate) async fn resolve_repo(
468 app: &App,
469 viewer: Option<&User>,
470 owner: &str,
471 name: &str,
472) -> Result<(PathBuf, Repository), Response> {
473 let owner_user = users::find_by_username(&app.db, owner)
474 .await
475 .map_err(server_error)?
476 .ok_or_else(|| not_found("no such user"))?;
477 let repo = repos::find(&app.db, owner_user.id, name)
478 .await
479 .map_err(server_error)?
480 .ok_or_else(|| not_found("no such repository"))?;
481 if !access::can_read(&repo, viewer) {
482 return Err(not_found("no such repository"));
483 }
484 let path = anvil_core::storage::repo_path(&app.config.repositories_dir(), owner, name);
485 if !path.exists() {
486 return Err(not_found("repository not found on disk"));
487 }
488 Ok((path, repo))
489}
490
491/// `GET /` — list repositories visible to the current user.
492async fn home(State(app): State<App>, CurrentUser(user): CurrentUser) -> Result<Markup, Response> {
493 let all = repos::list_all_with_owner(&app.db)
494 .await
495 .map_err(server_error)?;
496 let repos: Vec<_> = all
497 .into_iter()
498 .filter(|r| {
499 !r.is_private
500 || user
501 .as_ref()
502 .is_some_and(|u| u.id == r.owner_id || u.is_admin)
503 })
504 .collect();
505 Ok(layout(
506 "Repositories",
507 user.as_ref(),
508 html! {
509 div style="display:flex;align-items:center" {
510 h1 style="margin-right:auto" { "Repositories" }
511 @if user.is_some() { a.btn href="/-/new" { "New repository" } }
512 }
513 @if repos.is_empty() {
514 p.muted {
515 "No repositories yet. "
516 @if user.is_some() { a href="/-/new" { "Create one" } "." }
517 @else { "Sign in to create one." }
518 }
519 } @else {
520 ul.repo-list {
521 @for r in &repos {
522 li {
523 div.name {
524 a href=(format!("/{}", r.owner)) { (r.owner) }
525 "/"
526 a href=(format!("/{}/{}", r.owner, r.name)) { (r.name) }
527 @if r.is_private { " " span.pill { "private" } }
528 }
529 @if !r.description.is_empty() { div.muted { (r.description) } }
530 }
531 }
532 }
533 }
534 },
535 ))
536}
537
538/// `GET /{username}` — a user's profile: their repositories (public to all;
539/// private only to themselves or an admin).
540async fn user_profile(
541 State(app): State<App>,
542 CurrentUser(viewer): CurrentUser,
543 Path(username): Path<String>,
544) -> Result<Markup, Response> {
545 let owner = users::find_by_username(&app.db, &username)
546 .await
547 .map_err(server_error)?
548 .ok_or_else(|| not_found("no such user"))?;
549 let visible: Vec<_> = repos::list_by_owner(&app.db, owner.id)
550 .await
551 .map_err(server_error)?
552 .into_iter()
553 .filter(|r| access::can_read(r, viewer.as_ref()))
554 .collect();
555 let is_self = viewer.as_ref().is_some_and(|u| u.id == owner.id);
556
557 Ok(layout(
558 &owner.username,
559 viewer.as_ref(),
560 html! {
561 div style="display:flex;align-items:center" {
562 h1 style="margin-right:auto" { (owner.username) }
563 @if is_self { a.btn href="/-/new" { "New repository" } }
564 }
565 h2 { "Repositories" }
566 @if visible.is_empty() {
567 p.muted { "No repositories." }
568 } @else {
569 ul.repo-list {
570 @for r in &visible {
571 li {
572 div.name {
573 a href=(format!("/{}/{}", owner.username, r.name)) { (r.name) }
574 @if r.is_private { " " span.pill { "private" } }
575 }
576 @if !r.description.is_empty() { div.muted { (r.description) } }
577 }
578 }
579 }
580 }
581 },
582 ))
583}
584
585#[derive(serde::Deserialize)]
586struct AddKeyForm {
587 #[serde(default)]
588 title: String,
589 key: String,
590 #[serde(default)]
591 csrf: String,
592}
593
594/// `GET /settings` — account settings: profile + SSH keys.
595async fn account_settings(
596 State(app): State<App>,
597 CurrentUser(user): CurrentUser,
598 csrf: Csrf,
599) -> Response {
600 let Some(user) = user else {
601 return Redirect::to("/-/login").into_response();
602 };
603 let keys = match ssh_keys::list_by_user(&app.db, user.id).await {
604 Ok(keys) => keys,
605 Err(e) => return server_error(e),
606 };
607 let tokens = api_tokens::list(&app.db, user.id).await.unwrap_or_default();
608 account_page(&user, &keys, &tokens, None, None, &csrf.0).into_response()
609}
610
611/// `POST /settings/keys` — register an SSH public key for the current user.
612async fn add_ssh_key(
613 State(app): State<App>,
614 CurrentUser(user): CurrentUser,
615 csrf: Csrf,
616 Form(form): Form<AddKeyForm>,
617) -> Response {
618 let Some(user) = user else {
619 return Redirect::to("/-/login").into_response();
620 };
621 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
622 return resp;
623 }
624 let result = match ssh_keys::parse_public_key(&form.key) {
625 Ok((fingerprint, content)) => {
626 ssh_keys::add(&app.db, user.id, &form.title, &fingerprint, &content)
627 .await
628 .map(|_| ())
629 }
630 Err(e) => Err(e),
631 };
632 match result {
633 Ok(()) => Redirect::to("/-/settings").into_response(),
634 Err(e) => {
635 let keys = ssh_keys::list_by_user(&app.db, user.id)
636 .await
637 .unwrap_or_default();
638 let tokens = api_tokens::list(&app.db, user.id).await.unwrap_or_default();
639 (
640 StatusCode::BAD_REQUEST,
641 account_page(&user, &keys, &tokens, None, Some(&e.to_string()), &csrf.0),
642 )
643 .into_response()
644 }
645 }
646}
647
648#[derive(serde::Deserialize)]
649struct CreateTokenForm {
650 #[serde(default)]
651 name: String,
652 #[serde(default)]
653 csrf: String,
654}
655
656/// `POST /settings/tokens` — mint a read-only PAT for the current user and show
657/// the plaintext once (it's only stored hashed, so it can't be shown again).
658async fn create_token(
659 State(app): State<App>,
660 CurrentUser(user): CurrentUser,
661 csrf: Csrf,
662 Form(form): Form<CreateTokenForm>,
663) -> Response {
664 let Some(user) = user else {
665 return Redirect::to("/-/login").into_response();
666 };
667 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
668 return resp;
669 }
670 let name = match form.name.trim() {
671 "" => "api",
672 n => n,
673 };
674 let plaintext = match api_tokens::create(&app.db, user.id, name, api_tokens::READ).await {
675 Ok((_, plaintext)) => plaintext,
676 Err(e) => return server_error(e),
677 };
678 let keys = ssh_keys::list_by_user(&app.db, user.id)
679 .await
680 .unwrap_or_default();
681 let tokens = api_tokens::list(&app.db, user.id).await.unwrap_or_default();
682 account_page(&user, &keys, &tokens, Some(&plaintext), None, &csrf.0).into_response()
683}
684
685/// `POST /settings/tokens/{id}/delete` — revoke one of the current user's
686/// tokens (ownership enforced: a user can only revoke their own).
687async fn revoke_token(
688 State(app): State<App>,
689 CurrentUser(user): CurrentUser,
690 csrf: Csrf,
691 Path(id): Path<i64>,
692 Form(form): Form<crate::auth::CsrfForm>,
693) -> Response {
694 let Some(user) = user else {
695 return Redirect::to("/-/login").into_response();
696 };
697 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
698 return resp;
699 }
700 let owned = api_tokens::list(&app.db, user.id).await.unwrap_or_default();
701 if owned.iter().any(|t| t.id == id)
702 && let Err(e) = api_tokens::revoke(&app.db, id).await
703 {
704 return server_error(e);
705 }
706 Redirect::to("/-/settings").into_response()
707}
708
709/// `POST /settings/keys/{id}/delete` — remove one of the current user's keys.
710async fn delete_ssh_key(
711 State(app): State<App>,
712 CurrentUser(user): CurrentUser,
713 csrf: Csrf,
714 Path(id): Path<i64>,
715 Form(form): Form<crate::auth::CsrfForm>,
716) -> Response {
717 let Some(user) = user else {
718 return Redirect::to("/-/login").into_response();
719 };
720 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
721 return resp;
722 }
723 if let Err(e) = ssh_keys::delete(&app.db, id, user.id).await {
724 return server_error(e);
725 }
726 Redirect::to("/-/settings").into_response()
727}
728
729#[allow(clippy::too_many_arguments)]
730fn account_page(
731 user: &User,
732 keys: &[SshKey],
733 tokens: &[ApiToken],
734 new_token: Option<&str>,
735 error: Option<&str>,
736 csrf: &str,
737) -> Markup {
738 layout(
739 "Account settings",
740 Some(user),
741 html! {
742 h1 { "Account settings" }
743 p.muted {
744 "Signed in as " strong { (user.username) }
745 @if !user.email.is_empty() { " · " (user.email) }
746 }
747
748 h2 { "SSH keys" }
749 p.muted { "Add a public key to clone and push over SSH." }
750 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
751 @if keys.is_empty() {
752 p.muted { "No SSH keys yet." }
753 } @else {
754 div.box {
755 @for k in keys {
756 div.row {
757 div {
758 @if !k.title.is_empty() { strong { (k.title) } " " }
759 span.sha { (k.fingerprint) }
760 div.muted style="font-size:12px" { "added " (fmt_time(k.created_at)) }
761 }
762 form method="post" action=(format!("/-/settings/keys/{}/delete", k.id)) {
763 (csrf_input(csrf))
764 button.linkbtn type="submit" { "delete" }
765 }
766 }
767 }
768 }
769 }
770
771 form.stack method="post" action="/-/settings/keys" style="margin-top:16px" {
772 (csrf_input(csrf))
773 p { label { "Title" br; input type="text" name="title" placeholder="laptop"; } }
774 p { label { "Public key" br; textarea name="key" rows="4" placeholder="ssh-ed25519 AAAA…" {} } }
775 p { button.btn type="submit" { "Add SSH key" } }
776 }
777
778 h2 style="margin-top:28px" { "Personal access tokens" }
779 p.muted { "Read-only API tokens for tooling (e.g. fetching attachments over HTTP). The secret is shown once, at creation." }
780 @if let Some(token) = new_token {
781 div.box style="border-color:var(--accent)" {
782 p style="margin-top:0" { strong { "New token — copy it now; it won't be shown again." } }
783 pre.cmds { (token) }
784 }
785 }
786 @if tokens.is_empty() {
787 p.muted { "No tokens yet." }
788 } @else {
789 div.box {
790 @for t in tokens {
791 div.row {
792 div {
793 strong { (t.name) } " " span.pill { (t.scopes) }
794 div.muted style="font-size:12px" { "added " (fmt_time(t.created_at)) }
795 }
796 form method="post" action=(format!("/-/settings/tokens/{}/delete", t.id)) {
797 (csrf_input(csrf))
798 button.linkbtn type="submit" { "revoke" }
799 }
800 }
801 }
802 }
803 }
804 form.stack method="post" action="/-/settings/tokens" style="margin-top:16px" {
805 (csrf_input(csrf))
806 p { label { "Name" br; input type="text" name="name" placeholder="claude"; } }
807 p { button.btn type="submit" { "Create token" } }
808 }
809 },
810 )
811}
812
813pub(crate) fn forbidden() -> Response {
814 (
815 StatusCode::FORBIDDEN,
816 layout(
817 "Forbidden",
818 None,
819 html! { h1 { "Forbidden" } p.muted { "You don't have access to this." } },
820 ),
821 )
822 .into_response()
823}
824
825#[derive(serde::Deserialize)]
826struct NewRepoForm {
827 name: String,
828 #[serde(default)]
829 description: String,
830 private: Option<String>,
831 #[serde(default)]
832 csrf: String,
833}
834
835#[derive(serde::Deserialize)]
836struct SettingsForm {
837 #[serde(default)]
838 description: String,
839 private: Option<String>,
840 #[serde(default)]
841 mirror_url: String,
842 #[serde(default)]
843 csrf: String,
844}
845
846/// `GET /new` — new-repository form (requires login).
847async fn new_repo_form(
848 State(app): State<App>,
849 CurrentUser(user): CurrentUser,
850 csrf: Csrf,
851) -> Response {
852 let Some(user) = user else {
853 return Redirect::to("/-/login").into_response();
854 };
855 let remote = push_remote_url(&app, &user.username, "");
856 new_repo_page(&user, None, "", "", false, &remote, &csrf.0).into_response()
857}
858
859/// The remote URL to suggest for push-to-create: SSH when enabled (pushes
860/// without a credential prompt), otherwise HTTP. `name` may be empty, in which
861/// case a `<name>` placeholder is used.
862fn push_remote_url(app: &App, owner: &str, name: &str) -> String {
863 let name = if name.is_empty() { "<name>" } else { name };
864 if app.config.ssh.enabled {
865 app.config.ssh_clone_url(owner, name)
866 } else {
867 app.config.http_clone_url(owner, name)
868 }
869}
870
871/// `POST /new` — create a repository owned by the current user.
872async fn new_repo_submit(
873 State(app): State<App>,
874 CurrentUser(user): CurrentUser,
875 csrf: Csrf,
876 Form(form): Form<NewRepoForm>,
877) -> Response {
878 let Some(user) = user else {
879 return Redirect::to("/-/login").into_response();
880 };
881 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
882 return resp;
883 }
884 let private = form.private.is_some();
885 match repos::create(
886 &app.db,
887 &app.config.repositories_dir(),
888 &user,
889 &form.name,
890 &form.description,
891 private,
892 )
893 .await
894 {
895 Ok(repo) => Redirect::to(&format!("/{}/{}", user.username, repo.name)).into_response(),
896 Err(e) => {
897 let remote = push_remote_url(&app, &user.username, &form.name);
898 (
899 StatusCode::BAD_REQUEST,
900 new_repo_page(
901 &user,
902 Some(&e.to_string()),
903 &form.name,
904 &form.description,
905 private,
906 &remote,
907 &csrf.0,
908 ),
909 )
910 .into_response()
911 }
912 }
913}
914
915fn new_repo_page(
916 user: &User,
917 error: Option<&str>,
918 name: &str,
919 description: &str,
920 private: bool,
921 remote: &str,
922 csrf: &str,
923) -> Markup {
924 layout(
925 "New repository",
926 Some(user),
927 html! {
928 h1 { "New repository" }
929 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
930 form.stack method="post" action="/-/new" {
931 (csrf_input(csrf))
932 p { label { "Name" br; input type="text" name="name" value=(name) placeholder="my-project" autofocus; } }
933 p { label { "Description" br; input type="text" name="description" value=(description); } }
934 p { label.check { input type="checkbox" name="private" value="on" checked[private]; span { "Private — only you can see and push to it" } } }
935 p { button.btn type="submit" { "Create repository" } }
936 }
937 p.muted { "It will be created at " code { (user.username) "/" (if name.is_empty() { "<name>" } else { name }) } "." }
938
939 h2 { "…or push an existing repository" }
940 p.muted { "Pushing to a name that doesn't exist yet creates the repository (private). No need for the form above." }
941 pre.cmds { (format!("git remote add origin {remote}\ngit push -u origin main")) }
942 },
943 )
944}
945
946/// Load a repo for an owner-only settings action, enforcing write access.
947async fn resolve_for_settings(
948 app: &App,
949 viewer: Option<&User>,
950 owner: &str,
951 name: &str,
952) -> Result<Repository, Response> {
953 let owner_user = users::find_by_username(&app.db, owner)
954 .await
955 .map_err(server_error)?
956 .ok_or_else(|| not_found("no such repository"))?;
957 let repo = repos::find(&app.db, owner_user.id, name)
958 .await
959 .map_err(server_error)?
960 .ok_or_else(|| not_found("no such repository"))?;
961 if !access::can_read(&repo, viewer) {
962 return Err(not_found("no such repository"));
963 }
964 if !access::can_write(&repo, viewer) {
965 return Err(forbidden());
966 }
967 Ok(repo)
968}
969
970/// `GET /{owner}/{repo}/settings` — owner-only repository settings.
971async fn repo_settings(
972 State(app): State<App>,
973 CurrentUser(user): CurrentUser,
974 csrf: Csrf,
975 Path((owner, repo)): Path<(String, String)>,
976) -> Response {
977 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
978 Ok(m) => m,
979 Err(resp) => return resp,
980 };
981 settings_page(user.as_ref(), &owner, &repo, &meta, None, &csrf.0).into_response()
982}
983
984/// `POST /{owner}/{repo}/settings` — update description / visibility.
985async fn repo_settings_submit(
986 State(app): State<App>,
987 CurrentUser(user): CurrentUser,
988 csrf: Csrf,
989 Path((owner, repo)): Path<(String, String)>,
990 Form(form): Form<SettingsForm>,
991) -> Response {
992 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
993 Ok(m) => m,
994 Err(resp) => return resp,
995 };
996 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
997 return resp;
998 }
999 if let Err(e) = repos::update_settings(
1000 &app.db,
1001 meta.id,
1002 &form.description,
1003 form.private.is_some(),
1004 &form.mirror_url,
1005 )
1006 .await
1007 {
1008 return server_error(e);
1009 }
1010 Redirect::to(&format!("/{owner}/{repo}")).into_response()
1011}
1012
1013fn settings_page(
1014 user: Option<&User>,
1015 owner: &str,
1016 repo: &str,
1017 meta: &Repository,
1018 error: Option<&str>,
1019 csrf: &str,
1020) -> Markup {
1021 layout(
1022 &format!("{owner}/{repo}: settings"),
1023 user,
1024 html! {
1025 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · settings" }
1026 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
1027 form.stack method="post" action=(format!("/{owner}/{repo}/settings")) {
1028 (csrf_input(csrf))
1029 p { label { "Description" br; input type="text" name="description" value=(meta.description); } }
1030 p { label.check { input type="checkbox" name="private" value="on" checked[meta.is_private]; span { "Private — only you can see and push to it" } } }
1031 p {
1032 label {
1033 "Mirror push URL" br;
1034 input type="text" name="mirror_url" value=(meta.mirror_url)
1035 placeholder="https://x-access-token:<token>@github.com/you/repo.git";
1036 }
1037 br;
1038 span.muted style="font-size:12px" {
1039 "After every push here, all refs are mirrored to this remote ("
1040 code { "git push --mirror" }
1041 "). Stored as-is — use a scoped token. Empty disables it."
1042 }
1043 }
1044 p { button.btn type="submit" { "Save changes" } }
1045 }
1046 },
1047 )
1048}
1049
1050fn clone_box(app: &App, owner: &str, name: &str) -> Markup {
1051 let http = app.config.http_clone_url(owner, name);
1052 let ssh = app
1053 .config
1054 .ssh
1055 .enabled
1056 .then(|| app.config.ssh_clone_url(owner, name));
1057 // SSH first and preselected when available — it's the protocol that can
1058 // push without a credential prompt.
1059 let default_cmd = format!("git clone {}", ssh.as_deref().unwrap_or(&http));
1060 html! {
1061 div.clone data-http=(format!("git clone {http}")) data-ssh=[ssh.as_ref().map(|s| format!("git clone {s}"))] {
1062 div.clone-head {
1063 span.muted { "Clone" }
1064 div.clone-tabs {
1065 @if ssh.is_some() {
1066 button.clone-tab.active type="button" data-proto="ssh" { "SSH" }
1067 button.clone-tab type="button" data-proto="http" { "HTTP" }
1068 } @else {
1069 button.clone-tab.active type="button" data-proto="http" { "HTTP" }
1070 }
1071 }
1072 }
1073 div.clone-cmd {
1074 code { (default_cmd) }
1075 button.copy-btn type="button" title="Copy to clipboard" aria-label="Copy" {
1076 (icon(Icon::Clipboard))
1077 }
1078 span.copied-msg { "Copied!" }
1079 }
1080 }
1081 }
1082}
1083
1084/// `GET /{owner}/{repo}` — repository overview with the root tree.
1085async fn repo_index(
1086 State(app): State<App>,
1087 CurrentUser(user): CurrentUser,
1088 Path((owner, repo)): Path<(String, String)>,
1089) -> Result<Markup, Response> {
1090 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1091 let overview = browse::overview(&path).map_err(server_error)?;
1092
1093 let can_write = access::can_write(&meta, user.as_ref());
1094 let header = html! {
1095 div.repo-head {
1096 span.repo-title {
1097 h1 { a href=(format!("/{owner}")) { (owner) } " / " (repo) }
1098 @if meta.is_private { span.pill { "private" } }
1099 }
1100 nav.repo-nav {
1101 a href=(format!("/{owner}/{repo}/issues")) { "Issues" }
1102 span.sep { "·" }
1103 a href=(format!("/{owner}/{repo}/ci")) { "CI" }
1104 span.sep { "·" }
1105 a href=(format!("/{owner}/{repo}/pages")) { "Pages" }
1106 @if can_write {
1107 span.sep { "·" }
1108 a href=(format!("/{owner}/{repo}/settings")) { "Settings" }
1109 }
1110 }
1111 }
1112 @if !meta.description.is_empty() { p.muted { (meta.description) } }
1113 p.repo-meta {
1114 span { b { (overview.branches.len()) } " " (plural(overview.branches.len(), "branch", "branches")) }
1115 span { b { (overview.tags.len()) } " " (plural(overview.tags.len(), "tag", "tags")) }
1116 }
1117 (clone_box(&app, &owner, &repo))
1118 };
1119
1120 if overview.is_empty {
1121 return Ok(layout(
1122 &format!("{owner}/{repo}"),
1123 user.as_ref(),
1124 html! {
1125 (header)
1126 p.muted { "This repository is empty. Push to it to get started." }
1127 },
1128 ));
1129 }
1130
1131 let rev = overview
1132 .default_branch
1133 .clone()
1134 .unwrap_or_else(|| "HEAD".to_string());
1135 let entries = browse::list_tree(&path, &rev, "").map_err(server_error)?;
1136 let latest = browse::commit_log(&path, &rev, 1)
1137 .map_err(server_error)?
1138 .into_iter()
1139 .next();
1140 // Best-effort: a failed walk only costs the per-entry annotations.
1141 let entry_commits =
1142 browse::latest_entry_commits(&path, &rev, "", ENTRY_LOG_WALK).unwrap_or_default();
1143
1144 // A root README renders below the tree, GitHub-style. Best-effort: a
1145 // missing or unreadable file just omits the section.
1146 let readme = entries
1147 .iter()
1148 .find(|e| !e.is_dir && e.name.eq_ignore_ascii_case("readme.md"))
1149 .and_then(|e| {
1150 let bytes = browse::read_blob(&path, &rev, &e.name).ok().flatten()?;
1151 Some((
1152 render_markdown(&String::from_utf8_lossy(&bytes)),
1153 e.name.clone(),
1154 ))
1155 });
1156
1157 // A root TODO.md with tasks renders as a kanban board below the README.
1158 let todo_board = entries
1159 .iter()
1160 .find(|e| !e.is_dir && e.name.eq_ignore_ascii_case("todo.md"))
1161 .and_then(|e| {
1162 let bytes = browse::read_blob(&path, &rev, &e.name).ok().flatten()?;
1163 let board = todomd::render_board(&String::from_utf8_lossy(&bytes), None)?;
1164 Some((board, e.name.clone()))
1165 });
1166
1167 Ok(layout(
1168 &format!("{owner}/{repo}"),
1169 user.as_ref(),
1170 html! {
1171 (header)
1172 p {
1173 (rev_switcher(&owner, &repo, &rev, &overview))
1174 " · "
1175 a href=(format!("/{owner}/{repo}/commits/{}", enc_ref(&rev))) { "commits" }
1176 }
1177 @if let Some(c) = &latest {
1178 div.latest-commit {
1179 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
1180 a href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.summary) }
1181 span.muted style="margin-left:auto" {
1182 (c.author) " · "
1183 span title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
1184 }
1185 }
1186 }
1187 (tree_table(&owner, &repo, &rev, "", &entries, &entry_commits))
1188 @if let Some((rendered, name)) = &readme {
1189 div.box.readme {
1190 div.readme-head {
1191 a href=(format!("/{owner}/{repo}/blob/{}/{name}", enc_ref(&rev))) { (name) }
1192 }
1193 div.md-body { (rendered) }
1194 }
1195 }
1196 @if let Some((board, name)) = &todo_board {
1197 p.todo-board-head {
1198 a href=(format!("/{owner}/{repo}/blob/{}/{name}", enc_ref(&rev))) { (name) }
1199 }
1200 (board)
1201 }
1202 },
1203 ))
1204}
1205
1206async fn tree_root(
1207 State(app): State<App>,
1208 user: CurrentUser,
1209 Path((owner, repo, rev)): Path<(String, String, String)>,
1210) -> Result<Markup, Response> {
1211 render_tree(&app, user, &owner, &repo, &rev, "").await
1212}
1213
1214async fn tree_path(
1215 State(app): State<App>,
1216 user: CurrentUser,
1217 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1218) -> Result<Markup, Response> {
1219 render_tree(&app, user, &owner, &repo, &rev, &path).await
1220}
1221
1222async fn render_tree(
1223 app: &App,
1224 CurrentUser(user): CurrentUser,
1225 owner: &str,
1226 repo: &str,
1227 rev: &str,
1228 path: &str,
1229) -> Result<Markup, Response> {
1230 let (repo_path, _) = resolve_repo(app, user.as_ref(), owner, repo).await?;
1231 let overview = browse::overview(&repo_path).map_err(server_error)?;
1232 let entries = browse::list_tree(&repo_path, rev, path).map_err(server_error)?;
1233 // Best-effort: a failed walk only costs the per-entry annotations.
1234 let entry_commits =
1235 browse::latest_entry_commits(&repo_path, rev, path, ENTRY_LOG_WALK).unwrap_or_default();
1236 Ok(layout(
1237 &format!("{owner}/{repo}: {path}"),
1238 user.as_ref(),
1239 html! {
1240 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1241 p { (rev_switcher(owner, repo, rev, &overview)) }
1242 (breadcrumbs(owner, repo, rev, path, false))
1243 (tree_table(owner, repo, rev, path, &entries, &entry_commits))
1244 },
1245 ))
1246}
1247
1248/// `GET /{owner}/{repo}/blob/{rev}/{*path}` — view a file. Markdown renders
1249/// by default; `?plain=1` shows the raw source (toggle links on the page).
1250async fn blob(
1251 State(app): State<App>,
1252 CurrentUser(user): CurrentUser,
1253 csrf: Csrf,
1254 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1255 Query(query): Query<HashMap<String, String>>,
1256) -> Result<Markup, Response> {
1257 let (repo_path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1258 let (oid, bytes) = browse::read_blob_with_id(&repo_path, &rev, &path)
1259 .map_err(server_error)?
1260 .ok_or_else(|| not_found("file not found"))?;
1261
1262 // Editing writes a commit onto a branch, so it's offered only to writers
1263 // viewing a text file at a branch tip (not a tag or detached commit). The
1264 // resolved tip is the compare-and-swap guard for board delete actions.
1265 let edit_tip = (!is_binary(&bytes) && access::can_write(&meta, user.as_ref()))
1266 .then(|| browse::resolve_commit(&repo_path, &format!("refs/heads/{rev}")).ok())
1267 .flatten();
1268 let can_edit = edit_tip.is_some();
1269
1270 let markdown = is_markdown(&path) && !is_binary(&bytes);
1271 // Custom renderers for well-known filenames (the plugin point — add new
1272 // filename → renderer pairs here). TODO.md defaults to a kanban board.
1273 let is_todo = todomd::is_todo_md(&path) && !is_binary(&bytes);
1274 let board_actions = edit_tip.as_ref().map(|tip| todomd::BoardActions {
1275 owner: &owner,
1276 repo: &repo,
1277 rev: &rev,
1278 path: &path,
1279 tip,
1280 csrf: &csrf.0,
1281 });
1282 let board = (is_todo && !query.contains_key("plain") && !query.contains_key("md"))
1283 .then(|| todomd::render_board(&String::from_utf8_lossy(&bytes), board_actions.as_ref()))
1284 .flatten();
1285 let rendered = markdown && !query.contains_key("plain") && board.is_none();
1286
1287 let body = if let Some(board) = &board {
1288 board.clone()
1289 } else if is_binary(&bytes) {
1290 html! { p.muted { "Binary file (" (bytes.len()) " bytes)" } }
1291 } else if rendered {
1292 let text = String::from_utf8_lossy(&bytes);
1293 html! { div.md-body { (render_markdown(&text)) } }
1294 } else {
1295 let text = String::from_utf8_lossy(&bytes);
1296 let budget = app.config.http.highlight_cache_mb.saturating_mul(1 << 20);
1297 let lines = cached_highlight(budget, &oid, &path, &text);
1298 html! {
1299 table.code {
1300 @for (i, line) in lines.iter().enumerate() {
1301 tr {
1302 td.ln { (i + 1) }
1303 td { (PreEscaped(line)) }
1304 }
1305 }
1306 }
1307 }
1308 };
1309
1310 let blob_url = format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev));
1311 Ok(layout(
1312 &format!("{owner}/{repo}: {path}"),
1313 user.as_ref(),
1314 html! {
1315 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1316 (breadcrumbs(&owner, &repo, &rev, &path, true))
1317 @if can_edit {
1318 p.file-actions {
1319 a.btn.btn-secondary href=(format!("/{owner}/{repo}/edit/{}/{path}", enc_ref(&rev))) {
1320 (icon(Icon::Pencil)) "Edit"
1321 }
1322 @if is_todo {
1323 a.btn.btn-secondary href=(format!("/{owner}/{repo}/add-task/{}/{path}", enc_ref(&rev))) {
1324 (icon(Icon::Plus)) "Add task"
1325 }
1326 }
1327 }
1328 }
1329 @if markdown {
1330 p.view-toggle {
1331 span.pill-group {
1332 @if is_todo {
1333 @if board.is_some() { span.pill.active { "Board" } }
1334 @else { a.pill href=(&blob_url) { "Board" } }
1335 @if rendered { span.pill.active { "Rendered" } }
1336 @else { a.pill href=(format!("{blob_url}?md=1")) { "Rendered" } }
1337 } @else if rendered {
1338 span.pill.active { "Rendered" }
1339 } @else {
1340 a.pill href=(&blob_url) { "Rendered" }
1341 }
1342 @if rendered || board.is_some() {
1343 a.pill href=(format!("{blob_url}?plain=1")) { "Source" }
1344 } @else {
1345 span.pill.active { "Source" }
1346 }
1347 }
1348 }
1349 }
1350 @if board.is_some() {
1351 // The board supplies its own column structure; an enclosing
1352 // box would just nest frames.
1353 (body)
1354 } @else {
1355 div.box style="overflow-x:auto" { (body) }
1356 }
1357 },
1358 ))
1359}
1360
1361#[derive(serde::Deserialize)]
1362struct EditFileForm {
1363 csrf: String,
1364 /// Expected branch tip the editor saw — the compare-and-swap guard.
1365 expected_tip: String,
1366 message: String,
1367 content: String,
1368}
1369
1370/// Resolve a repo for a web edit, enforcing read+write access and that `rev`
1371/// names a branch (editing advances a branch ref). Returns the repo path and
1372/// the branch tip the editor is working from.
1373async fn resolve_for_edit(
1374 app: &App,
1375 user: Option<&User>,
1376 owner: &str,
1377 repo: &str,
1378 rev: &str,
1379) -> Result<(PathBuf, String), Response> {
1380 let (repo_path, meta) = resolve_repo(app, user, owner, repo).await?;
1381 if user.is_none() {
1382 return Err(Redirect::to("/-/login").into_response());
1383 }
1384 if !access::can_write(&meta, user) {
1385 return Err(forbidden());
1386 }
1387 let tip = browse::resolve_commit(&repo_path, &format!("refs/heads/{rev}"))
1388 .map_err(|_| not_found("not an editable branch"))?;
1389 Ok((repo_path, tip))
1390}
1391
1392/// `GET /{owner}/{repo}/edit/{rev}/{*path}` — textarea editor for an existing
1393/// text file on a branch.
1394async fn edit_form(
1395 State(app): State<App>,
1396 CurrentUser(user): CurrentUser,
1397 csrf: Csrf,
1398 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1399) -> Response {
1400 let (repo_path, tip) = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1401 Ok(v) => v,
1402 Err(resp) => return resp,
1403 };
1404 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1405 Ok(Some(b)) => b,
1406 Ok(None) => return not_found("file not found"),
1407 Err(e) => return server_error(e),
1408 };
1409 if is_binary(&bytes) {
1410 return bad_request_page(
1411 user.as_ref(),
1412 "Binary files can't be edited in the browser.",
1413 );
1414 }
1415 let content = String::from_utf8_lossy(&bytes).into_owned();
1416 edit_page(
1417 &owner,
1418 &repo,
1419 &rev,
1420 &path,
1421 &content,
1422 &format!("Update {path}"),
1423 &tip,
1424 None,
1425 user.as_ref(),
1426 &csrf.0,
1427 )
1428 .into_response()
1429}
1430
1431/// `POST /{owner}/{repo}/edit/{rev}/{*path}` — commit the edited content.
1432async fn edit_submit(
1433 State(app): State<App>,
1434 CurrentUser(user): CurrentUser,
1435 csrf: Csrf,
1436 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1437 Form(form): Form<EditFileForm>,
1438) -> Response {
1439 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1440 Ok((p, _)) => p,
1441 Err(resp) => return resp,
1442 };
1443 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1444 return resp;
1445 }
1446 let user = user.expect("resolve_for_edit requires a logged-in user");
1447
1448 // Browsers serialize textarea newlines as CRLF; normalize so an edit
1449 // doesn't rewrite every line ending.
1450 let content = form.content.replace("\r\n", "\n");
1451 let message = if form.message.trim().is_empty() {
1452 format!("Update {path}")
1453 } else {
1454 form.message.clone()
1455 };
1456
1457 match anvil_git::edit::commit_file_change(
1458 &repo_path,
1459 &rev,
1460 &form.expected_tip,
1461 &path,
1462 content.as_bytes(),
1463 &user.username,
1464 &user.email,
1465 &message,
1466 ) {
1467 Ok(_) => {
1468 Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev))).into_response()
1469 }
1470 Err(e) => edit_page(
1471 &owner,
1472 &repo,
1473 &rev,
1474 &path,
1475 &content,
1476 &message,
1477 &form.expected_tip,
1478 Some(&e.to_string()),
1479 Some(&user),
1480 &csrf.0,
1481 )
1482 .into_response(),
1483 }
1484}
1485
1486/// The file-editor page: a textarea, a commit-message field, and the
1487/// compare-and-swap tip carried in a hidden field.
1488#[allow(clippy::too_many_arguments)]
1489fn edit_page(
1490 owner: &str,
1491 repo: &str,
1492 rev: &str,
1493 path: &str,
1494 content: &str,
1495 message: &str,
1496 expected_tip: &str,
1497 error: Option<&str>,
1498 user: Option<&User>,
1499 csrf: &str,
1500) -> Markup {
1501 let action = format!("/{owner}/{repo}/edit/{}/{path}", enc_ref(rev));
1502 let cancel = format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(rev));
1503 let upload_url = format!("/{owner}/{repo}/-/attachments");
1504 layout(
1505 &format!("Edit {path}"),
1506 user,
1507 html! {
1508 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1509 (breadcrumbs(owner, repo, rev, path, true))
1510 p.muted { "Editing on branch " code { (rev) } " — commits as you." }
1511 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
1512 form.stack method="post" action=(action) {
1513 (csrf_input(csrf))
1514 input type="hidden" name="expected_tip" value=(expected_tip);
1515 p {
1516 textarea.editor name="content" rows="24" spellcheck="false" autofocus
1517 data-upload-url=(upload_url) data-csrf=(csrf) { (content) }
1518 }
1519 p.upload-hint {
1520 label.btn.btn-secondary.attach-btn {
1521 "Attach image"
1522 input.attach-input type="file" accept="image/*" multiple hidden;
1523 }
1524 " "
1525 span.muted { "or paste/drop one — it's stored outside git and a Markdown link is inserted." }
1526 }
1527 p { label { "Commit message" br; input type="text" name="message" value=(message); } }
1528 p {
1529 button.btn type="submit" { "Commit changes" }
1530 " "
1531 a.btn.btn-secondary href=(cancel) { "Cancel" }
1532 }
1533 }
1534 script { (PreEscaped(EDITOR_JS)) }
1535 },
1536 )
1537}
1538
1539/// Paste/drop-to-upload for the file editor: image clipboard items and dropped
1540/// image files are POSTed to the repo's attachment endpoint as a raw body, and
1541/// the returned Markdown is spliced into the textarea at the cursor. The blob
1542/// is stored outside git; only the URL lands in the file.
1543const EDITOR_JS: &str = r#"
1544(function(){
1545 var ta = document.querySelector('textarea.editor');
1546 if (!ta || !ta.dataset.uploadUrl) return;
1547 var url = ta.dataset.uploadUrl, csrf = ta.dataset.csrf;
1548 function insertAtCursor(text){
1549 var s = ta.selectionStart, e = ta.selectionEnd;
1550 ta.value = ta.value.slice(0, s) + text + ta.value.slice(e);
1551 ta.selectionStart = ta.selectionEnd = s + text.length;
1552 ta.focus();
1553 }
1554 function replaceFirst(find, repl){
1555 var i = ta.value.indexOf(find);
1556 if (i >= 0) ta.value = ta.value.slice(0, i) + repl + ta.value.slice(i + find.length);
1557 }
1558 function upload(file){
1559 var token = '![uploading ' + (file.name || 'image') + '…]()';
1560 insertAtCursor(token + '\n');
1561 fetch(url, {
1562 method: 'POST',
1563 headers: {'X-CSRF-Token': csrf, 'Content-Type': file.type || 'application/octet-stream'},
1564 body: file
1565 }).then(function(r){
1566 if (!r.ok) throw new Error('upload failed (' + r.status + ')');
1567 return r.json();
1568 }).then(function(d){
1569 replaceFirst(token, d.markdown);
1570 }).catch(function(err){
1571 replaceFirst(token, '![upload failed]()');
1572 console.error(err);
1573 });
1574 }
1575 ta.addEventListener('paste', function(ev){
1576 var items = (ev.clipboardData || {}).items || [];
1577 for (var i = 0; i < items.length; i++){
1578 if (items[i].kind === 'file' && items[i].type.indexOf('image/') === 0){
1579 ev.preventDefault();
1580 upload(items[i].getAsFile());
1581 }
1582 }
1583 });
1584 ta.addEventListener('dragover', function(ev){ ev.preventDefault(); });
1585 ta.addEventListener('drop', function(ev){
1586 var files = (ev.dataTransfer || {}).files || [], imgs = [];
1587 for (var i = 0; i < files.length; i++){
1588 if (files[i].type.indexOf('image/') === 0) imgs.push(files[i]);
1589 }
1590 if (imgs.length){ ev.preventDefault(); imgs.forEach(upload); }
1591 });
1592 // The "Attach image" button (works where paste/drop don't, e.g. mobile):
1593 // a file picker that uploads each chosen image.
1594 var picker = document.querySelector('input.attach-input');
1595 if (picker) picker.addEventListener('change', function(){
1596 var files = picker.files || [];
1597 for (var i = 0; i < files.length; i++){
1598 if (files[i].type.indexOf('image/') === 0) upload(files[i]);
1599 }
1600 picker.value = ''; // let the same file be re-picked
1601 });
1602})();
1603"#;
1604
1605#[derive(serde::Deserialize)]
1606struct AddTaskForm {
1607 csrf: String,
1608 expected_tip: String,
1609 section: String,
1610 title: String,
1611 #[serde(default)]
1612 body: String,
1613}
1614
1615/// `GET /{owner}/{repo}/add-task/{rev}/{*path}` — structured "add a task" form
1616/// for a `TODO.md`, appending a `- [ ]` item per the todo-md round-trip rules.
1617async fn add_task_form(
1618 State(app): State<App>,
1619 CurrentUser(user): CurrentUser,
1620 csrf: Csrf,
1621 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1622) -> Response {
1623 let (repo_path, tip) = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1624 Ok(v) => v,
1625 Err(resp) => return resp,
1626 };
1627 if !todomd::is_todo_md(&path) {
1628 return not_found("not a TODO.md");
1629 }
1630 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1631 Ok(Some(b)) => b,
1632 Ok(None) => return not_found("file not found"),
1633 Err(e) => return server_error(e),
1634 };
1635 let sections = todomd::task_sections(&String::from_utf8_lossy(&bytes));
1636 if sections.is_empty() {
1637 return bad_request_page(user.as_ref(), "This TODO.md has no sections to add to.");
1638 }
1639 add_task_page(
1640 &owner,
1641 &repo,
1642 &rev,
1643 &path,
1644 &sections,
1645 "",
1646 "",
1647 &tip,
1648 None,
1649 user.as_ref(),
1650 &csrf.0,
1651 )
1652 .into_response()
1653}
1654
1655/// `POST /{owner}/{repo}/add-task/{rev}/{*path}` — append the task and commit.
1656async fn add_task_submit(
1657 State(app): State<App>,
1658 CurrentUser(user): CurrentUser,
1659 csrf: Csrf,
1660 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1661 Form(form): Form<AddTaskForm>,
1662) -> Response {
1663 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1664 Ok((p, _)) => p,
1665 Err(resp) => return resp,
1666 };
1667 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1668 return resp;
1669 }
1670 let user = user.expect("resolve_for_edit requires a logged-in user");
1671 if !todomd::is_todo_md(&path) {
1672 return not_found("not a TODO.md");
1673 }
1674 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1675 Ok(Some(b)) => b,
1676 Ok(None) => return not_found("file not found"),
1677 Err(e) => return server_error(e),
1678 };
1679 let text = String::from_utf8_lossy(&bytes);
1680 let sections = todomd::task_sections(&text);
1681
1682 // Browsers serialize textarea newlines as CRLF; store LF.
1683 let body = form.body.replace("\r\n", "\n");
1684
1685 let render_err = |msg: &str, csrf: &Csrf| {
1686 add_task_page(
1687 &owner,
1688 &repo,
1689 &rev,
1690 &path,
1691 &sections,
1692 &form.title,
1693 &body,
1694 &form.expected_tip,
1695 Some(msg),
1696 Some(&user),
1697 &csrf.0,
1698 )
1699 .into_response()
1700 };
1701
1702 let Some(updated) = todomd::add_task(&text, &form.section, &form.title, &body) else {
1703 return render_err(
1704 "Couldn't add the task — check the title isn't empty and the section exists.",
1705 &csrf,
1706 );
1707 };
1708
1709 let message = format!("Add task to {}", form.section);
1710 match anvil_git::edit::commit_file_change(
1711 &repo_path,
1712 &rev,
1713 &form.expected_tip,
1714 &path,
1715 updated.as_bytes(),
1716 &user.username,
1717 &user.email,
1718 &message,
1719 ) {
1720 Ok(_) => {
1721 Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev))).into_response()
1722 }
1723 Err(e) => render_err(&e.to_string(), &csrf),
1724 }
1725}
1726
1727#[derive(serde::Deserialize)]
1728struct DeleteTaskForm {
1729 #[serde(default)]
1730 csrf: String,
1731 expected_tip: String,
1732 section: String,
1733 title: String,
1734}
1735
1736/// `POST /{owner}/{repo}/delete-task/{rev}/{*path}` — remove a task/ticket from
1737/// a `TODO.md` (the ✕ on a board card) and commit. Compare-and-swap guarded by
1738/// `expected_tip`, so a concurrent change is rejected rather than clobbered.
1739async fn delete_task(
1740 State(app): State<App>,
1741 CurrentUser(user): CurrentUser,
1742 csrf: Csrf,
1743 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1744 Form(form): Form<DeleteTaskForm>,
1745) -> Response {
1746 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1747 Ok((p, _)) => p,
1748 Err(resp) => return resp,
1749 };
1750 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1751 return resp;
1752 }
1753 let user = user.expect("resolve_for_edit requires a logged-in user");
1754 if !todomd::is_todo_md(&path) {
1755 return not_found("not a TODO.md");
1756 }
1757 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1758 Ok(Some(b)) => b,
1759 Ok(None) => return not_found("file not found"),
1760 Err(e) => return server_error(e),
1761 };
1762 let text = String::from_utf8_lossy(&bytes);
1763
1764 let Some(updated) = todomd::remove_task(&text, &form.section, &form.title) else {
1765 // Already gone (e.g. a double submit) — just show the current board.
1766 return Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev)))
1767 .into_response();
1768 };
1769
1770 let message = format!("Delete task: {}", form.title);
1771 match anvil_git::edit::commit_file_change(
1772 &repo_path,
1773 &rev,
1774 &form.expected_tip,
1775 &path,
1776 updated.as_bytes(),
1777 &user.username,
1778 &user.email,
1779 &message,
1780 ) {
1781 Ok(_) => {
1782 Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev))).into_response()
1783 }
1784 Err(e) => bad_request_page(Some(&user), &format!("Couldn't delete the task: {e}")),
1785 }
1786}
1787
1788#[derive(serde::Deserialize)]
1789struct MoveTaskForm {
1790 #[serde(default)]
1791 csrf: String,
1792 expected_tip: String,
1793 title: String,
1794 from_section: String,
1795 to_section: String,
1796 to_index: usize,
1797}
1798
1799/// `POST /{owner}/{repo}/move-task/{rev}/{*path}` — reorder/move a task on the
1800/// board (drag-and-drop). Write-gated, CSRF-checked, compare-and-swap on the
1801/// branch tip. Driven by `fetch`, so it returns bare status codes.
1802async fn move_task(
1803 State(app): State<App>,
1804 CurrentUser(user): CurrentUser,
1805 csrf: Csrf,
1806 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1807 Form(form): Form<MoveTaskForm>,
1808) -> Response {
1809 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1810 Ok((p, _)) => p,
1811 Err(resp) => return resp,
1812 };
1813 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1814 return resp;
1815 }
1816 let user = user.expect("resolve_for_edit requires a logged-in user");
1817 if !todomd::is_todo_md(&path) {
1818 return not_found("not a TODO.md");
1819 }
1820 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1821 Ok(Some(b)) => b,
1822 Ok(None) => return not_found("file not found"),
1823 Err(e) => return server_error(e),
1824 };
1825 let text = String::from_utf8_lossy(&bytes);
1826
1827 let Some(updated) = todomd::move_task(
1828 &text,
1829 &form.title,
1830 &form.from_section,
1831 &form.to_section,
1832 form.to_index,
1833 ) else {
1834 return (StatusCode::BAD_REQUEST, "could not move task").into_response();
1835 };
1836
1837 let message = if form.from_section == form.to_section {
1838 format!("Reorder {} in {}", form.title, form.to_section)
1839 } else {
1840 format!("Move {} to {}", form.title, form.to_section)
1841 };
1842 match anvil_git::edit::commit_file_change(
1843 &repo_path,
1844 &rev,
1845 &form.expected_tip,
1846 &path,
1847 updated.as_bytes(),
1848 &user.username,
1849 &user.email,
1850 &message,
1851 ) {
1852 // A no-op drop (dropped back in place) is success, not an error.
1853 Ok(_) | Err(anvil_git::edit::EditError::NoChanges) => StatusCode::OK.into_response(),
1854 Err(anvil_git::edit::EditError::BranchMoved { .. }) => {
1855 (StatusCode::CONFLICT, "branch moved — reload").into_response()
1856 }
1857 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1858 }
1859}
1860
1861/// The add-task form: a section dropdown, a title field, and a Markdown
1862/// description (which supports paste/drop image upload, like the file editor).
1863#[allow(clippy::too_many_arguments)]
1864fn add_task_page(
1865 owner: &str,
1866 repo: &str,
1867 rev: &str,
1868 path: &str,
1869 sections: &[String],
1870 title: &str,
1871 body: &str,
1872 expected_tip: &str,
1873 error: Option<&str>,
1874 user: Option<&User>,
1875 csrf: &str,
1876) -> Markup {
1877 let action = format!("/{owner}/{repo}/add-task/{}/{path}", enc_ref(rev));
1878 let cancel = format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(rev));
1879 let upload_url = format!("/{owner}/{repo}/-/attachments");
1880 layout(
1881 &format!("Add task · {path}"),
1882 user,
1883 html! {
1884 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1885 (breadcrumbs(owner, repo, rev, path, true))
1886 h2 { "Add a task" }
1887 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
1888 form.stack method="post" action=(action) {
1889 (csrf_input(csrf))
1890 input type="hidden" name="expected_tip" value=(expected_tip);
1891 p { label { "Section" br;
1892 select name="section" {
1893 @for s in sections { option value=(s) { (s) } }
1894 }
1895 } }
1896 p { label { "Title" br;
1897 input type="text" name="title" value=(title) placeholder="Short ticket title" autofocus;
1898 } }
1899 p { label { "Description" br;
1900 textarea.editor name="body" rows="10" spellcheck="false"
1901 placeholder="Markdown — attach an image with the button below, or paste/drop one"
1902 data-upload-url=(upload_url) data-csrf=(csrf) { (body) }
1903 } }
1904 p.upload-hint {
1905 label.btn.btn-secondary.attach-btn {
1906 "Attach image"
1907 input.attach-input type="file" accept="image/*" multiple hidden;
1908 }
1909 " "
1910 span.muted { "stored outside git; a Markdown link is inserted into the description." }
1911 }
1912 p {
1913 button.btn type="submit" { "Add task" }
1914 " "
1915 a.btn.btn-secondary href=(cancel) { "Cancel" }
1916 }
1917 }
1918 script { (PreEscaped(EDITOR_JS)) }
1919 },
1920 )
1921}
1922
1923/// A 400 page for malformed edit requests (binary file, no sections, …).
1924fn bad_request_page(user: Option<&User>, message: &str) -> Response {
1925 (
1926 StatusCode::BAD_REQUEST,
1927 layout(
1928 "Can't edit",
1929 user,
1930 html! { h1 { "Can't edit" } p.muted { (message) } },
1931 ),
1932 )
1933 .into_response()
1934}
1935
1936/// Pick the singular or plural noun for a count (`1 branch` / `2 branches`).
1937fn plural<'a>(n: usize, one: &'a str, many: &'a str) -> &'a str {
1938 if n == 1 { one } else { many }
1939}
1940
1941/// Whether a path should be treated as markdown (by extension).
1942fn is_markdown(path: &str) -> bool {
1943 std::path::Path::new(path)
1944 .extension()
1945 .and_then(|e| e.to_str())
1946 .is_some_and(|e| e.eq_ignore_ascii_case("md") || e.eq_ignore_ascii_case("markdown"))
1947}
1948
1949/// Render markdown to HTML (tables, strikethrough, task lists, footnotes).
1950///
1951/// Repo content is untrusted, so this is a stored-XSS surface: raw HTML in the
1952/// source is emitted as escaped literal text, and `javascript:`/`data:`-style
1953/// link and image destinations are dropped.
1954pub(crate) fn render_markdown(text: &str) -> Markup {
1955 use pulldown_cmark::{
1956 Event,
1957 Options,
1958 Parser,
1959 Tag,
1960 html,
1961 };
1962
1963 fn safe_url(dest: &str) -> bool {
1964 let d = dest.trim().to_ascii_lowercase();
1965 !(d.starts_with("javascript:") || d.starts_with("data:") || d.starts_with("vbscript:"))
1966 }
1967
1968 let opts = Options::ENABLE_TABLES
1969 | Options::ENABLE_STRIKETHROUGH
1970 | Options::ENABLE_TASKLISTS
1971 | Options::ENABLE_FOOTNOTES;
1972 let events = Parser::new_ext(text, opts).map(|ev| match ev {
1973 Event::Html(h) => Event::Text(h),
1974 Event::InlineHtml(h) => Event::Text(h),
1975 Event::Start(Tag::Link {
1976 link_type,
1977 dest_url,
1978 title,
1979 id,
1980 }) if !safe_url(&dest_url) => Event::Start(Tag::Link {
1981 link_type,
1982 dest_url: "".into(),
1983 title,
1984 id,
1985 }),
1986 Event::Start(Tag::Image {
1987 link_type,
1988 dest_url,
1989 title,
1990 id,
1991 }) if !safe_url(&dest_url) => Event::Start(Tag::Image {
1992 link_type,
1993 dest_url: "".into(),
1994 title,
1995 id,
1996 }),
1997 e => e,
1998 });
1999 let mut out = String::new();
2000 html::push_html(&mut out, events);
2001 PreEscaped(out)
2002}
2003
2004/// How far back the per-entry "latest commit" walk looks. Entries last touched
2005/// beyond this many commits just lose the annotation.
2006const ENTRY_LOG_WALK: usize = 400;
2007
2008/// Folder or file icon for an entry row (tree listings, pages, artifacts).
2009pub(crate) fn entry_icon(is_dir: bool) -> Markup {
2010 if is_dir {
2011 icon_with(Icon::Folder, "icon dir")
2012 } else {
2013 icon(Icon::File)
2014 }
2015}
2016
2017/// Human-readable byte size (`482 B`, `1.2 KiB`, `34.0 MiB`).
2018pub(crate) fn fmt_size(bytes: i64) -> String {
2019 let b = bytes.max(0) as f64;
2020 match b {
2021 b if b < 1024.0 => format!("{bytes} B"),
2022 b if b < 1024.0 * 1024.0 => format!("{:.1} KiB", b / 1024.0),
2023 b if b < 1024.0 * 1024.0 * 1024.0 => format!("{:.1} MiB", b / (1024.0 * 1024.0)),
2024 b => format!("{:.1} GiB", b / (1024.0 * 1024.0 * 1024.0)),
2025 }
2026}
2027
2028/// Percent-encode a ref name for use as one path segment in a URL. Axum
2029/// matches routes before decoding, so an encoded `/` keeps a branch like
2030/// `feat/x` inside the single `{rev}` segment.
2031pub(crate) fn enc_ref(name: &str) -> String {
2032 name.replace('%', "%25")
2033 .replace('/', "%2F")
2034 .replace('?', "%3F")
2035 .replace('#', "%23")
2036}
2037
2038/// Branch/tag switcher: a dropdown over the current rev linking each ref to
2039/// its tree view. Branch names, tag names, and commit ids all work as `rev`.
2040fn rev_switcher(owner: &str, repo: &str, rev: &str, overview: &browse::Overview) -> Markup {
2041 html! {
2042 details.nav-menu.rev-menu {
2043 summary { span.pill { (rev) } }
2044 div.nav-dropdown.left {
2045 @if !overview.branches.is_empty() {
2046 div.dd-head { "Branches" }
2047 @for b in &overview.branches {
2048 a.current[b == rev] href=(format!("/{owner}/{repo}/tree/{}", enc_ref(b))) { (b) }
2049 }
2050 }
2051 @if !overview.tags.is_empty() {
2052 div.dd-head { "Tags" }
2053 @for t in &overview.tags {
2054 a.current[t == rev] href=(format!("/{owner}/{repo}/tree/{}", enc_ref(t))) { (t) }
2055 }
2056 }
2057 }
2058 }
2059 }
2060}
2061
2062/// Render a tree listing as a box of rows; directories link to `tree`, files to
2063/// `blob`. Each entry also shows the subject of (and links to) the latest
2064/// commit that touched it, when `latest` has one for it.
2065fn tree_table(
2066 owner: &str,
2067 repo: &str,
2068 rev: &str,
2069 path: &str,
2070 entries: &[browse::TreeEntry],
2071 latest: &BTreeMap<String, browse::CommitInfo>,
2072) -> Markup {
2073 let join = |name: &str| {
2074 if path.is_empty() {
2075 name.to_string()
2076 } else {
2077 format!("{path}/{name}")
2078 }
2079 };
2080 html! {
2081 div.box {
2082 @if !path.is_empty() {
2083 div.row {
2084 a.entry href=(parent_link(owner, repo, rev, path)) { span.icon { ".." } "up" }
2085 }
2086 }
2087 @for e in entries {
2088 @let child = join(&e.name);
2089 @let kind = if e.is_dir { "tree" } else { "blob" };
2090 div.row {
2091 a.entry href=(format!("/{owner}/{repo}/{kind}/{}/{child}", enc_ref(rev))) {
2092 (entry_icon(e.is_dir))
2093 (e.name) @if e.is_dir { "/" }
2094 }
2095 @if let Some(c) = latest.get(&e.name) {
2096 a.fc-msg href=(format!("/{owner}/{repo}/commit/{}", c.id)) title=(c.summary) { (c.summary) }
2097 span.fc-time title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
2098 }
2099 }
2100 }
2101 }
2102 }
2103}
2104
2105fn parent_link(owner: &str, repo: &str, rev: &str, path: &str) -> String {
2106 match path.rsplit_once('/') {
2107 Some((parent, _)) => format!("/{owner}/{repo}/tree/{}/{parent}", enc_ref(rev)),
2108 None => format!("/{owner}/{repo}/tree/{}", enc_ref(rev)),
2109 }
2110}
2111
2112/// Path breadcrumbs. `is_blob` marks the final component as a file.
2113fn breadcrumbs(owner: &str, repo: &str, rev: &str, path: &str, is_blob: bool) -> Markup {
2114 // Precompute (label, cumulative_path) for each path component.
2115 let mut crumbs: Vec<(String, String)> = Vec::new();
2116 let mut acc = String::new();
2117 for part in path.split('/').filter(|p| !p.is_empty()) {
2118 if !acc.is_empty() {
2119 acc.push('/');
2120 }
2121 acc.push_str(part);
2122 crumbs.push((part.to_string(), acc.clone()));
2123 }
2124 let last = crumbs.len();
2125 html! {
2126 div.crumbs {
2127 a href=(format!("/{owner}/{repo}/tree/{}", enc_ref(rev))) { (rev) }
2128 @for (i, (label, cum)) in crumbs.iter().enumerate() {
2129 " / "
2130 @if i + 1 == last && is_blob {
2131 span { (label) }
2132 } @else {
2133 a href=(format!("/{owner}/{repo}/tree/{}/{cum}", enc_ref(rev))) { (label) }
2134 }
2135 }
2136 }
2137 }
2138}
2139
2140/// `GET /{owner}/{repo}/commits/{rev}` — commit history.
2141async fn commits(
2142 State(app): State<App>,
2143 CurrentUser(user): CurrentUser,
2144 Path((owner, repo, rev)): Path<(String, String, String)>,
2145) -> Result<Markup, Response> {
2146 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2147 let log = browse::commit_log(&path, &rev, 100).map_err(server_error)?;
2148
2149 // Map each commit oid to its latest run status, for inline badges. One query
2150 // for the repo's recent runs; first match wins (list is newest-first).
2151 let runs = ci::list_by_repo(&app.db, meta.id, 200)
2152 .await
2153 .unwrap_or_default();
2154 let mut status_of: HashMap<&str, &str> = HashMap::new();
2155 for r in &runs {
2156 status_of
2157 .entry(r.commit.as_str())
2158 .or_insert(r.status.as_str());
2159 }
2160
2161 Ok(layout(
2162 &format!("{owner}/{repo}: commits"),
2163 user.as_ref(),
2164 html! {
2165 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · commits" }
2166 ul.commit-list {
2167 @for c in &log {
2168 li {
2169 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
2170 @if let Some(st) = status_of.get(c.id.as_str()) {
2171 a href=(format!("/{owner}/{repo}/ci")) { (status_badge(st)) }
2172 }
2173 span { (c.summary) }
2174 span.muted style="margin-left:auto" {
2175 (c.author) " · "
2176 span title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
2177 }
2178 }
2179 }
2180 }
2181 },
2182 ))
2183}
2184
2185/// `GET /{owner}/{repo}/commit/{id}` — a commit with its diff.
2186async fn commit(
2187 State(app): State<App>,
2188 CurrentUser(user): CurrentUser,
2189 Path((owner, repo, id)): Path<(String, String, String)>,
2190) -> Result<Markup, Response> {
2191 let (path, _) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2192 let detail = browse::commit_detail(&path, &id).map_err(server_error)?;
2193 Ok(layout(
2194 &format!("{owner}/{repo}: {}", detail.info.short),
2195 user.as_ref(),
2196 html! {
2197 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · " span.sha { (detail.info.short) } }
2198 p { (detail.info.summary) }
2199 p.muted {
2200 (detail.info.author) " · " (fmt_time(detail.info.time)) " · "
2201 span.sha { (detail.info.id) }
2202 @if let Some(parent) = &detail.parent {
2203 " · parent " a.sha href=(format!("/{owner}/{repo}/commit/{parent}")) { (&parent[..parent.len().min(8)]) }
2204 }
2205 " · "
2206 a href=(format!("/{owner}/{repo}/tree/{}", detail.info.id)) { "browse files" }
2207 }
2208 @if detail.changes.is_empty() {
2209 p.muted { "No file changes." }
2210 }
2211 @for change in &detail.changes {
2212 (render_file_diff(change))
2213 }
2214 },
2215 ))
2216}
2217
2218/// `GET /{owner}/{repo}/ci` — recent CI runs for the repository.
2219async fn ci_runs(
2220 State(app): State<App>,
2221 CurrentUser(user): CurrentUser,
2222 Path((owner, repo)): Path<(String, String)>,
2223) -> Result<Markup, Response> {
2224 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2225 let runs = ci::list_by_repo(&app.db, meta.id, 100)
2226 .await
2227 .map_err(server_error)?;
2228 Ok(layout(
2229 &format!("{owner}/{repo}: CI"),
2230 user.as_ref(),
2231 html! {
2232 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · CI" }
2233 @if runs.is_empty() {
2234 p.muted {
2235 "No CI runs yet. Add a " code { ".anvil/ci.yml" }
2236 " pipeline and push to trigger one."
2237 }
2238 } @else {
2239 div.box {
2240 @for r in &runs {
2241 div.row {
2242 a.entry href=(format!("/{owner}/{repo}/ci/{}", r.id)) {
2243 (status_badge(&r.status))
2244 span.sha { (short_commit(&r.commit)) }
2245 span { (r.ref_name) }
2246 }
2247 span.muted { (fmt_time(r.created_at)) }
2248 }
2249 }
2250 }
2251 }
2252 },
2253 ))
2254}
2255
2256/// `GET /{owner}/{repo}/ci/{id}` — one run's status, timing, and log output.
2257async fn ci_run(
2258 State(app): State<App>,
2259 CurrentUser(user): CurrentUser,
2260 Path((owner, repo, id)): Path<(String, String, i64)>,
2261) -> Result<Markup, Response> {
2262 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2263 let run = ci::get(&app.db, id)
2264 .await
2265 .map_err(server_error)?
2266 .filter(|r| r.repo_id == meta.id)
2267 .ok_or_else(|| not_found("no such CI run"))?;
2268 let artifacts = ci::artifacts_for_run(&app.db, run.id)
2269 .await
2270 .map_err(server_error)?;
2271 Ok(layout(
2272 &format!("{owner}/{repo}: CI #{}", run.id),
2273 user.as_ref(),
2274 html! {
2275 h1 {
2276 a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) }
2277 " · " a href=(format!("/{owner}/{repo}/ci")) { "CI" }
2278 " · #" (run.id)
2279 }
2280 p {
2281 (status_badge(&run.status))
2282 " "
2283 a.sha href=(format!("/{owner}/{repo}/commit/{}", run.commit)) { (short_commit(&run.commit)) }
2284 " " span.muted { (run.ref_name) }
2285 }
2286 p.muted {
2287 "queued " (fmt_time(run.created_at))
2288 @if run.started_at > 0 { " · started " (fmt_time(run.started_at)) }
2289 @if run.finished_at > 0 { " · finished " (fmt_time(run.finished_at)) }
2290 @if let Some(d) = run_duration(&run) { " · took " (d) }
2291 }
2292 @if !artifacts.is_empty() {
2293 h2 { "Artifacts" }
2294 div.box {
2295 @for a in &artifacts {
2296 div.row {
2297 a.entry href=(format!("/{owner}/{repo}/ci/{}/artifacts/{}", run.id, a.name)) {
2298 (entry_icon(a.is_dir))
2299 (a.name)
2300 @if a.browse { " " span.pill { "site" } }
2301 @else if a.is_dir { ".tar.gz" }
2302 }
2303 span.muted {
2304 (artifact_meta_chips(&a.meta))
2305 (fmt_size(a.size))
2306 }
2307 }
2308 }
2309 }
2310 }
2311 @if run.log.is_empty() {
2312 p.muted { "No output yet." }
2313 } @else {
2314 pre.log { (run.log) }
2315 }
2316 },
2317 ))
2318}
2319
2320/// Render an artifact's extractor metadata (a JSON object of key → value) as
2321/// inline `key: value` chips before the size.
2322fn artifact_meta_chips(meta: &str) -> Markup {
2323 let map: BTreeMap<String, String> = serde_json::from_str(meta).unwrap_or_default();
2324 html! {
2325 @for (k, v) in &map {
2326 span.pill title=(k) { (k) ": " (v) }
2327 " "
2328 }
2329 }
2330}
2331
2332/// A coloured status pill for a CI run status string.
2333fn status_badge(status: &str) -> Markup {
2334 html! { span class=(format!("st {status}")) { (status) } }
2335}
2336
2337/// First 8 hex chars of a commit oid (for compact display).
2338fn short_commit(commit: &str) -> &str {
2339 &commit[..commit.len().min(8)]
2340}
2341
2342/// Wall-clock run duration (`started`→`finished`) as a short string, if known.
2343fn run_duration(run: &CiRun) -> Option<String> {
2344 if run.started_at > 0 && run.finished_at >= run.started_at {
2345 Some(format!("{}s", run.finished_at - run.started_at))
2346 } else {
2347 None
2348 }
2349}
2350
2351/// Render one file's diff (added/deleted/modified) as a unified line diff.
2352/// A file diff bigger than this many rows starts collapsed (its header still
2353/// shows the +/− counts; clicking expands it — native `details`, no JS).
2354const DIFF_COLLAPSE_ROWS: usize = 400;
2355
2356fn render_file_diff(change: &FileChange) -> Markup {
2357 let (badge_cls, badge) = match change.kind {
2358 ChangeKind::Added => ("add", "added"),
2359 ChangeKind::Deleted => ("del", "deleted"),
2360 ChangeKind::Modified => ("mod", "modified"),
2361 };
2362 let head = |stat: Markup| {
2363 html! {
2364 summary.head {
2365 span class=(format!("badge {badge_cls}")) { (badge) }
2366 span { (change.path) }
2367 span.stat { (stat) }
2368 }
2369 }
2370 };
2371
2372 let binary = change.old.as_deref().is_some_and(is_binary)
2373 || change.new.as_deref().is_some_and(is_binary);
2374 if binary {
2375 return html! {
2376 details.file-diff open {
2377 (head(html! { span.muted { "binary" } }))
2378 div.box { div.row { span.muted { "Binary file" } } }
2379 }
2380 };
2381 }
2382
2383 let old = change
2384 .old
2385 .as_deref()
2386 .map(|b| String::from_utf8_lossy(b).into_owned())
2387 .unwrap_or_default();
2388 let new = change
2389 .new
2390 .as_deref()
2391 .map(|b| String::from_utf8_lossy(b).into_owned())
2392 .unwrap_or_default();
2393 let diff = TextDiff::from_lines(&old, &new);
2394 let (mut adds, mut dels) = (0usize, 0usize);
2395 for c in diff.iter_all_changes() {
2396 match c.tag() {
2397 ChangeTag::Insert => adds += 1,
2398 ChangeTag::Delete => dels += 1,
2399 ChangeTag::Equal => {}
2400 }
2401 }
2402 // Hunks: changed lines plus 3 lines of context, not the whole file.
2403 let groups = diff.grouped_ops(3);
2404 let rendered_rows: usize = groups
2405 .iter()
2406 .flatten()
2407 .map(|op| diff.iter_changes(op).count())
2408 .sum();
2409
2410 html! {
2411 details.file-diff open[rendered_rows <= DIFF_COLLAPSE_ROWS] {
2412 (head(html! { span.plus { "+" (adds) } " " span.minus { "−" (dels) } }))
2413 (diff_table(&diff, &groups, old.lines().count()))
2414 }
2415 }
2416}
2417
2418/// Render grouped diff hunks as a table: old/new line numbers, a +/- sign
2419/// column, and the line. Elided stretches show a "⋯ N unchanged lines" row
2420/// (including before the first hunk and after the last).
2421fn diff_table<'a>(
2422 diff: &TextDiff<'a, 'a, '_, str>,
2423 groups: &[Vec<similar::DiffOp>],
2424 old_total: usize,
2425) -> Markup {
2426 let gap_row = |n: usize| {
2427 html! {
2428 @if n > 0 {
2429 tr.gap { td colspan="4" { "⋯ " (n) " unchanged line" @if n != 1 { "s" } } }
2430 }
2431 }
2432 };
2433 // Unchanged-line gap before each group, and after the last one.
2434 let mut prev_end = 0usize; // end of the previous group, in old-file lines
2435 let mut with_gaps = Vec::with_capacity(groups.len());
2436 for group in groups {
2437 let start = group.first().map_or(prev_end, |op| op.old_range().start);
2438 with_gaps.push((start.saturating_sub(prev_end), group));
2439 prev_end = group.last().map_or(prev_end, |op| op.old_range().end);
2440 }
2441 let trailing = old_total.saturating_sub(prev_end);
2442
2443 html! {
2444 table.code.diff {
2445 @for (gap, group) in &with_gaps {
2446 (gap_row(*gap))
2447 @for op in group.iter() {
2448 @for change in diff.iter_changes(op) {
2449 @let (sign, cls) = match change.tag() {
2450 ChangeTag::Delete => ("-", "del"),
2451 ChangeTag::Insert => ("+", "ins"),
2452 ChangeTag::Equal => (" ", ""),
2453 };
2454 tr class=(cls) {
2455 td.ln { @if let Some(i) = change.old_index() { (i + 1) } }
2456 td.ln { @if let Some(i) = change.new_index() { (i + 1) } }
2457 td.sign { (sign) }
2458 td { (change.value().trim_end_matches('\n')) }
2459 }
2460 }
2461 }
2462 }
2463 (gap_row(trailing))
2464 }
2465 }
2466}
2467
2468/// Lazily-loaded syntax set and theme (pure-Rust fancy-regex backend).
2469fn highlighter() -> &'static (SyntaxSet, Theme) {
2470 static HL: OnceLock<(SyntaxSet, Theme)> = OnceLock::new();
2471 HL.get_or_init(|| {
2472 let syntaxes = SyntaxSet::load_defaults_newlines();
2473 let themes = ThemeSet::load_defaults();
2474 let theme = themes
2475 .themes
2476 .get("InspiredGitHub")
2477 .or_else(|| themes.themes.values().next())
2478 .cloned()
2479 .expect("at least one default theme");
2480 (syntaxes, theme)
2481 })
2482}
2483
2484/// [`highlight`] through a byte-budgeted LRU keyed by blob oid + extension: a
2485/// blob's rendered HTML is immutable for its object id (the extension is part
2486/// of the key because it picks the syntax), so each file is highlighted once
2487/// rather than once per request — highlighting large files is by far the most
2488/// expensive thing a page view can do. The budget is
2489/// `http.highlight_cache_mb`; `0` bypasses the cache entirely (for
2490/// RAM-constrained hosts). Concurrent misses may both compute and the last
2491/// insert wins; that's benign.
2492fn cached_highlight(budget_bytes: usize, oid: &str, path: &str, text: &str) -> Arc<Vec<String>> {
2493 if budget_bytes == 0 {
2494 return Arc::new(highlight(path, text));
2495 }
2496 struct Cache {
2497 lru: lru::LruCache<String, Arc<Vec<String>>>,
2498 bytes: usize,
2499 }
2500 fn cost(key: &str, lines: &[String]) -> usize {
2501 key.len() + lines.iter().map(String::len).sum::<usize>()
2502 }
2503 static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
2504 let cache = CACHE.get_or_init(|| {
2505 Mutex::new(Cache {
2506 lru: lru::LruCache::unbounded(),
2507 bytes: 0,
2508 })
2509 });
2510
2511 let ext = std::path::Path::new(path)
2512 .extension()
2513 .and_then(|e| e.to_str())
2514 .unwrap_or("");
2515 let key = format!("{oid}\x00{ext}");
2516 if let Some(hit) = cache.lock().expect("cache lock").lru.get(&key) {
2517 return hit.clone();
2518 }
2519
2520 let lines = Arc::new(highlight(path, text));
2521 let mut c = cache.lock().expect("cache lock");
2522 c.bytes += cost(&key, &lines);
2523 if let Some(old) = c.lru.put(key.clone(), Arc::clone(&lines)) {
2524 c.bytes -= cost(&key, &old); // concurrent miss inserted it first
2525 }
2526 // Evict oldest entries until we're back under budget. An entry larger than
2527 // the whole budget evicts itself — memory stays bounded, it just never caches.
2528 while c.bytes > budget_bytes {
2529 let Some((k, v)) = c.lru.pop_lru() else { break };
2530 c.bytes -= cost(&k, &v);
2531 }
2532 lines
2533}
2534
2535/// Syntax-highlight `text` (chosen by file extension), returning per-line HTML.
2536/// Falls back to escaped plain text for large files or on any failure.
2537fn highlight(path: &str, text: &str) -> Vec<String> {
2538 if text.len() > 512 * 1024 {
2539 return text.lines().map(escape).collect();
2540 }
2541 let (syntaxes, theme) = highlighter();
2542 let syntax = std::path::Path::new(path)
2543 .extension()
2544 .and_then(|e| e.to_str())
2545 .and_then(|ext| syntaxes.find_syntax_by_extension(ext))
2546 .or_else(|| syntaxes.find_syntax_by_first_line(text.lines().next().unwrap_or("")))
2547 .unwrap_or_else(|| syntaxes.find_syntax_plain_text());
2548
2549 let mut h = HighlightLines::new(syntax, theme);
2550 text.lines()
2551 .map(|line| match h.highlight_line(line, syntaxes) {
2552 Ok(ranges) => styled_line_to_highlighted_html(&ranges, IncludeBackground::No)
2553 .unwrap_or_else(|_| escape(line)),
2554 Err(_) => escape(line),
2555 })
2556 .collect()
2557}
2558
2559fn escape(s: &str) -> String {
2560 s.replace('&', "&amp;")
2561 .replace('<', "&lt;")
2562 .replace('>', "&gt;")
2563}
2564
2565/// Format a Unix timestamp as `YYYY-MM-DD HH:MM UTC`.
2566pub(crate) fn fmt_time(secs: i64) -> String {
2567 match OffsetDateTime::from_unix_timestamp(secs) {
2568 Ok(t) => format!(
2569 "{:04}-{:02}-{:02} {:02}:{:02} UTC",
2570 t.year(),
2571 u8::from(t.month()),
2572 t.day(),
2573 t.hour(),
2574 t.minute()
2575 ),
2576 Err(_) => secs.to_string(),
2577 }
2578}
2579
2580/// Format a Unix timestamp relative to now (`2 hours ago`, `last month`).
2581pub(crate) fn fmt_relative(secs: i64) -> String {
2582 relative_to(secs, OffsetDateTime::now_utc().unix_timestamp())
2583}
2584
2585fn relative_to(secs: i64, now: i64) -> String {
2586 fn ago(n: i64, one: &str, unit: &str) -> String {
2587 if n == 1 {
2588 one.to_string()
2589 } else {
2590 format!("{n} {unit}s ago")
2591 }
2592 }
2593 let delta = now - secs;
2594 if delta < 60 {
2595 return "just now".to_string();
2596 }
2597 let minutes = delta / 60;
2598 if minutes < 60 {
2599 return ago(minutes, "1 minute ago", "minute");
2600 }
2601 let hours = delta / 3600;
2602 if hours < 24 {
2603 return ago(hours, "1 hour ago", "hour");
2604 }
2605 let days = delta / 86_400;
2606 if days < 7 {
2607 return ago(days, "yesterday", "day");
2608 }
2609 let weeks = days / 7;
2610 if weeks < 5 {
2611 return ago(weeks, "last week", "week");
2612 }
2613 let months = days / 30;
2614 if months < 12 {
2615 return ago(months, "last month", "month");
2616 }
2617 ago(days / 365, "last year", "year")
2618}
2619
2620/// Heuristic: treat content with a NUL in the first 8 KiB as binary.
2621fn is_binary(bytes: &[u8]) -> bool {
2622 bytes.iter().take(8192).any(|&b| b == 0)
2623}
2624
2625#[cfg(test)]
2626mod tests {
2627 use super::*;
2628
2629 #[test]
2630 fn markdown_by_extension_only() {
2631 assert!(is_markdown("README.md"));
2632 assert!(is_markdown("docs/guide.MarkDown"));
2633 assert!(!is_markdown("main.rs"));
2634 assert!(!is_markdown("md")); // no extension
2635 }
2636
2637 // Repo content is untrusted; rendered markdown must not become stored XSS.
2638 #[test]
2639 fn rendered_markdown_neutralizes_html_and_script_urls() {
2640 let out = render_markdown(
2641 "# 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",
2642 )
2643 .into_string();
2644 assert!(out.contains("<h1>title</h1>"), "markdown renders: {out}");
2645 assert!(!out.contains("<script>"), "raw HTML escaped: {out}");
2646 assert!(
2647 out.contains("&lt;script&gt;"),
2648 "raw HTML kept as text: {out}"
2649 );
2650 assert!(!out.contains("javascript:"), "script URL dropped: {out}");
2651 assert!(!out.contains("data:"), "data URL dropped: {out}");
2652 assert!(
2653 out.contains(r#"href="https://example.com""#),
2654 "normal links survive: {out}"
2655 );
2656 }
2657
2658 #[test]
2659 fn relative_time_buckets() {
2660 const NOW: i64 = 1_000_000_000;
2661 let at = |delta: i64| relative_to(NOW - delta, NOW);
2662 assert_eq!(at(0), "just now");
2663 assert_eq!(at(59), "just now");
2664 assert_eq!(at(60), "1 minute ago");
2665 assert_eq!(at(45 * 60), "45 minutes ago");
2666 assert_eq!(at(3600), "1 hour ago");
2667 assert_eq!(at(23 * 3600), "23 hours ago");
2668 assert_eq!(at(86_400), "yesterday");
2669 assert_eq!(at(3 * 86_400), "3 days ago");
2670 assert_eq!(at(8 * 86_400), "last week");
2671 assert_eq!(at(20 * 86_400), "2 weeks ago");
2672 assert_eq!(at(40 * 86_400), "last month");
2673 assert_eq!(at(200 * 86_400), "6 months ago");
2674 assert_eq!(at(400 * 86_400), "last year");
2675 assert_eq!(at(900 * 86_400), "2 years ago");
2676 }
2677}