| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | use std::{ |
| 23 | collections::HashMap, |
| 24 | time::{SystemTime, UNIX_EPOCH}, |
| 25 | }; |
| 26 | |
| 27 | use topcoat::{ |
| 28 | Result, |
| 29 | context::Cx, |
| 30 | icon::{icon, iconify::iconify_icon}, |
| 31 | router::{ |
| 32 | Body, Response, StatusCode, |
| 33 | error::{RouterErrorExt, not_found}, |
| 34 | header::{CONTENT_DISPOSITION, CONTENT_TYPE}, |
| 35 | page, path_param, query_params, route, |
| 36 | }, |
| 37 | view::{Unescaped, attributes, component, view}, |
| 38 | }; |
| 39 | |
| 40 | use crate::{ |
| 41 | application::{ |
| 42 | Browsed, EntryDetail, FileView, RepoView, |
| 43 | browse::resolve_relative, |
| 44 | browse::{RawFile, RefList, list_refs, read_raw_file}, |
| 45 | browse_repo, repo_log, |
| 46 | }, |
| 47 | components::badge::{BadgeVariant, badge}, |
| 48 | domain::{CommitSummary, EntryCommit, EntryKind, RefName, RepoPath, TreeEntry}, |
| 49 | infrastructure::highlight::{Source, SourceLine, language_of}, |
| 50 | }; |
| 51 | |
| 52 | use super::{ |
| 53 | atom::{commits_feed_path, feed_link}, |
| 54 | blame::{FileTab, blame_url, view_toggle}, |
| 55 | commit::commit_url, |
| 56 | context::{current_actor, highlights, memberships, orgs, queries, repos, server_error}, |
| 57 | layout::wide, |
| 58 | markdown, |
| 59 | paging::{Pages, list_pages, requested_page, showing}, |
| 60 | refs::{branches_url, tags_url}, |
| 61 | repo::{Tab, clone_url_for, repo_for, repo_header, split_fragment}, |
| 62 | search::search_form, |
| 63 | }; |
| 64 | |
| 65 | |
| 66 | #[path_param] |
| 67 | struct Rev(str); |
| 68 | |
| 69 | |
| 70 | #[path_param] |
| 71 | struct Path(str); |
| 72 | |
| 73 | |
| 74 | |
| 75 | #[query_params(error = bad_request)] |
| 76 | pub(super) struct PageQuery { |
| 77 | pub page: Option<String>, |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | #[query_params(error = bad_request)] |
| 87 | struct ViewQuery { |
| 88 | view: Option<String>, |
| 89 | } |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | fn rev_param(cx: &Cx) -> Result<RefName> { |
| 96 | Ok(RefName::new(path_param::<Rev>(cx)).map_err(|_| not_found())?) |
| 97 | } |
| 98 | |
| 99 | |
| 100 | fn path_arg(cx: &Cx) -> Result<RepoPath> { |
| 101 | Ok(RepoPath::new(path_param::<Path>(cx)).map_err(|_| not_found())?) |
| 102 | } |
| 103 | |
| 104 | #[page("/{handle}/repos/{name}/tree/{rev}")] |
| 105 | async fn tree_root_page(cx: &Cx) -> Result { |
| 106 | let rev = rev_param(cx)?; |
| 107 | |
| 108 | view! { browsing(rev: Some(rev), path: RepoPath::root(), show_source: false) } |
| 109 | } |
| 110 | |
| 111 | #[page("/{handle}/repos/{name}/tree/{rev}/-/{*path}")] |
| 112 | async fn tree_path_page(cx: &Cx) -> Result { |
| 113 | let rev = rev_param(cx)?; |
| 114 | let path = path_arg(cx)?; |
| 115 | let show_source = wants_source(cx)?; |
| 116 | |
| 117 | view! { browsing(rev: Some(rev), path: path, show_source: show_source) } |
| 118 | } |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | fn wants_source(cx: &Cx) -> Result<bool> { |
| 125 | Ok(query_params::<ViewQuery>(cx)?.view.as_deref() == Some("source")) |
| 126 | } |
| 127 | |
| 128 | #[page("/{handle}/repos/{name}/log")] |
| 129 | async fn log_page(_cx: &Cx) -> Result { |
| 130 | view! { history(rev: None) } |
| 131 | } |
| 132 | |
| 133 | #[page("/{handle}/repos/{name}/log/{rev}")] |
| 134 | async fn log_rev_page(cx: &Cx) -> Result { |
| 135 | let rev = rev_param(cx)?; |
| 136 | |
| 137 | view! { history(rev: Some(rev)) } |
| 138 | } |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | #[route(GET "/{handle}/repos/{name}/raw/{rev}/-/{*path}")] |
| 149 | async fn raw_page(cx: &Cx) -> Result<Response<Body>> { |
| 150 | let rev = rev_param(cx)?; |
| 151 | let path = path_arg(cx)?; |
| 152 | let repo = repo_for(cx).await?; |
| 153 | |
| 154 | let raw = read_raw_file( |
| 155 | &repo.handle, |
| 156 | &repo.name, |
| 157 | Some(&rev), |
| 158 | &path, |
| 159 | ¤t_actor(cx).await?, |
| 160 | &orgs(cx), |
| 161 | &memberships(cx), |
| 162 | &repos(cx), |
| 163 | &queries(cx), |
| 164 | ) |
| 165 | .await |
| 166 | .map_err(server_error)? |
| 167 | .ok_or_not_found()?; |
| 168 | |
| 169 | match raw { |
| 170 | RawFile::Ready { name, content } => raw_response(&name, content), |
| 171 | |
| 172 | |
| 173 | RawFile::TooLarge { size } => Response::builder() |
| 174 | .status(StatusCode::PAYLOAD_TOO_LARGE) |
| 175 | .header(CONTENT_TYPE, "text/plain; charset=utf-8") |
| 176 | .header(NOSNIFF.0, NOSNIFF.1) |
| 177 | .body(Body::from(format!( |
| 178 | "This file is {}, which is larger than this instance serves raw. Clone the repository to read it.\n", |
| 179 | size_of(size) |
| 180 | ))) |
| 181 | .map_err(server_error), |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | pub(super) async fn browsed_at( |
| 189 | cx: &Cx, |
| 190 | repo: &RepoView, |
| 191 | rev: Option<&RefName>, |
| 192 | path: &RepoPath, |
| 193 | ) -> Result<Browsed> { |
| 194 | Ok(browse_repo( |
| 195 | &repo.handle, |
| 196 | &repo.name, |
| 197 | rev, |
| 198 | path, |
| 199 | ¤t_actor(cx).await?, |
| 200 | &orgs(cx), |
| 201 | &memberships(cx), |
| 202 | &repos(cx), |
| 203 | &queries(cx), |
| 204 | ) |
| 205 | .await |
| 206 | .map_err(server_error)? |
| 207 | .ok_or_not_found()?) |
| 208 | } |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | pub(super) async fn refs_for(cx: &Cx, repo: &RepoView) -> Result<RefList> { |
| 218 | Ok(list_refs( |
| 219 | &repo.handle, |
| 220 | &repo.name, |
| 221 | ¤t_actor(cx).await?, |
| 222 | &orgs(cx), |
| 223 | &memberships(cx), |
| 224 | &repos(cx), |
| 225 | &queries(cx), |
| 226 | ) |
| 227 | .await |
| 228 | .map_err(server_error)? |
| 229 | .ok_or_not_found()?) |
| 230 | } |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | #[component] |
| 238 | async fn browsing(cx: &Cx, rev: Option<RefName>, path: RepoPath, show_source: bool) -> Result { |
| 239 | let repo = repo_for(cx).await?; |
| 240 | let browsed = browsed_at(cx, &repo, rev.as_ref(), &path).await?; |
| 241 | let clone = clone_url_for(cx, &repo); |
| 242 | |
| 243 | |
| 244 | let refs = match browsed { |
| 245 | Browsed::Empty => RefList::default(), |
| 246 | _ => refs_for(cx, &repo).await?, |
| 247 | }; |
| 248 | |
| 249 | let at = browsed_rev(&browsed); |
| 250 | let switch = Switch::Tree(&path); |
| 251 | let handle = repo.handle.as_str(); |
| 252 | let name = repo.name.as_str(); |
| 253 | let known = RefName::new(at).is_ok_and(|at| refs.contains(&at)); |
| 254 | let branches = ref_links(handle, name, &refs.branches, at, &switch); |
| 255 | let tags = ref_links(handle, name, &refs.tags, at, &switch); |
| 256 | |
| 257 | view! { |
| 258 | wide( |
| 259 | repo_header( |
| 260 | repo: &repo, |
| 261 | rev: at, |
| 262 | active: Tab::Code, |
| 263 | rev_switcher(current: at, known: known, branches: &branches, tags: &tags) |
| 264 | ) |
| 265 | |
| 266 | match &browsed { |
| 267 | Browsed::Empty => empty_repo(url: clone.as_str()), |
| 268 | Browsed::Directory { rev, path, entries, history: last_commits, details } => directory( |
| 269 | handle: repo.handle.as_str(), |
| 270 | name: repo.name.as_str(), |
| 271 | rev: rev, |
| 272 | path: path, |
| 273 | entries: entries, |
| 274 | listing: Listing::of(last_commits, details), |
| 275 | ), |
| 276 | Browsed::File { rev, path, file } => blob( |
| 277 | handle: repo.handle.as_str(), |
| 278 | name: repo.name.as_str(), |
| 279 | rev: rev, |
| 280 | path: path, |
| 281 | file: file, |
| 282 | show_source: show_source, |
| 283 | ), |
| 284 | } |
| 285 | ) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | |
| 290 | #[component] |
| 291 | async fn history(cx: &Cx, rev: Option<RefName>) -> Result { |
| 292 | let repo = repo_for(cx).await?; |
| 293 | |
| 294 | let log = repo_log( |
| 295 | &repo.handle, |
| 296 | &repo.name, |
| 297 | rev.as_ref(), |
| 298 | requested_page(query_params::<PageQuery>(cx)?.page.as_deref()), |
| 299 | ¤t_actor(cx).await?, |
| 300 | &orgs(cx), |
| 301 | &memberships(cx), |
| 302 | &repos(cx), |
| 303 | &queries(cx), |
| 304 | ) |
| 305 | .await |
| 306 | .map_err(server_error)? |
| 307 | .ok_or_not_found()?; |
| 308 | |
| 309 | let refs = refs_for(cx, &repo).await?; |
| 310 | let at = rev.as_ref().map(RefName::as_str).unwrap_or_default(); |
| 311 | let handle = repo.handle.as_str(); |
| 312 | let name = repo.name.as_str(); |
| 313 | let known = RefName::new(at).is_ok_and(|at| refs.contains(&at)); |
| 314 | let branches = ref_links(handle, name, &refs.branches, at, &Switch::Log); |
| 315 | let tags = ref_links(handle, name, &refs.tags, at, &Switch::Log); |
| 316 | |
| 317 | |
| 318 | |
| 319 | let feed = match at.is_empty() { |
| 320 | true => commits_feed_path(handle, name), |
| 321 | false => format!( |
| 322 | "{}?rev={}", |
| 323 | commits_feed_path(handle, name), |
| 324 | encode(at, false) |
| 325 | ), |
| 326 | }; |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | let sentence = showing(log.offset(), log.items.len(), log.total, "commits"); |
| 332 | let pages = Pages::numbered(log.page, log.pages, |page| { |
| 333 | format!("{}?page={page}", log_url(handle, name, at)) |
| 334 | }); |
| 335 | |
| 336 | view! { |
| 337 | wide( |
| 338 | repo_header( |
| 339 | repo: &repo, |
| 340 | rev: at, |
| 341 | active: Tab::Commits, |
| 342 | <span class="flex items-center gap-3"> |
| 343 | feed_link(href: feed.as_str()) |
| 344 | // At the default branch the URL names no revision and `repo_log` does |
| 345 | // not report the one it resolved, so the switcher opens with nothing |
| 346 | // marked current rather than guessing. Noted in `plans/current.md`. |
| 347 | rev_switcher(current: at, known: known, branches: &branches, tags: &tags) |
| 348 | </span> |
| 349 | ) |
| 350 | commit_log(handle: handle, name: name, commits: &log.items) |
| 351 | list_pages(summary: sentence.as_str(), pages: &pages) |
| 352 | ) |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | /// The revision a browse landed on, for display. Empty when there is none. |
| 357 | pub(super) fn browsed_rev(browsed: &Browsed) -> &str { |
| 358 | match browsed { |
| 359 | Browsed::Empty => "", |
| 360 | Browsed::Directory { rev, .. } | Browsed::File { rev, .. } => rev.as_str(), |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | // --- Serving bytes ---------------------------------------------------------------- |
| 365 | |
| 366 | /// The header that stops a browser second-guessing a `Content-Type`. |
| 367 | /// |
| 368 | /// A pair rather than a constant string so the name is written once; `http` has no |
| 369 | /// constant for it. |
| 370 | const NOSNIFF: (&str, &str) = ("x-content-type-options", "nosniff"); |
| 371 | |
| 372 | /// What a raw file is served as. |
| 373 | /// |
| 374 | /// **Never the file's own type, and never guessed from its extension.** Steid serves |
| 375 | /// repository contents from the same origin as the application, so a file the origin |
| 376 | /// labels `text/html` runs *as this site*: it reads the session cookie, calls Steid's |
| 377 | /// own endpoints as the viewer, and rewrites the page around it. Somebody pushing |
| 378 | /// `evil.html` would then have stored XSS on every visitor who followed a link to it. |
| 379 | /// The same holds for SVG (scriptable), XML, and anything a browser will render. |
| 380 | /// |
| 381 | /// Today only the repository's owner can push, so the only person who could attack a |
| 382 | /// viewer is the person whose site it is. Milestone 7 adds other users and this endpoint |
| 383 | /// will outlive that assumption, so the policy is written for the world where the bytes |
| 384 | /// are hostile. |
| 385 | /// |
| 386 | /// Four headers, each closing a different door: |
| 387 | /// |
| 388 | /// - `application/octet-stream` — a type no browser renders. Not `text/plain`, which |
| 389 | /// *is* rendered, and which older browsers have been talked into sniffing as HTML. |
| 390 | /// - `nosniff` — without it a browser is free to ignore the type above and decide from |
| 391 | /// the content, which is exactly the guess this policy refuses to make. |
| 392 | /// - `Content-Disposition: attachment` — the file is saved, not shown, so nothing it |
| 393 | /// contains is ever parsed in this origin's context. It also stops a same-origin |
| 394 | /// `<iframe>` from rendering it. |
| 395 | /// - `Content-Security-Policy: default-src 'none'; sandbox` — belt and braces for the |
| 396 | /// case where one of the above is wrong or unsupported. Nothing in the response may |
| 397 | /// load, run, or navigate. |
| 398 | /// |
| 399 | /// The cost is that a raw URL downloads rather than displays. That is the correct trade |
| 400 | /// for a forge serving other people's bytes, and it is what `curl` wants anyway. |
| 401 | fn raw_response(name: &str, content: Vec<u8>) -> Result<Response<Body>> { |
| 402 | Response::builder() |
| 403 | .header(CONTENT_TYPE, "application/octet-stream") |
| 404 | .header(NOSNIFF.0, NOSNIFF.1) |
| 405 | .header(CONTENT_DISPOSITION, disposition(name)) |
| 406 | .header("content-security-policy", "default-src 'none'; sandbox") |
| 407 | .body(Body::from(content)) |
| 408 | .map_err(server_error) |
| 409 | } |
| 410 | |
| 411 | /// The `Content-Disposition` for a downloaded file. |
| 412 | /// |
| 413 | /// Two filenames, per RFC 6266: a plain `filename` every client understands, and a |
| 414 | /// `filename*` carrying the real name as percent-encoded UTF-8 for those that do. The |
| 415 | /// plain one is reduced to characters that cannot end the quoted string or be read as a |
| 416 | /// header of their own — a name is repository content, so a quote or a newline in it |
| 417 | /// would otherwise be header injection. |
| 418 | fn disposition(name: &str) -> String { |
| 419 | let mut safe = String::with_capacity(name.len()); |
| 420 | |
| 421 | for char in name.chars() { |
| 422 | match char { |
| 423 | 'A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_' => safe.push(char), |
| 424 | _ => safe.push('_'), |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | // A name reduced to nothing recognisable — punctuation, or a name written entirely |
| 429 | // in a script the plain form cannot carry — downloads as `file` rather than as |
| 430 | // `___`. The real name is still in `filename*` for anything that reads it. |
| 431 | if !safe.chars().any(|char| char.is_ascii_alphanumeric()) { |
| 432 | safe = "file".to_owned(); |
| 433 | } |
| 434 | |
| 435 | format!( |
| 436 | "attachment; filename=\"{safe}\"; filename*=UTF-8''{}", |
| 437 | encode(name, false) |
| 438 | ) |
| 439 | } |
| 440 | |
| 441 | |
| 442 | |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | pub(super) fn tree_url(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> String { |
| 449 | let encoded = encode(rev.as_str(), false); |
| 450 | |
| 451 | if path.is_root() { |
| 452 | format!("/{handle}/repos/{name}/tree/{encoded}") |
| 453 | } else { |
| 454 | format!( |
| 455 | "/{handle}/repos/{name}/tree/{encoded}/-/{}", |
| 456 | encode(path.as_str(), true) |
| 457 | ) |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | pub(super) fn raw_url(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> String { |
| 466 | format!( |
| 467 | "/{handle}/repos/{name}/raw/{}/-/{}", |
| 468 | encode(rev.as_str(), false), |
| 469 | encode(path.as_str(), true) |
| 470 | ) |
| 471 | } |
| 472 | |
| 473 | |
| 474 | pub(super) fn log_url(handle: &str, name: &str, rev: &str) -> String { |
| 475 | if rev.is_empty() { |
| 476 | format!("/{handle}/repos/{name}/log") |
| 477 | } else { |
| 478 | format!("/{handle}/repos/{name}/log/{}", encode(rev, false)) |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | |
| 483 | |
| 484 | |
| 485 | |
| 486 | |
| 487 | pub(super) fn path_log_url(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> String { |
| 488 | format!( |
| 489 | "/{handle}/repos/{name}/log/{}/-/{}", |
| 490 | encode(rev.as_str(), false), |
| 491 | encode(path.as_str(), true) |
| 492 | ) |
| 493 | } |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | |
| 501 | |
| 502 | |
| 503 | pub(super) enum Switch<'a> { |
| 504 | Tree(&'a RepoPath), |
| 505 | Blame(&'a RepoPath), |
| 506 | Log, |
| 507 | |
| 508 | |
| 509 | PathLog(&'a RepoPath), |
| 510 | |
| 511 | |
| 512 | |
| 513 | Search(&'a str), |
| 514 | } |
| 515 | |
| 516 | |
| 517 | pub(super) struct RefLink { |
| 518 | name: String, |
| 519 | href: String, |
| 520 | current: bool, |
| 521 | } |
| 522 | |
| 523 | pub(super) fn ref_links( |
| 524 | handle: &str, |
| 525 | name: &str, |
| 526 | refs: &[RefName], |
| 527 | current: &str, |
| 528 | switch: &Switch, |
| 529 | ) -> Vec<RefLink> { |
| 530 | refs.iter() |
| 531 | .map(|git_ref| RefLink { |
| 532 | name: git_ref.to_string(), |
| 533 | href: match switch { |
| 534 | Switch::Tree(path) => tree_url(handle, name, git_ref, path), |
| 535 | Switch::Blame(path) => blame_url(handle, name, git_ref, path), |
| 536 | Switch::Log => log_url(handle, name, git_ref.as_str()), |
| 537 | Switch::PathLog(path) => path_log_url(handle, name, git_ref, path), |
| 538 | Switch::Search(query) => super::search::search_url(handle, name, git_ref, query), |
| 539 | }, |
| 540 | current: git_ref.as_str() == current, |
| 541 | }) |
| 542 | .collect() |
| 543 | } |
| 544 | |
| 545 | |
| 546 | |
| 547 | |
| 548 | |
| 549 | fn is_object_id(rev: &str) -> bool { |
| 550 | rev.len() >= 7 && rev.len() <= 64 && rev.chars().all(|char| char.is_ascii_hexdigit()) |
| 551 | } |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | fn rev_label(rev: &str, known: bool) -> String { |
| 558 | if !known && is_object_id(rev) { |
| 559 | rev[..7].to_owned() |
| 560 | } else { |
| 561 | rev.to_owned() |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | |
| 566 | |
| 567 | |
| 568 | |
| 569 | |
| 570 | pub(super) fn encode(value: &str, keep_slash: bool) -> String { |
| 571 | let mut encoded = String::with_capacity(value.len()); |
| 572 | |
| 573 | for byte in value.bytes() { |
| 574 | match byte { |
| 575 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { |
| 576 | encoded.push(byte as char); |
| 577 | } |
| 578 | b'/' if keep_slash => encoded.push('/'), |
| 579 | other => encoded.push_str(&format!("%{other:02X}")), |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | encoded |
| 584 | } |
| 585 | |
| 586 | |
| 587 | |
| 588 | |
| 589 | pub(super) fn size_of(bytes: u64) -> String { |
| 590 | const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"]; |
| 591 | |
| 592 | if bytes < 1024 { |
| 593 | return format!("{bytes} B"); |
| 594 | } |
| 595 | |
| 596 | let mut value = bytes as f64 / 1024.0; |
| 597 | let mut unit = UNITS[0]; |
| 598 | |
| 599 | for next in &UNITS[1..] { |
| 600 | if value < 1024.0 { |
| 601 | break; |
| 602 | } |
| 603 | |
| 604 | value /= 1024.0; |
| 605 | unit = next; |
| 606 | } |
| 607 | |
| 608 | format!("{value:.1} {unit}") |
| 609 | } |
| 610 | |
| 611 | |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | pub(super) fn ago(time: SystemTime) -> String { |
| 617 | let Ok(elapsed) = SystemTime::now().duration_since(time) else { |
| 618 | return "just now".to_owned(); |
| 619 | }; |
| 620 | |
| 621 | let seconds = elapsed.as_secs(); |
| 622 | |
| 623 | let (count, unit) = match seconds { |
| 624 | 0..=59 => return "just now".to_owned(), |
| 625 | 60..=3599 => (seconds / 60, "minute"), |
| 626 | 3600..=86_399 => (seconds / 3600, "hour"), |
| 627 | 86_400..=2_591_999 => (seconds / 86_400, "day"), |
| 628 | 2_592_000..=31_535_999 => (seconds / 2_592_000, "month"), |
| 629 | _ => (seconds / 31_536_000, "year"), |
| 630 | }; |
| 631 | |
| 632 | if count == 1 { |
| 633 | format!("1 {unit} ago") |
| 634 | } else { |
| 635 | format!("{count} {unit}s ago") |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | |
| 640 | pub(super) fn timestamp(time: SystemTime) -> String { |
| 641 | let seconds = time |
| 642 | .duration_since(UNIX_EPOCH) |
| 643 | .map(|since| since.as_secs() as i64) |
| 644 | .unwrap_or(0); |
| 645 | |
| 646 | let (year, month, day) = civil_from_days(seconds.div_euclid(86_400)); |
| 647 | let rest = seconds.rem_euclid(86_400); |
| 648 | |
| 649 | format!( |
| 650 | "{year:04}-{month:02}-{day:02} {:02}:{:02} UTC", |
| 651 | rest / 3600, |
| 652 | (rest % 3600) / 60 |
| 653 | ) |
| 654 | } |
| 655 | |
| 656 | |
| 657 | |
| 658 | |
| 659 | |
| 660 | pub(super) fn civil_from_days(days: i64) -> (i64, u32, u32) { |
| 661 | |
| 662 | let shifted = days + 719_468; |
| 663 | let era = shifted.div_euclid(146_097); |
| 664 | let day_of_era = shifted.rem_euclid(146_097); |
| 665 | |
| 666 | let year_of_era = |
| 667 | (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; |
| 668 | let year = year_of_era + era * 400; |
| 669 | let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); |
| 670 | |
| 671 | let shifted_month = (5 * day_of_year + 2) / 153; |
| 672 | let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32; |
| 673 | let month = if shifted_month < 10 { |
| 674 | shifted_month + 3 |
| 675 | } else { |
| 676 | shifted_month - 9 |
| 677 | } as u32; |
| 678 | |
| 679 | (if month <= 2 { year + 1 } else { year }, month, day) |
| 680 | } |
| 681 | |
| 682 | |
| 683 | |
| 684 | |
| 685 | |
| 686 | |
| 687 | |
| 688 | |
| 689 | |
| 690 | |
| 691 | |
| 692 | |
| 693 | #[component] |
| 694 | pub(super) async fn repo_toolbar( |
| 695 | handle: &str, |
| 696 | name: &str, |
| 697 | rev: &str, |
| 698 | path: &RepoPath, |
| 699 | refs: &RefList, |
| 700 | ) -> Result { |
| 701 | let known = RefName::new(rev).is_ok_and(|at| refs.contains(&at)); |
| 702 | let switch = Switch::Tree(path); |
| 703 | let branches = ref_links(handle, name, &refs.branches, rev, &switch); |
| 704 | let tags = ref_links(handle, name, &refs.tags, rev, &switch); |
| 705 | |
| 706 | view! { |
| 707 | <div class="mb-2 flex flex-wrap items-center gap-x-3 gap-y-2"> |
| 708 | rev_switcher(current: rev, known: known, branches: &branches, tags: &tags) |
| 709 | <span class="inline-flex items-center gap-1.5 text-xs text-muted-foreground"> |
| 710 | icon(data: iconify_icon!("feather:git-branch"), attrs: attributes! { |
| 711 | class="size-3.5" |
| 712 | }) |
| 713 | <a href=(branches_url(handle, name)) class="font-mono hover:text-foreground"> |
| 714 | (counted(refs.branches.len(), "branch", "branches")) |
| 715 | </a> |
| 716 | "·" |
| 717 | <a href=(tags_url(handle, name)) class="font-mono hover:text-foreground"> |
| 718 | (counted(refs.tags.len(), "tag", "tags")) |
| 719 | </a> |
| 720 | </span> |
| 721 | |
| 722 | <div class="w-full sm:ml-auto sm:w-auto"> |
| 723 | search_form( |
| 724 | handle: handle, |
| 725 | name: name, |
| 726 | rev: rev, |
| 727 | query: "", |
| 728 | full_width: false, |
| 729 | ) |
| 730 | </div> |
| 731 | </div> |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | |
| 736 | fn counted(count: usize, one: &str, many: &str) -> String { |
| 737 | format!("{count} {}", if count == 1 { one } else { many }) |
| 738 | } |
| 739 | |
| 740 | |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | #[component] |
| 750 | pub(super) async fn rev_switcher( |
| 751 | current: &str, |
| 752 | known: bool, |
| 753 | branches: &[RefLink], |
| 754 | tags: &[RefLink], |
| 755 | ) -> Result { |
| 756 | let label = rev_label(current, known); |
| 757 | let empty = branches.is_empty() && tags.is_empty(); |
| 758 | |
| 759 | view! { |
| 760 | if empty { |
| 761 | |
| 762 | |
| 763 | if !current.is_empty() { |
| 764 | <span class="inline-flex items-center gap-1.5 font-mono text-xs text-muted-foreground"> |
| 765 | icon(data: iconify_icon!("feather:git-branch"), attrs: attributes! { |
| 766 | class="size-3.5" |
| 767 | }) |
| 768 | (label) |
| 769 | </span> |
| 770 | } |
| 771 | } else { |
| 772 | <details class="group relative inline-block"> |
| 773 | <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"> |
| 774 | icon( |
| 775 | data: if known { |
| 776 | iconify_icon!("feather:git-branch") |
| 777 | } else { |
| 778 | iconify_icon!("feather:git-commit") |
| 779 | }, |
| 780 | attrs: attributes! { class="size-3.5" }, |
| 781 | ) |
| 782 | (if label.is_empty() { "Revision" } else { label.as_str() }) |
| 783 | icon( |
| 784 | data: iconify_icon!("feather:chevron-down"), |
| 785 | attrs: attributes! { |
| 786 | class="size-3.5 transition-transform group-open:rotate-180" |
| 787 | }, |
| 788 | ) |
| 789 | </summary> |
| 790 | |
| 791 | <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"> |
| 792 | if !known && !current.is_empty() { |
| 793 | <p class="px-2 py-1.5 font-mono text-xs text-muted-foreground"> |
| 794 | "At commit " (label) |
| 795 | </p> |
| 796 | } |
| 797 | |
| 798 | ref_group(title: "Branches", links: branches) |
| 799 | ref_group(title: "Tags", links: tags) |
| 800 | </div> |
| 801 | </details> |
| 802 | } |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | |
| 807 | |
| 808 | |
| 809 | |
| 810 | |
| 811 | #[component] |
| 812 | async fn ref_group(title: &str, links: &[RefLink]) -> Result { |
| 813 | view! { |
| 814 | if !links.is_empty() { |
| 815 | <p class="px-2 pt-1.5 pb-1 text-xs font-medium uppercase tracking-wider text-muted-foreground"> |
| 816 | (title) |
| 817 | </p> |
| 818 | <ul> |
| 819 | for link in links { |
| 820 | <li> |
| 821 | <a |
| 822 | href=(&link.href) |
| 823 | class=(format!( |
| 824 | "flex items-center gap-2 rounded-md px-2 py-1.5 font-mono text-sm hover:bg-foreground/5 {}", |
| 825 | if link.current { "font-medium" } else { "" }, |
| 826 | )) |
| 827 | > |
| 828 | <span class="truncate">(&link.name)</span> |
| 829 | if link.current { |
| 830 | <span class="ml-auto text-muted-foreground"> |
| 831 | icon( |
| 832 | data: iconify_icon!("feather:check"), |
| 833 | label: "Current", |
| 834 | attrs: attributes! { class="size-3.5" }, |
| 835 | ) |
| 836 | </span> |
| 837 | } |
| 838 | </a> |
| 839 | </li> |
| 840 | } |
| 841 | </ul> |
| 842 | } |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | #[component] |
| 851 | pub(super) async fn empty_repo(url: &str) -> Result { |
| 852 | let push = format!("git remote add origin {url}\ngit branch -M main\ngit push -u origin main"); |
| 853 | |
| 854 | view! { |
| 855 | <div class="rounded-lg border border-border px-4 py-5"> |
| 856 | <p class="text-sm text-muted-foreground"> |
| 857 | "This repository has no commits yet. Push one to see it here." |
| 858 | </p> |
| 859 | <p class="mt-4 text-xs font-medium uppercase tracking-wider text-muted-foreground"> |
| 860 | "Push an existing repository" |
| 861 | </p> |
| 862 | <pre class="mt-2 overflow-x-auto rounded-lg border border-border bg-surface px-4 py-3 font-mono text-sm">(push)</pre> |
| 863 | </div> |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | |
| 871 | #[component] |
| 872 | pub(super) async fn crumbs(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> Result { |
| 873 | let parts: Vec<&str> = path.components().collect(); |
| 874 | let mut walked = RepoPath::root(); |
| 875 | let mut trail: Vec<(String, String)> = Vec::new(); |
| 876 | |
| 877 | for (index, part) in parts.iter().enumerate() { |
| 878 | walked = walked.join(part); |
| 879 | |
| 880 | let href = if index + 1 == parts.len() { |
| 881 | String::new() |
| 882 | } else { |
| 883 | tree_url(handle, name, rev, &walked) |
| 884 | }; |
| 885 | |
| 886 | trail.push(((*part).to_owned(), href)); |
| 887 | } |
| 888 | |
| 889 | view! { |
| 890 | <div class="flex flex-wrap items-center gap-1 font-mono text-sm"> |
| 891 | <a |
| 892 | href=(tree_url(handle, name, rev, &RepoPath::root())) |
| 893 | class="text-muted-foreground hover:text-foreground" |
| 894 | >(name)</a> |
| 895 | |
| 896 | for (part, href) in &trail { |
| 897 | <span class="text-muted-foreground">"/"</span> |
| 898 | match href.is_empty() { |
| 899 | true => <span class="font-medium">(part)</span>, |
| 900 | false => <a href=(href) class="text-muted-foreground hover:text-foreground">(part)</a>, |
| 901 | } |
| 902 | } |
| 903 | </div> |
| 904 | } |
| 905 | } |
| 906 | |
| 907 | /// What a listing knows about its entries beyond the tree itself. |
| 908 | /// |
| 909 | /// One parameter rather than one map per fact: every one of them is sparse, keyed by |
| 910 | /// entry name, and read by the same row at the same moment. Copied rather than borrowed |
| 911 | /// because it is two references and nothing else. |
| 912 | #[derive(Clone, Copy)] |
| 913 | pub(super) struct Listing<'a> { |
| 914 | pub last_commits: &'a HashMap<String, EntryCommit>, |
| 915 | pub details: &'a HashMap<String, EntryDetail>, |
| 916 | } |
| 917 | |
| 918 | impl<'a> Listing<'a> { |
| 919 | pub fn of( |
| 920 | last_commits: &'a HashMap<String, EntryCommit>, |
| 921 | details: &'a HashMap<String, EntryDetail>, |
| 922 | ) -> Self { |
| 923 | Self { |
| 924 | last_commits, |
| 925 | details, |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | /// A directory listing. |
| 931 | /// |
| 932 | /// Entries arrive ordered by the use case — directories first, then case-insensitively |
| 933 | /// by name — so nothing here re-sorts them. |
| 934 | #[component] |
| 935 | pub(super) async fn directory( |
| 936 | handle: &str, |
| 937 | name: &str, |
| 938 | rev: &RefName, |
| 939 | path: &RepoPath, |
| 940 | entries: &[TreeEntry], |
| 941 | listing: Listing<'_>, |
| 942 | ) -> Result { |
| 943 | // The root's history is the whole log, which already has a page and a URL of its |
| 944 | // own; only a subdirectory needs the narrowed one. |
| 945 | // Named for what it holds, not for the page it points at: `history` is a |
| 946 | // `#[component]` in this module and so a unit struct in scope — a `let history` |
| 947 | // would parse as a pattern rather than a new binding. |
| 948 | let history_href = match path.is_root() { |
| 949 | true => log_url(handle, name, rev.as_str()), |
| 950 | false => path_log_url(handle, name, rev, path), |
| 951 | }; |
| 952 | |
| 953 | view! { |
| 954 | <div class="overflow-hidden rounded-lg border border-border"> |
| 955 | <div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-2.5"> |
| 956 | crumbs(handle: handle, name: name, rev: rev, path: path) |
| 957 | // The directory's own history, in the same muted mono as a file |
| 958 | // header's — the entry point for "what has been happening in here", |
| 959 | // which the log answers only for the repository as a whole. |
| 960 | <a |
| 961 | href=(&history_href) |
| 962 | class="font-mono text-xs text-muted-foreground hover:text-foreground" |
| 963 | >"History"</a> |
| 964 | </div> |
| 965 | |
| 966 | if entries.is_empty() { |
| 967 | <p class="px-4 py-6 text-center text-sm text-muted-foreground"> |
| 968 | "This directory is empty." |
| 969 | </p> |
| 970 | } else { |
| 971 | <ul class="divide-y divide-border text-sm"> |
| 972 | match path.parent() { |
| 973 | Some(parent) => <li class="px-4 py-2"> |
| 974 | <a |
| 975 | href=(tree_url(handle, name, rev, &parent)) |
| 976 | class="inline-flex items-center gap-2 font-mono text-muted-foreground hover:text-foreground" |
| 977 | > |
| 978 | icon(data: iconify_icon!("feather:corner-left-up"), attrs: attributes! { |
| 979 | class="size-4" |
| 980 | }) |
| 981 | ".." |
| 982 | </a> |
| 983 | </li>, |
| 984 | None => "", |
| 985 | } |
| 986 | |
| 987 | for entry in entries { |
| 988 | <li class="flex items-center gap-3 px-4 py-2"> |
| 989 | entry_row( |
| 990 | handle: handle, |
| 991 | name: name, |
| 992 | rev: rev, |
| 993 | path: path, |
| 994 | entry: entry, |
| 995 | listing: listing, |
| 996 | ) |
| 997 | </li> |
| 998 | } |
| 999 | </ul> |
| 1000 | } |
| 1001 | </div> |
| 1002 | } |
| 1003 | } |
| 1004 | |
| 1005 | /// One entry in a listing. |
| 1006 | /// |
| 1007 | /// A symlink and a submodule are their own kinds, not files: a submodule is another |
| 1008 | /// repository Steid cannot look inside, so it is labelled and left unlinked rather |
| 1009 | /// than offered as a click that would 404. |
| 1010 | #[component] |
| 1011 | async fn entry_row( |
| 1012 | handle: &str, |
| 1013 | name: &str, |
| 1014 | rev: &RefName, |
| 1015 | path: &RepoPath, |
| 1016 | entry: &TreeEntry, |
| 1017 | listing: Listing<'_>, |
| 1018 | ) -> Result { |
| 1019 | let last = listing.last_commits.get(&entry.name); |
| 1020 | let detail = listing.details.get(&entry.name); |
| 1021 | let detail = detail.cloned().unwrap_or_default(); |
| 1022 | |
| 1023 | // Where the name goes when clicked, in the three cases a listing has: |
| 1024 | // |
| 1025 | // - a submodule links **out**, to the upstream `.gitmodules` names, when that is an |
| 1026 | // `https://` one. Steid cannot look inside another repository, so the alternative |
| 1027 | // is a click that 404s. |
| 1028 | // - a symlink follows itself, to whatever it points at inside this repository. A |
| 1029 | // link out of the tree, or one Steid could not read, falls back to the blob — |
| 1030 | // which is the link's own text, since a symlink is stored as its target path. |
| 1031 | // - everything else is the path it is. |
| 1032 | let href = match (&detail.url, &detail.resolved) { |
| 1033 | (Some(url), _) if entry.kind == EntryKind::Submodule => url.clone(), |
| 1034 | (_, Some(target)) if entry.kind == EntryKind::Symlink => { |
| 1035 | tree_url(handle, name, rev, target) |
| 1036 | } |
| 1037 | _ => tree_url(handle, name, rev, &path.join(&entry.name)), |
| 1038 | }; |
| 1039 | |
| 1040 | // Only a submodule with no upstream to send anyone to. A symlink always has |
| 1041 | // somewhere to go, even if that is only its own contents. |
| 1042 | let linkable = entry.kind != EntryKind::Submodule || detail.url.is_some(); |
| 1043 | |
| 1044 | // An external link, so it carries the two attributes any link out of Steid does. |
| 1045 | let external = entry.kind == EntryKind::Submodule && detail.url.is_some(); |
| 1046 | |
| 1047 | view! { |
| 1048 | <span class="text-muted-foreground"> |
| 1049 | match entry.kind { |
| 1050 | EntryKind::Tree => icon( |
| 1051 | data: iconify_icon!("feather:folder"), |
| 1052 | label: "Directory", |
| 1053 | attrs: attributes! { class="size-4" }, |
| 1054 | ), |
| 1055 | EntryKind::Blob => icon( |
| 1056 | data: iconify_icon!("feather:file"), |
| 1057 | label: "File", |
| 1058 | attrs: attributes! { class="size-4" }, |
| 1059 | ), |
| 1060 | EntryKind::Symlink => icon( |
| 1061 | data: iconify_icon!("feather:link-2"), |
| 1062 | label: "Symlink", |
| 1063 | attrs: attributes! { class="size-4" }, |
| 1064 | ), |
| 1065 | EntryKind::Submodule => icon( |
| 1066 | data: iconify_icon!("feather:package"), |
| 1067 | label: "Submodule", |
| 1068 | attrs: attributes! { class="size-4" }, |
| 1069 | ), |
| 1070 | } |
| 1071 | </span> |
| 1072 | |
| 1073 | match (linkable, external) { |
| 1074 | // The one link in a listing that leaves Steid, so it says so: a click that |
| 1075 | // silently lands on another host is a surprise, and the icon is the same |
| 1076 | // muted size the rest of the row's metadata is. |
| 1077 | (true, true) => <a |
| 1078 | href=(href) |
| 1079 | rel="noopener noreferrer" |
| 1080 | class="inline-flex items-center gap-1 font-mono hover:underline" |
| 1081 | > |
| 1082 | (&entry.name) |
| 1083 | icon( |
| 1084 | data: iconify_icon!("feather:external-link"), |
| 1085 | label: "Opens the submodule's own repository", |
| 1086 | attrs: attributes! { class="size-3 text-muted-foreground" }, |
| 1087 | ) |
| 1088 | </a>, |
| 1089 | (true, false) => <a |
| 1090 | href=(href) |
| 1091 | class=(if entry.kind.is_tree() { |
| 1092 | "font-mono font-medium hover:underline" |
| 1093 | } else { |
| 1094 | "font-mono hover:underline" |
| 1095 | }) |
| 1096 | >(&entry.name)</a>, |
| 1097 | (false, _) => <span class="font-mono">(&entry.name)</span>, |
| 1098 | } |
| 1099 | |
| 1100 | // Where a link points, muted and after the name: part of what the row *is*, |
| 1101 | // and never mistakable for the name itself. Absent when the target could not |
| 1102 | // be read, which is honest — the row then says only that this is a symlink. |
| 1103 | match &detail.target { |
| 1104 | Some(target) => <span class="hidden truncate font-mono text-xs text-muted-foreground sm:inline"> |
| 1105 | "→ " (target) |
| 1106 | </span>, |
| 1107 | None => "", |
| 1108 | } |
| 1109 | |
| 1110 | match entry.kind { |
| 1111 | EntryKind::Symlink => badge(variant: BadgeVariant::Outline, "symlink"), |
| 1112 | EntryKind::Submodule => badge(variant: BadgeVariant::Outline, "submodule"), |
| 1113 | _ => "", |
| 1114 | } |
| 1115 | |
| 1116 | // The two columns 0006 deferred until a kept-alive `cat-file` made them |
| 1117 | // affordable. Muted and small: what changed and when is context for the name, |
| 1118 | // not a second thing to read. **Dropped below `md` rather than wrapped** — the |
| 1119 | // rule the branches page settled: a row is a scanning surface, and a row that |
| 1120 | // wraps stops being one. The latest-commit bar above says the same thing once |
| 1121 | // for the directory as a whole, which is what a narrow viewport keeps. |
| 1122 | match last { |
| 1123 | Some(commit) => <a |
| 1124 | href=(commit_url(handle, name, commit.id.as_str())) |
| 1125 | title=(&commit.summary) |
| 1126 | class="ml-3 hidden min-w-0 flex-1 truncate text-xs text-muted-foreground hover:text-foreground md:block" |
| 1127 | >(&commit.summary)</a>, |
| 1128 | // An entry whose last change is older than the walk reaches. The gap still |
| 1129 | // has to hold the column open, or the sizes beside it stop lining up. |
| 1130 | None => <span class="ml-3 hidden min-w-0 flex-1 md:block"></span>, |
| 1131 | } |
| 1132 | |
| 1133 | <span class="ml-auto flex shrink-0 items-center gap-3 font-mono text-xs text-muted-foreground"> |
| 1134 | match last { |
| 1135 | Some(commit) => <span |
| 1136 | class="hidden md:inline" |
| 1137 | title=(timestamp(commit.committed_at)) |
| 1138 | >(ago(commit.committed_at))</span>, |
| 1139 | None => "", |
| 1140 | } |
| 1141 | // Fixed width and right-aligned, so the dates beside it line up rather |
| 1142 | // than stepping in and out with whether a row has a size at all — a |
| 1143 | // directory has none. The same rule the branches page settled on for the |
| 1144 | // sha: trailing metadata is a column, not a trailer. |
| 1145 | <span class="w-16 text-right"> |
| 1146 | match entry.size { |
| 1147 | Some(size) => (size_of(size)), |
| 1148 | None if entry.kind == EntryKind::Submodule => (entry.id.short()), |
| 1149 | None => "", |
| 1150 | } |
| 1151 | </span> |
| 1152 | </span> |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | /// A single file. |
| 1157 | /// |
| 1158 | /// Three outcomes, all of them a page rather than an error: text, something that is not |
| 1159 | /// text, and something too big to be worth rendering. The last says how big, because |
| 1160 | /// that is the only useful thing left to say about it. |
| 1161 | #[component] |
| 1162 | pub(super) async fn blob( |
| 1163 | handle: &str, |
| 1164 | name: &str, |
| 1165 | rev: &RefName, |
| 1166 | path: &RepoPath, |
| 1167 | file: &FileView, |
| 1168 | /// Whether `?view=source` asked for the line table of a file that would otherwise |
| 1169 | /// be rendered. Nothing for a file with only one view. |
| 1170 | show_source: bool, |
| 1171 | ) -> Result { |
| 1172 | // Rendered *by default*, because a rendered document is what the file is for — the |
| 1173 | // source of a README is the last thing a reader arriving at it wants. The toggle is |
| 1174 | // in the header and the URL says which it is showing. |
| 1175 | let markdown = is_markdown(path); |
| 1176 | let rendered = markdown && !show_source; |
| 1177 | // Only when a grammar was actually found: a file shown as plain text says nothing |
| 1178 | // here rather than naming a language whose colour is absent. Nothing at all for a |
| 1179 | // binary or an over-large file — `file.text` is `None` there and there is no language |
| 1180 | // to have detected. |
| 1181 | let language = file |
| 1182 | .text |
| 1183 | .as_deref() |
| 1184 | .and_then(|text| language_of(path.file_name().unwrap_or_default(), text)); |
| 1185 | |
| 1186 | view! { |
| 1187 | <div class="overflow-hidden rounded-lg border border-border"> |
| 1188 | <div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-2.5"> |
| 1189 | crumbs(handle: handle, name: name, rev: rev, path: path) |
| 1190 | <span class="flex items-center gap-3 font-mono text-xs text-muted-foreground"> |
| 1191 | // Beside the size and in the same muted mono, because it is the same |
| 1192 | // kind of fact about the file: what it is, not what to do with it. |
| 1193 | // In its own element rather than as bare text: two adjacent text |
| 1194 | // nodes are one anonymous flex item, so the row's `gap-3` would not |
| 1195 | // separate them and the header would read "Rust7.3 KB". |
| 1196 | match language { |
| 1197 | Some(language) => <span>(language)</span>, |
| 1198 | None => "", |
| 1199 | } |
| 1200 | <span>(size_of(file.size))</span> |
| 1201 | view_toggle( |
| 1202 | handle: handle, |
| 1203 | name: name, |
| 1204 | rev: rev, |
| 1205 | path: path, |
| 1206 | active: if rendered { FileTab::Code } else if markdown { FileTab::Source } else { FileTab::Code }, |
| 1207 | markdown: markdown, |
| 1208 | ) |
| 1209 | </span> |
| 1210 | </div> |
| 1211 | |
| 1212 | match &file.text { |
| 1213 | Some(text) if rendered => rendered_markdown( |
| 1214 | handle: handle, |
| 1215 | name: name, |
| 1216 | rev: rev, |
| 1217 | path: path, |
| 1218 | text: text.as_str(), |
| 1219 | ), |
| 1220 | Some(text) => source( |
| 1221 | text: text.as_str(), |
| 1222 | file_name: path.file_name().unwrap_or_default(), |
| 1223 | id: file.id.as_str(), |
| 1224 | ), |
| 1225 | None if file.too_large => <p class="px-4 py-6 text-center text-sm text-muted-foreground"> |
| 1226 | "This file is " (size_of(file.size)) ", which is too large to display. Clone the repository to read it." |
| 1227 | </p>, |
| 1228 | None => <p class="px-4 py-6 text-center text-sm text-muted-foreground"> |
| 1229 | "This file cannot be displayed as text." |
| 1230 | </p>, |
| 1231 | } |
| 1232 | </div> |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | /// Extensions Steid renders as markdown. |
| 1237 | /// |
| 1238 | /// The same set the README card accepts, minus the extensionless spelling: a file |
| 1239 | /// called `NOTES` is not markdown, whereas a `README` is by convention. |
| 1240 | const MARKDOWN_EXTENSIONS: [&str; 4] = ["md", "markdown", "mdown", "mkd"]; |
| 1241 | |
| 1242 | /// Whether a path names a markdown file, which is what gives it two views. |
| 1243 | pub(super) fn is_markdown(path: &RepoPath) -> bool { |
| 1244 | let Some(name) = path.file_name() else { |
| 1245 | return false; |
| 1246 | }; |
| 1247 | let Some((_, extension)) = name.rsplit_once('.') else { |
| 1248 | return false; |
| 1249 | }; |
| 1250 | |
| 1251 | MARKDOWN_EXTENSIONS.contains(&extension.to_ascii_lowercase().as_str()) |
| 1252 | } |
| 1253 | |
| 1254 | /// A markdown file, rendered. |
| 1255 | /// |
| 1256 | /// The README card's typography, because it is the same thing in a different frame — |
| 1257 | /// two readings of one document would be two designs for one thing. |
| 1258 | /// |
| 1259 | /// **Relative destinations resolve against the file's own directory**, which is where |
| 1260 | /// they were written from, and links and images resolve *differently*: a link to |
| 1261 | /// another file means the page that shows it, and an image means the file's bytes. The |
| 1262 | /// README card resolves against the root and leaves images alone, which is the same |
| 1263 | /// rule for a document that happens to be at the root. |
| 1264 | #[component] |
| 1265 | async fn rendered_markdown( |
| 1266 | handle: &str, |
| 1267 | name: &str, |
| 1268 | rev: &RefName, |
| 1269 | path: &RepoPath, |
| 1270 | text: &str, |
| 1271 | ) -> Result { |
| 1272 | // A file has a parent by construction — the root is a directory, not a file. |
| 1273 | let dir = path.parent().unwrap_or_default(); |
| 1274 | |
| 1275 | view! { |
| 1276 | // The only unescaped content on any Steid page, and safe for the reason the |
| 1277 | // README card's is: `markdown` writes every tag itself and never passes source |
| 1278 | // HTML through. See that module's header. |
| 1279 | <div class="px-5 py-4 text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"> |
| 1280 | (markdown::render_with_targets( |
| 1281 | text, |
| 1282 | Some(markdown::Crossref { |
| 1283 | handle, |
| 1284 | name, |
| 1285 | origin: None, |
| 1286 | }), |
| 1287 | |kind, destination| { |
| 1288 | // The fragment is carried across: rendered headings have ids, so |
| 1289 | // `notes.md#usage` lands on the section it names. A query means |
| 1290 | // nothing to a tree URL and is dropped, and a bare `#section` has no |
| 1291 | // path to resolve and is left exactly as written. |
| 1292 | let (target, fragment) = split_fragment(destination); |
| 1293 | let target = target.split('?').next()?; |
| 1294 | let resolved = resolve_relative(&dir, target)?; |
| 1295 | |
| 1296 | Some(match kind { |
| 1297 | markdown::Relative::Link => { |
| 1298 | format!("{}{fragment}", tree_url(handle, name, rev, &resolved)) |
| 1299 | } |
| 1300 | // Bytes, not a page: an image pointed at a tree URL is a broken |
| 1301 | // image rather than a picture, and a fragment means nothing to |
| 1302 | // one. |
| 1303 | markdown::Relative::Image => raw_url(handle, name, rev, &resolved), |
| 1304 | }) |
| 1305 | }, |
| 1306 | )) |
| 1307 | </div> |
| 1308 | } |
| 1309 | } |
| 1310 | |
| 1311 | /// A file's contents, with line numbers. |
| 1312 | /// |
| 1313 | /// A table rather than a `<pre>` with a gutter: the numbers stay put when the code |
| 1314 | /// scrolls sideways, and selecting the code does not drag the numbers along with it. |
| 1315 | /// |
| 1316 | /// Highlighting only ever changes what is *inside* the code cell — the rows, the |
| 1317 | /// numbers and the scroll container are the same whether a language was recognised or |
| 1318 | /// not, so nothing else on the page has to know. |
| 1319 | /// |
| 1320 | /// |
| 1321 | /// Each number cell carries an `id="L{n}"`, which is what a search result links to: a |
| 1322 | /// match on line 400 of a long file should land on line 400. |
| 1323 | #[component] |
| 1324 | async fn source(cx: &Cx, text: &str, file_name: &str, id: &str) -> Result { |
| 1325 | // Through the cache, keyed by the blob's object id: git has already hashed these |
| 1326 | // bytes, so the key is free and two revisions of an unchanged file share one entry. |
| 1327 | // |
| 1328 | // Cloned out of the `Arc` rather than borrowed from it, because the view outlives |
| 1329 | // this function body and a local it only borrows does not — the same reason blame |
| 1330 | // flattens its rows before its `view!`. It is a `Vec<String>` copy against a parse |
| 1331 | // of the whole file: three orders of magnitude apart, and the parse is what the |
| 1332 | // cache is here to skip. |
| 1333 | let Source { lines, too_large } = highlights(cx) |
| 1334 | .source_lines(id, file_name, text) |
| 1335 | .as_ref() |
| 1336 | .clone(); |
| 1337 | |
| 1338 | view! { |
| 1339 | if too_large { |
| 1340 | <p class="border-b border-border px-4 py-1.5 font-mono text-xs text-muted-foreground"> |
| 1341 | "Too large to highlight — shown as plain text." |
| 1342 | </p> |
| 1343 | } |
| 1344 | |
| 1345 | <div class="overflow-x-auto"> |
| 1346 | <table class="w-full border-collapse font-mono text-xs leading-relaxed"> |
| 1347 | <tbody> |
| 1348 | for (index, line) in lines.into_iter().enumerate() { |
| 1349 | <tr> |
| 1350 | <td |
| 1351 | id=(format!("L{}", index + 1)) |
| 1352 | class="w-px select-none border-r border-border px-3 text-right align-top text-muted-foreground" |
| 1353 | > |
| 1354 | ((index + 1).to_string()) |
| 1355 | </td> |
| 1356 | <td class="whitespace-pre px-4 align-top"> |
| 1357 | match line { |
| 1358 | // Markup this codebase wrote: `highlight` escapes |
| 1359 | // the source itself and emits nothing but spans. |
| 1360 | SourceLine::Classed(html) => (Unescaped::new_unchecked(html)), |
| 1361 | SourceLine::Plain(text) => (text), |
| 1362 | } |
| 1363 | </td> |
| 1364 | </tr> |
| 1365 | } |
| 1366 | </tbody> |
| 1367 | </table> |
| 1368 | </div> |
| 1369 | } |
| 1370 | } |
| 1371 | |
| 1372 | /// The commit log — the most recent commits, newest first, and no paging in v1. |
| 1373 | /// |
| 1374 | /// Shared with the compare page, which lists the commits a branch adds in exactly this |
| 1375 | /// shape: two lists of commits that read differently would be two designs for one |
| 1376 | /// thing. |
| 1377 | #[component] |
| 1378 | pub(super) async fn commit_log(handle: &str, name: &str, commits: &[CommitSummary]) -> Result { |
| 1379 | view! { |
| 1380 | if commits.is_empty() { |
| 1381 | <p class="rounded-lg border border-border px-4 py-10 text-center text-sm text-muted-foreground"> |
| 1382 | "No commits yet." |
| 1383 | </p> |
| 1384 | } else { |
| 1385 | <ul class="divide-y divide-border rounded-lg border border-border"> |
| 1386 | for commit in commits { |
| 1387 | <li class="px-4 py-3"> |
| 1388 | <div class="flex items-baseline justify-between gap-4"> |
| 1389 | <p class="text-sm font-medium">(&commit.summary)</p> |
| 1390 | <a |
| 1391 | href=(commit_url(handle, name, commit.id.as_str())) |
| 1392 | class="shrink-0 font-mono text-xs text-muted-foreground hover:text-foreground" |
| 1393 | >(commit.id.short())</a> |
| 1394 | </div> |
| 1395 | <p class="mt-1 text-xs text-muted-foreground"> |
| 1396 | (&commit.author_name) |
| 1397 | " committed " |
| 1398 | <span title=(timestamp(commit.committed_at))>(ago(commit.committed_at))</span> |
| 1399 | </p> |
| 1400 | </li> |
| 1401 | } |
| 1402 | </ul> |
| 1403 | } |
| 1404 | } |
| 1405 | } |
| 1406 | |
| 1407 | #[cfg(test)] |
| 1408 | mod tests { |
| 1409 | use std::time::Duration; |
| 1410 | |
| 1411 | use super::*; |
| 1412 | |
| 1413 | fn rev(value: &str) -> RefName { |
| 1414 | RefName::new(value).expect("valid revision") |
| 1415 | } |
| 1416 | |
| 1417 | #[test] |
| 1418 | fn a_root_tree_url_has_no_separator() { |
| 1419 | assert_eq!( |
| 1420 | tree_url("ada", "steid", &rev("main"), &RepoPath::root()), |
| 1421 | "/ada/repos/steid/tree/main" |
| 1422 | ); |
| 1423 | } |
| 1424 | |
| 1425 | #[test] |
| 1426 | fn a_path_follows_the_separator_with_its_slashes_intact() { |
| 1427 | let path = RepoPath::new("src/domain/repo.rs").expect("valid"); |
| 1428 | |
| 1429 | assert_eq!( |
| 1430 | tree_url("ada", "steid", &rev("main"), &path), |
| 1431 | "/ada/repos/steid/tree/main/-/src/domain/repo.rs" |
| 1432 | ); |
| 1433 | } |
| 1434 | |
| 1435 | #[test] |
| 1436 | fn a_revisions_slashes_are_encoded_so_it_stays_one_segment() { |
| 1437 | // Otherwise `feature/login` would look like a revision plus a path, which is |
| 1438 | // the ambiguity the separator exists to remove. |
| 1439 | assert_eq!( |
| 1440 | tree_url("ada", "steid", &rev("feature/login"), &RepoPath::root()), |
| 1441 | "/ada/repos/steid/tree/feature%2Flogin" |
| 1442 | ); |
| 1443 | } |
| 1444 | |
| 1445 | #[test] |
| 1446 | fn names_needing_escaping_are_encoded() { |
| 1447 | let path = RepoPath::new("docs/a b#c.md").expect("valid"); |
| 1448 | |
| 1449 | assert_eq!( |
| 1450 | tree_url("ada", "steid", &rev("main"), &path), |
| 1451 | "/ada/repos/steid/tree/main/-/docs/a%20b%23c.md" |
| 1452 | ); |
| 1453 | } |
| 1454 | |
| 1455 | #[test] |
| 1456 | fn the_log_url_is_the_default_branch_when_no_revision_is_named() { |
| 1457 | assert_eq!(log_url("ada", "steid", ""), "/ada/repos/steid/log"); |
| 1458 | assert_eq!( |
| 1459 | log_url("ada", "steid", "feature/login"), |
| 1460 | "/ada/repos/steid/log/feature%2Flogin" |
| 1461 | ); |
| 1462 | } |
| 1463 | |
| 1464 | #[test] |
| 1465 | fn markdown_is_recognised_by_extension_and_nothing_else() { |
| 1466 | for name in ["README.md", "docs/design.MARKDOWN", "notes.mkd", "a.mdown"] { |
| 1467 | assert!( |
| 1468 | is_markdown(&RepoPath::new(name).expect("valid")), |
| 1469 | "{name} should be markdown" |
| 1470 | ); |
| 1471 | } |
| 1472 | |
| 1473 | for name in ["README", "main.rs", "docs/md", "notes.md.bak"] { |
| 1474 | assert!( |
| 1475 | !is_markdown(&RepoPath::new(name).expect("valid")), |
| 1476 | "{name} should not be markdown" |
| 1477 | ); |
| 1478 | } |
| 1479 | } |
| 1480 | |
| 1481 | #[test] |
| 1482 | fn a_paths_history_url_is_the_logs_with_the_separator_on_the_end() { |
| 1483 | let path = RepoPath::new("src/main.rs").expect("valid"); |
| 1484 | |
| 1485 | assert_eq!( |
| 1486 | path_log_url("ada", "steid", &rev("main"), &path), |
| 1487 | "/ada/repos/steid/log/main/-/src/main.rs" |
| 1488 | ); |
| 1489 | // The revision keeps its slashes encoded, so it stays one segment and the |
| 1490 | // separator keeps its meaning — the tree URL's rule. |
| 1491 | assert_eq!( |
| 1492 | path_log_url("ada", "steid", &rev("feature/login"), &path), |
| 1493 | "/ada/repos/steid/log/feature%2Flogin/-/src/main.rs" |
| 1494 | ); |
| 1495 | } |
| 1496 | |
| 1497 | #[test] |
| 1498 | fn switching_revision_on_a_paths_history_stays_on_that_path() { |
| 1499 | let refs = [RefName::from_trusted("v1.0")]; |
| 1500 | let path = RepoPath::new("src").expect("valid"); |
| 1501 | let links = ref_links("ada", "steid", &refs, "main", &Switch::PathLog(&path)); |
| 1502 | |
| 1503 | assert_eq!(links[0].href, "/ada/repos/steid/log/v1.0/-/src"); |
| 1504 | } |
| 1505 | |
| 1506 | #[test] |
| 1507 | fn a_raw_url_always_carries_a_path() { |
| 1508 | let path = RepoPath::new("src/main.rs").expect("valid"); |
| 1509 | |
| 1510 | assert_eq!( |
| 1511 | raw_url("ada", "steid", &rev("main"), &path), |
| 1512 | "/ada/repos/steid/raw/main/-/src/main.rs" |
| 1513 | ); |
| 1514 | assert_eq!( |
| 1515 | raw_url("ada", "steid", &rev("feature/login"), &path), |
| 1516 | "/ada/repos/steid/raw/feature%2Flogin/-/src/main.rs" |
| 1517 | ); |
| 1518 | } |
| 1519 | |
| 1520 | #[test] |
| 1521 | fn a_raw_response_carries_the_whole_policy() { |
| 1522 | let response = raw_response("notes.txt", b"hello".to_vec()).expect("should build"); |
| 1523 | let header = |name: &str| { |
| 1524 | response |
| 1525 | .headers() |
| 1526 | .get(name) |
| 1527 | .and_then(|value| value.to_str().ok()) |
| 1528 | .unwrap_or_default() |
| 1529 | .to_owned() |
| 1530 | }; |
| 1531 | |
| 1532 | // Each of these is load-bearing on its own; see `raw_response`. |
| 1533 | assert_eq!(header("content-type"), "application/octet-stream"); |
| 1534 | assert_eq!(header("x-content-type-options"), "nosniff"); |
| 1535 | assert!(header("content-disposition").starts_with("attachment;")); |
| 1536 | assert_eq!( |
| 1537 | header("content-security-policy"), |
| 1538 | "default-src \'none\'; sandbox" |
| 1539 | ); |
| 1540 | } |
| 1541 | |
| 1542 | #[test] |
| 1543 | fn a_disposition_carries_both_spellings_of_the_name() { |
| 1544 | assert_eq!( |
| 1545 | disposition("notes.txt"), |
| 1546 | "attachment; filename=\"notes.txt\"; filename*=UTF-8\'\'notes.txt" |
| 1547 | ); |
| 1548 | } |
| 1549 | |
| 1550 | #[test] |
| 1551 | fn a_disposition_cannot_be_escaped_by_a_filename() { |
| 1552 | |
| 1553 | |
| 1554 | |
| 1555 | let hostile = disposition("a\"; x=1\r\nSet-Cookie: nope=1"); |
| 1556 | |
| 1557 | assert!(!hostile.contains('\r')); |
| 1558 | assert!(!hostile.contains('\n')); |
| 1559 | assert_eq!(hostile.matches('"').count(), 2); |
| 1560 | } |
| 1561 | |
| 1562 | #[test] |
| 1563 | fn a_nameless_file_still_downloads_as_something() { |
| 1564 | assert!(disposition("...").starts_with("attachment; filename=\"file\"")); |
| 1565 | } |
| 1566 | |
| 1567 | #[test] |
| 1568 | fn a_non_ascii_name_survives_in_the_extended_form() { |
| 1569 | let value = disposition("日本語.txt"); |
| 1570 | |
| 1571 | |
| 1572 | |
| 1573 | assert!(value.contains("filename=\"___.txt\"")); |
| 1574 | assert!(value.contains("filename*=UTF-8\'\'%E6%97%A5%E6%9C%AC%E8%AA%9E.txt")); |
| 1575 | } |
| 1576 | |
| 1577 | #[test] |
| 1578 | fn the_switcher_marks_the_revision_it_is_on() { |
| 1579 | let refs = [RefName::from_trusted("main"), RefName::from_trusted("next")]; |
| 1580 | let path = RepoPath::new("src").expect("valid"); |
| 1581 | let links = ref_links("ada", "steid", &refs, "next", &Switch::Tree(&path)); |
| 1582 | |
| 1583 | assert_eq!(links[0].href, "/ada/repos/steid/tree/main/-/src"); |
| 1584 | assert!(!links[0].current); |
| 1585 | assert!(links[1].current); |
| 1586 | } |
| 1587 | |
| 1588 | #[test] |
| 1589 | fn switching_from_the_log_stays_on_the_log() { |
| 1590 | let refs = [RefName::from_trusted("v1.0")]; |
| 1591 | let links = ref_links("ada", "steid", &refs, "main", &Switch::Log); |
| 1592 | |
| 1593 | assert_eq!(links[0].href, "/ada/repos/steid/log/v1.0"); |
| 1594 | } |
| 1595 | |
| 1596 | #[test] |
| 1597 | fn an_object_id_is_labelled_as_a_commit_rather_than_a_branch() { |
| 1598 | let id = "0123456789abcdef0123456789abcdef01234567"; |
| 1599 | |
| 1600 | assert!(is_object_id(id)); |
| 1601 | assert_eq!(rev_label(id, false), "0123456"); |
| 1602 | |
| 1603 | assert_eq!(rev_label("deadbeef", true), "deadbeef"); |
| 1604 | assert_eq!(rev_label("main", false), "main"); |
| 1605 | } |
| 1606 | |
| 1607 | #[test] |
| 1608 | fn sizes_read_as_sizes() { |
| 1609 | assert_eq!(size_of(0), "0 B"); |
| 1610 | assert_eq!(size_of(999), "999 B"); |
| 1611 | assert_eq!(size_of(1024), "1.0 KB"); |
| 1612 | assert_eq!(size_of(1_048_576), "1.0 MB"); |
| 1613 | assert_eq!(size_of(1_572_864), "1.5 MB"); |
| 1614 | } |
| 1615 | |
| 1616 | #[test] |
| 1617 | fn elapsed_time_reads_as_words() { |
| 1618 | let now = SystemTime::now(); |
| 1619 | let since = |seconds| ago(now - Duration::from_secs(seconds)); |
| 1620 | |
| 1621 | assert_eq!(since(5), "just now"); |
| 1622 | assert_eq!(since(60), "1 minute ago"); |
| 1623 | assert_eq!(since(7200), "2 hours ago"); |
| 1624 | assert_eq!(since(86_400 * 3), "3 days ago"); |
| 1625 | assert_eq!(since(86_400 * 400), "1 year ago"); |
| 1626 | } |
| 1627 | |
| 1628 | #[test] |
| 1629 | fn a_commit_from_the_future_reads_as_now_rather_than_as_a_negative() { |
| 1630 | |
| 1631 | assert_eq!( |
| 1632 | ago(SystemTime::now() + Duration::from_secs(3600)), |
| 1633 | "just now" |
| 1634 | ); |
| 1635 | } |
| 1636 | |
| 1637 | #[test] |
| 1638 | fn timestamps_are_utc_calendar_dates() { |
| 1639 | assert_eq!( |
| 1640 | timestamp(UNIX_EPOCH + Duration::from_secs(0)), |
| 1641 | "1970-01-01 00:00 UTC" |
| 1642 | ); |
| 1643 | |
| 1644 | assert_eq!( |
| 1645 | timestamp(UNIX_EPOCH + Duration::from_secs(1_788_006_840)), |
| 1646 | "2026-08-29 12:34 UTC" |
| 1647 | ); |
| 1648 | |
| 1649 | assert_eq!( |
| 1650 | timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), |
| 1651 | "2024-02-29 00:00 UTC" |
| 1652 | ); |
| 1653 | } |
| 1654 | } |