anvilsign in

collin/anvil

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