forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB197fa34Tahinli1 month ago68 commits

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