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 let passkeys = anvil_core::passkeys::list(&app.db, user.id)
663 .await
664 .unwrap_or_default();
665 account_page(&user, &keys, &tokens, &passkeys, None, None, &csrf.0).into_response()
666}
667
668/// `POST /settings/keys` — register an SSH public key for the current user.
669async fn add_ssh_key(
670 State(app): State<App>,
671 CurrentUser(user): CurrentUser,
672 csrf: Csrf,
673 Form(form): Form<AddKeyForm>,
674) -> Response {
675 let Some(user) = user else {
676 return Redirect::to("/-/login").into_response();
677 };
678 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
679 return resp;
680 }
681 let result = match ssh_keys::parse_public_key(&form.key) {
682 Ok((fingerprint, content)) => {
683 ssh_keys::add(&app.db, user.id, &form.title, &fingerprint, &content)
684 .await
685 .map(|_| ())
686 }
687 Err(e) => Err(e),
688 };
689 match result {
690 Ok(()) => Redirect::to("/-/settings").into_response(),
691 Err(e) => {
692 let keys = ssh_keys::list_by_user(&app.db, user.id)
693 .await
694 .unwrap_or_default();
695 let tokens = api_tokens::list(&app.db, user.id).await.unwrap_or_default();
696 let passkeys = anvil_core::passkeys::list(&app.db, user.id)
697 .await
698 .unwrap_or_default();
699 (
700 StatusCode::BAD_REQUEST,
701 account_page(
702 &user,
703 &keys,
704 &tokens,
705 &passkeys,
706 None,
707 Some(&e.to_string()),
708 &csrf.0,
709 ),
710 )
711 .into_response()
712 }
713 }
714}
715
716#[derive(serde::Deserialize)]
717struct CreateTokenForm {
718 #[serde(default)]
719 name: String,
720 #[serde(default)]
721 csrf: String,
722}
723
724/// `POST /settings/tokens` — mint a read-only PAT for the current user and show
725/// the plaintext once (it's only stored hashed, so it can't be shown again).
726async fn create_token(
727 State(app): State<App>,
728 CurrentUser(user): CurrentUser,
729 csrf: Csrf,
730 Form(form): Form<CreateTokenForm>,
731) -> Response {
732 let Some(user) = user else {
733 return Redirect::to("/-/login").into_response();
734 };
735 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
736 return resp;
737 }
738 let name = match form.name.trim() {
739 "" => "api",
740 n => n,
741 };
742 let plaintext = match api_tokens::create(&app.db, user.id, name, api_tokens::READ).await {
743 Ok((_, plaintext)) => plaintext,
744 Err(e) => return server_error(e),
745 };
746 let keys = ssh_keys::list_by_user(&app.db, user.id)
747 .await
748 .unwrap_or_default();
749 let tokens = api_tokens::list(&app.db, user.id).await.unwrap_or_default();
750 let passkeys = anvil_core::passkeys::list(&app.db, user.id)
751 .await
752 .unwrap_or_default();
753 account_page(
754 &user,
755 &keys,
756 &tokens,
757 &passkeys,
758 Some(&plaintext),
759 None,
760 &csrf.0,
761 )
762 .into_response()
763}
764
765/// `POST /settings/tokens/{id}/delete` — revoke one of the current user's
766/// tokens (ownership enforced: a user can only revoke their own).
767async fn revoke_token(
768 State(app): State<App>,
769 CurrentUser(user): CurrentUser,
770 csrf: Csrf,
771 Path(id): Path<i64>,
772 Form(form): Form<crate::auth::CsrfForm>,
773) -> Response {
774 let Some(user) = user else {
775 return Redirect::to("/-/login").into_response();
776 };
777 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
778 return resp;
779 }
780 let owned = api_tokens::list(&app.db, user.id).await.unwrap_or_default();
781 if owned.iter().any(|t| t.id == id)
782 && let Err(e) = api_tokens::revoke(&app.db, id).await
783 {
784 return server_error(e);
785 }
786 Redirect::to("/-/settings").into_response()
787}
788
789/// `POST /settings/keys/{id}/delete` — remove one of the current user's keys.
790async fn delete_ssh_key(
791 State(app): State<App>,
792 CurrentUser(user): CurrentUser,
793 csrf: Csrf,
794 Path(id): Path<i64>,
795 Form(form): Form<crate::auth::CsrfForm>,
796) -> Response {
797 let Some(user) = user else {
798 return Redirect::to("/-/login").into_response();
799 };
800 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
801 return resp;
802 }
803 if let Err(e) = ssh_keys::delete(&app.db, id, user.id).await {
804 return server_error(e);
805 }
806 Redirect::to("/-/settings").into_response()
807}
808
809#[allow(clippy::too_many_arguments)]
810fn account_page(
811 user: &User,
812 keys: &[SshKey],
813 tokens: &[ApiToken],
814 passkeys: &[anvil_core::Passkey],
815 new_token: Option<&str>,
816 error: Option<&str>,
817 csrf: &str,
818) -> Markup {
819 layout(
820 "Account settings",
821 Some(user),
822 html! {
823 h1 { "Account settings" }
824 p.muted {
825 "Signed in as " strong { (user.username) }
826 @if !user.email.is_empty() { " · " (user.email) }
827 }
828
829 h2 { "SSH keys" }
830 p.muted { "Add a public key to clone and push over SSH." }
831 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
832 @if keys.is_empty() {
833 p.muted { "No SSH keys yet." }
834 } @else {
835 div.box {
836 @for k in keys {
837 div.row {
838 div {
839 @if !k.title.is_empty() { strong { (k.title) } " " }
840 span.sha { (k.fingerprint) }
841 div.muted style="font-size:12px" { "added " (fmt_time(k.created_at)) }
842 }
843 form method="post" action=(format!("/-/settings/keys/{}/delete", k.id)) {
844 (csrf_input(csrf))
845 button.linkbtn type="submit" { "delete" }
846 }
847 }
848 }
849 }
850 }
851
852 form.stack method="post" action="/-/settings/keys" style="margin-top:16px" {
853 (csrf_input(csrf))
854 p { label { "Title" br; input type="text" name="title" placeholder="laptop"; } }
855 p { label { "Public key" br; textarea name="key" rows="4" placeholder="ssh-ed25519 AAAA…" {} } }
856 p { button.btn type="submit" { "Add SSH key" } }
857 }
858
859 h2 style="margin-top:28px" { "Personal access tokens" }
860 p.muted { "Read-only API tokens for tooling (e.g. fetching attachments over HTTP). The secret is shown once, at creation." }
861 @if let Some(token) = new_token {
862 div.box style="border-color:var(--accent)" {
863 p style="margin-top:0" { strong { "New token — copy it now; it won't be shown again." } }
864 pre.cmds { (token) }
865 }
866 }
867 @if tokens.is_empty() {
868 p.muted { "No tokens yet." }
869 } @else {
870 div.box {
871 @for t in tokens {
872 div.row {
873 div {
874 strong { (t.name) } " " span.pill { (t.scopes) }
875 div.muted style="font-size:12px" { "added " (fmt_time(t.created_at)) }
876 }
877 form method="post" action=(format!("/-/settings/tokens/{}/delete", t.id)) {
878 (csrf_input(csrf))
879 button.linkbtn type="submit" { "revoke" }
880 }
881 }
882 }
883 }
884 }
885 form.stack method="post" action="/-/settings/tokens" style="margin-top:16px" {
886 (csrf_input(csrf))
887 p { label { "Name" br; input type="text" name="name" placeholder="claude"; } }
888 p { button.btn type="submit" { "Create token" } }
889 }
890 (crate::passkeys::shared_script())
891 (crate::passkeys::settings_section(user, passkeys, csrf))
892 },
893 )
894}
895
896pub(crate) fn forbidden() -> Response {
897 (
898 StatusCode::FORBIDDEN,
899 layout(
900 "Forbidden",
901 None,
902 html! { h1 { "Forbidden" } p.muted { "You don't have access to this." } },
903 ),
904 )
905 .into_response()
906}
907
908#[derive(serde::Deserialize)]
909struct NewRepoForm {
910 name: String,
911 #[serde(default)]
912 description: String,
913 private: Option<String>,
914 #[serde(default)]
915 csrf: String,
916}
917
918#[derive(serde::Deserialize)]
919struct SettingsForm {
920 #[serde(default)]
921 description: String,
922 private: Option<String>,
923 #[serde(default)]
924 mirror_url: String,
925 #[serde(default)]
926 csrf: String,
927}
928
929/// `GET /new` — new-repository form (requires login).
930async fn new_repo_form(
931 State(app): State<App>,
932 CurrentUser(user): CurrentUser,
933 csrf: Csrf,
934) -> Response {
935 let Some(user) = user else {
936 return Redirect::to("/-/login").into_response();
937 };
938 let remote = push_remote_url(&app, &user.username, "");
939 new_repo_page(&user, None, "", "", false, &remote, &csrf.0).into_response()
940}
941
942/// The remote URL to suggest for push-to-create: SSH when enabled (pushes
943/// without a credential prompt), otherwise HTTP. `name` may be empty, in which
944/// case a `<name>` placeholder is used.
945fn push_remote_url(app: &App, owner: &str, name: &str) -> String {
946 let name = if name.is_empty() { "<name>" } else { name };
947 if app.config.ssh.enabled {
948 app.config.ssh_clone_url(owner, name)
949 } else {
950 app.config.http_clone_url(owner, name)
951 }
952}
953
954/// `POST /new` — create a repository owned by the current user.
955async fn new_repo_submit(
956 State(app): State<App>,
957 CurrentUser(user): CurrentUser,
958 csrf: Csrf,
959 Form(form): Form<NewRepoForm>,
960) -> Response {
961 let Some(user) = user else {
962 return Redirect::to("/-/login").into_response();
963 };
964 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
965 return resp;
966 }
967 let private = form.private.is_some();
968 match repos::create(
969 &app.db,
970 &app.config.repositories_dir(),
971 &user,
972 &form.name,
973 &form.description,
974 private,
975 )
976 .await
977 {
978 Ok(repo) => Redirect::to(&format!("/{}/{}", user.username, repo.name)).into_response(),
979 Err(e) => {
980 let remote = push_remote_url(&app, &user.username, &form.name);
981 (
982 StatusCode::BAD_REQUEST,
983 new_repo_page(
984 &user,
985 Some(&e.to_string()),
986 &form.name,
987 &form.description,
988 private,
989 &remote,
990 &csrf.0,
991 ),
992 )
993 .into_response()
994 }
995 }
996}
997
998fn new_repo_page(
999 user: &User,
1000 error: Option<&str>,
1001 name: &str,
1002 description: &str,
1003 private: bool,
1004 remote: &str,
1005 csrf: &str,
1006) -> Markup {
1007 layout(
1008 "New repository",
1009 Some(user),
1010 html! {
1011 h1 { "New repository" }
1012 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
1013 form.stack method="post" action="/-/new" {
1014 (csrf_input(csrf))
1015 p { label { "Name" br; input type="text" name="name" value=(name) placeholder="my-project" autofocus; } }
1016 p { label { "Description" br; input type="text" name="description" value=(description); } }
1017 p { label.check { input type="checkbox" name="private" value="on" checked[private]; span { "Private — only you can see and push to it" } } }
1018 p { button.btn type="submit" { "Create repository" } }
1019 }
1020 p.muted { "It will be created at " code { (user.username) "/" (if name.is_empty() { "<name>" } else { name }) } "." }
1021
1022 h2 { "…or push an existing repository" }
1023 p.muted { "Pushing to a name that doesn't exist yet creates the repository (private). No need for the form above." }
1024 pre.cmds { (format!("git remote add origin {remote}\ngit push -u origin main")) }
1025 },
1026 )
1027}
1028
1029/// Load a repo for an owner-only settings action, enforcing write access.
1030async fn resolve_for_settings(
1031 app: &App,
1032 viewer: Option<&User>,
1033 owner: &str,
1034 name: &str,
1035) -> Result<Repository, Response> {
1036 let owner_user = users::find_by_username(&app.db, owner)
1037 .await
1038 .map_err(server_error)?
1039 .ok_or_else(|| not_found("no such repository"))?;
1040 let repo = repos::find(&app.db, owner_user.id, name)
1041 .await
1042 .map_err(server_error)?
1043 .ok_or_else(|| not_found("no such repository"))?;
1044 if !access::can_read(&repo, viewer) {
1045 return Err(not_found("no such repository"));
1046 }
1047 if !access::can_write(&repo, viewer) {
1048 return Err(forbidden());
1049 }
1050 Ok(repo)
1051}
1052
1053/// `GET /{owner}/{repo}/settings` — owner-only repository settings.
1054async fn repo_settings(
1055 State(app): State<App>,
1056 CurrentUser(user): CurrentUser,
1057 csrf: Csrf,
1058 Path((owner, repo)): Path<(String, String)>,
1059) -> Response {
1060 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
1061 Ok(m) => m,
1062 Err(resp) => return resp,
1063 };
1064 let secrets = crate::secrets::settings_section(&app, &owner, &repo, &meta).await;
1065 settings_page(user.as_ref(), &owner, &repo, &meta, secrets, None, &csrf.0).into_response()
1066}
1067
1068/// `POST /{owner}/{repo}/settings` — update description / visibility.
1069async fn repo_settings_submit(
1070 State(app): State<App>,
1071 CurrentUser(user): CurrentUser,
1072 csrf: Csrf,
1073 Path((owner, repo)): Path<(String, String)>,
1074 Form(form): Form<SettingsForm>,
1075) -> Response {
1076 let meta = match resolve_for_settings(&app, user.as_ref(), &owner, &repo).await {
1077 Ok(m) => m,
1078 Err(resp) => return resp,
1079 };
1080 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1081 return resp;
1082 }
1083 if let Err(e) = repos::update_settings(
1084 &app.db,
1085 meta.id,
1086 &form.description,
1087 form.private.is_some(),
1088 &form.mirror_url,
1089 )
1090 .await
1091 {
1092 return server_error(e);
1093 }
1094 Redirect::to(&format!("/{owner}/{repo}")).into_response()
1095}
1096
1097fn settings_page(
1098 user: Option<&User>,
1099 owner: &str,
1100 repo: &str,
1101 meta: &Repository,
1102 secrets: Markup,
1103 error: Option<&str>,
1104 csrf: &str,
1105) -> Markup {
1106 layout(
1107 &format!("{owner}/{repo}: settings"),
1108 user,
1109 html! {
1110 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · settings" }
1111 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
1112 form.stack method="post" action=(format!("/{owner}/{repo}/settings")) {
1113 (csrf_input(csrf))
1114 p { label { "Description" br; input type="text" name="description" value=(meta.description); } }
1115 p { label.check { input type="checkbox" name="private" value="on" checked[meta.is_private]; span { "Private — only you can see and push to it" } } }
1116 p {
1117 label {
1118 "Mirror push URL" br;
1119 input type="text" name="mirror_url" value=(meta.mirror_url)
1120 placeholder="https://x-access-token:<token>@github.com/you/repo.git";
1121 }
1122 br;
1123 span.muted style="font-size:12px" {
1124 "After every push here, all refs are mirrored to this remote ("
1125 code { "git push --mirror" }
1126 "). Stored as-is — use a scoped token. Empty disables it."
1127 }
1128 }
1129 p { button.btn type="submit" { "Save changes" } }
1130 }
1131 (secrets)
1132 },
1133 )
1134}
1135
1136fn clone_box(app: &App, owner: &str, name: &str) -> Markup {
1137 let http = app.config.http_clone_url(owner, name);
1138 let ssh = app
1139 .config
1140 .ssh
1141 .enabled
1142 .then(|| app.config.ssh_clone_url(owner, name));
1143 // SSH first and preselected when available — it's the protocol that can
1144 // push without a credential prompt.
1145 let default_cmd = format!("git clone {}", ssh.as_deref().unwrap_or(&http));
1146 html! {
1147 div.clone data-http=(format!("git clone {http}")) data-ssh=[ssh.as_ref().map(|s| format!("git clone {s}"))] {
1148 div.clone-head {
1149 span.muted { "Clone" }
1150 div.clone-tabs {
1151 @if ssh.is_some() {
1152 button.clone-tab.active type="button" data-proto="ssh" { "SSH" }
1153 button.clone-tab type="button" data-proto="http" { "HTTP" }
1154 } @else {
1155 button.clone-tab.active type="button" data-proto="http" { "HTTP" }
1156 }
1157 }
1158 }
1159 div.clone-cmd {
1160 code { (default_cmd) }
1161 button.copy-btn type="button" title="Copy to clipboard" aria-label="Copy" {
1162 (icon(Icon::Clipboard))
1163 }
1164 span.copied-msg { "Copied!" }
1165 }
1166 }
1167 }
1168}
1169
1170/// `GET /{owner}/{repo}` — repository overview with the root tree.
1171async fn repo_index(
1172 State(app): State<App>,
1173 CurrentUser(user): CurrentUser,
1174 Path((owner, repo)): Path<(String, String)>,
1175) -> Result<Markup, Response> {
1176 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1177 let overview = browse::overview(&path).map_err(server_error)?;
1178
1179 let can_write = access::can_write(&meta, user.as_ref());
1180 let header = html! {
1181 div.repo-head {
1182 span.repo-title {
1183 h1 { a href=(format!("/{owner}")) { (owner) } " / " (repo) }
1184 @if meta.is_private { span.pill { "private" } }
1185 }
1186 nav.repo-nav {
1187 a href=(format!("/{owner}/{repo}/blob/{}/TODO.md", enc_ref(overview.default_branch.as_deref().unwrap_or("main")))) { "Todo" }
1188 span.sep { "·" }
1189 a href=(format!("/{owner}/{repo}/ci")) { "CI" }
1190 span.sep { "·" }
1191 a href=(format!("/{owner}/{repo}/pages")) { "Pages" }
1192 @if can_write {
1193 span.sep { "·" }
1194 a href=(format!("/{owner}/{repo}/settings")) { "Settings" }
1195 }
1196 }
1197 }
1198 @if !meta.description.is_empty() { p.muted { (meta.description) } }
1199 p.repo-meta {
1200 span { b { (overview.branches.len()) } " " (plural(overview.branches.len(), "branch", "branches")) }
1201 span { b { (overview.tags.len()) } " " (plural(overview.tags.len(), "tag", "tags")) }
1202 }
1203 (clone_box(&app, &owner, &repo))
1204 };
1205
1206 if overview.is_empty {
1207 return Ok(layout(
1208 &format!("{owner}/{repo}"),
1209 user.as_ref(),
1210 html! {
1211 (header)
1212 p.muted { "This repository is empty. Push to it to get started." }
1213 },
1214 ));
1215 }
1216
1217 let rev = overview
1218 .default_branch
1219 .clone()
1220 .unwrap_or_else(|| "HEAD".to_string());
1221 let entries = browse::list_tree(&path, &rev, "").map_err(server_error)?;
1222 let latest = browse::commit_log(&path, &rev, 1)
1223 .map_err(server_error)?
1224 .into_iter()
1225 .next();
1226 // Best-effort: a failed walk only costs the per-entry annotations.
1227 let entry_commits =
1228 browse::latest_entry_commits(&path, &rev, "", ENTRY_LOG_WALK).unwrap_or_default();
1229
1230 // A root README renders below the tree, GitHub-style. Best-effort: a
1231 // missing or unreadable file just omits the section.
1232 let readme = entries
1233 .iter()
1234 .find(|e| !e.is_dir && e.name.eq_ignore_ascii_case("readme.md"))
1235 .and_then(|e| {
1236 let bytes = browse::read_blob(&path, &rev, &e.name).ok().flatten()?;
1237 Some((
1238 render_markdown(&String::from_utf8_lossy(&bytes)),
1239 e.name.clone(),
1240 ))
1241 });
1242
1243 // A root TODO.md with tasks renders as a kanban board below the README.
1244 let todo_board = entries
1245 .iter()
1246 .find(|e| !e.is_dir && e.name.eq_ignore_ascii_case("todo.md"))
1247 .and_then(|e| {
1248 let bytes = browse::read_blob(&path, &rev, &e.name).ok().flatten()?;
1249 let board = todomd::render_board(&String::from_utf8_lossy(&bytes), None)?;
1250 Some((board, e.name.clone()))
1251 });
1252
1253 Ok(layout(
1254 &format!("{owner}/{repo}"),
1255 user.as_ref(),
1256 html! {
1257 (header)
1258 p {
1259 (rev_switcher(&owner, &repo, &rev, &overview))
1260 " · "
1261 a href=(format!("/{owner}/{repo}/commits/{}", enc_ref(&rev))) { "commits" }
1262 }
1263 @if let Some((board, name)) = &todo_board {
1264 section.todo-preview {
1265 p.todo-board-head {
1266 a href=(format!("/{owner}/{repo}/blob/{}/{name}", enc_ref(&rev))) { (name) }
1267 }
1268 input.todo-expand #todo-expand type="checkbox";
1269 div.todo-preview-body { (board) }
1270 label.todo-more for="todo-expand" {}
1271 }
1272 script { (maud::PreEscaped(TODO_PREVIEW_JS)) }
1273 }
1274 @if let Some(c) = &latest {
1275 div.latest-commit {
1276 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
1277 a href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.summary) }
1278 span.muted style="margin-left:auto" {
1279 (c.author) " · "
1280 span title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
1281 }
1282 }
1283 }
1284 (tree_table(&owner, &repo, &rev, "", &entries, &entry_commits))
1285 @if let Some(lang_bar) = render_languages_bar(&meta.languages_json) {
1286 div.box {
1287 div.readme-head { "Languages" }
1288 div style="padding:8px 16px;" { (lang_bar) }
1289 }
1290 }
1291 @if let Some((rendered, name)) = &readme {
1292 div.box.readme {
1293 div.readme-head {
1294 a href=(format!("/{owner}/{repo}/blob/{}/{name}", enc_ref(&rev))) { (name) }
1295 }
1296 div.md-body { (rendered) }
1297 }
1298 }
1299 },
1300 ))
1301}
1302
1303/// Drops the clip (and its "show more" toggle) when the preview isn't actually
1304/// taller than the cap, so a short board doesn't get a pointless teaser.
1305const TODO_PREVIEW_JS: &str = r#"
1306(function(){
1307 var d = document.querySelector('.todo-preview');
1308 if (!d) return;
1309 var body = d.querySelector('.todo-preview-body');
1310 if (body.scrollHeight <= body.clientHeight + 8) d.classList.add('fits');
1311})();
1312"#;
1313
1314async fn tree_root(
1315 State(app): State<App>,
1316 user: CurrentUser,
1317 Path((owner, repo, rev)): Path<(String, String, String)>,
1318) -> Result<Markup, Response> {
1319 render_tree(&app, user, &owner, &repo, &rev, "").await
1320}
1321
1322async fn tree_path(
1323 State(app): State<App>,
1324 user: CurrentUser,
1325 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1326) -> Result<Markup, Response> {
1327 render_tree(&app, user, &owner, &repo, &rev, &path).await
1328}
1329
1330async fn render_tree(
1331 app: &App,
1332 CurrentUser(user): CurrentUser,
1333 owner: &str,
1334 repo: &str,
1335 rev: &str,
1336 path: &str,
1337) -> Result<Markup, Response> {
1338 let (repo_path, _) = resolve_repo(app, user.as_ref(), owner, repo).await?;
1339 let overview = browse::overview(&repo_path).map_err(server_error)?;
1340 let entries = browse::list_tree(&repo_path, rev, path).map_err(server_error)?;
1341 // Best-effort: a failed walk only costs the per-entry annotations.
1342 let entry_commits =
1343 browse::latest_entry_commits(&repo_path, rev, path, ENTRY_LOG_WALK).unwrap_or_default();
1344 Ok(layout(
1345 &format!("{owner}/{repo}: {path}"),
1346 user.as_ref(),
1347 html! {
1348 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1349 p { (rev_switcher(owner, repo, rev, &overview)) }
1350 (breadcrumbs(owner, repo, rev, path, false))
1351 (tree_table(owner, repo, rev, path, &entries, &entry_commits))
1352 },
1353 ))
1354}
1355
1356/// `GET /{owner}/{repo}/blob/{rev}/{*path}` — view a file. Markdown renders
1357/// by default; `?plain=1` shows the raw source (toggle links on the page).
1358async fn blob(
1359 State(app): State<App>,
1360 CurrentUser(user): CurrentUser,
1361 csrf: Csrf,
1362 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1363 Query(query): Query<HashMap<String, String>>,
1364) -> Result<Markup, Response> {
1365 let (repo_path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
1366 let (oid, bytes) = browse::read_blob_with_id(&repo_path, &rev, &path)
1367 .map_err(server_error)?
1368 .ok_or_else(|| not_found("file not found"))?;
1369
1370 // Editing writes a commit onto a branch, so it's offered only to writers
1371 // viewing a text file at a branch tip (not a tag or detached commit). The
1372 // resolved tip is the compare-and-swap guard for board delete actions.
1373 let edit_tip = (!is_binary(&bytes) && access::can_write(&meta, user.as_ref()))
1374 .then(|| browse::resolve_commit(&repo_path, &format!("refs/heads/{rev}")).ok())
1375 .flatten();
1376 let can_edit = edit_tip.is_some();
1377
1378 let markdown = is_markdown(&path) && !is_binary(&bytes);
1379 // Custom renderers for well-known filenames (the plugin point — add new
1380 // filename → renderer pairs here). TODO.md defaults to a kanban board.
1381 let is_todo = todomd::is_todo_md(&path) && !is_binary(&bytes);
1382 let board_actions = edit_tip.as_ref().map(|tip| todomd::BoardActions {
1383 owner: &owner,
1384 repo: &repo,
1385 rev: &rev,
1386 path: &path,
1387 tip,
1388 csrf: &csrf.0,
1389 });
1390 let board = (is_todo && !query.contains_key("plain") && !query.contains_key("md"))
1391 .then(|| todomd::render_board(&String::from_utf8_lossy(&bytes), board_actions.as_ref()))
1392 .flatten();
1393 let rendered = markdown && !query.contains_key("plain") && board.is_none();
1394
1395 let body = if let Some(board) = &board {
1396 board.clone()
1397 } else if is_binary(&bytes) {
1398 html! { p.muted { "Binary file (" (bytes.len()) " bytes)" } }
1399 } else if rendered {
1400 let text = String::from_utf8_lossy(&bytes);
1401 html! { div.md-body { (render_markdown(&text)) } }
1402 } else {
1403 let text = String::from_utf8_lossy(&bytes);
1404 let budget = app.config.http.highlight_cache_mb.saturating_mul(1 << 20);
1405 let lines = cached_highlight(budget, &oid, &path, &text);
1406 html! {
1407 table.code {
1408 @for (i, line) in lines.iter().enumerate() {
1409 tr {
1410 td.ln { (i + 1) }
1411 td { (PreEscaped(line)) }
1412 }
1413 }
1414 }
1415 }
1416 };
1417
1418 let blob_url = format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev));
1419 Ok(layout(
1420 &format!("{owner}/{repo}: {path}"),
1421 user.as_ref(),
1422 html! {
1423 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1424 (breadcrumbs(&owner, &repo, &rev, &path, true))
1425 @if can_edit {
1426 p.file-actions {
1427 a.btn.btn-secondary href=(format!("/{owner}/{repo}/edit/{}/{path}", enc_ref(&rev))) {
1428 (icon(Icon::Pencil)) "Edit"
1429 }
1430 @if is_todo {
1431 a.btn.btn-secondary href=(format!("/{owner}/{repo}/add-task/{}/{path}", enc_ref(&rev))) {
1432 (icon(Icon::Plus)) "Add task"
1433 }
1434 }
1435 }
1436 }
1437 @if markdown {
1438 p.view-toggle {
1439 span.pill-group {
1440 @if is_todo {
1441 @if board.is_some() { span.pill.active { "Board" } }
1442 @else { a.pill href=(&blob_url) { "Board" } }
1443 @if rendered { span.pill.active { "Rendered" } }
1444 @else { a.pill href=(format!("{blob_url}?md=1")) { "Rendered" } }
1445 } @else if rendered {
1446 span.pill.active { "Rendered" }
1447 } @else {
1448 a.pill href=(&blob_url) { "Rendered" }
1449 }
1450 @if rendered || board.is_some() {
1451 a.pill href=(format!("{blob_url}?plain=1")) { "Source" }
1452 } @else {
1453 span.pill.active { "Source" }
1454 }
1455 }
1456 }
1457 }
1458 @if board.is_some() {
1459 // The board supplies its own column structure; an enclosing
1460 // box would just nest frames.
1461 (body)
1462 } @else {
1463 div.box style="overflow-x:auto" { (body) }
1464 }
1465 },
1466 ))
1467}
1468
1469#[derive(serde::Deserialize)]
1470struct EditFileForm {
1471 csrf: String,
1472 /// Expected branch tip the editor saw — the compare-and-swap guard.
1473 expected_tip: String,
1474 message: String,
1475 content: String,
1476}
1477
1478/// Resolve a repo for a web edit, enforcing read+write access and that `rev`
1479/// names a branch (editing advances a branch ref). Returns the repo path and
1480/// the branch tip the editor is working from.
1481async fn resolve_for_edit(
1482 app: &App,
1483 user: Option<&User>,
1484 owner: &str,
1485 repo: &str,
1486 rev: &str,
1487) -> Result<(PathBuf, String), Response> {
1488 let (repo_path, meta) = resolve_repo(app, user, owner, repo).await?;
1489 if user.is_none() {
1490 return Err(Redirect::to("/-/login").into_response());
1491 }
1492 if !access::can_write(&meta, user) {
1493 return Err(forbidden());
1494 }
1495 let tip = browse::resolve_commit(&repo_path, &format!("refs/heads/{rev}"))
1496 .map_err(|_| not_found("not an editable branch"))?;
1497 Ok((repo_path, tip))
1498}
1499
1500/// `GET /{owner}/{repo}/edit/{rev}/{*path}` — textarea editor for an existing
1501/// text file on a branch.
1502async fn edit_form(
1503 State(app): State<App>,
1504 CurrentUser(user): CurrentUser,
1505 csrf: Csrf,
1506 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1507) -> Response {
1508 let (repo_path, tip) = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1509 Ok(v) => v,
1510 Err(resp) => return resp,
1511 };
1512 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1513 Ok(Some(b)) => b,
1514 Ok(None) => return not_found("file not found"),
1515 Err(e) => return server_error(e),
1516 };
1517 if is_binary(&bytes) {
1518 return bad_request_page(
1519 user.as_ref(),
1520 "Binary files can't be edited in the browser.",
1521 );
1522 }
1523 let content = String::from_utf8_lossy(&bytes).into_owned();
1524 edit_page(
1525 &owner,
1526 &repo,
1527 &rev,
1528 &path,
1529 &content,
1530 &format!("Update {path}"),
1531 &tip,
1532 None,
1533 user.as_ref(),
1534 &csrf.0,
1535 )
1536 .into_response()
1537}
1538
1539/// `POST /{owner}/{repo}/edit/{rev}/{*path}` — commit the edited content.
1540async fn edit_submit(
1541 State(app): State<App>,
1542 CurrentUser(user): CurrentUser,
1543 csrf: Csrf,
1544 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1545 Form(form): Form<EditFileForm>,
1546) -> Response {
1547 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1548 Ok((p, _)) => p,
1549 Err(resp) => return resp,
1550 };
1551 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1552 return resp;
1553 }
1554 let user = user.expect("resolve_for_edit requires a logged-in user");
1555
1556 // Browsers serialize textarea newlines as CRLF; normalize so an edit
1557 // doesn't rewrite every line ending.
1558 let content = form.content.replace("\r\n", "\n");
1559 let message = if form.message.trim().is_empty() {
1560 format!("Update {path}")
1561 } else {
1562 form.message.clone()
1563 };
1564
1565 match anvil_git::edit::commit_file_change(
1566 &repo_path,
1567 &rev,
1568 &form.expected_tip,
1569 &path,
1570 content.as_bytes(),
1571 &user.username,
1572 &user.email,
1573 &message,
1574 ) {
1575 Ok(_) => {
1576 Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev))).into_response()
1577 }
1578 Err(e) => edit_page(
1579 &owner,
1580 &repo,
1581 &rev,
1582 &path,
1583 &content,
1584 &message,
1585 &form.expected_tip,
1586 Some(&e.to_string()),
1587 Some(&user),
1588 &csrf.0,
1589 )
1590 .into_response(),
1591 }
1592}
1593
1594/// The file-editor page: a textarea, a commit-message field, and the
1595/// compare-and-swap tip carried in a hidden field.
1596#[allow(clippy::too_many_arguments)]
1597fn edit_page(
1598 owner: &str,
1599 repo: &str,
1600 rev: &str,
1601 path: &str,
1602 content: &str,
1603 message: &str,
1604 expected_tip: &str,
1605 error: Option<&str>,
1606 user: Option<&User>,
1607 csrf: &str,
1608) -> Markup {
1609 let action = format!("/{owner}/{repo}/edit/{}/{path}", enc_ref(rev));
1610 let cancel = format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(rev));
1611 let upload_url = format!("/{owner}/{repo}/-/attachments");
1612 layout(
1613 &format!("Edit {path}"),
1614 user,
1615 html! {
1616 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1617 (breadcrumbs(owner, repo, rev, path, true))
1618 p.muted { "Editing on branch " code { (rev) } " — commits as you." }
1619 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
1620 form.stack method="post" action=(action) {
1621 (csrf_input(csrf))
1622 input type="hidden" name="expected_tip" value=(expected_tip);
1623 p {
1624 textarea.editor name="content" rows="24" spellcheck="false" autofocus
1625 data-upload-url=(upload_url) data-csrf=(csrf) { (content) }
1626 }
1627 p.upload-hint {
1628 label.btn.btn-secondary.attach-btn {
1629 "Attach image"
1630 input.attach-input type="file" accept="image/*" multiple hidden;
1631 }
1632 " "
1633 span.muted { "or paste/drop one — it's stored outside git and a Markdown link is inserted." }
1634 }
1635 p { label { "Commit message" br; input type="text" name="message" value=(message); } }
1636 p {
1637 button.btn type="submit" { "Commit changes" }
1638 " "
1639 a.btn.btn-secondary href=(cancel) { "Cancel" }
1640 }
1641 }
1642 script { (PreEscaped(EDITOR_JS)) }
1643 },
1644 )
1645}
1646
1647/// Paste/drop-to-upload for the file editor: image clipboard items and dropped
1648/// image files are POSTed to the repo's attachment endpoint as a raw body, and
1649/// the returned Markdown is spliced into the textarea at the cursor. The blob
1650/// is stored outside git; only the URL lands in the file.
1651const EDITOR_JS: &str = r#"
1652(function(){
1653 var ta = document.querySelector('textarea.editor');
1654 if (!ta || !ta.dataset.uploadUrl) return;
1655 var url = ta.dataset.uploadUrl, csrf = ta.dataset.csrf;
1656 function insertAtCursor(text){
1657 var s = ta.selectionStart, e = ta.selectionEnd;
1658 ta.value = ta.value.slice(0, s) + text + ta.value.slice(e);
1659 ta.selectionStart = ta.selectionEnd = s + text.length;
1660 ta.focus();
1661 }
1662 function replaceFirst(find, repl){
1663 var i = ta.value.indexOf(find);
1664 if (i >= 0) ta.value = ta.value.slice(0, i) + repl + ta.value.slice(i + find.length);
1665 }
1666 function upload(file){
1667 var token = '![uploading ' + (file.name || 'image') + '…]()';
1668 insertAtCursor(token + '\n');
1669 fetch(url, {
1670 method: 'POST',
1671 headers: {'X-CSRF-Token': csrf, 'Content-Type': file.type || 'application/octet-stream'},
1672 body: file
1673 }).then(function(r){
1674 if (!r.ok) throw new Error('upload failed (' + r.status + ')');
1675 return r.json();
1676 }).then(function(d){
1677 replaceFirst(token, d.markdown);
1678 }).catch(function(err){
1679 replaceFirst(token, '![upload failed]()');
1680 console.error(err);
1681 });
1682 }
1683 ta.addEventListener('paste', function(ev){
1684 var items = (ev.clipboardData || {}).items || [];
1685 for (var i = 0; i < items.length; i++){
1686 if (items[i].kind === 'file' && items[i].type.indexOf('image/') === 0){
1687 ev.preventDefault();
1688 upload(items[i].getAsFile());
1689 }
1690 }
1691 });
1692 ta.addEventListener('dragover', function(ev){ ev.preventDefault(); });
1693 ta.addEventListener('drop', function(ev){
1694 var files = (ev.dataTransfer || {}).files || [], imgs = [];
1695 for (var i = 0; i < files.length; i++){
1696 if (files[i].type.indexOf('image/') === 0) imgs.push(files[i]);
1697 }
1698 if (imgs.length){ ev.preventDefault(); imgs.forEach(upload); }
1699 });
1700 // The "Attach image" button (works where paste/drop don't, e.g. mobile):
1701 // a file picker that uploads each chosen image.
1702 var picker = document.querySelector('input.attach-input');
1703 if (picker) picker.addEventListener('change', function(){
1704 var files = picker.files || [];
1705 for (var i = 0; i < files.length; i++){
1706 if (files[i].type.indexOf('image/') === 0) upload(files[i]);
1707 }
1708 picker.value = ''; // let the same file be re-picked
1709 });
1710})();
1711"#;
1712
1713#[derive(serde::Deserialize)]
1714struct AddTaskForm {
1715 csrf: String,
1716 expected_tip: String,
1717 section: String,
1718 title: String,
1719 #[serde(default)]
1720 body: String,
1721}
1722
1723/// `GET /{owner}/{repo}/add-task/{rev}/{*path}` — structured "add a task" form
1724/// for a `TODO.md`, appending a `- [ ]` item per the todo-md round-trip rules.
1725async fn add_task_form(
1726 State(app): State<App>,
1727 CurrentUser(user): CurrentUser,
1728 csrf: Csrf,
1729 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1730) -> Response {
1731 let (repo_path, tip) = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1732 Ok(v) => v,
1733 Err(resp) => return resp,
1734 };
1735 if !todomd::is_todo_md(&path) {
1736 return not_found("not a TODO.md");
1737 }
1738 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1739 Ok(Some(b)) => b,
1740 Ok(None) => return not_found("file not found"),
1741 Err(e) => return server_error(e),
1742 };
1743 let sections = todomd::task_sections(&String::from_utf8_lossy(&bytes));
1744 if sections.is_empty() {
1745 return bad_request_page(user.as_ref(), "This TODO.md has no sections to add to.");
1746 }
1747 add_task_page(
1748 &owner,
1749 &repo,
1750 &rev,
1751 &path,
1752 &sections,
1753 "",
1754 "",
1755 &tip,
1756 None,
1757 user.as_ref(),
1758 &csrf.0,
1759 )
1760 .into_response()
1761}
1762
1763/// `POST /{owner}/{repo}/add-task/{rev}/{*path}` — append the task and commit.
1764async fn add_task_submit(
1765 State(app): State<App>,
1766 CurrentUser(user): CurrentUser,
1767 csrf: Csrf,
1768 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1769 Form(form): Form<AddTaskForm>,
1770) -> Response {
1771 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1772 Ok((p, _)) => p,
1773 Err(resp) => return resp,
1774 };
1775 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1776 return resp;
1777 }
1778 let user = user.expect("resolve_for_edit requires a logged-in user");
1779 if !todomd::is_todo_md(&path) {
1780 return not_found("not a TODO.md");
1781 }
1782 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1783 Ok(Some(b)) => b,
1784 Ok(None) => return not_found("file not found"),
1785 Err(e) => return server_error(e),
1786 };
1787 let text = String::from_utf8_lossy(&bytes);
1788 let sections = todomd::task_sections(&text);
1789
1790 // Browsers serialize textarea newlines as CRLF; store LF.
1791 let body = form.body.replace("\r\n", "\n");
1792
1793 let render_err = |msg: &str, csrf: &Csrf| {
1794 add_task_page(
1795 &owner,
1796 &repo,
1797 &rev,
1798 &path,
1799 &sections,
1800 &form.title,
1801 &body,
1802 &form.expected_tip,
1803 Some(msg),
1804 Some(&user),
1805 &csrf.0,
1806 )
1807 .into_response()
1808 };
1809
1810 let Some(updated) = todomd::add_task(&text, &form.section, &form.title, &body) else {
1811 return render_err(
1812 "Couldn't add the task — check the title isn't empty and the section exists.",
1813 &csrf,
1814 );
1815 };
1816
1817 let message = format!("Add task to {}", form.section);
1818 match anvil_git::edit::commit_file_change(
1819 &repo_path,
1820 &rev,
1821 &form.expected_tip,
1822 &path,
1823 updated.as_bytes(),
1824 &user.username,
1825 &user.email,
1826 &message,
1827 ) {
1828 Ok(_) => {
1829 Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev))).into_response()
1830 }
1831 Err(e) => render_err(&e.to_string(), &csrf),
1832 }
1833}
1834
1835#[derive(serde::Deserialize)]
1836struct DeleteTaskForm {
1837 #[serde(default)]
1838 csrf: String,
1839 expected_tip: String,
1840 section: String,
1841 title: String,
1842}
1843
1844/// `POST /{owner}/{repo}/delete-task/{rev}/{*path}` — remove a task/ticket from
1845/// a `TODO.md` (the ✕ on a board card) and commit. Compare-and-swap guarded by
1846/// `expected_tip`, so a concurrent change is rejected rather than clobbered.
1847async fn delete_task(
1848 State(app): State<App>,
1849 CurrentUser(user): CurrentUser,
1850 csrf: Csrf,
1851 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1852 Form(form): Form<DeleteTaskForm>,
1853) -> Response {
1854 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1855 Ok((p, _)) => p,
1856 Err(resp) => return resp,
1857 };
1858 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1859 return resp;
1860 }
1861 let user = user.expect("resolve_for_edit requires a logged-in user");
1862 if !todomd::is_todo_md(&path) {
1863 return not_found("not a TODO.md");
1864 }
1865 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1866 Ok(Some(b)) => b,
1867 Ok(None) => return not_found("file not found"),
1868 Err(e) => return server_error(e),
1869 };
1870 let text = String::from_utf8_lossy(&bytes);
1871
1872 let Some(updated) = todomd::remove_task(&text, &form.section, &form.title) else {
1873 // Already gone (e.g. a double submit) — just show the current board.
1874 return Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev)))
1875 .into_response();
1876 };
1877
1878 let message = format!("Delete task: {}", form.title);
1879 match anvil_git::edit::commit_file_change(
1880 &repo_path,
1881 &rev,
1882 &form.expected_tip,
1883 &path,
1884 updated.as_bytes(),
1885 &user.username,
1886 &user.email,
1887 &message,
1888 ) {
1889 Ok(_) => {
1890 Redirect::to(&format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(&rev))).into_response()
1891 }
1892 Err(e) => bad_request_page(Some(&user), &format!("Couldn't delete the task: {e}")),
1893 }
1894}
1895
1896#[derive(serde::Deserialize)]
1897struct MoveTaskForm {
1898 #[serde(default)]
1899 csrf: String,
1900 expected_tip: String,
1901 title: String,
1902 from_section: String,
1903 to_section: String,
1904 to_index: usize,
1905}
1906
1907/// `POST /{owner}/{repo}/move-task/{rev}/{*path}` — reorder/move a task on the
1908/// board (drag-and-drop). Write-gated, CSRF-checked, compare-and-swap on the
1909/// branch tip. Driven by `fetch`, so it returns bare status codes.
1910async fn move_task(
1911 State(app): State<App>,
1912 CurrentUser(user): CurrentUser,
1913 csrf: Csrf,
1914 Path((owner, repo, rev, path)): Path<(String, String, String, String)>,
1915 Form(form): Form<MoveTaskForm>,
1916) -> Response {
1917 let repo_path = match resolve_for_edit(&app, user.as_ref(), &owner, &repo, &rev).await {
1918 Ok((p, _)) => p,
1919 Err(resp) => return resp,
1920 };
1921 if let Err(resp) = verify_csrf(&csrf, &form.csrf) {
1922 return resp;
1923 }
1924 let user = user.expect("resolve_for_edit requires a logged-in user");
1925 if !todomd::is_todo_md(&path) {
1926 return not_found("not a TODO.md");
1927 }
1928 let bytes = match browse::read_blob(&repo_path, &rev, &path) {
1929 Ok(Some(b)) => b,
1930 Ok(None) => return not_found("file not found"),
1931 Err(e) => return server_error(e),
1932 };
1933 let text = String::from_utf8_lossy(&bytes);
1934
1935 let Some(updated) = todomd::move_task(
1936 &text,
1937 &form.title,
1938 &form.from_section,
1939 &form.to_section,
1940 form.to_index,
1941 ) else {
1942 return (StatusCode::BAD_REQUEST, "could not move task").into_response();
1943 };
1944
1945 let message = if form.from_section == form.to_section {
1946 format!("Reorder {} in {}", form.title, form.to_section)
1947 } else {
1948 format!("Move {} to {}", form.title, form.to_section)
1949 };
1950 match anvil_git::edit::commit_file_change(
1951 &repo_path,
1952 &rev,
1953 &form.expected_tip,
1954 &path,
1955 updated.as_bytes(),
1956 &user.username,
1957 &user.email,
1958 &message,
1959 ) {
1960 // A no-op drop (dropped back in place) is success, not an error.
1961 Ok(_) | Err(anvil_git::edit::EditError::NoChanges) => StatusCode::OK.into_response(),
1962 Err(anvil_git::edit::EditError::BranchMoved { .. }) => {
1963 (StatusCode::CONFLICT, "branch moved — reload").into_response()
1964 }
1965 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
1966 }
1967}
1968
1969/// The add-task form: a section dropdown, a title field, and a Markdown
1970/// description (which supports paste/drop image upload, like the file editor).
1971#[allow(clippy::too_many_arguments)]
1972fn add_task_page(
1973 owner: &str,
1974 repo: &str,
1975 rev: &str,
1976 path: &str,
1977 sections: &[String],
1978 title: &str,
1979 body: &str,
1980 expected_tip: &str,
1981 error: Option<&str>,
1982 user: Option<&User>,
1983 csrf: &str,
1984) -> Markup {
1985 let action = format!("/{owner}/{repo}/add-task/{}/{path}", enc_ref(rev));
1986 let cancel = format!("/{owner}/{repo}/blob/{}/{path}", enc_ref(rev));
1987 let upload_url = format!("/{owner}/{repo}/-/attachments");
1988 layout(
1989 &format!("Add task · {path}"),
1990 user,
1991 html! {
1992 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } }
1993 (breadcrumbs(owner, repo, rev, path, true))
1994 h2 { "Add a task" }
1995 @if let Some(error) = error { p style="color:#cf222e" { (error) } }
1996 form.stack method="post" action=(action) {
1997 (csrf_input(csrf))
1998 input type="hidden" name="expected_tip" value=(expected_tip);
1999 p { label { "Section" br;
2000 select name="section" {
2001 @for s in sections { option value=(s) { (s) } }
2002 }
2003 } }
2004 p { label { "Title" br;
2005 input type="text" name="title" value=(title) placeholder="Short ticket title" autofocus;
2006 } }
2007 p { label { "Description" br;
2008 textarea.editor name="body" rows="10" spellcheck="false"
2009 placeholder="Markdown — attach an image with the button below, or paste/drop one"
2010 data-upload-url=(upload_url) data-csrf=(csrf) { (body) }
2011 } }
2012 p.upload-hint {
2013 label.btn.btn-secondary.attach-btn {
2014 "Attach image"
2015 input.attach-input type="file" accept="image/*" multiple hidden;
2016 }
2017 " "
2018 span.muted { "stored outside git; a Markdown link is inserted into the description." }
2019 }
2020 p {
2021 button.btn type="submit" { "Add task" }
2022 " "
2023 a.btn.btn-secondary href=(cancel) { "Cancel" }
2024 }
2025 }
2026 script { (PreEscaped(EDITOR_JS)) }
2027 },
2028 )
2029}
2030
2031/// A 400 page for malformed edit requests (binary file, no sections, …).
2032fn bad_request_page(user: Option<&User>, message: &str) -> Response {
2033 (
2034 StatusCode::BAD_REQUEST,
2035 layout(
2036 "Can't edit",
2037 user,
2038 html! { h1 { "Can't edit" } p.muted { (message) } },
2039 ),
2040 )
2041 .into_response()
2042}
2043
2044/// Pick the singular or plural noun for a count (`1 branch` / `2 branches`).
2045fn plural<'a>(n: usize, one: &'a str, many: &'a str) -> &'a str {
2046 if n == 1 { one } else { many }
2047}
2048
2049/// Whether a path should be treated as markdown (by extension).
2050fn is_markdown(path: &str) -> bool {
2051 std::path::Path::new(path)
2052 .extension()
2053 .and_then(|e| e.to_str())
2054 .is_some_and(|e| e.eq_ignore_ascii_case("md") || e.eq_ignore_ascii_case("markdown"))
2055}
2056
2057/// Render markdown to HTML (tables, strikethrough, task lists, footnotes).
2058///
2059/// Repo content is untrusted, so this is a stored-XSS surface: raw HTML in the
2060/// source is emitted as escaped literal text, and `javascript:`/`data:`-style
2061/// link and image destinations are dropped.
2062pub(crate) fn render_markdown(text: &str) -> Markup {
2063 use pulldown_cmark::{
2064 Event,
2065 Options,
2066 Parser,
2067 Tag,
2068 html,
2069 };
2070
2071 fn safe_url(dest: &str) -> bool {
2072 let d = dest.trim().to_ascii_lowercase();
2073 !(d.starts_with("javascript:") || d.starts_with("data:") || d.starts_with("vbscript:"))
2074 }
2075
2076 let opts = Options::ENABLE_TABLES
2077 | Options::ENABLE_STRIKETHROUGH
2078 | Options::ENABLE_TASKLISTS
2079 | Options::ENABLE_FOOTNOTES;
2080 let events = Parser::new_ext(text, opts).map(|ev| match ev {
2081 Event::Html(h) => Event::Text(h),
2082 Event::InlineHtml(h) => Event::Text(h),
2083 Event::Start(Tag::Link {
2084 link_type,
2085 dest_url,
2086 title,
2087 id,
2088 }) if !safe_url(&dest_url) => Event::Start(Tag::Link {
2089 link_type,
2090 dest_url: "".into(),
2091 title,
2092 id,
2093 }),
2094 Event::Start(Tag::Image {
2095 link_type,
2096 dest_url,
2097 title,
2098 id,
2099 }) if !safe_url(&dest_url) => Event::Start(Tag::Image {
2100 link_type,
2101 dest_url: "".into(),
2102 title,
2103 id,
2104 }),
2105 e => e,
2106 });
2107 let mut out = String::new();
2108 html::push_html(&mut out, events);
2109 PreEscaped(out)
2110}
2111
2112/// Render a language breakdown bar showing percentages of each detected language.
2113/// Displays as a horizontal bar with each language's proportion.
2114pub(crate) fn render_languages_bar(languages_json: &str) -> Option<Markup> {
2115 if languages_json.is_empty() || languages_json == "[]" {
2116 return None;
2117 }
2118
2119 // Parse the JSON array
2120 let langs: Vec<serde_json::Value> = serde_json::from_str(languages_json).ok()?;
2121 if langs.is_empty() {
2122 return None;
2123 }
2124
2125 // Color palette for languages (simple heuristic)
2126 let color_for_lang = |lang: &str| -> &'static str {
2127 match lang {
2128 "Rust" => "#CE422B",
2129 "Python" => "#3776AB",
2130 "JavaScript" => "#F7DF1E",
2131 "TypeScript" => "#3178C6",
2132 "Go" => "#00ADD8",
2133 "Java" => "#007396",
2134 "C++" => "#00599C",
2135 "C#" => "#239120",
2136 "Ruby" => "#CC342D",
2137 "PHP" => "#777BB4",
2138 "Markdown" => "#083FA1",
2139 "HTML" => "#E34C26",
2140 "CSS" => "#563D7C",
2141 "SQL" => "#336791",
2142 _ => "#999999",
2143 }
2144 };
2145
2146 let mut html = String::from(
2147 r#"<div class="language-bar" style="display:flex;border-radius:4px;overflow:hidden;height:20px;background:#f0f0f0;">"#,
2148 );
2149 for lang_obj in langs {
2150 if let (Some(lang), Some(percent)) = (
2151 lang_obj.get("lang").and_then(|v| v.as_str()),
2152 lang_obj.get("percent").and_then(|v| v.as_f64()),
2153 ) {
2154 let color = color_for_lang(lang);
2155 html.push_str(&format!(
2156 r#"<div style="width:{:.1}%;background-color:{};tooltip:'{}';height:100%" title="{}"></div>"#,
2157 percent, color, lang, lang
2158 ));
2159 }
2160 }
2161 html.push_str("</div>");
2162
2163 Some(PreEscaped(html))
2164}
2165
2166/// How far back the per-entry "latest commit" walk looks. Entries last touched
2167/// beyond this many commits just lose the annotation.
2168const ENTRY_LOG_WALK: usize = 400;
2169
2170/// Folder or file icon for an entry row (tree listings, pages, artifacts).
2171pub(crate) fn entry_icon(is_dir: bool) -> Markup {
2172 if is_dir {
2173 icon_with(Icon::Folder, "icon dir")
2174 } else {
2175 icon(Icon::File)
2176 }
2177}
2178
2179/// Human-readable byte size (`482 B`, `1.2 KiB`, `34.0 MiB`).
2180pub(crate) fn fmt_size(bytes: i64) -> String {
2181 let b = bytes.max(0) as f64;
2182 match b {
2183 b if b < 1024.0 => format!("{bytes} B"),
2184 b if b < 1024.0 * 1024.0 => format!("{:.1} KiB", b / 1024.0),
2185 b if b < 1024.0 * 1024.0 * 1024.0 => format!("{:.1} MiB", b / (1024.0 * 1024.0)),
2186 b => format!("{:.1} GiB", b / (1024.0 * 1024.0 * 1024.0)),
2187 }
2188}
2189
2190/// Percent-encode a ref name for use as one path segment in a URL. Axum
2191/// matches routes before decoding, so an encoded `/` keeps a branch like
2192/// `feat/x` inside the single `{rev}` segment.
2193pub(crate) fn enc_ref(name: &str) -> String {
2194 name.replace('%', "%25")
2195 .replace('/', "%2F")
2196 .replace('?', "%3F")
2197 .replace('#', "%23")
2198}
2199
2200/// Branch/tag switcher: a dropdown over the current rev linking each ref to
2201/// its tree view. Branch names, tag names, and commit ids all work as `rev`.
2202fn rev_switcher(owner: &str, repo: &str, rev: &str, overview: &browse::Overview) -> Markup {
2203 html! {
2204 details.nav-menu.rev-menu {
2205 summary { span.pill { (rev) } }
2206 div.nav-dropdown.left {
2207 @if !overview.branches.is_empty() {
2208 div.dd-head { "Branches" }
2209 @for b in &overview.branches {
2210 a.current[b == rev] href=(format!("/{owner}/{repo}/tree/{}", enc_ref(b))) { (b) }
2211 }
2212 }
2213 @if !overview.tags.is_empty() {
2214 div.dd-head { "Tags" }
2215 @for t in &overview.tags {
2216 a.current[t == rev] href=(format!("/{owner}/{repo}/tree/{}", enc_ref(t))) { (t) }
2217 }
2218 }
2219 }
2220 }
2221 }
2222}
2223
2224/// Render a tree listing as a box of rows; directories link to `tree`, files to
2225/// `blob`. Each entry also shows the subject of (and links to) the latest
2226/// commit that touched it, when `latest` has one for it.
2227fn tree_table(
2228 owner: &str,
2229 repo: &str,
2230 rev: &str,
2231 path: &str,
2232 entries: &[browse::TreeEntry],
2233 latest: &BTreeMap<String, browse::CommitInfo>,
2234) -> Markup {
2235 let join = |name: &str| {
2236 if path.is_empty() {
2237 name.to_string()
2238 } else {
2239 format!("{path}/{name}")
2240 }
2241 };
2242 html! {
2243 div.box {
2244 @if !path.is_empty() {
2245 div.row {
2246 a.entry href=(parent_link(owner, repo, rev, path)) { span.icon { ".." } "up" }
2247 }
2248 }
2249 @for e in entries {
2250 @let child = join(&e.name);
2251 @let kind = if e.is_dir { "tree" } else { "blob" };
2252 div.row {
2253 a.entry href=(format!("/{owner}/{repo}/{kind}/{}/{child}", enc_ref(rev))) {
2254 (entry_icon(e.is_dir))
2255 (e.name) @if e.is_dir { "/" }
2256 }
2257 @if let Some(c) = latest.get(&e.name) {
2258 a.fc-msg href=(format!("/{owner}/{repo}/commit/{}", c.id)) title=(c.summary) { (c.summary) }
2259 span.fc-time title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
2260 }
2261 }
2262 }
2263 }
2264 }
2265}
2266
2267fn parent_link(owner: &str, repo: &str, rev: &str, path: &str) -> String {
2268 match path.rsplit_once('/') {
2269 Some((parent, _)) => format!("/{owner}/{repo}/tree/{}/{parent}", enc_ref(rev)),
2270 None => format!("/{owner}/{repo}/tree/{}", enc_ref(rev)),
2271 }
2272}
2273
2274/// Path breadcrumbs. `is_blob` marks the final component as a file.
2275fn breadcrumbs(owner: &str, repo: &str, rev: &str, path: &str, is_blob: bool) -> Markup {
2276 // Precompute (label, cumulative_path) for each path component.
2277 let mut crumbs: Vec<(String, String)> = Vec::new();
2278 let mut acc = String::new();
2279 for part in path.split('/').filter(|p| !p.is_empty()) {
2280 if !acc.is_empty() {
2281 acc.push('/');
2282 }
2283 acc.push_str(part);
2284 crumbs.push((part.to_string(), acc.clone()));
2285 }
2286 let last = crumbs.len();
2287 html! {
2288 div.crumbs {
2289 a href=(format!("/{owner}/{repo}/tree/{}", enc_ref(rev))) { (rev) }
2290 @for (i, (label, cum)) in crumbs.iter().enumerate() {
2291 " / "
2292 @if i + 1 == last && is_blob {
2293 span { (label) }
2294 } @else {
2295 a href=(format!("/{owner}/{repo}/tree/{}/{cum}", enc_ref(rev))) { (label) }
2296 }
2297 }
2298 }
2299 }
2300}
2301
2302/// `GET /{owner}/{repo}/commits/{rev}` — commit history.
2303async fn commits(
2304 State(app): State<App>,
2305 CurrentUser(user): CurrentUser,
2306 Path((owner, repo, rev)): Path<(String, String, String)>,
2307) -> Result<Markup, Response> {
2308 let (path, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2309 let log = browse::commit_log(&path, &rev, 100).map_err(server_error)?;
2310
2311 // Map each commit oid to its latest run status, for inline badges. One query
2312 // for the repo's recent runs; first match wins (list is newest-first).
2313 let runs = ci::list_by_repo(&app.db, meta.id, 200)
2314 .await
2315 .unwrap_or_default();
2316 let mut status_of: HashMap<&str, &str> = HashMap::new();
2317 for r in &runs {
2318 status_of
2319 .entry(r.commit.as_str())
2320 .or_insert(r.status.as_str());
2321 }
2322
2323 Ok(layout(
2324 &format!("{owner}/{repo}: commits"),
2325 user.as_ref(),
2326 html! {
2327 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · commits" }
2328 ul.commit-list {
2329 @for c in &log {
2330 li {
2331 a.sha href=(format!("/{owner}/{repo}/commit/{}", c.id)) { (c.short) }
2332 @if let Some(st) = status_of.get(c.id.as_str()) {
2333 a href=(format!("/{owner}/{repo}/ci")) { (status_badge(st)) }
2334 }
2335 span { (c.summary) }
2336 span.muted style="margin-left:auto" {
2337 (c.author) " · "
2338 span title=(fmt_time(c.time)) { (fmt_relative(c.time)) }
2339 }
2340 }
2341 }
2342 }
2343 },
2344 ))
2345}
2346
2347/// `GET /{owner}/{repo}/commit/{id}` — a commit with its diff.
2348async fn commit(
2349 State(app): State<App>,
2350 CurrentUser(user): CurrentUser,
2351 Path((owner, repo, id)): Path<(String, String, String)>,
2352) -> Result<Markup, Response> {
2353 let (path, _) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2354 let detail = browse::commit_detail(&path, &id).map_err(server_error)?;
2355 Ok(layout(
2356 &format!("{owner}/{repo}: {}", detail.info.short),
2357 user.as_ref(),
2358 html! {
2359 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · " span.sha { (detail.info.short) } }
2360 p { (detail.info.summary) }
2361 p.muted {
2362 (detail.info.author) " · " (fmt_time(detail.info.time)) " · "
2363 span.sha { (detail.info.id) }
2364 @if let Some(parent) = &detail.parent {
2365 " · parent " a.sha href=(format!("/{owner}/{repo}/commit/{parent}")) { (&parent[..parent.len().min(8)]) }
2366 }
2367 " · "
2368 a href=(format!("/{owner}/{repo}/tree/{}", detail.info.id)) { "browse files" }
2369 }
2370 @if detail.changes.is_empty() {
2371 p.muted { "No file changes." }
2372 }
2373 @for change in &detail.changes {
2374 (render_file_diff(change))
2375 }
2376 },
2377 ))
2378}
2379
2380/// `GET /{owner}/{repo}/ci` — recent CI runs for the repository.
2381async fn ci_runs(
2382 State(app): State<App>,
2383 CurrentUser(user): CurrentUser,
2384 Path((owner, repo)): Path<(String, String)>,
2385) -> Result<Markup, Response> {
2386 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2387 let runs = ci::list_by_repo(&app.db, meta.id, 100)
2388 .await
2389 .map_err(server_error)?;
2390 Ok(layout(
2391 &format!("{owner}/{repo}: CI"),
2392 user.as_ref(),
2393 html! {
2394 h1 { a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) } " · CI" }
2395 @if runs.is_empty() {
2396 p.muted {
2397 "No CI runs yet. Add a " code { ".anvil/ci.yml" }
2398 " pipeline and push to trigger one."
2399 }
2400 } @else {
2401 div.box {
2402 @for r in &runs {
2403 div.row {
2404 a.entry href=(format!("/{owner}/{repo}/ci/{}", r.id)) {
2405 (status_badge(&r.status))
2406 span.sha { (short_commit(&r.commit)) }
2407 span { (r.ref_name) }
2408 }
2409 span.muted { (fmt_time(r.created_at)) }
2410 }
2411 }
2412 }
2413 }
2414 },
2415 ))
2416}
2417
2418/// `GET /{owner}/{repo}/ci/{id}` — one run's status, timing, and log output.
2419async fn ci_run(
2420 State(app): State<App>,
2421 CurrentUser(user): CurrentUser,
2422 Path((owner, repo, id)): Path<(String, String, i64)>,
2423) -> Result<Markup, Response> {
2424 let (_, meta) = resolve_repo(&app, user.as_ref(), &owner, &repo).await?;
2425 let run = ci::get(&app.db, id)
2426 .await
2427 .map_err(server_error)?
2428 .filter(|r| r.repo_id == meta.id)
2429 .ok_or_else(|| not_found("no such CI run"))?;
2430 let artifacts = ci::artifacts_for_run(&app.db, run.id)
2431 .await
2432 .map_err(server_error)?;
2433 Ok(layout(
2434 &format!("{owner}/{repo}: CI #{}", run.id),
2435 user.as_ref(),
2436 html! {
2437 h1 {
2438 a href=(format!("/{owner}/{repo}")) { (owner) "/" (repo) }
2439 " · " a href=(format!("/{owner}/{repo}/ci")) { "CI" }
2440 " · #" (run.id)
2441 }
2442 p {
2443 (status_badge(&run.status))
2444 " "
2445 a.sha href=(format!("/{owner}/{repo}/commit/{}", run.commit)) { (short_commit(&run.commit)) }
2446 " " span.muted { (run.ref_name) }
2447 }
2448 p.muted {
2449 "queued " (fmt_time(run.created_at))
2450 @if run.started_at > 0 { " · started " (fmt_time(run.started_at)) }
2451 @if run.finished_at > 0 { " · finished " (fmt_time(run.finished_at)) }
2452 @if let Some(d) = run_duration(&run) { " · took " (d) }
2453 }
2454 @if !artifacts.is_empty() {
2455 h2 { "Artifacts" }
2456 div.box {
2457 @for a in &artifacts {
2458 div.row {
2459 a.entry href=(format!("/{owner}/{repo}/ci/{}/artifacts/{}", run.id, a.name)) {
2460 (entry_icon(a.is_dir))
2461 (a.name)
2462 @if a.browse { " " span.pill { "site" } }
2463 @else if a.is_dir { ".tar.gz" }
2464 }
2465 span.muted {
2466 (artifact_meta_chips(&a.meta))
2467 (fmt_size(a.size))
2468 }
2469 }
2470 }
2471 }
2472 }
2473 @if run.log.is_empty() {
2474 p.muted { "No output yet." }
2475 } @else {
2476 pre.log { (run.log) }
2477 }
2478 },
2479 ))
2480}
2481
2482/// Render an artifact's extractor metadata (a JSON object of key → value) as
2483/// inline `key: value` chips before the size.
2484fn artifact_meta_chips(meta: &str) -> Markup {
2485 let map: BTreeMap<String, String> = serde_json::from_str(meta).unwrap_or_default();
2486 html! {
2487 @for (k, v) in &map {
2488 span.pill title=(k) { (k) ": " (v) }
2489 " "
2490 }
2491 }
2492}
2493
2494/// A coloured status pill for a CI run status string.
2495fn status_badge(status: &str) -> Markup {
2496 html! { span class=(format!("st {status}")) { (status) } }
2497}
2498
2499/// First 8 hex chars of a commit oid (for compact display).
2500fn short_commit(commit: &str) -> &str {
2501 &commit[..commit.len().min(8)]
2502}
2503
2504/// Wall-clock run duration (`started`→`finished`) as a short string, if known.
2505fn run_duration(run: &CiRun) -> Option<String> {
2506 if run.started_at > 0 && run.finished_at >= run.started_at {
2507 Some(format!("{}s", run.finished_at - run.started_at))
2508 } else {
2509 None
2510 }
2511}
2512
2513/// Render one file's diff (added/deleted/modified) as a unified line diff.
2514/// A file diff bigger than this many rows starts collapsed (its header still
2515/// shows the +/− counts; clicking expands it — native `details`, no JS).
2516const DIFF_COLLAPSE_ROWS: usize = 400;
2517
2518fn render_file_diff(change: &FileChange) -> Markup {
2519 let (badge_cls, badge) = match change.kind {
2520 ChangeKind::Added => ("add", "added"),
2521 ChangeKind::Deleted => ("del", "deleted"),
2522 ChangeKind::Modified => ("mod", "modified"),
2523 };
2524 let head = |stat: Markup| {
2525 html! {
2526 summary.head {
2527 span class=(format!("badge {badge_cls}")) { (badge) }
2528 span { (change.path) }
2529 span.stat { (stat) }
2530 }
2531 }
2532 };
2533
2534 let binary = change.old.as_deref().is_some_and(is_binary)
2535 || change.new.as_deref().is_some_and(is_binary);
2536 if binary {
2537 return html! {
2538 details.file-diff open {
2539 (head(html! { span.muted { "binary" } }))
2540 div.box { div.row { span.muted { "Binary file" } } }
2541 }
2542 };
2543 }
2544
2545 let old = change
2546 .old
2547 .as_deref()
2548 .map(|b| String::from_utf8_lossy(b).into_owned())
2549 .unwrap_or_default();
2550 let new = change
2551 .new
2552 .as_deref()
2553 .map(|b| String::from_utf8_lossy(b).into_owned())
2554 .unwrap_or_default();
2555 let diff = TextDiff::from_lines(&old, &new);
2556 let (mut adds, mut dels) = (0usize, 0usize);
2557 for c in diff.iter_all_changes() {
2558 match c.tag() {
2559 ChangeTag::Insert => adds += 1,
2560 ChangeTag::Delete => dels += 1,
2561 ChangeTag::Equal => {}
2562 }
2563 }
2564 // Hunks: changed lines plus 3 lines of context, not the whole file.
2565 let groups = diff.grouped_ops(3);
2566 let rendered_rows: usize = groups
2567 .iter()
2568 .flatten()
2569 .map(|op| diff.iter_changes(op).count())
2570 .sum();
2571
2572 html! {
2573 details.file-diff open[rendered_rows <= DIFF_COLLAPSE_ROWS] {
2574 (head(html! { span.plus { "+" (adds) } " " span.minus { "−" (dels) } }))
2575 (diff_table(&diff, &groups, old.lines().count()))
2576 }
2577 }
2578}
2579
2580/// Render grouped diff hunks as a table: old/new line numbers, a +/- sign
2581/// column, and the line. Elided stretches show a "⋯ N unchanged lines" row
2582/// (including before the first hunk and after the last).
2583fn diff_table<'a>(
2584 diff: &TextDiff<'a, 'a, '_, str>,
2585 groups: &[Vec<similar::DiffOp>],
2586 old_total: usize,
2587) -> Markup {
2588 let gap_row = |n: usize| {
2589 html! {
2590 @if n > 0 {
2591 tr.gap { td colspan="4" { "⋯ " (n) " unchanged line" @if n != 1 { "s" } } }
2592 }
2593 }
2594 };
2595 // Unchanged-line gap before each group, and after the last one.
2596 let mut prev_end = 0usize; // end of the previous group, in old-file lines
2597 let mut with_gaps = Vec::with_capacity(groups.len());
2598 for group in groups {
2599 let start = group.first().map_or(prev_end, |op| op.old_range().start);
2600 with_gaps.push((start.saturating_sub(prev_end), group));
2601 prev_end = group.last().map_or(prev_end, |op| op.old_range().end);
2602 }
2603 let trailing = old_total.saturating_sub(prev_end);
2604
2605 html! {
2606 table.code.diff {
2607 @for (gap, group) in &with_gaps {
2608 (gap_row(*gap))
2609 @for op in group.iter() {
2610 @for change in diff.iter_changes(op) {
2611 @let (sign, cls) = match change.tag() {
2612 ChangeTag::Delete => ("-", "del"),
2613 ChangeTag::Insert => ("+", "ins"),
2614 ChangeTag::Equal => (" ", ""),
2615 };
2616 tr class=(cls) {
2617 td.ln { @if let Some(i) = change.old_index() { (i + 1) } }
2618 td.ln { @if let Some(i) = change.new_index() { (i + 1) } }
2619 td.sign { (sign) }
2620 td { (change.value().trim_end_matches('\n')) }
2621 }
2622 }
2623 }
2624 }
2625 (gap_row(trailing))
2626 }
2627 }
2628}
2629
2630/// Lazily-loaded syntax set and theme (pure-Rust fancy-regex backend).
2631fn highlighter() -> &'static (SyntaxSet, Theme) {
2632 static HL: OnceLock<(SyntaxSet, Theme)> = OnceLock::new();
2633 HL.get_or_init(|| {
2634 let syntaxes = SyntaxSet::load_defaults_newlines();
2635 let themes = ThemeSet::load_defaults();
2636 let theme = themes
2637 .themes
2638 .get("Monokai Extended")
2639 .or_else(|| themes.themes.get("Solarized (dark)"))
2640 .or_else(|| themes.themes.values().next())
2641 .cloned()
2642 .expect("at least one default theme");
2643 (syntaxes, theme)
2644 })
2645}
2646
2647/// [`highlight`] through a byte-budgeted LRU keyed by blob oid + extension: a
2648/// blob's rendered HTML is immutable for its object id (the extension is part
2649/// of the key because it picks the syntax), so each file is highlighted once
2650/// rather than once per request — highlighting large files is by far the most
2651/// expensive thing a page view can do. The budget is
2652/// `http.highlight_cache_mb`; `0` bypasses the cache entirely (for
2653/// RAM-constrained hosts). Concurrent misses may both compute and the last
2654/// insert wins; that's benign.
2655fn cached_highlight(budget_bytes: usize, oid: &str, path: &str, text: &str) -> Arc<Vec<String>> {
2656 if budget_bytes == 0 {
2657 return Arc::new(highlight(path, text));
2658 }
2659 struct Cache {
2660 lru: lru::LruCache<String, Arc<Vec<String>>>,
2661 bytes: usize,
2662 }
2663 fn cost(key: &str, lines: &[String]) -> usize {
2664 key.len() + lines.iter().map(String::len).sum::<usize>()
2665 }
2666 static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
2667 let cache = CACHE.get_or_init(|| {
2668 Mutex::new(Cache {
2669 lru: lru::LruCache::unbounded(),
2670 bytes: 0,
2671 })
2672 });
2673
2674 let ext = std::path::Path::new(path)
2675 .extension()
2676 .and_then(|e| e.to_str())
2677 .unwrap_or("");
2678 let key = format!("{oid}\x00{ext}");
2679 if let Some(hit) = cache.lock().expect("cache lock").lru.get(&key) {
2680 return hit.clone();
2681 }
2682
2683 let lines = Arc::new(highlight(path, text));
2684 let mut c = cache.lock().expect("cache lock");
2685 c.bytes += cost(&key, &lines);
2686 if let Some(old) = c.lru.put(key.clone(), Arc::clone(&lines)) {
2687 c.bytes -= cost(&key, &old); // concurrent miss inserted it first
2688 }
2689 // Evict oldest entries until we're back under budget. An entry larger than
2690 // the whole budget evicts itself — memory stays bounded, it just never caches.
2691 while c.bytes > budget_bytes {
2692 let Some((k, v)) = c.lru.pop_lru() else { break };
2693 c.bytes -= cost(&k, &v);
2694 }
2695 lines
2696}
2697
2698/// Syntax-highlight `text` (chosen by file extension), returning per-line HTML.
2699/// Falls back to escaped plain text for large files or on any failure.
2700fn highlight(path: &str, text: &str) -> Vec<String> {
2701 if text.len() > 512 * 1024 {
2702 return text.lines().map(escape).collect();
2703 }
2704 let (syntaxes, theme) = highlighter();
2705 let syntax = std::path::Path::new(path)
2706 .extension()
2707 .and_then(|e| e.to_str())
2708 .and_then(|ext| syntaxes.find_syntax_by_extension(ext))
2709 .or_else(|| syntaxes.find_syntax_by_first_line(text.lines().next().unwrap_or("")))
2710 .unwrap_or_else(|| syntaxes.find_syntax_plain_text());
2711
2712 let mut h = HighlightLines::new(syntax, theme);
2713 text.lines()
2714 .map(|line| match h.highlight_line(line, syntaxes) {
2715 Ok(ranges) => styled_line_to_highlighted_html(&ranges, IncludeBackground::No)
2716 .unwrap_or_else(|_| escape(line)),
2717 Err(_) => escape(line),
2718 })
2719 .collect()
2720}
2721
2722fn escape(s: &str) -> String {
2723 s.replace('&', "&amp;")
2724 .replace('<', "&lt;")
2725 .replace('>', "&gt;")
2726}
2727
2728/// Format a Unix timestamp as `YYYY-MM-DD HH:MM UTC`.
2729pub(crate) fn fmt_time(secs: i64) -> String {
2730 match OffsetDateTime::from_unix_timestamp(secs) {
2731 Ok(t) => format!(
2732 "{:04}-{:02}-{:02} {:02}:{:02} UTC",
2733 t.year(),
2734 u8::from(t.month()),
2735 t.day(),
2736 t.hour(),
2737 t.minute()
2738 ),
2739 Err(_) => secs.to_string(),
2740 }
2741}
2742
2743/// Format a Unix timestamp relative to now (`2 hours ago`, `last month`).
2744pub(crate) fn fmt_relative(secs: i64) -> String {
2745 relative_to(secs, OffsetDateTime::now_utc().unix_timestamp())
2746}
2747
2748fn relative_to(secs: i64, now: i64) -> String {
2749 fn ago(n: i64, one: &str, unit: &str) -> String {
2750 if n == 1 {
2751 one.to_string()
2752 } else {
2753 format!("{n} {unit}s ago")
2754 }
2755 }
2756 let delta = now - secs;
2757 if delta < 60 {
2758 return "just now".to_string();
2759 }
2760 let minutes = delta / 60;
2761 if minutes < 60 {
2762 return ago(minutes, "1 minute ago", "minute");
2763 }
2764 let hours = delta / 3600;
2765 if hours < 24 {
2766 return ago(hours, "1 hour ago", "hour");
2767 }
2768 let days = delta / 86_400;
2769 if days < 7 {
2770 return ago(days, "yesterday", "day");
2771 }
2772 let weeks = days / 7;
2773 if weeks < 5 {
2774 return ago(weeks, "last week", "week");
2775 }
2776 let months = days / 30;
2777 if months < 12 {
2778 return ago(months, "last month", "month");
2779 }
2780 ago(days / 365, "last year", "year")
2781}
2782
2783/// Heuristic: treat content with a NUL in the first 8 KiB as binary.
2784fn is_binary(bytes: &[u8]) -> bool {
2785 bytes.iter().take(8192).any(|&b| b == 0)
2786}
2787
2788#[cfg(test)]
2789mod tests {
2790 use super::*;
2791
2792 #[test]
2793 fn markdown_by_extension_only() {
2794 assert!(is_markdown("README.md"));
2795 assert!(is_markdown("docs/guide.MarkDown"));
2796 assert!(!is_markdown("main.rs"));
2797 assert!(!is_markdown("md")); // no extension
2798 }
2799
2800 // Repo content is untrusted; rendered markdown must not become stored XSS.
2801 #[test]
2802 fn rendered_markdown_neutralizes_html_and_script_urls() {
2803 let out = render_markdown(
2804 "# 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",
2805 )
2806 .into_string();
2807 assert!(out.contains("<h1>title</h1>"), "markdown renders: {out}");
2808 assert!(!out.contains("<script>"), "raw HTML escaped: {out}");
2809 assert!(
2810 out.contains("&lt;script&gt;"),
2811 "raw HTML kept as text: {out}"
2812 );
2813 assert!(!out.contains("javascript:"), "script URL dropped: {out}");
2814 assert!(!out.contains("data:"), "data URL dropped: {out}");
2815 assert!(
2816 out.contains(r#"href="https://example.com""#),
2817 "normal links survive: {out}"
2818 );
2819 }
2820
2821 #[test]
2822 fn relative_time_buckets() {
2823 const NOW: i64 = 1_000_000_000;
2824 let at = |delta: i64| relative_to(NOW - delta, NOW);
2825 assert_eq!(at(0), "just now");
2826 assert_eq!(at(59), "just now");
2827 assert_eq!(at(60), "1 minute ago");
2828 assert_eq!(at(45 * 60), "45 minutes ago");
2829 assert_eq!(at(3600), "1 hour ago");
2830 assert_eq!(at(23 * 3600), "23 hours ago");
2831 assert_eq!(at(86_400), "yesterday");
2832 assert_eq!(at(3 * 86_400), "3 days ago");
2833 assert_eq!(at(8 * 86_400), "last week");
2834 assert_eq!(at(20 * 86_400), "2 weeks ago");
2835 assert_eq!(at(40 * 86_400), "last month");
2836 assert_eq!(at(200 * 86_400), "6 months ago");
2837 assert_eq!(at(400 * 86_400), "last year");
2838 assert_eq!(at(900 * 86_400), "2 years ago");
2839 }
2840}