forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·8.8 MiB·b00f3f4·Tahinli·1 month ago·147 commits
| 1 | //! Page: one commit at `/{owner}/{repo}/commit/{oid}`: metadata, file list and unified diff. |
| 2 | |
| 3 | use forge_core::tz::format_in_tz; |
| 4 | use forge_git::browse; |
| 5 | use forge_git::history; |
| 6 | use topcoat::Result; |
| 7 | use topcoat::context::{Cx, app_context}; |
| 8 | use topcoat::router::error::{content_too_large, not_found}; |
| 9 | use topcoat::router::{page, path_param, route}; |
| 10 | use topcoat::view::{View, view}; |
| 11 | |
| 12 | use crate::i18n::code::{self as g, K}; |
| 13 | use crate::i18n::{self}; |
| 14 | use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid}; |
| 15 | use crate::pages::ref_live; |
| 16 | use crate::pages::repo::repo_head; |
| 17 | use crate::pages::repo_ctx::{RawDownload, load_repo}; |
| 18 | use crate::render::emoji::emojify; |
| 19 | use crate::signatures; |
| 20 | use crate::state::AppState; |
| 21 | use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary}; |
| 22 | use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; |
| 23 | use crate::views::relative_time; |
| 24 | use crate::views::shell; |
| 25 | |
| 26 | path_param!(owner); |
| 27 | path_param!(repo); |
| 28 | path_param!(oid); |
| 29 | |
| 30 | /// Author, committer or parent line data. |
| 31 | struct Person { |
| 32 | name: String, |
| 33 | relative: String, |
| 34 | absolute: String, |
| 35 | iso: String, |
| 36 | } |
| 37 | |
| 38 | struct ParentLink { |
| 39 | href: String, |
| 40 | short: String, |
| 41 | } |
| 42 | |
| 43 | fn is_hex_prefix(s: &str) -> bool { |
| 44 | (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit()) |
| 45 | } |
| 46 | |
| 47 | /// Which plain download a `.patch` or `.diff` suffix asks for. |
| 48 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 49 | pub enum Download { |
| 50 | Patch, |
| 51 | Diff, |
| 52 | } |
| 53 | |
| 54 | impl Download { |
| 55 | /// Splits a `.patch` or `.diff` suffix off `spec`. |
| 56 | pub fn split(spec: &str) -> (&str, Option<Download>) { |
| 57 | if let Some(rest) = spec.strip_suffix(".patch") { |
| 58 | (rest, Some(Download::Patch)) |
| 59 | } else if let Some(rest) = spec.strip_suffix(".diff") { |
| 60 | (rest, Some(Download::Diff)) |
| 61 | } else { |
| 62 | (spec, None) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | /// The bytes as a download. Output cut at the cap is refused rather than served broken. |
| 67 | pub fn serve(self, out: history::PatchOut, stem: &str) -> Result<RawDownload> { |
| 68 | if !out.complete { |
| 69 | return Err(content_too_large().into()); |
| 70 | } |
| 71 | let ext = match self { |
| 72 | Download::Patch => "patch", |
| 73 | Download::Diff => "diff", |
| 74 | }; |
| 75 | Ok(RawDownload { |
| 76 | content_type: "text/plain; charset=utf-8", |
| 77 | filename: format!("{stem}.{ext}"), |
| 78 | data: out.data, |
| 79 | }) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | #[page("/{owner}/{repo}/commit/{oid}")] |
| 84 | async fn commit_page(cx: &Cx) -> Result<impl View> { |
| 85 | let owner = path_param::<Owner>(cx); |
| 86 | let name = path_param::<Repo>(cx); |
| 87 | let (rev, download) = Download::split(path_param::<Oid>(cx)); |
| 88 | if !is_hex_prefix(rev) { |
| 89 | return Err(not_found().into()); |
| 90 | } |
| 91 | |
| 92 | let ctx = load_repo(cx, owner, name).await?; |
| 93 | let state = app_context::<AppState>(cx); |
| 94 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); |
| 95 | |
| 96 | let repo_dir = ctx.path.clone(); |
| 97 | let rev = rev.to_owned(); |
| 98 | let Some(oid) = blocking(move || browse::resolve_commit(&repo_dir, &rev)).await? else { |
| 99 | return Err(not_found().into()); |
| 100 | }; |
| 101 | let repo_dir = ctx.path.clone(); |
| 102 | let lookup = oid.clone(); |
| 103 | let Some(info) = blocking(move || browse::read_commit(&repo_dir, &lookup)).await? else { |
| 104 | return Err(not_found().into()); |
| 105 | }; |
| 106 | if let Some(kind) = download { |
| 107 | let out = match kind { |
| 108 | Download::Patch => history::commit_patch(&state.git, &ctx.path, &info.oid).await?, |
| 109 | Download::Diff => history::commit_raw_diff(&state.git, &ctx.path, &info.oid).await?, |
| 110 | }; |
| 111 | return Err(kind.serve(out, &info.oid)?.into()); |
| 112 | } |
| 113 | let opts = DiffOpts::from_cx( |
| 114 | cx, |
| 115 | Some(( |
| 116 | format!( |
| 117 | "/{}/{}/commit/{}.patch", |
| 118 | ctx.repo.owner_name, ctx.repo.name, info.oid |
| 119 | ), |
| 120 | format!( |
| 121 | "/{}/{}/commit/{}.diff", |
| 122 | ctx.repo.owner_name, ctx.repo.name, info.oid |
| 123 | ), |
| 124 | )), |
| 125 | ); |
| 126 | let diff = |
| 127 | history::commit_diff_ws(&state.git, &ctx.path, &info.oid, LIMITS, opts.ignore_ws).await?; |
| 128 | |
| 129 | let owner_name = ctx.repo.owner_name.clone(); |
| 130 | let repo_name = ctx.repo.name.clone(); |
| 131 | let tz = ctx.viewer_tz().to_owned(); |
| 132 | let parent = info.parents.first().cloned(); |
| 133 | |
| 134 | let now = now_secs(); |
| 135 | let author = Person { |
| 136 | name: info.author_name.clone(), |
| 137 | relative: relative_time(lang, info.author_time, now), |
| 138 | absolute: format_in_tz(info.author_time, &tz), |
| 139 | iso: iso_time(info.author_time), |
| 140 | }; |
| 141 | let committer_differs = |
| 142 | info.committer_name != info.author_name || info.committer_email != info.author_email; |
| 143 | let committer = Person { |
| 144 | name: info.committer_name.clone(), |
| 145 | relative: relative_time(lang, info.committer_time, now), |
| 146 | absolute: format_in_tz(info.committer_time, &tz), |
| 147 | iso: iso_time(info.committer_time), |
| 148 | }; |
| 149 | let parents: Vec<ParentLink> = info |
| 150 | .parents |
| 151 | .iter() |
| 152 | .map(|p| ParentLink { |
| 153 | href: format!("/{owner_name}/{repo_name}/commit/{p}"), |
| 154 | short: short_oid(p).to_owned(), |
| 155 | }) |
| 156 | .collect(); |
| 157 | let is_root = parents.is_empty(); |
| 158 | let has_body = !info.message.trim().is_empty(); |
| 159 | let title = format!("{owner_name}/{repo_name}"); |
| 160 | let repo_href = format!("/{owner_name}/{repo_name}"); |
| 161 | let tree_href = format!("/{owner_name}/{repo_name}/tree/{}", info.oid); |
| 162 | let summary = emojify(&info.summary).into_owned(); |
| 163 | let full_oid = info.oid.clone(); |
| 164 | let message = emojify(&info.message).into_owned(); |
| 165 | let statuses = state.store.statuses_for(&ctx.repo.id, &full_oid).await?; |
| 166 | let checks = (!statuses.is_empty()).then(|| StatusSummary::from_rows(&statuses)); |
| 167 | let sig = signatures::badges(state, &ctx.repo, std::slice::from_ref(&full_oid)) |
| 168 | .await |
| 169 | .get(&full_oid) |
| 170 | .map(|badge| SigBadgeView::from_badge(badge, lang)); |
| 171 | |
| 172 | let (copy, copied, copy_failed) = match lang { |
| 173 | i18n::Lang::En => ("Copy", "Copied", "Failed"), |
| 174 | i18n::Lang::Tr => ("Kopyala", "Kopyalandı", "Başarısız"), |
| 175 | }; |
| 176 | let mut header = ctx.head(state, "commits").await?; |
| 177 | header.live = ref_live::live_url(&owner_name, &repo_name); |
| 178 | Ok(view! { |
| 179 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), |
| 180 | repo_head(head: header) |
| 181 | <h2 class="commit-summary-title">(summary.as_str())</h2> |
| 182 | <p class="muted small"><a href=(repo_href.as_str())>(title.as_str())</a></p> |
| 183 | <section class="card commit-info"> |
| 184 | <p class="commit-full-oid"> |
| 185 | <span class="copy-box"> |
| 186 | <code id="commit-oid" title=(full_oid.as_str())>(full_oid.as_str())</code> |
| 187 | <button type="button" data-copy="commit-oid" data-copied=(copied) data-failed=(copy_failed)>(copy)</button> |
| 188 | </span> |
| 189 | if let Some(badge) = sig { |
| 190 | <span class=(badge.class) title=(badge.title.as_str())>(badge.label)</span> |
| 191 | } |
| 192 | </p> |
| 193 | if let Some(summary) = checks { |
| 194 | checks_summary(summary: summary, lang: StatusLang(lang)) |
| 195 | } |
| 196 | <p class="muted">(g::t(lang, K::AuthorLabel)) <strong>(author.name.as_str())</strong> " · " <time datetime=(author.iso.as_str()) title=(author.absolute.as_str())>(author.relative.as_str())</time></p> |
| 197 | if committer_differs { |
| 198 | <p class="muted">(g::t(lang, K::CommitterLabel)) <strong>(committer.name.as_str())</strong> " · " <time datetime=(committer.iso.as_str()) title=(committer.absolute.as_str())>(committer.relative.as_str())</time></p> |
| 199 | } |
| 200 | if is_root { |
| 201 | <p class="muted">(g::t(lang, K::RootCommit))</p> |
| 202 | } else { |
| 203 | <p class="muted">(g::t(lang, K::ParentLabel)) |
| 204 | for p in parents.iter() { |
| 205 | <a class="mono" href=(p.href.as_str())>(p.short.as_str())</a> " " |
| 206 | } |
| 207 | </p> |
| 208 | } |
| 209 | <p><a href=(tree_href.as_str())>(g::t(lang, K::BrowseFiles))</a></p> |
| 210 | </section> |
| 211 | if has_body { |
| 212 | <pre class="code commit-message"><code>(message.as_str())</code></pre> |
| 213 | } |
| 214 | diff_section(diff: &diff, owner: owner_name.as_str(), repo: repo_name.as_str(), oid: info.oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisCommit), lang: DiffLang(lang), opts: opts) |
| 215 | ) |
| 216 | }) |
| 217 | } |
| 218 | |
| 219 | /// Other methods on a commit path get a plain 404. |
| 220 | #[route(* "/{owner}/{repo}/commit/{oid}")] |
| 221 | async fn commit_other_methods() -> Result<&'static str> { |
| 222 | Err(not_found().into()) |
| 223 | } |
| 224 | |
| 225 | #[cfg(test)] |
| 226 | mod tests { |
| 227 | use forge_core::Visibility; |
| 228 | use scraper::{Html, Selector}; |
| 229 | |
| 230 | use super::is_hex_prefix; |
| 231 | use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get}; |
| 232 | |
| 233 | fn doc(body: &[u8]) -> Html { |
| 234 | Html::parse_document(std::str::from_utf8(body).unwrap()) |
| 235 | } |
| 236 | |
| 237 | /// Text of each cell in every `tr` matching `row_selector`, as `[old, new, code]`. |
| 238 | fn rows(html: &Html, row_selector: &str) -> Vec<Vec<String>> { |
| 239 | let tr = Selector::parse(row_selector).unwrap(); |
| 240 | let td = Selector::parse("td").unwrap(); |
| 241 | html.select(&tr) |
| 242 | .map(|row| { |
| 243 | row.select(&td) |
| 244 | .map(|c| c.text().collect::<String>().trim().to_owned()) |
| 245 | .collect() |
| 246 | }) |
| 247 | .collect() |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn hex_prefix_bounds() { |
| 252 | assert!(is_hex_prefix("abcd")); |
| 253 | assert!(is_hex_prefix(&"a".repeat(64))); |
| 254 | assert!(!is_hex_prefix("abc")); |
| 255 | assert!(!is_hex_prefix(&"a".repeat(65))); |
| 256 | assert!(!is_hex_prefix("zzzz")); |
| 257 | } |
| 258 | |
| 259 | #[tokio::test] |
| 260 | async fn modified_and_added_files_have_line_numbers() { |
| 261 | let fx = Fixture::new(Visibility::Public).await; |
| 262 | let (status, _, body) = get( |
| 263 | &fx.router, |
| 264 | &format!("/{OWNER}/{REPO}/commit/{}", fx.modified), |
| 265 | ) |
| 266 | .await; |
| 267 | assert_eq!(status, 200); |
| 268 | let html = doc(&body); |
| 269 | |
| 270 | let rows = rows(&html, "tr.diff-line"); |
| 271 | let find = |code: &str| { |
| 272 | rows.iter() |
| 273 | .find(|r| r.get(2).map(String::as_str) == Some(code)) |
| 274 | .unwrap_or_else(|| panic!("no row {code:?} in {rows:?}")) |
| 275 | .clone() |
| 276 | }; |
| 277 | assert_eq!(find("-two"), vec!["2", "", "-two"]); |
| 278 | assert_eq!(find("+TWO"), vec!["", "2", "+TWO"]); |
| 279 | assert_eq!(find("three"), vec!["3", "3", "three"]); |
| 280 | assert_eq!(find("+four"), vec!["", "4", "+four"]); |
| 281 | assert_eq!(find("+new file"), vec!["", "1", "+new file"]); |
| 282 | |
| 283 | let added = Selector::parse(".diff-file-header").unwrap(); |
| 284 | let headers: Vec<String> = html |
| 285 | .select(&added) |
| 286 | .map(|h| h.text().collect::<String>()) |
| 287 | .collect(); |
| 288 | assert!( |
| 289 | headers |
| 290 | .iter() |
| 291 | .any(|h| h.contains("new.txt") && h.contains("added")) |
| 292 | ); |
| 293 | assert!( |
| 294 | headers |
| 295 | .iter() |
| 296 | .any(|h| h.contains("a.txt") && h.contains("modified")) |
| 297 | ); |
| 298 | let text = String::from_utf8_lossy(&body).into_owned(); |
| 299 | assert!(text.contains("Body line one.")); |
| 300 | assert!(text.contains("class=\"mono\"")); |
| 301 | assert!(text.contains("diff-file-body")); |
| 302 | assert!(!text.contains("sig-badge"), "unsigned commit has no badge"); |
| 303 | } |
| 304 | |
| 305 | #[tokio::test] |
| 306 | async fn root_commit_page_renders() { |
| 307 | let fx = Fixture::new(Visibility::Public).await; |
| 308 | let (status, _, body) = |
| 309 | get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await; |
| 310 | assert_eq!(status, 200); |
| 311 | let html = String::from_utf8(body.clone()).unwrap(); |
| 312 | assert!(html.contains("Root commit (no parents)")); |
| 313 | let rows = rows(&doc(&body), "tr.diff-line"); |
| 314 | assert!( |
| 315 | rows.iter() |
| 316 | .any(|r| r.get(2).map(String::as_str) == Some("+one")) |
| 317 | ); |
| 318 | } |
| 319 | |
| 320 | #[tokio::test] |
| 321 | async fn commit_title_uses_viewer_timezone() { |
| 322 | use topcoat::router::request::Request; |
| 323 | use topcoat::router::{Body, to_bytes}; |
| 324 | |
| 325 | use crate::auth::SESSION_COOKIE; |
| 326 | |
| 327 | let fx = Fixture::new(Visibility::Public).await; |
| 328 | let tokyo = fx |
| 329 | .store |
| 330 | .create_user("tokyo", None, "not-a-real-hash", false) |
| 331 | .await |
| 332 | .unwrap(); |
| 333 | fx.store |
| 334 | .set_profile(&tokyo.id, "", "Asia/Tokyo") |
| 335 | .await |
| 336 | .unwrap(); |
| 337 | crate::test_support::create_session(&fx.store, &tokyo.id, "tokyo-token", "tokyo-csrf") |
| 338 | .await; |
| 339 | let uri = format!("/{OWNER}/{REPO}/commit/{}", fx.root); |
| 340 | |
| 341 | let req = Request::builder() |
| 342 | .method("GET") |
| 343 | .uri(&uri) |
| 344 | .header("cookie", format!("__Host-{SESSION_COOKIE}=tokyo-token")) |
| 345 | .body(Body::empty()) |
| 346 | .unwrap(); |
| 347 | let res = fx.router.handle(req).await; |
| 348 | assert_eq!(res.status(), 200); |
| 349 | let html = String::from_utf8( |
| 350 | to_bytes(res.into_body(), usize::MAX) |
| 351 | .await |
| 352 | .unwrap() |
| 353 | .to_vec(), |
| 354 | ) |
| 355 | .unwrap(); |
| 356 | // Scope to the page's own `<main>`: the shell's theme button has a `title` with ':'. |
| 357 | let main = html |
| 358 | .split_once("<main") |
| 359 | .and_then(|(_, rest)| rest.split_once("</main>")) |
| 360 | .map(|(main, _)| main) |
| 361 | .expect("page has a <main> element"); |
| 362 | let titles: Vec<&str> = main |
| 363 | .split("title=\"") |
| 364 | .skip(1) |
| 365 | .filter_map(|rest| rest.split('"').next()) |
| 366 | .filter(|t| t.contains(':')) |
| 367 | .collect(); |
| 368 | assert!(!titles.is_empty(), "absolute time in title: {html}"); |
| 369 | assert!( |
| 370 | titles.iter().all(|t| t.ends_with("+09")), |
| 371 | "titles in Tokyo time: {titles:?}" |
| 372 | ); |
| 373 | |
| 374 | // Anonymous viewers see UTC, so no +09 offset. |
| 375 | let (status, _, body) = get(&fx.router, &uri).await; |
| 376 | assert_eq!(status, 200); |
| 377 | let anon = String::from_utf8(body).unwrap(); |
| 378 | assert!(!anon.contains("+09\""), "anonymous view is not Tokyo time"); |
| 379 | } |
| 380 | |
| 381 | #[tokio::test] |
| 382 | async fn bad_oid_is_404() { |
| 383 | let fx = Fixture::new(Visibility::Public).await; |
| 384 | let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/zzzz")).await; |
| 385 | assert_eq!(status, 404); |
| 386 | let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/abc")).await; |
| 387 | assert_eq!(status, 404); |
| 388 | let unknown = "0123456789abcdef0123456789abcdef01234567"; |
| 389 | let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{unknown}")).await; |
| 390 | assert_eq!(status, 404); |
| 391 | } |
| 392 | |
| 393 | #[tokio::test] |
| 394 | async fn private_repo_is_404_for_anonymous() { |
| 395 | let fx = Fixture::new(Visibility::Private).await; |
| 396 | let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await; |
| 397 | assert_eq!(status, 404); |
| 398 | } |
| 399 | } |