forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

commit.rs547 lines, 21.5 KiBHistoryRawDownload
1//! Page: one commit at `/{owner}/{repo}/commit/{oid}`: metadata, file list and unified diff.
2
3use forge_core::tz::format_in_tz;
4use forge_git::browse;
5use forge_git::history;
6use forge_git::trailers;
7use topcoat::Result;
8use topcoat::context::{Cx, context};
9use topcoat::router::error::{content_too_large, not_found};
10use topcoat::router::{page, path_param, route};
11use topcoat::view::{View, view};
12
13use crate::i18n::code::{self as g, K};
14use crate::i18n::{self};
15use crate::layers::RawDownload;
16use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid};
17use crate::pages::ref_live;
18use crate::pages::repo::repo_head;
19use crate::pages::repo_ctx::load_repo;
20use crate::render::commit_message::CommitMessage;
21use crate::render::emoji::emojify;
22use crate::signatures;
23use crate::state::AppState;
24use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary};
25use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
26use crate::views::shell;
27use crate::views::{avatar_url, display_name, relative_time, user_href};
28
29path_param!(owner);
30path_param!(repo);
31path_param!(oid);
32
33/// Author, committer or parent line data.
34struct Person {
35 name: String,
36 email: String,
37 relative: String,
38 absolute: String,
39 iso: String,
40}
41
42struct ParentLink {
43 href: String,
44 short: String,
45}
46
47/// One `Co-authored-by` person: linked and avatar-shown when a verified user has the email.
48struct CoAuthorView {
49 name: String,
50 email: String,
51 href: Option<String>,
52 avatar: Option<String>,
53 /// Whether a comma separates this one from the entry before it.
54 sep: bool,
55}
56
57fn is_hex_prefix(s: &str) -> bool {
58 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
59}
60
61/// Which plain download a `.patch` or `.diff` suffix asks for.
62#[derive(Clone, Copy, PartialEq, Eq)]
63pub enum Download {
64 Patch,
65 Diff,
66}
67
68impl Download {
69 /// Splits a `.patch` or `.diff` suffix off `spec`.
70 pub fn split(spec: &str) -> (&str, Option<Download>) {
71 if let Some(rest) = spec.strip_suffix(".patch") {
72 (rest, Some(Download::Patch))
73 } else if let Some(rest) = spec.strip_suffix(".diff") {
74 (rest, Some(Download::Diff))
75 } else {
76 (spec, None)
77 }
78 }
79
80 /// The bytes as a download. Output cut at the cap is refused rather than served broken.
81 pub fn serve(self, out: history::PatchOut, stem: &str) -> Result<RawDownload> {
82 if !out.complete {
83 return Err(content_too_large().into());
84 }
85 let ext = match self {
86 Download::Patch => "patch",
87 Download::Diff => "diff",
88 };
89 Ok(RawDownload {
90 content_type: "text/plain; charset=utf-8",
91 filename: format!("{stem}.{ext}"),
92 data: out.data,
93 })
94 }
95}
96
97#[page("/{owner}/{repo}/commit/{oid}")]
98async fn commit_page(cx: &Cx) -> Result<impl View> {
99 let owner = owner(cx);
100 let name = repo(cx);
101 let (rev, download) = Download::split(oid(cx));
102 if !is_hex_prefix(rev) {
103 return Err(not_found().into());
104 }
105
106 let ctx = load_repo(cx, owner, name).await?;
107 let state = context::<AppState>(cx);
108 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user));
109
110 let repo_dir = ctx.path.clone();
111 let rev = rev.to_owned();
112 let Some(oid) = blocking(move || browse::resolve_commit(&repo_dir, &rev)).await? else {
113 return Err(not_found().into());
114 };
115 let repo_dir = ctx.path.clone();
116 let lookup = oid.clone();
117 let Some(info) = blocking(move || browse::read_commit(&repo_dir, &lookup)).await? else {
118 return Err(not_found().into());
119 };
120 if let Some(kind) = download {
121 let out = match kind {
122 Download::Patch => history::commit_patch(&state.git, &ctx.path, &info.oid).await?,
123 Download::Diff => history::commit_raw_diff(&state.git, &ctx.path, &info.oid).await?,
124 };
125 return Err(kind.serve(out, &info.oid)?.into());
126 }
127 let opts = DiffOpts::from_cx(
128 cx,
129 Some((
130 format!(
131 "/{}/{}/commit/{}.patch",
132 ctx.repo.owner_name, ctx.repo.name, info.oid
133 ),
134 format!(
135 "/{}/{}/commit/{}.diff",
136 ctx.repo.owner_name, ctx.repo.name, info.oid
137 ),
138 )),
139 )
140 .await?;
141 let diff =
142 history::commit_diff_ws(&state.git, &ctx.path, &info.oid, LIMITS, opts.ignore_ws).await?;
143
144 let owner_name = ctx.repo.owner_name.clone();
145 let repo_name = ctx.repo.name.clone();
146 let tz = ctx.viewer_tz().to_owned();
147 let parent = info.parents.first().cloned();
148
149 let now = now_secs();
150 let author = Person {
151 name: info.author_name.clone(),
152 email: info.author_email.clone(),
153 relative: relative_time(lang, info.author_time, now),
154 absolute: format_in_tz(info.author_time, &tz),
155 iso: iso_time(info.author_time),
156 };
157 let committer_differs =
158 info.committer_name != info.author_name || info.committer_email != info.author_email;
159 let committer = Person {
160 name: info.committer_name.clone(),
161 email: info.committer_email.clone(),
162 relative: relative_time(lang, info.committer_time, now),
163 absolute: format_in_tz(info.committer_time, &tz),
164 iso: iso_time(info.committer_time),
165 };
166 let parents: Vec<ParentLink> = info
167 .parents
168 .iter()
169 .map(|p| ParentLink {
170 href: format!("/{owner_name}/{repo_name}/commit/{p}"),
171 short: short_oid(p).to_owned(),
172 })
173 .collect();
174 let is_root = parents.is_empty();
175 let body = trailers::strip_co_authors(&info.message);
176 // The first line is the head's title, so only what follows it is shown as the message.
177 let body_rest = body.split_once('\n').map_or("", |(_, rest)| rest).trim();
178 let has_body = !body_rest.is_empty();
179 let mut coauthors: Vec<CoAuthorView> = Vec::new();
180 for co in trailers::co_authors(&info.message) {
181 if co.email.eq_ignore_ascii_case(&info.author_email) {
182 continue;
183 }
184 let user = state
185 .store
186 .verified_user_by_email(&co.email)
187 .await
188 .ok()
189 .flatten();
190 let (name, href, avatar) = match user {
191 Some(user) => (
192 display_name(lang, &user.username),
193 Some(user_href(&user.username)),
194 Some(avatar_url(&user.username, user.avatar_hash.as_deref())),
195 ),
196 None => (co.name.clone(), None, None),
197 };
198 let sep = !coauthors.is_empty();
199 coauthors.push(CoAuthorView {
200 name,
201 email: co.email,
202 href,
203 avatar,
204 sep,
205 });
206 }
207 // Three or more: the first is shown, the rest sit behind a "+N others" disclosure.
208 let has_coauthors = !coauthors.is_empty();
209 let folded = coauthors.len() >= 3;
210 let rest: Vec<CoAuthorView> = if folded {
211 coauthors.split_off(1)
212 } else {
213 Vec::new()
214 };
215 let others = g::co_author_others(lang, rest.len());
216 let coauthors_label = g::t(lang, K::CoAuthorsLabel);
217 let title = format!("{owner_name}/{repo_name}");
218 let tree_href = format!("/{owner_name}/{repo_name}/tree/{}", info.oid);
219 let summary = emojify(&info.summary).into_owned();
220 // A typed subject shows its first clause as the title and its groups as a list below.
221 let parsed = CommitMessage::parse(&summary);
222 let heading = match &parsed {
223 Some(msg) => msg.title(),
224 None => summary.clone(),
225 };
226 let changes_label = g::t(lang, K::CommitChangesLabel);
227 let show_full = g::t(lang, K::ShowFullMessage);
228 let full_oid = info.oid.clone();
229 let message = emojify(&body).into_owned();
230 let rest_message = emojify(body_rest).into_owned();
231 let statuses = state.store.statuses_for(&ctx.repo.id, &full_oid).await?;
232 let checks = (!statuses.is_empty()).then(|| StatusSummary::from_rows(&statuses));
233 let sig = signatures::badges(state, &ctx.repo, std::slice::from_ref(&full_oid))
234 .await
235 .get(&full_oid)
236 .map(|badge| SigBadgeView::from_badge(badge, lang));
237
238 let short = short_oid(&info.oid).to_owned();
239 // The committer is not shown on the line when it is the author: a title holds it when it differs.
240 let who_title = if committer_differs {
241 format!(
242 "{} {} <{}>\n{} {} <{}> · {}",
243 g::t(lang, K::AuthorLabel),
244 author.name,
245 author.email,
246 g::t(lang, K::CommitterLabel),
247 committer.name,
248 committer.email,
249 committer.absolute,
250 )
251 } else if author.email.is_empty() {
252 String::new()
253 } else {
254 format!("<{}>", author.email)
255 };
256 let (copied, copy_failed) = match lang {
257 i18n::Lang::En => ("Copied", "Failed"),
258 i18n::Lang::Tr => ("Kopyalandı", "Başarısız"),
259 };
260 let mut header = ctx.head(state, "commits").await?;
261 header.live = ref_live::live_url(&owner_name, &repo_name);
262 Ok(view! {
263 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
264 repo_head(head: header, title: Some(heading.clone()),
265 <a class="act" href=(tree_href.as_str())>(g::t(lang, K::BrowseFiles))</a>
266 )
267 <div class="sheet">
268 <div class="sheet-tools">
269 <button type="button" class="act commit-hash" data-copy="commit-oid" data-copied=(copied) data-failed=(copy_failed) title=(full_oid.as_str())>(short.as_str())</button>
270 <code id="commit-oid" class="sr-only">(full_oid.as_str())</code>
271 if let Some(badge) = sig {
272 <span class=(badge.class) title=(badge.title.as_str())>(badge.label)</span>
273 }
274 <span class="commit-author-line" title=(who_title.as_str())>
275 <strong>(author.name.as_str())</strong>
276 if has_coauthors {
277 (g::t(lang, K::CoAuthorAnd))
278 for c in coauthors.iter() {
279 if c.sep { ", " }
280 if let Some(href) = c.href.as_ref() {
281 <a class="coauthor" href=(href.as_str())>
282 if let Some(src) = c.avatar.as_ref() {
283 <img class="avatar coauthor-avatar" src=(src.as_str()) alt="" width="16" height="16">
284 }
285 (c.name.as_str())
286 </a>
287 } else {
288 <span class="coauthor" title=(c.email.as_str())>(c.name.as_str())</span>
289 }
290 }
291 if folded {
292 ", "
293 <details class="coauthors-more">
294 <summary class="act">(others.as_str())</summary>
295 <ul class="coauthors-list" aria-label=(coauthors_label)>
296 for c in rest.iter() {
297 <li>
298 if let Some(href) = c.href.as_ref() {
299 <a class="coauthor" href=(href.as_str())>
300 if let Some(src) = c.avatar.as_ref() {
301 <img class="avatar coauthor-avatar" src=(src.as_str()) alt="" width="16" height="16">
302 }
303 (c.name.as_str())
304 </a>
305 } else {
306 <span class="coauthor" title=(c.email.as_str())>(c.name.as_str())</span>
307 }
308 </li>
309 }
310 </ul>
311 </details>
312 }
313 }
314 </span>
315 <time data-rel="true" datetime=(author.iso.as_str()) title=(author.absolute.as_str())>(author.relative.as_str())</time>
316 if is_root {
317 <span>(g::t(lang, K::RootCommit))</span>
318 } else {
319 <span>(g::t(lang, K::ParentLabel))
320 for p in parents.iter() {
321 <a class="mono" href=(p.href.as_str())>(p.short.as_str())</a>
322 }
323 </span>
324 }
325 if let Some(summary) = checks {
326 checks_summary(summary: summary, lang: StatusLang(lang))
327 }
328 </div>
329 if let Some(msg) = parsed.as_ref() {
330 <section class="sec">
331 <ul class="commit-groups" aria-label=(changes_label)>
332 for group in msg.groups.iter() {
333 <li class="commit-group">
334 <span class="mono commit-kind">(group.kind.as_str())</span>
335 <ul class="commit-clauses">
336 for clause in group.clauses.iter() {
337 <li>(clause.as_str())</li>
338 }
339 </ul>
340 </li>
341 }
342 </ul>
343 <details class="reveal commit-full-message">
344 <summary class="act">(show_full)</summary>
345 <div class="opened">
346 <pre class="code commit-message"><code>(message.as_str())</code></pre>
347 </div>
348 </details>
349 </section>
350 }
351 if parsed.is_none() && has_body {
352 <section class="sec">
353 <pre class="code commit-message"><code>(rest_message.as_str())</code></pre>
354 </section>
355 }
356 </div>
357 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)
358 )
359 })
360}
361
362/// Other methods on a commit path get a plain 404.
363#[route(* "/{owner}/{repo}/commit/{oid}")]
364async fn commit_other_methods(cx: &Cx) -> Result<&'static str> {
365 Err(not_found().into())
366}
367
368#[cfg(test)]
369mod tests {
370 use forge_core::Visibility;
371 use scraper::{Html, Selector};
372
373 use super::is_hex_prefix;
374 use crate::auth::SESSION_COOKIE;
375 use crate::test_support::fixture::{Fixture, OWNER, REPO, get};
376 use topcoat::router::request::Request;
377 use topcoat::router::{Body, to_bytes};
378
379 fn doc(body: &[u8]) -> Html {
380 Html::parse_document(std::str::from_utf8(body).unwrap())
381 }
382
383 /// Text of each cell in every `tr` matching `row_selector`, as `[old, new, code]`.
384 fn rows(html: &Html, row_selector: &str) -> Vec<Vec<String>> {
385 let tr = Selector::parse(row_selector).unwrap();
386 let td = Selector::parse("td").unwrap();
387 html.select(&tr)
388 .map(|row| {
389 row.select(&td)
390 .map(|c| c.text().collect::<String>().trim().to_owned())
391 .collect()
392 })
393 .collect()
394 }
395
396 #[test]
397 fn hex_prefix_bounds() {
398 assert!(is_hex_prefix("abcd"));
399 assert!(is_hex_prefix(&"a".repeat(64)));
400 assert!(!is_hex_prefix("abc"));
401 assert!(!is_hex_prefix(&"a".repeat(65)));
402 assert!(!is_hex_prefix("zzzz"));
403 }
404
405 /// The modified and added files show line numbers, with their body and file headers.
406 async fn scenario_modified_and_added(fx: &Fixture) {
407 let (status, _, body) = get(
408 &fx.router,
409 &format!("/{OWNER}/{REPO}/commit/{}", fx.modified),
410 )
411 .await;
412 assert_eq!(status, 200);
413 assert!(String::from_utf8_lossy(&body).contains("tester@example.com"));
414 let html = doc(&body);
415
416 let rows = rows(&html, "tr.diff-line");
417 let find = |code: &str| {
418 rows.iter()
419 .find(|r| r.get(2).map(String::as_str) == Some(code))
420 .unwrap_or_else(|| panic!("no row {code:?} in {rows:?}"))
421 .clone()
422 };
423 assert_eq!(find("-two"), vec!["2", "", "-two"]);
424 assert_eq!(find("+TWO"), vec!["", "2", "+TWO"]);
425 assert_eq!(find("three"), vec!["3", "3", "three"]);
426 assert_eq!(find("+four"), vec!["", "4", "+four"]);
427 assert_eq!(find("+new file"), vec!["", "1", "+new file"]);
428
429 let added = Selector::parse(".diff-file-header").unwrap();
430 let headers: Vec<String> = html
431 .select(&added)
432 .map(|h| h.text().collect::<String>())
433 .collect();
434 assert!(
435 headers
436 .iter()
437 .any(|h| h.contains("new.txt") && h.contains("added"))
438 );
439 assert!(
440 headers
441 .iter()
442 .any(|h| h.contains("a.txt") && h.contains("modified"))
443 );
444 let text = String::from_utf8_lossy(&body).into_owned();
445 assert!(text.contains("Body line one."));
446 assert!(text.contains("class=\"mono\""));
447 assert!(text.contains("diff-file-body"));
448 assert!(!text.contains("sig-badge"), "unsigned commit has no badge");
449 }
450
451 /// The root commit has no parent, and its one added line is shown.
452 async fn scenario_root_commit(fx: &Fixture) {
453 let (status, _, body) =
454 get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await;
455 assert_eq!(status, 200);
456 let html = String::from_utf8(body.clone()).unwrap();
457 assert!(html.contains("Root commit (no parents)"));
458 let rows = rows(&doc(&body), "tr.diff-line");
459 assert!(
460 rows.iter()
461 .any(|r| r.get(2).map(String::as_str) == Some("+one"))
462 );
463 }
464
465 /// Titles follow the viewer's timezone; anonymous viewers see UTC.
466 async fn scenario_title_timezone(fx: &Fixture) {
467 let tokyo = fx
468 .store
469 .create_user("tokyo", None, "not-a-real-hash", false)
470 .await
471 .unwrap();
472 fx.store
473 .set_profile(&tokyo.id, "", "Asia/Tokyo")
474 .await
475 .unwrap();
476 crate::test_support::create_session(&fx.store, &tokyo.id, "tokyo-token", "tokyo-csrf")
477 .await;
478 let uri = format!("/{OWNER}/{REPO}/commit/{}", fx.root);
479
480 let req = Request::builder()
481 .method("GET")
482 .uri(&uri)
483 .header("cookie", format!("__Host-{SESSION_COOKIE}=tokyo-token"))
484 .body(Body::empty())
485 .unwrap();
486 let res = fx.router.handle(req).await;
487 assert_eq!(res.status(), 200);
488 let html = String::from_utf8(
489 to_bytes(res.into_body(), usize::MAX)
490 .await
491 .unwrap()
492 .to_vec(),
493 )
494 .unwrap();
495 // Scope to the page's own `<main>`: the shell's theme button has a `title` with ':'.
496 let main = html
497 .split_once("<main")
498 .and_then(|(_, rest)| rest.split_once("</main>"))
499 .map(|(main, _)| main)
500 .expect("page has a <main> element");
501 let titles: Vec<&str> = main
502 .split("title=\"")
503 .skip(1)
504 .filter_map(|rest| rest.split('"').next())
505 .filter(|t| t.contains(':'))
506 .collect();
507 assert!(!titles.is_empty(), "absolute time in title: {html}");
508 assert!(
509 titles.iter().all(|t| t.ends_with("+09")),
510 "titles in Tokyo time: {titles:?}"
511 );
512
513 // Anonymous viewers see UTC, so no +09 offset.
514 let (status, _, body) = get(&fx.router, &uri).await;
515 assert_eq!(status, 200);
516 let anon = String::from_utf8(body).unwrap();
517 assert!(!anon.contains("+09\""), "anonymous view is not Tokyo time");
518 }
519
520 /// Bad and unknown oids are 404.
521 async fn scenario_bad_oid(fx: &Fixture) {
522 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/zzzz")).await;
523 assert_eq!(status, 404);
524 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/abc")).await;
525 assert_eq!(status, 404);
526 let unknown = "0123456789abcdef0123456789abcdef01234567";
527 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{unknown}")).await;
528 assert_eq!(status, 404);
529 }
530
531 /// Every page of one public commit, on one fixture. The scenarios only read, so order is free.
532 #[tokio::test]
533 async fn public_commit_pages() {
534 let fx = Fixture::new(Visibility::Public).await;
535 scenario_modified_and_added(&fx).await;
536 scenario_root_commit(&fx).await;
537 scenario_title_timezone(&fx).await;
538 scenario_bad_oid(&fx).await;
539 }
540
541 #[tokio::test]
542 async fn private_repo_is_404_for_anonymous() {
543 let fx = Fixture::new(Visibility::Private).await;
544 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await;
545 assert_eq!(status, 404);
546 }
547}