steid

@jamesgill /

dce0bf3feat: browse a repository's files and history8d
1//! Browsing a repository — the file tree, a single file, and the commit log.
2//!
3//! Four routes, all reading through [`browse_repo`] and [`repo_log`], so visibility is
4//! decided in one place: a repository invisible on its page is invisible here, and
5//! `Ok(None)` from either use case renders as the same 404 as a repository that was
6//! never created.
7//!
8//! The URL carries a `/-/` separator between the revision and the path
9//! (`/tree/{rev}/-/{path}`) because a ref may contain slashes, so a candidate split
10//! would cost a ref lookup — another `git` process — on every page. The separator is
11//! unambiguous by construction instead.
12//!
13//! One route serves both directories and files. Which one a path is, is git's answer,
14//! not the URL's, and a link that had to know would be wrong the moment a file became
15//! a directory.
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
16//!
17//! A fifth route, `/raw/{rev}/-/{*path}`, serves a file's bytes verbatim. It is not a
18//! page: it hands back arbitrary bytes an untrusted person put in a repository, so its
19//! response headers are a security policy rather than a convenience — see
20//! [`raw_response`].
dce0bf3feat: browse a repository's files and history8d
21
22use std::time::{SystemTime, UNIX_EPOCH};
23
24use topcoat::{
25 Result,
26 context::Cx,
27 icon::{icon, iconify::iconify_icon},
28 router::{
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
29 Body, Response, StatusCode,
dce0bf3feat: browse a repository's files and history8d
30 error::{RouterErrorExt, not_found},
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
31 header::{CONTENT_DISPOSITION, CONTENT_TYPE},
32 page, path_param, route,
dce0bf3feat: browse a repository's files and history8d
33 },
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
34 view::{View, attributes, component, view},
dce0bf3feat: browse a repository's files and history8d
35};
36
37use crate::{
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
38 application::{
39 Browsed, FileView, RepoView,
40 browse::{RawFile, RefList, list_refs, read_raw_file},
41 browse_repo, repo_log,
42 },
dce0bf3feat: browse a repository's files and history8d
43 components::badge::{BadgeVariant, badge},
44 domain::{CommitSummary, EntryKind, RefName, RepoPath, TreeEntry},
45};
46
47use super::{
48 context::{current_actor, memberships, orgs, queries, repos, server_error},
5d3dfa5feat: a global top bar, and pages choose their own width22h
49 layout::wide,
dce0bf3feat: browse a repository's files and history8d
50 repo::{clone_url, clone_url_for, repo_for},
51};
52
53/// `{rev}` from the path, raw — validation is [`RefName`]'s job.
54#[path_param]
55struct Rev(str);
56
57/// `{*path}` from the path: every remaining segment, as one string.
58#[path_param]
59struct Path(str);
60
61/// Which page of a repository is being looked at, for the nav.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub(super) enum Tab {
64 Files,
65 Log,
66}
67
68/// The revision from the URL, or 404.
69///
70/// A malformed revision is a page that does not exist rather than a bad request — the
71/// same reasoning that 404s a malformed handle.
72fn rev_param(cx: &Cx) -> Result<RefName> {
73 Ok(RefName::new(path_param::<Rev>(cx)).map_err(|_| not_found())?)
74}
75
76/// The path from the URL, or 404. Same reasoning as [`rev_param`].
77fn path_arg(cx: &Cx) -> Result<RepoPath> {
78 Ok(RepoPath::new(path_param::<Path>(cx)).map_err(|_| not_found())?)
79}
80
81#[page("/{handle}/repos/{name}/tree/{rev}")]
82async fn tree_root_page(cx: &Cx) -> Result {
83 let rev = rev_param(cx)?;
84
85 view! { browsing(rev: Some(rev), path: RepoPath::root()) }
86}
87
88#[page("/{handle}/repos/{name}/tree/{rev}/-/{*path}")]
89async fn tree_path_page(cx: &Cx) -> Result {
90 let rev = rev_param(cx)?;
91 let path = path_arg(cx)?;
92
93 view! { browsing(rev: Some(rev), path: path) }
94}
95
96#[page("/{handle}/repos/{name}/log")]
97async fn log_page(_cx: &Cx) -> Result {
98 view! { history(rev: None) }
99}
100
101#[page("/{handle}/repos/{name}/log/{rev}")]
102async fn log_rev_page(cx: &Cx) -> Result {
103 let rev = rev_param(cx)?;
104
105 view! { history(rev: Some(rev)) }
106}
107
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
108/// A file's bytes, exactly as they are stored.
109///
110/// A route rather than a page: the response is a file, not a document, so no layout
111/// wraps it. `/-/` separates the revision from the path for the same reason the tree
112/// route does — both can contain slashes and they sit adjacent.
113///
114/// Authorized through [`read_raw_file`], which goes through the same `view_repo` every
115/// browse page does, so a private repository answers 404 here exactly as it does there.
116#[route(GET "/{handle}/repos/{name}/raw/{rev}/-/{*path}")]
117async fn raw_page(cx: &Cx) -> Result<Response<Body>> {
118 let rev = rev_param(cx)?;
119 let path = path_arg(cx)?;
120 let repo = repo_for(cx).await?;
121
122 let raw = read_raw_file(
123 &repo.handle,
124 &repo.name,
125 Some(&rev),
126 &path,
127 &current_actor(cx).await?,
128 &orgs(cx),
129 &memberships(cx),
130 &repos(cx),
131 &queries(cx),
132 )
133 .await
134 .map_err(server_error)?
135 .ok_or_not_found()?;
136
137 match raw {
138 RawFile::Ready { name, content } => raw_response(&name, content),
139 // The only case that is neither a file nor a 404. Its body is Steid's own text,
140 // never the repository's, so it is the one raw response that may name a type.
141 RawFile::TooLarge { size } => Response::builder()
142 .status(StatusCode::PAYLOAD_TOO_LARGE)
143 .header(CONTENT_TYPE, "text/plain; charset=utf-8")
144 .header(NOSNIFF.0, NOSNIFF.1)
145 .body(Body::from(format!(
146 "This file is {}, which is larger than this instance serves raw. Clone the repository to read it.\n",
147 size_of(size)
148 )))
149 .map_err(server_error),
150 }
151}
152
dce0bf3feat: browse a repository's files and history8d
153/// Reads a path in a repository, or 404.
154///
155/// Shared with the repository page, which browses the default branch at the root.
156pub(super) async fn browsed_at(
157 cx: &Cx,
158 repo: &RepoView,
159 rev: Option<&RefName>,
160 path: &RepoPath,
161) -> Result<Browsed> {
162 Ok(browse_repo(
163 &repo.handle,
164 &repo.name,
165 rev,
166 path,
167 &current_actor(cx).await?,
168 &orgs(cx),
169 &memberships(cx),
170 &repos(cx),
171 &queries(cx),
172 )
173 .await
174 .map_err(server_error)?
175 .ok_or_not_found()?)
176}
177
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
178/// The branches and tags of a repository the viewer can already see, or 404.
179///
180/// **One extra `git` process, ~14ms**, on top of the two or three a browse already
181/// spends — see the Milestone 5 amendment to
182/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md). Called only by
183/// the pages that show the switcher, and skipped for a repository with no commits,
184/// where there is nothing to list.
185async fn refs_for(cx: &Cx, repo: &RepoView) -> Result<RefList> {
186 Ok(list_refs(
187 &repo.handle,
188 &repo.name,
189 &current_actor(cx).await?,
190 &orgs(cx),
191 &memberships(cx),
192 &repos(cx),
193 &queries(cx),
194 )
195 .await
196 .map_err(server_error)?
197 .ok_or_not_found()?)
198}
199
dce0bf3feat: browse a repository's files and history8d
200/// The tree and blob pages, which differ only in what git found at the path.
201///
202/// A component rather than a plain function because `view!` needs the request context
203/// in scope, and a component is how a body of markup gets it — the same reason the
204/// layout is a layout.
205#[component]
206async fn browsing(cx: &Cx, rev: Option<RefName>, path: RepoPath) -> Result {
207 let repo = repo_for(cx).await?;
208 let browsed = browsed_at(cx, &repo, rev.as_ref(), &path).await?;
209 let clone = clone_url_for(cx, &repo);
210
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
211 // An empty repository has no refs, so the fork is not spent asking.
212 let refs = match browsed {
213 Browsed::Empty => RefList::default(),
214 _ => refs_for(cx, &repo).await?,
215 };
216
217 let at = browsed_rev(&browsed);
218 let switch = Switch::Tree(&path);
219 let handle = repo.handle.as_str();
220 let name = repo.name.as_str();
221 let known = RefName::new(at).is_ok_and(|at| refs.contains(&at));
222 let branches = ref_links(handle, name, &refs.branches, at, &switch);
223 let tags = ref_links(handle, name, &refs.tags, at, &switch);
224
dce0bf3feat: browse a repository's files and history8d
225 view! {
5d3dfa5feat: a global top bar, and pages choose their own width22h
226 wide(
227 repo_bar(
228 repo: &repo,
229 rev: at,
230 active: Tab::Files,
231 rev_switcher(current: at, known: known, branches: &branches, tags: &tags)
232 )
233
234 match &browsed {
235 Browsed::Empty => {
236 clone_url(url: clone.as_str())
237 empty_repo(url: clone.as_str())
238 },
239 Browsed::Directory { rev, path, entries } => directory(
240 handle: repo.handle.as_str(),
241 name: repo.name.as_str(),
242 rev: rev,
243 path: path,
244 entries: entries,
245 ),
246 Browsed::File { rev, path, file } => blob(
247 handle: repo.handle.as_str(),
248 name: repo.name.as_str(),
249 rev: rev,
250 path: path,
251 file: file,
252 ),
253 }
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
254 )
dce0bf3feat: browse a repository's files and history8d
255 }
256}
257
258/// The commit log page. A component for the same reason as [`browsing`].
259#[component]
260async fn history(cx: &Cx, rev: Option<RefName>) -> Result {
261 let repo = repo_for(cx).await?;
262
263 let log = repo_log(
264 &repo.handle,
265 &repo.name,
266 rev.as_ref(),
267 &current_actor(cx).await?,
268 &orgs(cx),
269 &memberships(cx),
270 &repos(cx),
271 &queries(cx),
272 )
273 .await
274 .map_err(server_error)?
275 .ok_or_not_found()?;
276
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
277 let refs = refs_for(cx, &repo).await?;
278 let at = rev.as_ref().map(RefName::as_str).unwrap_or_default();
279 let handle = repo.handle.as_str();
280 let name = repo.name.as_str();
281 let known = RefName::new(at).is_ok_and(|at| refs.contains(&at));
282 let branches = ref_links(handle, name, &refs.branches, at, &Switch::Log);
283 let tags = ref_links(handle, name, &refs.tags, at, &Switch::Log);
284
dce0bf3feat: browse a repository's files and history8d
285 view! {
5d3dfa5feat: a global top bar, and pages choose their own width22h
286 wide(
287 repo_bar(
288 repo: &repo,
289 rev: at,
290 active: Tab::Log,
291 // At the default branch the URL names no revision and `repo_log` does not
292 // report the one it resolved, so the switcher opens with nothing marked
293 // current rather than guessing. Noted in `plans/current.md`.
294 rev_switcher(current: at, known: known, branches: &branches, tags: &tags)
295 )
296 commit_log(commits: &log)
dce0bf3feat: browse a repository's files and history8d
297 )
298 }
299}
300
301/// The revision a browse landed on, for display. Empty when there is none.
302fn browsed_rev(browsed: &Browsed) -> &str {
303 match browsed {
304 Browsed::Empty => "",
305 Browsed::Directory { rev, .. } | Browsed::File { rev, .. } => rev.as_str(),
306 }
307}
308
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
309// --- Serving bytes ----------------------------------------------------------------
310
311/// The header that stops a browser second-guessing a `Content-Type`.
312///
313/// A pair rather than a constant string so the name is written once; `http` has no
314/// constant for it.
315const NOSNIFF: (&str, &str) = ("x-content-type-options", "nosniff");
316
317/// What a raw file is served as.
318///
319/// **Never the file's own type, and never guessed from its extension.** Steid serves
320/// repository contents from the same origin as the application, so a file the origin
321/// labels `text/html` runs *as this site*: it reads the session cookie, calls Steid's
322/// own endpoints as the viewer, and rewrites the page around it. Somebody pushing
323/// `evil.html` would then have stored XSS on every visitor who followed a link to it.
324/// The same holds for SVG (scriptable), XML, and anything a browser will render.
325///
326/// Today only the repository's owner can push, so the only person who could attack a
327/// viewer is the person whose site it is. Milestone 7 adds other users and this endpoint
328/// will outlive that assumption, so the policy is written for the world where the bytes
329/// are hostile.
330///
331/// Four headers, each closing a different door:
332///
333/// - `application/octet-stream` — a type no browser renders. Not `text/plain`, which
334/// *is* rendered, and which older browsers have been talked into sniffing as HTML.
335/// - `nosniff` — without it a browser is free to ignore the type above and decide from
336/// the content, which is exactly the guess this policy refuses to make.
337/// - `Content-Disposition: attachment` — the file is saved, not shown, so nothing it
338/// contains is ever parsed in this origin's context. It also stops a same-origin
339/// `<iframe>` from rendering it.
340/// - `Content-Security-Policy: default-src 'none'; sandbox` — belt and braces for the
341/// case where one of the above is wrong or unsupported. Nothing in the response may
342/// load, run, or navigate.
343///
344/// The cost is that a raw URL downloads rather than displays. That is the correct trade
345/// for a forge serving other people's bytes, and it is what `curl` wants anyway.
346fn raw_response(name: &str, content: Vec<u8>) -> Result<Response<Body>> {
347 Response::builder()
348 .header(CONTENT_TYPE, "application/octet-stream")
349 .header(NOSNIFF.0, NOSNIFF.1)
350 .header(CONTENT_DISPOSITION, disposition(name))
351 .header("content-security-policy", "default-src 'none'; sandbox")
352 .body(Body::from(content))
353 .map_err(server_error)
354}
355
356/// The `Content-Disposition` for a downloaded file.
357///
358/// Two filenames, per RFC 6266: a plain `filename` every client understands, and a
359/// `filename*` carrying the real name as percent-encoded UTF-8 for those that do. The
360/// plain one is reduced to characters that cannot end the quoted string or be read as a
361/// header of their own — a name is repository content, so a quote or a newline in it
362/// would otherwise be header injection.
363fn disposition(name: &str) -> String {
364 let mut safe = String::with_capacity(name.len());
365
366 for char in name.chars() {
367 match char {
368 'A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_' => safe.push(char),
369 _ => safe.push('_'),
370 }
371 }
372
373 // A name reduced to nothing recognisable — punctuation, or a name written entirely
374 // in a script the plain form cannot carry — downloads as `file` rather than as
375 // `___`. The real name is still in `filename*` for anything that reads it.
376 if !safe.chars().any(|char| char.is_ascii_alphanumeric()) {
377 safe = "file".to_owned();
378 }
379
380 format!(
381 "attachment; filename=\"{safe}\"; filename*=UTF-8''{}",
382 encode(name, false)
383 )
384}
385
dce0bf3feat: browse a repository's files and history8d
386// --- URLs -------------------------------------------------------------------------
387
388/// The URL for a path at a revision.
389///
390/// The revision is encoded whole, slashes included, so `feature/login` stays one
391/// segment and the `/-/` separator keeps its meaning. The path keeps its slashes,
392/// because they *are* segments.
393pub(super) fn tree_url(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> String {
394 let encoded = encode(rev.as_str(), false);
395
396 if path.is_root() {
397 format!("/{handle}/repos/{name}/tree/{encoded}")
398 } else {
399 format!(
400 "/{handle}/repos/{name}/tree/{encoded}/-/{}",
401 encode(path.as_str(), true)
402 )
403 }
404}
405
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
406/// The URL a file's bytes are served from.
407///
408/// Always has a path: there are no raw bytes for a directory, so the root has no raw
409/// URL and the `/-/` separator is unconditional.
410pub(super) fn raw_url(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> String {
411 format!(
412 "/{handle}/repos/{name}/raw/{}/-/{}",
413 encode(rev.as_str(), false),
414 encode(path.as_str(), true)
415 )
416}
417
dce0bf3feat: browse a repository's files and history8d
418/// The commit log's URL, at a revision or at the default branch.
419fn log_url(handle: &str, name: &str, rev: &str) -> String {
420 if rev.is_empty() {
421 format!("/{handle}/repos/{name}/log")
422 } else {
423 format!("/{handle}/repos/{name}/log/{}", encode(rev, false))
424 }
425}
426
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
427// --- The revision switcher --------------------------------------------------------
428
429/// Which page a switcher's links lead back to.
430///
431/// Switching branch keeps you where you are: the same path on the tree, the log on the
432/// log. A path that does not exist on the revision you picked lands on a 404, which is
433/// the honest answer — the alternative is silently sending you somewhere you did not
434/// ask for.
435enum Switch<'a> {
436 Tree(&'a RepoPath),
437 Log,
438}
439
440/// One row of the switcher.
441struct RefLink {
442 name: String,
443 href: String,
444 current: bool,
445}
446
447fn ref_links(
448 handle: &str,
449 name: &str,
450 refs: &[RefName],
451 current: &str,
452 switch: &Switch,
453) -> Vec<RefLink> {
454 refs.iter()
455 .map(|git_ref| RefLink {
456 name: git_ref.to_string(),
457 href: match switch {
458 Switch::Tree(path) => tree_url(handle, name, git_ref, path),
459 Switch::Log => log_url(handle, name, git_ref.as_str()),
460 },
461 current: git_ref.as_str() == current,
462 })
463 .collect()
464}
465
466/// Whether a revision is an object id rather than a name.
467///
468/// A heuristic, and only used for display: the worst it can do is abbreviate a branch
469/// somebody named `deadbeef`.
470fn is_object_id(rev: &str) -> bool {
471 rev.len() >= 7 && rev.len() <= 64 && rev.chars().all(|char| char.is_ascii_hexdigit())
472}
473
474/// How the switcher labels the revision it is on.
475///
476/// A ref by its name; a commit browsed directly by its abbreviation, because forty
477/// characters of hex in a control reads as noise and is not a branch.
478fn rev_label(rev: &str, known: bool) -> String {
479 if !known && is_object_id(rev) {
480 rev[..7].to_owned()
481 } else {
482 rev.to_owned()
483 }
484}
485
dce0bf3feat: browse a repository's files and history8d
486/// Percent-encodes a URL segment.
487///
488/// Hand-rolled rather than pulled in as a dependency: it is the unreserved set from
489/// RFC 3986 and nothing else. `keep_slash` is the difference between a path, whose
490/// slashes are structure, and a revision, whose slashes are part of its name.
491fn encode(value: &str, keep_slash: bool) -> String {
492 let mut encoded = String::with_capacity(value.len());
493
494 for byte in value.bytes() {
495 match byte {
496 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
497 encoded.push(byte as char);
498 }
499 b'/' if keep_slash => encoded.push('/'),
500 other => encoded.push_str(&format!("%{other:02X}")),
501 }
502 }
503
504 encoded
505}
506
507// --- Formatting -------------------------------------------------------------------
508
509/// A file size, rounded for reading rather than for accounting.
510fn size_of(bytes: u64) -> String {
511 const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
512
513 if bytes < 1024 {
514 return format!("{bytes} B");
515 }
516
517 let mut value = bytes as f64 / 1024.0;
518 let mut unit = UNITS[0];
519
520 for next in &UNITS[1..] {
521 if value < 1024.0 {
522 break;
523 }
524
525 value /= 1024.0;
526 unit = next;
527 }
528
529 format!("{value:.1} {unit}")
530}
531
532/// How long ago something happened, in words.
533///
534/// A commit's timestamp comes from whoever made it, so it can sit in the future — a
535/// skewed clock, or a rewritten history. That reads as "just now" rather than as a
536/// negative duration.
ef23868feat: rebuild the profile page on flat navigation7d
537pub(super) fn ago(time: SystemTime) -> String {
dce0bf3feat: browse a repository's files and history8d
538 let Ok(elapsed) = SystemTime::now().duration_since(time) else {
539 return "just now".to_owned();
540 };
541
542 let seconds = elapsed.as_secs();
543
544 let (count, unit) = match seconds {
545 0..=59 => return "just now".to_owned(),
546 60..=3599 => (seconds / 60, "minute"),
547 3600..=86_399 => (seconds / 3600, "hour"),
548 86_400..=2_591_999 => (seconds / 86_400, "day"),
549 2_592_000..=31_535_999 => (seconds / 2_592_000, "month"),
550 _ => (seconds / 31_536_000, "year"),
551 };
552
553 if count == 1 {
554 format!("1 {unit} ago")
555 } else {
556 format!("{count} {unit}s ago")
557 }
558}
559
560/// The exact time, for the tooltip behind [`ago`].
561fn timestamp(time: SystemTime) -> String {
562 let seconds = time
563 .duration_since(UNIX_EPOCH)
564 .map(|since| since.as_secs() as i64)
565 .unwrap_or(0);
566
567 let (year, month, day) = civil_from_days(seconds.div_euclid(86_400));
568 let rest = seconds.rem_euclid(86_400);
569
570 format!(
571 "{year:04}-{month:02}-{day:02} {:02}:{:02} UTC",
572 rest / 3600,
573 (rest % 3600) / 60
574 )
575}
576
577/// Days since the epoch to a calendar date, by Howard Hinnant's `civil_from_days`.
578///
579/// Written out rather than taken as a dependency: this is the whole of the date
580/// handling Steid needs, and a date library is a large thing to add for one function.
581fn civil_from_days(days: i64) -> (i64, u32, u32) {
582 // Shift the epoch to 0000-03-01, which puts the leap day at the end of the year.
583 let shifted = days + 719_468;
584 let era = shifted.div_euclid(146_097);
585 let day_of_era = shifted.rem_euclid(146_097);
586
587 let year_of_era =
588 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
589 let year = year_of_era + era * 400;
590 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
591
592 let shifted_month = (5 * day_of_year + 2) / 153;
593 let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32;
594 let month = if shifted_month < 10 {
595 shifted_month + 3
596 } else {
597 shifted_month - 9
598 } as u32;
599
600 (if month <= 2 { year + 1 } else { year }, month, day)
601}
602
603// --- Views ------------------------------------------------------------------------
604
605/// The bar every repository page carries: where you are, and what else there is.
606///
607/// Kept out of the repository page's own header so that a tree, a file and a log all
608/// read as the same repository rather than as three unrelated pages.
609#[component]
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
610pub(super) async fn repo_bar(
611 repo: &RepoView,
612 rev: &str,
613 active: Tab,
614 /// The revision control, when the page has one. Empty on a page that does not.
615 #[default]
616 child: View,
617) -> Result {
dce0bf3feat: browse a repository's files and history8d
618 let handle = repo.handle.as_str();
619 let name = repo.name.as_str();
620 let tab = |current| {
621 if current {
622 "text-foreground border-foreground"
623 } else {
624 "text-muted-foreground border-transparent hover:text-foreground"
625 }
626 };
627
628 view! {
629 <header class="mb-6 border-b border-border pb-3">
630 <p class="font-mono text-sm text-muted-foreground">
631 <a href=(format!("/{handle}")) class="hover:text-foreground">"@" (handle)</a>
632 " / "
633 <a href=(format!("/{handle}/repos/{name}")) class="text-foreground hover:underline">
634 (name)
635 </a>
636 if !repo.visibility.is_public() {
637 " "
638 badge(variant: BadgeVariant::Outline, "Private")
639 }
640 </p>
641
642 <nav class="mt-3 flex items-center gap-5 text-sm">
643 <a
644 href=(format!("/{handle}/repos/{name}"))
645 class=(format!("-mb-3 border-b-2 pb-2 {}", tab(active == Tab::Files)))
646 >"Files"</a>
647 <a
648 href=(log_url(handle, name, rev))
649 class=(format!("-mb-3 border-b-2 pb-2 {}", tab(active == Tab::Log)))
650 >"Commits"</a>
651
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
652 <span class="ml-auto">(child)</span>
dce0bf3feat: browse a repository's files and history8d
653 </nav>
654 </header>
655 }
656}
657
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
658/// The branch and tag picker.
659///
660/// A `<details>` disclosure, so it opens and closes with no scripting — the rest of
661/// Steid works without JavaScript and a navigation control is the last place to start
662/// requiring it. Every entry is a plain link, so it is also the whole keyboard and
663/// screen-reader story for free.
664///
665/// Renders nothing at all when there is neither a revision nor a ref to offer, which is
666/// an empty repository.
667#[component]
668async fn rev_switcher(
669 current: &str,
670 known: bool,
671 branches: &[RefLink],
672 tags: &[RefLink],
673) -> Result {
674 let label = rev_label(current, known);
675 let empty = branches.is_empty() && tags.is_empty();
676
677 view! {
678 if empty {
679 // Nothing to switch to, so the control degrades to what it replaced: a
680 // statement of where you are.
681 if !current.is_empty() {
682 <span class="inline-flex items-center gap-1.5 font-mono text-xs text-muted-foreground">
683 icon(data: iconify_icon!("feather:git-branch"), attrs: attributes! {
684 class="size-3.5"
685 })
686 (label)
687 </span>
688 }
689 } else {
690 <details class="group relative inline-block">
691 <summary class="inline-flex cursor-pointer list-none items-center gap-1.5 rounded-lg border border-border px-2.5 py-1 font-mono text-xs text-muted-foreground hover:text-foreground [&::-webkit-details-marker]:hidden">
692 icon(
693 data: if known {
694 iconify_icon!("feather:git-branch")
695 } else {
696 iconify_icon!("feather:git-commit")
697 },
698 attrs: attributes! { class="size-3.5" },
699 )
700 (if label.is_empty() { "Revision" } else { label.as_str() })
701 icon(
702 data: iconify_icon!("feather:chevron-down"),
703 attrs: attributes! {
704 class="size-3.5 transition-transform group-open:rotate-180"
705 },
706 )
707 </summary>
708
709 <div class="absolute right-0 z-20 mt-1 max-h-80 w-64 overflow-y-auto rounded-lg border border-border bg-background p-1 shadow-lg">
710 if !known && !current.is_empty() {
711 <p class="px-2 py-1.5 font-mono text-xs text-muted-foreground">
712 "At commit " (label)
713 </p>
714 }
715
716 ref_group(title: "Branches", links: branches)
717 ref_group(title: "Tags", links: tags)
718 </div>
719 </details>
720 }
721 }
722}
723
724/// One labelled section of the switcher, omitted entirely when it is empty.
725///
726/// The heading is what tells a branch from a tag; nothing else in the list does, and
727/// picking a tag when you meant a branch of the same name is a confusing way to end up
728/// on the wrong tree.
729#[component]
730async fn ref_group(title: &str, links: &[RefLink]) -> Result {
731 view! {
732 if !links.is_empty() {
733 <p class="px-2 pt-1.5 pb-1 text-xs font-medium uppercase tracking-wider text-muted-foreground">
734 (title)
735 </p>
736 <ul>
737 for link in links {
738 <li>
739 <a
740 href=(&link.href)
741 class=(format!(
742 "flex items-center gap-2 rounded-md px-2 py-1.5 font-mono text-sm hover:bg-foreground/5 {}",
743 if link.current { "font-medium" } else { "" },
744 ))
745 >
746 <span class="truncate">(&link.name)</span>
747 if link.current {
748 <span class="ml-auto text-muted-foreground">
749 icon(
750 data: iconify_icon!("feather:check"),
751 label: "Current",
752 attrs: attributes! { class="size-3.5" },
753 )
754 </span>
755 }
756 </a>
757 </li>
758 }
759 </ul>
760 }
761 }
762}
763
dce0bf3feat: browse a repository's files and history8d
764/// What a repository with no commits offers instead of a listing.
765///
766/// This is the state every freshly-created repository is in, so it is the first thing
767/// its owner sees — the snippet is the point of the page, not decoration.
768#[component]
769pub(super) async fn empty_repo(url: &str) -> Result {
770 let push = format!("git remote add origin {url}\ngit branch -M main\ngit push -u origin main");
771
772 view! {
773 <div class="mt-6 rounded-lg border border-border px-4 py-5">
774 <p class="text-sm text-muted-foreground">
775 "This repository has no commits yet. Push one to see it here."
776 </p>
777 <p class="mt-4 text-xs font-medium uppercase tracking-wider text-muted-foreground">
778 "Push an existing repository"
779 </p>
780 <pre class="mt-2 overflow-x-auto rounded-lg border border-border bg-muted px-4 py-3 font-mono text-sm">(push)</pre>
781 </div>
782 }
783}
784
785/// The path you are at, with every ancestor linked.
786///
787/// The main way anyone moves around a tree: the last component is the current page and
788/// is deliberately not a link, so the trail reads as a position rather than a menu.
789#[component]
790async fn crumbs(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> Result {
791 let parts: Vec<&str> = path.components().collect();
792 let mut walked = RepoPath::root();
793 let mut trail: Vec<(String, String)> = Vec::new();
794
795 for (index, part) in parts.iter().enumerate() {
796 walked = walked.join(part);
797
798 let href = if index + 1 == parts.len() {
799 String::new()
800 } else {
801 tree_url(handle, name, rev, &walked)
802 };
803
804 trail.push(((*part).to_owned(), href));
805 }
806
807 view! {
808 <div class="flex flex-wrap items-center gap-1 font-mono text-sm">
809 <a
810 href=(tree_url(handle, name, rev, &RepoPath::root()))
811 class="text-muted-foreground hover:text-foreground"
812 >(name)</a>
813
814 for (part, href) in &trail {
815 <span class="text-muted-foreground">"/"</span>
816 match href.is_empty() {
817 true => <span class="font-medium">(part)</span>,
818 false => <a href=(href) class="text-muted-foreground hover:text-foreground">(part)</a>,
819 }
820 }
821 </div>
822 }
823}
824
825/// A directory listing.
826///
827/// Entries arrive ordered by the use case — directories first, then case-insensitively
828/// by name — so nothing here re-sorts them.
829#[component]
830pub(super) async fn directory(
831 handle: &str,
832 name: &str,
833 rev: &RefName,
834 path: &RepoPath,
835 entries: &[TreeEntry],
836) -> Result {
837 view! {
838 <div class="overflow-hidden rounded-lg border border-border">
839 <div class="border-b border-border px-4 py-2.5">
840 crumbs(handle: handle, name: name, rev: rev, path: path)
841 </div>
842
843 if entries.is_empty() {
844 <p class="px-4 py-6 text-center text-sm text-muted-foreground">
845 "This directory is empty."
846 </p>
847 } else {
848 <ul class="divide-y divide-border text-sm">
849 match path.parent() {
850 Some(parent) => <li class="px-4 py-2">
851 <a
852 href=(tree_url(handle, name, rev, &parent))
853 class="inline-flex items-center gap-2 font-mono text-muted-foreground hover:text-foreground"
854 >
855 icon(data: iconify_icon!("feather:corner-left-up"), attrs: attributes! {
856 class="size-4"
857 })
858 ".."
859 </a>
860 </li>,
861 None => "",
862 }
863
864 for entry in entries {
865 <li class="flex items-center gap-3 px-4 py-2">
866 entry_row(
867 handle: handle,
868 name: name,
869 rev: rev,
870 path: path,
871 entry: entry,
872 )
873 </li>
874 }
875 </ul>
876 }
877 </div>
878 }
879}
880
881/// One entry in a listing.
882///
883/// A symlink and a submodule are their own kinds, not files: a submodule is another
884/// repository Steid cannot look inside, so it is labelled and left unlinked rather
885/// than offered as a click that would 404.
886#[component]
887async fn entry_row(
888 handle: &str,
889 name: &str,
890 rev: &RefName,
891 path: &RepoPath,
892 entry: &TreeEntry,
893) -> Result {
894 let href = tree_url(handle, name, rev, &path.join(&entry.name));
895 let linkable = entry.kind != EntryKind::Submodule;
896
897 view! {
898 <span class="text-muted-foreground">
899 match entry.kind {
900 EntryKind::Tree => icon(
901 data: iconify_icon!("feather:folder"),
902 label: "Directory",
903 attrs: attributes! { class="size-4" },
904 ),
905 EntryKind::Blob => icon(
906 data: iconify_icon!("feather:file"),
907 label: "File",
908 attrs: attributes! { class="size-4" },
909 ),
910 EntryKind::Symlink => icon(
911 data: iconify_icon!("feather:link-2"),
912 label: "Symlink",
913 attrs: attributes! { class="size-4" },
914 ),
915 EntryKind::Submodule => icon(
916 data: iconify_icon!("feather:package"),
917 label: "Submodule",
918 attrs: attributes! { class="size-4" },
919 ),
920 }
921 </span>
922
923 match linkable {
924 true => <a
925 href=(href)
926 class=(if entry.kind.is_tree() {
927 "font-mono font-medium hover:underline"
928 } else {
929 "font-mono hover:underline"
930 })
931 >(&entry.name)</a>,
932 false => <span class="font-mono">(&entry.name)</span>,
933 }
934
935 match entry.kind {
936 EntryKind::Symlink => badge(variant: BadgeVariant::Outline, "symlink"),
937 EntryKind::Submodule => badge(variant: BadgeVariant::Outline, "submodule"),
938 _ => "",
939 }
940
941 <span class="ml-auto font-mono text-xs text-muted-foreground">
942 match entry.size {
943 Some(size) => (size_of(size)),
944 None if entry.kind == EntryKind::Submodule => (entry.id.short()),
945 None => "",
946 }
947 </span>
948 }
949}
950
951/// A single file.
952///
953/// Three outcomes, all of them a page rather than an error: text, something that is not
954/// text, and something too big to be worth rendering. The last says how big, because
955/// that is the only useful thing left to say about it.
956#[component]
957pub(super) async fn blob(
958 handle: &str,
959 name: &str,
960 rev: &RefName,
961 path: &RepoPath,
962 file: &FileView,
963) -> Result {
964 view! {
965 <div class="overflow-hidden rounded-lg border border-border">
966 <div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-2.5">
967 crumbs(handle: handle, name: name, rev: rev, path: path)
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
968 <span class="flex items-center gap-3 font-mono text-xs text-muted-foreground">
969 (size_of(file.size))
970 // The way out for anything the page cannot show — a binary, an
971 // oversized file — and the URL to hand to `curl`.
972 <a
973 href=(raw_url(handle, name, rev, path))
974 class="inline-flex items-center gap-1 hover:text-foreground"
975 >
976 icon(data: iconify_icon!("feather:download"), attrs: attributes! {
977 class="size-3.5"
978 })
979 "Raw"
980 </a>
981 </span>
dce0bf3feat: browse a repository's files and history8d
982 </div>
983
984 match &file.text {
985 Some(text) => source(text: text.as_str()),
986 None if file.too_large => <p class="px-4 py-6 text-center text-sm text-muted-foreground">
987 "This file is " (size_of(file.size)) ", which is too large to display. Clone the repository to read it."
988 </p>,
989 None => <p class="px-4 py-6 text-center text-sm text-muted-foreground">
990 "This file cannot be displayed as text."
991 </p>,
992 }
993 </div>
994 }
995}
996
997/// A file's contents, with line numbers.
998///
999/// A table rather than a `<pre>` with a gutter: the numbers stay put when the code
1000/// scrolls sideways, and selecting the code does not drag the numbers along with it.
1001#[component]
1002async fn source(text: &str) -> Result {
1003 view! {
1004 <div class="overflow-x-auto">
1005 <table class="w-full border-collapse font-mono text-xs leading-relaxed">
1006 <tbody>
1007 for (index, line) in text.lines().enumerate() {
1008 <tr>
1009 <td class="w-px select-none border-r border-border px-3 text-right align-top text-muted-foreground">
1010 ((index + 1).to_string())
1011 </td>
1012 <td class="whitespace-pre px-4 align-top">
1013 (if line.is_empty() { " " } else { line })
1014 </td>
1015 </tr>
1016 }
1017 </tbody>
1018 </table>
1019 </div>
1020 }
1021}
1022
1023/// The commit log — the most recent commits, newest first, and no paging in v1.
1024#[component]
1025async fn commit_log(commits: &[CommitSummary]) -> Result {
1026 view! {
1027 if commits.is_empty() {
1028 <p class="rounded-lg border border-border px-4 py-10 text-center text-sm text-muted-foreground">
1029 "No commits yet."
1030 </p>
1031 } else {
1032 <ul class="divide-y divide-border rounded-lg border border-border">
1033 for commit in commits {
1034 <li class="px-4 py-3">
1035 <div class="flex items-baseline justify-between gap-4">
1036 <p class="text-sm font-medium">(&commit.summary)</p>
1037 <code class="shrink-0 font-mono text-xs text-muted-foreground">
1038 (commit.id.short())
1039 </code>
1040 </div>
1041 <p class="mt-1 text-xs text-muted-foreground">
1042 (&commit.author_name)
1043 " committed "
1044 <span title=(timestamp(commit.committed_at))>(ago(commit.committed_at))</span>
1045 </p>
1046 </li>
1047 }
1048 </ul>
1049 }
1050 }
1051}
1052
1053#[cfg(test)]
1054mod tests {
1055 use std::time::Duration;
1056
1057 use super::*;
1058
1059 fn rev(value: &str) -> RefName {
1060 RefName::new(value).expect("valid revision")
1061 }
1062
1063 #[test]
1064 fn a_root_tree_url_has_no_separator() {
1065 assert_eq!(
1066 tree_url("ada", "steid", &rev("main"), &RepoPath::root()),
1067 "/ada/repos/steid/tree/main"
1068 );
1069 }
1070
1071 #[test]
1072 fn a_path_follows_the_separator_with_its_slashes_intact() {
1073 let path = RepoPath::new("src/domain/repo.rs").expect("valid");
1074
1075 assert_eq!(
1076 tree_url("ada", "steid", &rev("main"), &path),
1077 "/ada/repos/steid/tree/main/-/src/domain/repo.rs"
1078 );
1079 }
1080
1081 #[test]
1082 fn a_revisions_slashes_are_encoded_so_it_stays_one_segment() {
1083 // Otherwise `feature/login` would look like a revision plus a path, which is
1084 // the ambiguity the separator exists to remove.
1085 assert_eq!(
1086 tree_url("ada", "steid", &rev("feature/login"), &RepoPath::root()),
1087 "/ada/repos/steid/tree/feature%2Flogin"
1088 );
1089 }
1090
1091 #[test]
1092 fn names_needing_escaping_are_encoded() {
1093 let path = RepoPath::new("docs/a b#c.md").expect("valid");
1094
1095 assert_eq!(
1096 tree_url("ada", "steid", &rev("main"), &path),
1097 "/ada/repos/steid/tree/main/-/docs/a%20b%23c.md"
1098 );
1099 }
1100
1101 #[test]
1102 fn the_log_url_is_the_default_branch_when_no_revision_is_named() {
1103 assert_eq!(log_url("ada", "steid", ""), "/ada/repos/steid/log");
1104 assert_eq!(
1105 log_url("ada", "steid", "feature/login"),
1106 "/ada/repos/steid/log/feature%2Flogin"
1107 );
1108 }
1109
4ef3945feat: repository settings, README rendering, branch switcher, raw files7d
1110 #[test]
1111 fn a_raw_url_always_carries_a_path() {
1112 let path = RepoPath::new("src/main.rs").expect("valid");
1113
1114 assert_eq!(
1115 raw_url("ada", "steid", &rev("main"), &path),
1116 "/ada/repos/steid/raw/main/-/src/main.rs"
1117 );
1118 assert_eq!(
1119 raw_url("ada", "steid", &rev("feature/login"), &path),
1120 "/ada/repos/steid/raw/feature%2Flogin/-/src/main.rs"
1121 );
1122 }
1123
1124 #[test]
1125 fn a_raw_response_carries_the_whole_policy() {
1126 let response = raw_response("notes.txt", b"hello".to_vec()).expect("should build");
1127 let header = |name: &str| {
1128 response
1129 .headers()
1130 .get(name)
1131 .and_then(|value| value.to_str().ok())
1132 .unwrap_or_default()
1133 .to_owned()
1134 };
1135
1136 // Each of these is load-bearing on its own; see `raw_response`.
1137 assert_eq!(header("content-type"), "application/octet-stream");
1138 assert_eq!(header("x-content-type-options"), "nosniff");
1139 assert!(header("content-disposition").starts_with("attachment;"));
1140 assert_eq!(
1141 header("content-security-policy"),
1142 "default-src \'none\'; sandbox"
1143 );
1144 }
1145
1146 #[test]
1147 fn a_disposition_carries_both_spellings_of_the_name() {
1148 assert_eq!(
1149 disposition("notes.txt"),
1150 "attachment; filename=\"notes.txt\"; filename*=UTF-8\'\'notes.txt"
1151 );
1152 }
1153
1154 #[test]
1155 fn a_disposition_cannot_be_escaped_by_a_filename() {
1156 // A file name is repository content, so it is somebody else\'s input arriving
1157 // in a header. A quote would end the quoted string and a newline would start a
1158 // header of its own.
1159 let hostile = disposition("a\"; x=1\r\nSet-Cookie: nope=1");
1160
1161 assert!(!hostile.contains('\r'));
1162 assert!(!hostile.contains('\n'));
1163 assert_eq!(hostile.matches('"').count(), 2);
1164 }
1165
1166 #[test]
1167 fn a_nameless_file_still_downloads_as_something() {
1168 assert!(disposition("...").starts_with("attachment; filename=\"file\""));
1169 }
1170
1171 #[test]
1172 fn a_non_ascii_name_survives_in_the_extended_form() {
1173 let value = disposition("日本語.txt");
1174
1175 // The plain form is reduced to what a header can carry safely; the real name
1176 // rides along percent-encoded, which is what a modern client uses.
1177 assert!(value.contains("filename=\"___.txt\""));
1178 assert!(value.contains("filename*=UTF-8\'\'%E6%97%A5%E6%9C%AC%E8%AA%9E.txt"));
1179 }
1180
1181 #[test]
1182 fn the_switcher_marks_the_revision_it_is_on() {
1183 let refs = [RefName::from_trusted("main"), RefName::from_trusted("next")];
1184 let path = RepoPath::new("src").expect("valid");
1185 let links = ref_links("ada", "steid", &refs, "next", &Switch::Tree(&path));
1186
1187 assert_eq!(links[0].href, "/ada/repos/steid/tree/main/-/src");
1188 assert!(!links[0].current);
1189 assert!(links[1].current);
1190 }
1191
1192 #[test]
1193 fn switching_from_the_log_stays_on_the_log() {
1194 let refs = [RefName::from_trusted("v1.0")];
1195 let links = ref_links("ada", "steid", &refs, "main", &Switch::Log);
1196
1197 assert_eq!(links[0].href, "/ada/repos/steid/log/v1.0");
1198 }
1199
1200 #[test]
1201 fn an_object_id_is_labelled_as_a_commit_rather_than_a_branch() {
1202 let id = "0123456789abcdef0123456789abcdef01234567";
1203
1204 assert!(is_object_id(id));
1205 assert_eq!(rev_label(id, false), "0123456");
1206 // A branch that happens to look like hex is still shown by its name.
1207 assert_eq!(rev_label("deadbeef", true), "deadbeef");
1208 assert_eq!(rev_label("main", false), "main");
1209 }
1210
dce0bf3feat: browse a repository's files and history8d
1211 #[test]
1212 fn sizes_read_as_sizes() {
1213 assert_eq!(size_of(0), "0 B");
1214 assert_eq!(size_of(999), "999 B");
1215 assert_eq!(size_of(1024), "1.0 KB");
1216 assert_eq!(size_of(1_048_576), "1.0 MB");
1217 assert_eq!(size_of(1_572_864), "1.5 MB");
1218 }
1219
1220 #[test]
1221 fn elapsed_time_reads_as_words() {
1222 let now = SystemTime::now();
1223 let since = |seconds| ago(now - Duration::from_secs(seconds));
1224
1225 assert_eq!(since(5), "just now");
1226 assert_eq!(since(60), "1 minute ago");
1227 assert_eq!(since(7200), "2 hours ago");
1228 assert_eq!(since(86_400 * 3), "3 days ago");
1229 assert_eq!(since(86_400 * 400), "1 year ago");
1230 }
1231
1232 #[test]
1233 fn a_commit_from_the_future_reads_as_now_rather_than_as_a_negative() {
1234 // A commit carries whoever made it's clock, so this happens.
1235 assert_eq!(
1236 ago(SystemTime::now() + Duration::from_secs(3600)),
1237 "just now"
1238 );
1239 }
1240
1241 #[test]
1242 fn timestamps_are_utc_calendar_dates() {
1243 assert_eq!(
1244 timestamp(UNIX_EPOCH + Duration::from_secs(0)),
1245 "1970-01-01 00:00 UTC"
1246 );
1247 // 2026-08-29T12:34:00Z
1248 assert_eq!(
1249 timestamp(UNIX_EPOCH + Duration::from_secs(1_788_006_840)),
1250 "2026-08-29 12:34 UTC"
1251 );
1252 // A leap day, which is what the calendar arithmetic exists to get right.
1253 assert_eq!(
1254 timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)),
1255 "2024-02-29 00:00 UTC"
1256 );
1257 }
1258}