use forge_core::tz::format_in_tz; use forge_git::browse; use forge_git::history; use forge_git::trailers; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::error::{content_too_large, not_found}; use topcoat::router::{page, path_param, route}; use topcoat::view::{View, component, view}; use crate::i18n::code::{self as g, K}; use crate::i18n::{self}; use crate::layers::RawDownload; use crate::pages::commits::{SigBadgeView, blocking}; use crate::pages::ref_live; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::render::commit_message::CommitMessage; use crate::render::emoji::emojify; use crate::signatures; use crate::state::AppState; use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary}; use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; use crate::views::shell; use crate::views::{ avatar_url, display_name, iso_time, now_unix, relative_time, short_oid, user_href, }; path_param!(owner); path_param!(repo); path_param!(oid); struct Person { name: String, email: String, relative: String, absolute: String, iso: String, } struct ParentLink { href: String, short: String, } struct CoAuthorView { name: String, email: String, href: Option, avatar: Option, sep: bool, } #[component] async fn coauthor_link(cx: &Cx, c: &CoAuthorView) -> Result { Ok(view! { if let Some(href) = c.href.as_ref() { if let Some(src) = c.avatar.as_ref() { } (c.name.as_str()) } else { (c.name.as_str()) } }) } fn is_hex_prefix(s: &str) -> bool { (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit()) } #[derive(Clone, Copy, PartialEq, Eq)] pub enum Download { Patch, Diff, } impl Download { pub fn split(spec: &str) -> (&str, Option) { if let Some(rest) = spec.strip_suffix(".patch") { (rest, Some(Download::Patch)) } else if let Some(rest) = spec.strip_suffix(".diff") { (rest, Some(Download::Diff)) } else { (spec, None) } } pub fn serve(self, out: history::PatchOut, stem: &str) -> Result { if !out.complete { return Err(content_too_large().into()); } let ext = match self { Download::Patch => "patch", Download::Diff => "diff", }; Ok(RawDownload { content_type: "text/plain; charset=utf-8", filename: format!("{stem}.{ext}"), data: out.data, }) } } #[page("/{owner}/{repo}/commit/{oid}")] async fn commit_page(cx: &Cx) -> Result { let owner = owner(cx); let name = repo(cx); let (rev, download) = Download::split(oid(cx)); if !is_hex_prefix(rev) { return Err(not_found().into()); } let ctx = load_repo(cx, owner, name).await?; let state = context::(cx); let lang = i18n::lang(cx, ctx.viewer_user()); let repo_dir = ctx.path.clone(); let rev = rev.to_owned(); let Some(oid) = blocking(move || browse::resolve_commit(&repo_dir, &rev)).await? else { return Err(not_found().into()); }; let repo_dir = ctx.path.clone(); let lookup = oid.clone(); let Some(info) = blocking(move || browse::read_commit(&repo_dir, &lookup)).await? else { return Err(not_found().into()); }; if let Some(kind) = download { let out = match kind { Download::Patch => history::commit_patch(&state.git, &ctx.path, &info.oid).await?, Download::Diff => history::commit_raw_diff(&state.git, &ctx.path, &info.oid).await?, }; return Err(kind.serve(out, &info.oid)?.into()); } let opts = DiffOpts::from_cx( cx, Some(( format!( "/{}/{}/commit/{}.patch", ctx.repo.owner_name, ctx.repo.name, info.oid ), format!( "/{}/{}/commit/{}.diff", ctx.repo.owner_name, ctx.repo.name, info.oid ), )), ) .await?; let diff = history::commit_diff_ws(&state.git, &ctx.path, &info.oid, LIMITS, opts.ignore_ws).await?; let owner_name = ctx.repo.owner_name.clone(); let repo_name = ctx.repo.name.clone(); let tz = ctx.viewer_tz().to_owned(); let parent = info.parents.first().cloned(); let now = now_unix(); let author = Person { name: info.author_name.clone(), email: info.author_email.clone(), relative: relative_time(lang, info.author_time, now), absolute: format_in_tz(info.author_time, &tz), iso: iso_time(info.author_time), }; let committer_differs = info.committer_name != info.author_name || info.committer_email != info.author_email; let committer = Person { name: info.committer_name.clone(), email: info.committer_email.clone(), relative: relative_time(lang, info.committer_time, now), absolute: format_in_tz(info.committer_time, &tz), iso: iso_time(info.committer_time), }; let parents: Vec = info .parents .iter() .map(|p| ParentLink { href: format!("/{owner_name}/{repo_name}/commit/{p}"), short: short_oid(p).to_owned(), }) .collect(); let is_root = parents.is_empty(); let body = trailers::strip_co_authors(&info.message); let body_rest = body.split_once('\n').map_or("", |(_, rest)| rest).trim(); let has_body = !body_rest.is_empty(); let mut coauthors: Vec = Vec::new(); for co in trailers::co_authors(&info.message) { if co.email.eq_ignore_ascii_case(&info.author_email) { continue; } let user = state .store .verified_user_by_email(&co.email) .await .ok() .flatten(); let (name, href, avatar) = match user { Some(user) => ( display_name(lang, &user.username), Some(user_href(&user.username)), Some(avatar_url(&user.username, user.avatar_hash.as_deref())), ), None => (co.name.clone(), None, None), }; let sep = !coauthors.is_empty(); coauthors.push(CoAuthorView { name, email: co.email, href, avatar, sep, }); } let has_coauthors = !coauthors.is_empty(); let folded = coauthors.len() >= 3; let rest: Vec = if folded { coauthors.split_off(1) } else { Vec::new() }; let others = g::co_author_others(lang, rest.len()); let coauthors_label = g::t(lang, K::CoAuthorsLabel); let title = format!("{owner_name}/{repo_name}"); let tree_href = format!("/{owner_name}/{repo_name}/tree/{}", info.oid); let summary = emojify(&info.summary).into_owned(); let parsed = CommitMessage::parse(&summary); let heading = match &parsed { Some(msg) => msg.title(), None => summary.clone(), }; let changes_label = g::t(lang, K::CommitChangesLabel); let show_full = g::t(lang, K::ShowFullMessage); let full_oid = info.oid.clone(); let message = emojify(&body).into_owned(); let rest_message = emojify(body_rest).into_owned(); let statuses = state.store.statuses_for(&ctx.repo.id, &full_oid).await?; let checks = (!statuses.is_empty()).then(|| StatusSummary::from_rows(&statuses)); let sig = signatures::badges(state, &ctx.repo, std::slice::from_ref(&full_oid)) .await .get(&full_oid) .map(|badge| SigBadgeView::from_badge(badge, lang)); let short = short_oid(&info.oid).to_owned(); let who_title = if committer_differs { format!( "{} {} <{}>\n{} {} <{}> · {}", g::t(lang, K::AuthorLabel), author.name, author.email, g::t(lang, K::CommitterLabel), committer.name, committer.email, committer.absolute, ) } else if author.email.is_empty() { String::new() } else { format!("<{}>", author.email) }; let (copied, copy_failed) = match lang { i18n::Lang::En => ("Copied", "Failed"), i18n::Lang::Tr => ("Kopyalandı", "Başarısız"), }; let mut header = ctx.head(state, "commits").await?; header.live = ref_live::live_url(&owner_name, &repo_name); Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header, title: Some(heading.clone()), (g::t(lang, K::BrowseFiles)) )
(full_oid.as_str()) if let Some(badge) = sig { (badge.label) } (author.name.as_str()) if has_coauthors { (g::t(lang, K::CoAuthorAnd)) for c in coauthors.iter() { if c.sep { ", " } coauthor_link(c: c) } if folded { ", "
(others.as_str())
    for c in rest.iter() {
  • coauthor_link(c: c)
  • }
} }
if is_root { (g::t(lang, K::RootCommit)) } else { (g::t(lang, K::ParentLabel)) for p in parents.iter() { (p.short.as_str()) } } if let Some(summary) = checks { checks_summary(summary: summary, lang: StatusLang(lang)) }
if let Some(msg) = parsed.as_ref() {
    for group in msg.groups.iter() {
  • (group.kind.as_str())
      for clause in group.clauses.iter() {
    • (clause.as_str())
    • }
  • }
(show_full)
(message.as_str())
} if parsed.is_none() && has_body {
(rest_message.as_str())
}
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) ) }) } #[route(* "/{owner}/{repo}/commit/{oid}")] async fn commit_other_methods(cx: &Cx) -> Result<&'static str> { Err(not_found().into()) } #[cfg(test)] mod tests { use forge_core::Visibility; use scraper::{Html, Selector}; use super::is_hex_prefix; use crate::auth::SESSION_COOKIE; use crate::test_support::fixture::{Fixture, OWNER, REPO, get}; use topcoat::router::request::Request; use topcoat::router::{Body, to_bytes}; fn doc(body: &[u8]) -> Html { Html::parse_document(std::str::from_utf8(body).unwrap()) } fn rows(html: &Html, row_selector: &str) -> Vec> { let tr = Selector::parse(row_selector).unwrap(); let td = Selector::parse("td").unwrap(); html.select(&tr) .map(|row| { row.select(&td) .map(|c| c.text().collect::().trim().to_owned()) .collect() }) .collect() } #[test] fn hex_prefix_bounds() { assert!(is_hex_prefix("abcd")); assert!(is_hex_prefix(&"a".repeat(64))); assert!(!is_hex_prefix("abc")); assert!(!is_hex_prefix(&"a".repeat(65))); assert!(!is_hex_prefix("zzzz")); } async fn scenario_modified_and_added(fx: &Fixture) { let (status, _, body) = get( &fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.modified), ) .await; assert_eq!(status, 200); assert!(String::from_utf8_lossy(&body).contains("tester@example.com")); let html = doc(&body); let rows = rows(&html, "tr.diff-line"); let find = |code: &str| { rows.iter() .find(|r| r.get(2).map(String::as_str) == Some(code)) .unwrap_or_else(|| panic!("no row {code:?} in {rows:?}")) .clone() }; assert_eq!(find("-two"), vec!["2", "", "-two"]); assert_eq!(find("+TWO"), vec!["", "2", "+TWO"]); assert_eq!(find("three"), vec!["3", "3", "three"]); assert_eq!(find("+four"), vec!["", "4", "+four"]); assert_eq!(find("+new file"), vec!["", "1", "+new file"]); let added = Selector::parse(".diff-file-header").unwrap(); let headers: Vec = html .select(&added) .map(|h| h.text().collect::()) .collect(); assert!( headers .iter() .any(|h| h.contains("new.txt") && h.contains("added")) ); assert!( headers .iter() .any(|h| h.contains("a.txt") && h.contains("modified")) ); let text = String::from_utf8_lossy(&body).into_owned(); assert!(text.contains("Body line one.")); assert!(text.contains("class=\"mono\"")); assert!(text.contains("diff-file-body")); assert!(!text.contains("sig-badge"), "unsigned commit has no badge"); } async fn scenario_root_commit(fx: &Fixture) { let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await; assert_eq!(status, 200); let html = String::from_utf8(body.clone()).unwrap(); assert!(html.contains("Root commit (no parents)")); let rows = rows(&doc(&body), "tr.diff-line"); assert!( rows.iter() .any(|r| r.get(2).map(String::as_str) == Some("+one")) ); } async fn scenario_title_timezone(fx: &Fixture) { let tokyo = fx .store .create_user("tokyo", None, "not-a-real-hash", false) .await .unwrap(); fx.store .set_profile(&tokyo.id, "", "Asia/Tokyo") .await .unwrap(); crate::test_support::create_session(&fx.store, &tokyo.id, "tokyo-token", "tokyo-csrf") .await; let uri = format!("/{OWNER}/{REPO}/commit/{}", fx.root); let req = Request::builder() .method("GET") .uri(&uri) .header("cookie", format!("__Host-{SESSION_COOKIE}=tokyo-token")) .body(Body::empty()) .unwrap(); let res = fx.router.handle(req).await; assert_eq!(res.status(), 200); let html = String::from_utf8( to_bytes(res.into_body(), usize::MAX) .await .unwrap() .to_vec(), ) .unwrap(); let main = html .split_once("")) .map(|(main, _)| main) .expect("page has a
element"); let titles: Vec<&str> = main .split("title=\"") .skip(1) .filter_map(|rest| rest.split('"').next()) .filter(|t| t.contains(':')) .collect(); assert!(!titles.is_empty(), "absolute time in title: {html}"); assert!( titles.iter().all(|t| t.ends_with("+09")), "titles in Tokyo time: {titles:?}" ); let (status, _, body) = get(&fx.router, &uri).await; assert_eq!(status, 200); let anon = String::from_utf8(body).unwrap(); assert!(!anon.contains("+09\""), "anonymous view is not Tokyo time"); } async fn scenario_bad_oid(fx: &Fixture) { let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/zzzz")).await; assert_eq!(status, 404); let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/abc")).await; assert_eq!(status, 404); let unknown = "0123456789abcdef0123456789abcdef01234567"; let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{unknown}")).await; assert_eq!(status, 404); } #[tokio::test] async fn public_commit_pages() { let fx = Fixture::new(Visibility::Public).await; scenario_modified_and_added(&fx).await; scenario_root_commit(&fx).await; scenario_title_timezone(&fx).await; scenario_bad_oid(&fx).await; } #[tokio::test] async fn private_repo_is_404_for_anonymous() { let fx = Fixture::new(Visibility::Private).await; let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await; assert_eq!(status, 404); } }