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