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