forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiBbcaef90Tahinli1 month ago164 commits

commit.rs403 lines, 15.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 topcoat::Result;
7use topcoat::context::{Cx, app_context};
8use topcoat::router::error::{content_too_large, not_found};
9use topcoat::router::{page, path_param, route};
10use topcoat::view::{View, view};
11
12use crate::i18n::code::{self as g, K};
13use crate::i18n::{self};
14use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid};
15use crate::pages::ref_live;
16use crate::pages::repo::repo_head;
17use crate::pages::repo_ctx::{RawDownload, load_repo};
18use crate::render::emoji::emojify;
19use crate::signatures;
20use crate::state::AppState;
21use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary};
22use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
23use crate::views::relative_time;
24use crate::views::shell;
25
26path_param!(owner);
27path_param!(repo);
28path_param!(oid);
29
30/// Author, committer or parent line data.
31struct Person {
32 name: String,
33 relative: String,
34 absolute: String,
35 iso: String,
36}
37
38struct ParentLink {
39 href: String,
40 short: String,
41}
42
43fn 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)]
49pub enum Download {
50 Patch,
51 Diff,
52}
53
54impl 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}")]
84async 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 data-rel="true" 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 data-rel="true" 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}")]
221async fn commit_other_methods() -> Result<&'static str> {
222 Err(not_found().into())
223}
224
225#[cfg(test)]
226mod tests {
227 use forge_core::Visibility;
228 use scraper::{Html, Selector};
229
230 use super::is_hex_prefix;
231 use crate::auth::SESSION_COOKIE;
232 use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get};
233 use topcoat::router::request::Request;
234 use topcoat::router::{Body, to_bytes};
235
236 fn doc(body: &[u8]) -> Html {
237 Html::parse_document(std::str::from_utf8(body).unwrap())
238 }
239
240 /// Text of each cell in every `tr` matching `row_selector`, as `[old, new, code]`.
241 fn rows(html: &Html, row_selector: &str) -> Vec<Vec<String>> {
242 let tr = Selector::parse(row_selector).unwrap();
243 let td = Selector::parse("td").unwrap();
244 html.select(&tr)
245 .map(|row| {
246 row.select(&td)
247 .map(|c| c.text().collect::<String>().trim().to_owned())
248 .collect()
249 })
250 .collect()
251 }
252
253 #[test]
254 fn hex_prefix_bounds() {
255 assert!(is_hex_prefix("abcd"));
256 assert!(is_hex_prefix(&"a".repeat(64)));
257 assert!(!is_hex_prefix("abc"));
258 assert!(!is_hex_prefix(&"a".repeat(65)));
259 assert!(!is_hex_prefix("zzzz"));
260 }
261
262 /// The modified and added files show line numbers, with their body and file headers.
263 async fn scenario_modified_and_added(fx: &Fixture) {
264 let (status, _, body) = get(
265 &fx.router,
266 &format!("/{OWNER}/{REPO}/commit/{}", fx.modified),
267 )
268 .await;
269 assert_eq!(status, 200);
270 let html = doc(&body);
271
272 let rows = rows(&html, "tr.diff-line");
273 let find = |code: &str| {
274 rows.iter()
275 .find(|r| r.get(2).map(String::as_str) == Some(code))
276 .unwrap_or_else(|| panic!("no row {code:?} in {rows:?}"))
277 .clone()
278 };
279 assert_eq!(find("-two"), vec!["2", "", "-two"]);
280 assert_eq!(find("+TWO"), vec!["", "2", "+TWO"]);
281 assert_eq!(find("three"), vec!["3", "3", "three"]);
282 assert_eq!(find("+four"), vec!["", "4", "+four"]);
283 assert_eq!(find("+new file"), vec!["", "1", "+new file"]);
284
285 let added = Selector::parse(".diff-file-header").unwrap();
286 let headers: Vec<String> = html
287 .select(&added)
288 .map(|h| h.text().collect::<String>())
289 .collect();
290 assert!(
291 headers
292 .iter()
293 .any(|h| h.contains("new.txt") && h.contains("added"))
294 );
295 assert!(
296 headers
297 .iter()
298 .any(|h| h.contains("a.txt") && h.contains("modified"))
299 );
300 let text = String::from_utf8_lossy(&body).into_owned();
301 assert!(text.contains("Body line one."));
302 assert!(text.contains("class=\"mono\""));
303 assert!(text.contains("diff-file-body"));
304 assert!(!text.contains("sig-badge"), "unsigned commit has no badge");
305 }
306
307 /// The root commit has no parent, and its one added line is shown.
308 async fn scenario_root_commit(fx: &Fixture) {
309 let (status, _, body) =
310 get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await;
311 assert_eq!(status, 200);
312 let html = String::from_utf8(body.clone()).unwrap();
313 assert!(html.contains("Root commit (no parents)"));
314 let rows = rows(&doc(&body), "tr.diff-line");
315 assert!(
316 rows.iter()
317 .any(|r| r.get(2).map(String::as_str) == Some("+one"))
318 );
319 }
320
321 /// Titles follow the viewer's timezone; anonymous viewers see UTC.
322 async fn scenario_title_timezone(fx: &Fixture) {
323 let tokyo = fx
324 .store
325 .create_user("tokyo", None, "not-a-real-hash", false)
326 .await
327 .unwrap();
328 fx.store
329 .set_profile(&tokyo.id, "", "Asia/Tokyo")
330 .await
331 .unwrap();
332 crate::test_support::create_session(&fx.store, &tokyo.id, "tokyo-token", "tokyo-csrf")
333 .await;
334 let uri = format!("/{OWNER}/{REPO}/commit/{}", fx.root);
335
336 let req = Request::builder()
337 .method("GET")
338 .uri(&uri)
339 .header("cookie", format!("__Host-{SESSION_COOKIE}=tokyo-token"))
340 .body(Body::empty())
341 .unwrap();
342 let res = fx.router.handle(req).await;
343 assert_eq!(res.status(), 200);
344 let html = String::from_utf8(
345 to_bytes(res.into_body(), usize::MAX)
346 .await
347 .unwrap()
348 .to_vec(),
349 )
350 .unwrap();
351 // Scope to the page's own `<main>`: the shell's theme button has a `title` with ':'.
352 let main = html
353 .split_once("<main")
354 .and_then(|(_, rest)| rest.split_once("</main>"))
355 .map(|(main, _)| main)
356 .expect("page has a <main> element");
357 let titles: Vec<&str> = main
358 .split("title=\"")
359 .skip(1)
360 .filter_map(|rest| rest.split('"').next())
361 .filter(|t| t.contains(':'))
362 .collect();
363 assert!(!titles.is_empty(), "absolute time in title: {html}");
364 assert!(
365 titles.iter().all(|t| t.ends_with("+09")),
366 "titles in Tokyo time: {titles:?}"
367 );
368
369 // Anonymous viewers see UTC, so no +09 offset.
370 let (status, _, body) = get(&fx.router, &uri).await;
371 assert_eq!(status, 200);
372 let anon = String::from_utf8(body).unwrap();
373 assert!(!anon.contains("+09\""), "anonymous view is not Tokyo time");
374 }
375
376 /// Bad and unknown oids are 404.
377 async fn scenario_bad_oid(fx: &Fixture) {
378 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/zzzz")).await;
379 assert_eq!(status, 404);
380 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/abc")).await;
381 assert_eq!(status, 404);
382 let unknown = "0123456789abcdef0123456789abcdef01234567";
383 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{unknown}")).await;
384 assert_eq!(status, 404);
385 }
386
387 /// Every page of one public commit, on one fixture. The scenarios only read, so order is free.
388 #[tokio::test]
389 async fn public_commit_pages() {
390 let fx = Fixture::new(Visibility::Public).await;
391 scenario_modified_and_added(&fx).await;
392 scenario_root_commit(&fx).await;
393 scenario_title_timezone(&fx).await;
394 scenario_bad_oid(&fx).await;
395 }
396
397 #[tokio::test]
398 async fn private_repo_is_404_for_anonymous() {
399 let fx = Fixture::new(Visibility::Private).await;
400 let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/{}", fx.root)).await;
401 assert_eq!(status, 404);
402 }
403}