forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB3d53dfdTahinli1 month ago208 commits

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