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