steid

@jamesgill /

1//! Blame — the same file as the blob page, read by who last changed each line.
2//!
3//! One route, `/{handle}/repos/{name}/blame/{rev}/-/{*path}`, deliberately shaped like
4//! the tree URL: the `/-/` separator means the same thing here, a `{rev}` may still
5//! carry a `%2F`, and a reader editing `tree` to `blame` in the address bar lands
6//! exactly where they expected.
7//!
8//! The two views share a header, so switching between them does not feel like leaving
9//! the file. [`view_toggle`] is that header's control and is rendered by the blob page
10//! too — it lives here because blame is the view that needed it to exist.
11
12use std::time::SystemTime;
13
14use topcoat::{
15 Result,
16 context::Cx,
17 icon::{icon, iconify::iconify_icon},
18 router::{error::not_found, page, path_param},
19 view::{Unescaped, attributes, component, view},
20};
21
22use crate::{
23 application::{Blame, BlameContent, BlameFile, BlameGroup, blame::AGE_STEPS, blame_file},
24 domain::{ObjectId, RefName, RepoPath},
25 infrastructure::highlight::{Source, SourceLine, content_digest},
26};
27
28use super::{
29 browse::{
30 Switch, ago, crumbs, encode, is_markdown, path_log_url, raw_url, ref_links, refs_for,
31 rev_switcher, size_of, tree_url,
32 },
33 context::{
34 current_actor, highlights, memberships, orgs, queries, repos, server_error, timed_out,
35 },
36 layout::wide,
37 repo::{Tab, repo_for, repo_header},
38};
39
40/// `{rev}` from the path, raw — validation is [`RefName`]'s job, as on the tree routes.
41#[path_param]
42struct Rev(str);
43
44/// `{*path}` from the path: every remaining segment, as one string.
45#[path_param]
46struct Path(str);
47
48#[page("/{handle}/repos/{name}/blame/{rev}/-/{*path}")]
49async fn blame_page(cx: &Cx) -> Result {
50 // A malformed revision or path is a page that does not exist rather than a bad
51 // request — the same answer the tree routes give.
52 let rev = RefName::new(path_param::<Rev>(cx)).map_err(|_| not_found())?;
53 let path = RepoPath::new(path_param::<Path>(cx)).map_err(|_| not_found())?;
54
55 view! { blaming(rev: rev, path: path) }
56}
57
58/// What the page has to render, once the use case has answered.
59///
60/// Flattened into one enum before the view rather than matched in nested branches
61/// inside it: every one of these is a designed state, and a flat match is what makes it
62/// obvious when one has been left out.
63enum Body<'a> {
64 /// git was still walking history when the adapter's timeout cut it off.
65 TimedOut,
66 Ready(&'a Blame),
67 /// A file with no lines at all. Blame has nothing to say about it.
68 Empty,
69 Binary,
70 TooLarge(u64),
71}
72
73/// The blame page. A component rather than a plain function because `view!` needs the
74/// request context in scope.
75#[component]
76async fn blaming(cx: &Cx, rev: RefName, path: RepoPath) -> Result {
77 let repo = repo_for(cx).await?;
78
79 let outcome = blame_file(
80 &repo.handle,
81 &repo.name,
82 &rev,
83 &path,
84 &current_actor(cx).await?,
85 &orgs(cx),
86 &memberships(cx),
87 &repos(cx),
88 &queries(cx),
89 )
90 .await;
91
92 // A blame that ran out of time is the one failure this page answers with a page.
93 // It is a statement about *this file* — long history, many lines — not about the
94 // instance being broken, so a 500 would both look wrong and hide the reason.
95 let file: Option<BlameFile> = match outcome {
96 Ok(Some(file)) => Some(file),
97 Ok(None) => return Err(not_found().into()),
98 Err(error) if timed_out(&error) => None,
99 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
100 };
101
102 let body = match &file {
103 None => Body::TimedOut,
104 Some(file) => match &file.content {
105 BlameContent::Binary => Body::Binary,
106 BlameContent::TooLarge => Body::TooLarge(file.size),
107 BlameContent::Ready(blame) if blame.is_empty() => Body::Empty,
108 BlameContent::Ready(blame) => Body::Ready(blame),
109 },
110 };
111
112 let handle = repo.handle.as_str();
113 let name = repo.name.as_str();
114 let blob = tree_url(handle, name, &rev, &path);
115
116 // One more `git` process, and the reason blame shipped without a switcher: the
117 // header is shared with the tree and the log, and a file header with no way to
118 // change revision is the odd one out of the three. Switching keeps you on blame at
119 // the same path — [`Switch::Blame`].
120 let refs = refs_for(cx, &repo).await?;
121 let at = rev.as_str();
122 let known = refs.contains(&rev);
123 let switch = Switch::Blame(&path);
124 let branches = ref_links(handle, name, &refs.branches, at, &switch);
125 let tags = ref_links(handle, name, &refs.tags, at, &switch);
126
127 // Built here rather than inside the view: the message borrows a formatted string,
128 // and a temporary created inside `view!` does not outlive the branch that made it.
129 let oversized = match &body {
130 Body::TooLarge(size) => format!(
131 "This file is {}, which is too large to blame. Clone the repository to read it.",
132 size_of(*size),
133 ),
134 _ => String::new(),
135 };
136
137 view! {
138 wide(
139 repo_header(
140 repo: &repo,
141 rev: at,
142 active: Tab::Code,
143 rev_switcher(current: at, known: known, branches: &branches, tags: &tags)
144 )
145
146 <div class="overflow-hidden rounded-lg border border-border">
147 <div class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-2.5">
148 crumbs(handle: handle, name: name, rev: &rev, path: &path)
149 <span class="flex items-center gap-3 font-mono text-xs text-muted-foreground">
150 match &file {
151 // Unknown after a timeout: the size came from the read that
152 // did finish, and there was none.
153 Some(file) => (size_of(file.size)),
154 None => "",
155 }
156 view_toggle(
157 handle: handle,
158 name: name,
159 rev: &rev,
160 path: &path,
161 active: FileTab::Blame,
162 markdown: is_markdown(&path),
163 )
164 </span>
165 </div>
166
167 match body {
168 Body::Ready(blame) => blame_rows(
169 handle: handle,
170 name: name,
171 path: &path,
172 blob: blob.as_str(),
173 blame: blame,
174 ),
175 Body::Empty => note(message: "This file is empty."),
176 Body::Binary => note(message: "This file cannot be blamed as text."),
177 Body::TooLarge(_) => note(message: oversized.as_str()),
178 Body::TimedOut => took_too_long(blob: blob.as_str()),
179 }
180 </div>
181 )
182 }
183}
184
185/// Anything the page has instead of a table, in the blob page's own words and shape.
186#[component]
187async fn note(message: &str) -> Result {
188 view! {
189 <p class="px-4 py-6 text-center text-sm text-muted-foreground">(message)</p>
190 }
191}
192
193/// What a blame that could not finish says.
194///
195/// It offers the file itself rather than a retry: the read will take just as long the
196/// second time, and the reader came here to see the file.
197#[component]
198async fn took_too_long(blob: &str) -> Result {
199 view! {
200 <div class="px-4 py-6 text-center">
201 <p class="text-sm text-muted-foreground">
202 "Blame took too long for this file."
203 </p>
204 <p class="mt-1 text-xs text-muted-foreground">
205 "Its history is long enough that walking it ran out of time. "
206 <a href=(blob) class="text-primary hover:underline">"Read the file instead"</a>
207 "."
208 </p>
209 </div>
210 }
211}
212
213/// One rendered line of the table.
214struct Row<'a> {
215 group: &'a BlameGroup,
216 /// The first line of a run, which is the only one that names its commit.
217 starts_run: bool,
218 /// Whether this row opens a run with a hairline — every run but the file's first.
219 ruled: bool,
220 /// 1-based, and what the `#L{n}` link points at.
221 number: usize,
222 code: SourceLine,
223}
224
225/// Where a line of a run sits in the file, 0-based.
226///
227/// One function because the reassembled text and the rendered rows must agree about it;
228/// two copies of `start_line + offset - 1` is exactly how they would stop agreeing.
229fn line_index(group: &BlameGroup, offset: usize) -> usize {
230 (group.start_line + offset).saturating_sub(1)
231}
232
233/// The blame table: commit, line number, code.
234///
235/// A table, and one row per line with the same type and leading as the blob's, so
236/// scrolling from one view to the other lands on the same lines in the same places. The
237/// commit cell is deliberately **one line tall** — anything taller would make the two
238/// views of a file disagree about where line 400 is.
239///
240/// The code cell goes through [`source_lines`], the same adapter and therefore the same
241/// classes, caps and plain fallback as the blob's. It is called **once for the whole
242/// file, not once per run**: `highlight.rs` carries parse state across lines — a block
243/// comment opens on one line and closes on another — and a blamed run is an arbitrary
244/// slice of the file, so highlighting a run on its own would start mid-language.
245/// Highlighting only ever changes what is inside the cell, so the row height is the
246/// blob's either way.
247#[component]
248async fn blame_rows(
249 cx: &Cx,
250 handle: &str,
251 name: &str,
252 path: &RepoPath,
253 blob: &str,
254 blame: &Blame,
255) -> Result {
256 // Reassembled by line number rather than by walking the groups in order, so the
257 // colouring cannot drift from the numbering even if a run ever arrives out of
258 // sequence. Joined with `\n` and never a trailing one, so the line count is exactly
259 // `blame.line_count()` — the invariant `source_lines` checks before it trusts its
260 // own output.
261 let mut ordered = vec![""; blame.line_count()];
262 for group in &blame.groups {
263 for (offset, line) in group.lines.iter().enumerate() {
264 if let Some(slot) = ordered.get_mut(line_index(group, offset)) {
265 *slot = line.as_str();
266 }
267 }
268 }
269
270 // Through the same cache the blob view uses, keyed by a digest of the reassembled
271 // text rather than by the blob's object id: blame's body is joined from runs and has
272 // no trailing newline, so it is *not* byte-identical to the blob and must not be
273 // handed the blob's key. Keying by content means the two views simply hold two
274 // entries, and neither can ever serve the other's markup.
275 let text = ordered.join("\n");
276 let Source { lines, too_large } = highlights(cx)
277 .source_lines(
278 &content_digest(&text),
279 path.file_name().unwrap_or_default(),
280 &text,
281 )
282 .as_ref()
283 .clone();
284
285 // Flattened to one row per line before the view rather than nested `for`s inside
286 // it: the code cell now owns highlighted markup, and a local the view only borrows
287 // does not outlive it.
288 let mut rows: Vec<Row> = Vec::new();
289 let mut code = lines.into_iter();
290 for (index, group) in blame.groups.iter().enumerate() {
291 for offset in 0..group.lines.len() {
292 rows.push(Row {
293 group,
294 // The commit is shown once per run, and every run but the first opens
295 // with a hairline. Repeating the sha down forty adjacent rows is noise;
296 // saying it once is the whole reason blame is grouped.
297 starts_run: offset == 0,
298 ruled: offset == 0 && index > 0,
299 number: line_index(group, offset) + 1,
300 // An empty cell has no height, and a blame row must keep the blob's.
301 code: code
302 .next()
303 .unwrap_or_else(|| SourceLine::Plain(" ".to_owned())),
304 });
305 }
306 }
307
308 view! {
309 if too_large {
310 <p class="border-b border-border px-4 py-1.5 font-mono text-xs text-muted-foreground">
311 "Too large to highlight — shown as plain text."
312 </p>
313 }
314
315 <div class="overflow-x-auto">
316 <table class="w-full border-collapse font-mono text-xs leading-relaxed">
317 <tbody>
318 for row in rows {
319 <tr class=(if row.ruled { "border-t border-border" } else { "" })>
320 // The age tint rides on the leftmost cell of every row in
321 // the run, so consecutive rows draw one unbroken edge. See
322 // `styles.css`.
323 <td class=(format!(
324 "w-px border-r border-border pl-2 pr-3 align-top blame-age blame-age-{}",
325 row.group.age.min(AGE_STEPS - 1),
326 ))>
327 if row.starts_run {
328 commit_cell(
329 handle: handle,
330 name: name,
331 path: path,
332 group: row.group,
333 )
334 }
335 </td>
336 <td class="w-px select-none border-r border-border px-3 text-right align-top text-muted-foreground">
337 <a
338 href=(format!("{blob}#L{}", row.number))
339 class="hover:text-foreground"
340 >((row.number).to_string())</a>
341 </td>
342 <td class="whitespace-pre px-4 align-top">
343 match row.code {
344 // Markup this codebase wrote: `highlight` escapes
345 // the source itself and emits nothing but spans.
346 SourceLine::Classed(html) => (Unescaped::new_unchecked(html)),
347 SourceLine::Plain(text) => (text),
348 }
349 </td>
350 </tr>
351 }
352 </tbody>
353 </table>
354 </div>
355 }
356}
357
358/// Who a run of lines came from, on the first row of the run and nowhere else.
359///
360/// Repeating the same commit down forty adjacent rows is noise; saying it once is the
361/// whole reason blame is grouped.
362///
363/// A fixed width, narrower on a small viewport: the code beside it is what the reader
364/// came for, and on an 800px window a 20rem column of attribution would take half of
365/// it. The summary truncates inside whichever width applies.
366#[component]
367async fn commit_cell(handle: &str, name: &str, path: &RepoPath, group: &BlameGroup) -> Result {
368 let commit = &group.commit;
369 // git names the file once per commit, so an empty one is a run it said nothing
370 // about rather than a rename from nowhere.
371 let moved = !commit.filename.is_empty() && commit.filename != path.as_str();
372
373 let mut about = format!(
374 "{} · {} · {}",
375 commit.author_name,
376 ago(commit.authored_at),
377 commit.summary,
378 );
379
380 // A boundary commit is where git stopped walking, so the lines it holds may be
381 // older than it is. Worth saying, not worth a mark on a row that has to stay one
382 // line tall.
383 if commit.boundary {
384 about.push_str(" · the oldest commit blame reached");
385 }
386
387 view! {
388 <div class="flex w-56 items-baseline gap-2 overflow-hidden lg:w-80">
389 <a
390 href=(commit_url(handle, name, &commit.id))
391 title=(about.as_str())
392 class="shrink-0 text-muted-foreground hover:text-foreground"
393 >(commit.id.short())</a>
394
395 if moved {
396 <span
397 class="shrink-0 self-center text-muted-foreground"
398 title=(format!("Moved from {}", commit.filename))
399 >
400 icon(
401 data: iconify_icon!("feather:corner-down-right"),
402 label: "Moved from another file",
403 attrs: attributes! { class="size-3" },
404 )
405 </span>
406 }
407
408 <span class="min-w-0 flex-1 truncate text-muted-foreground" title=(about.as_str())>
409 (&commit.summary)
410 </span>
411 <span class="shrink-0 text-muted-foreground">(short_ago(commit.authored_at))</span>
412 </div>
413 }
414}
415
416// --- The shared file header -------------------------------------------------------
417
418/// Which view of a file is being looked at.
419///
420/// Raw is not a variant: it downloads rather than displays, so it is never the view you
421/// are on.
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423pub(super) enum FileTab {
424 /// The file as it is meant to be read: the line table, or the rendered document
425 /// for a markdown file.
426 Code,
427 /// A markdown file's own source. Never reached for anything else, which has one
428 /// reading and therefore one entry in the toggle.
429 Source,
430 Blame,
431 /// The path's own history. Not a reading of the file's *contents* like the other
432 /// two, but it is reached from here and belongs in the same row: a reader looking
433 /// at a file wants "who changed this" and "what happened to this" side by side.
434 History,
435}
436
437/// `Code · Blame · History · Raw`, in the file header of every view of a file.
438///
439/// A markdown file reads `Rendered · Source · …` instead of `Code`, because it has two
440/// readings of its contents rather than one and the first entry would otherwise be the
441/// only one that did not say which it was.
442///
443/// The active one is marked with the primary colour, which is the same rule the
444/// repository's tab strip follows: the primary colour says where you are, and nothing
445/// else on the header is coloured.
446#[component]
447pub(super) async fn view_toggle(
448 handle: &str,
449 name: &str,
450 rev: &RefName,
451 path: &RepoPath,
452 active: FileTab,
453 /// Whether this file has a rendering as well as a source.
454 markdown: bool,
455) -> Result {
456 let item = |current| {
457 if current {
458 "text-primary"
459 } else {
460 "text-muted-foreground hover:text-foreground"
461 }
462 };
463
464 view! {
465 <span class="flex items-center gap-1.5">
466 if markdown {
467 <a
468 href=(tree_url(handle, name, rev, path))
469 class=(item(active == FileTab::Code))
470 >"Rendered"</a>
471 <span class="text-border">"·"</span>
472 <a
473 href=(source_url(handle, name, rev, path))
474 class=(item(active == FileTab::Source))
475 >"Source"</a>
476 } else {
477 <a
478 href=(tree_url(handle, name, rev, path))
479 class=(item(active == FileTab::Code || active == FileTab::Source))
480 >"Code"</a>
481 }
482 <span class="text-border">"·"</span>
483 <a
484 href=(blame_url(handle, name, rev, path))
485 class=(item(active == FileTab::Blame))
486 >"Blame"</a>
487 <span class="text-border">"·"</span>
488 <a
489 href=(path_log_url(handle, name, rev, path))
490 class=(item(active == FileTab::History))
491 >"History"</a>
492 <span class="text-border">"·"</span>
493 // The way out for anything neither view can show — a binary, an oversized
494 // file — and the URL to hand to `curl`.
495 <a
496 href=(raw_url(handle, name, rev, path))
497 class="inline-flex items-center gap-1 text-muted-foreground hover:text-foreground"
498 >
499 icon(data: iconify_icon!("feather:download"), attrs: attributes! {
500 class="size-3.5"
501 })
502 "Raw"
503 </a>
504 </span>
505 }
506}
507
508// --- URLs -------------------------------------------------------------------------
509
510/// A markdown file's source, which is the ordinary file URL asking for the other view.
511///
512/// A query parameter rather than a route: it is the same file at the same address read
513/// two ways, and a second route would make its canonical URL ambiguous.
514pub(super) fn source_url(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> String {
515 format!("{}?view=source", tree_url(handle, name, rev, path))
516}
517
518/// Blame's URL for a path at a revision. Shaped exactly like the tree's, and encoded
519/// the same way — the revision whole, the path with its slashes intact.
520pub(super) fn blame_url(handle: &str, name: &str, rev: &RefName, path: &RepoPath) -> String {
521 format!(
522 "/{handle}/repos/{name}/blame/{}/-/{}",
523 encode(rev.as_str(), false),
524 encode(path.as_str(), true)
525 )
526}
527
528/// Where a commit's own page is.
529///
530/// Rendered before that page exists, by agreement: the sha is the most useful thing on
531/// a blame row and a sha with nowhere to go is the least.
532fn commit_url(handle: &str, name: &str, id: &ObjectId) -> String {
533 format!("/{handle}/repos/{name}/commits/{}", id.as_str())
534}
535
536// --- Formatting -------------------------------------------------------------------
537
538/// How long ago, in as few characters as it can be said.
539///
540/// The long form `ago` gives — "3 months ago" — is the tooltip. On the row itself the
541/// date shares one line with a sha and a summary, and the summary is what deserves the
542/// space.
543fn short_ago(time: SystemTime) -> String {
544 let Ok(elapsed) = SystemTime::now().duration_since(time) else {
545 // A commit carries whoever made it's clock, so a future timestamp is a thing
546 // that happens rather than a thing to render as a negative.
547 return "now".to_owned();
548 };
549
550 let seconds = elapsed.as_secs();
551
552 match seconds {
553 0..=59 => "now".to_owned(),
554 60..=3599 => format!("{}m", seconds / 60),
555 3600..=86_399 => format!("{}h", seconds / 3600),
556 86_400..=2_591_999 => format!("{}d", seconds / 86_400),
557 2_592_000..=31_535_999 => format!("{}mo", seconds / 2_592_000),
558 _ => format!("{}y", seconds / 31_536_000),
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use std::time::Duration;
565
566 use super::*;
567
568 fn rev(value: &str) -> RefName {
569 RefName::new(value).expect("valid revision")
570 }
571
572 #[test]
573 fn a_blame_url_mirrors_the_tree_url_it_is_reached_from() {
574 let path = RepoPath::new("src/domain/repo.rs").expect("valid");
575
576 assert_eq!(
577 blame_url("ada", "steid", &rev("main"), &path),
578 "/ada/repos/steid/blame/main/-/src/domain/repo.rs"
579 );
580 }
581
582 #[test]
583 fn a_revisions_slashes_stay_inside_one_segment() {
584 // Otherwise `feature/login` would look like a revision plus a path, which is the
585 // ambiguity the `/-/` separator exists to remove.
586 let path = RepoPath::new("README.md").expect("valid");
587
588 assert_eq!(
589 blame_url("ada", "steid", &rev("feature/login"), &path),
590 "/ada/repos/steid/blame/feature%2Flogin/-/README.md"
591 );
592 }
593
594 #[test]
595 fn a_source_url_is_the_file_asking_for_its_other_view() {
596 let path = RepoPath::new("docs/design.md").expect("valid");
597
598 assert_eq!(
599 source_url("ada", "steid", &rev("main"), &path),
600 "/ada/repos/steid/tree/main/-/docs/design.md?view=source"
601 );
602 }
603
604 #[test]
605 fn a_commit_url_carries_the_whole_id() {
606 // Never the abbreviation: it is unambiguous today and need not stay so.
607 let id = ObjectId::from_trusted("0123456789abcdef0123456789abcdef01234567");
608
609 assert_eq!(
610 commit_url("ada", "steid", &id),
611 "/ada/repos/steid/commits/0123456789abcdef0123456789abcdef01234567"
612 );
613 }
614
615 #[test]
616 fn a_relative_date_fits_beside_a_sha() {
617 let now = SystemTime::now();
618 let since = |seconds| short_ago(now - Duration::from_secs(seconds));
619
620 assert_eq!(since(5), "now");
621 assert_eq!(since(600), "10m");
622 assert_eq!(since(7200), "2h");
623 assert_eq!(since(86_400 * 3), "3d");
624 assert_eq!(since(86_400 * 70), "2mo");
625 assert_eq!(since(86_400 * 400), "1y");
626 }
627
628 #[test]
629 fn a_commit_from_the_future_reads_as_now() {
630 assert_eq!(
631 short_ago(SystemTime::now() + Duration::from_secs(3600)),
632 "now"
633 );
634 }
635}