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