steid

@jamesgill /

Rust23.9 KBCode·Blame·History·Raw
1//! Who last changed each line of a file.
2//!
3//! Two halves. [`parse_blame`] is a pure parser for `git blame --porcelain`, which is
4//! where all of the fiddly knowledge about that format lives and where it is tested.
5//! [`blame_file`] is the use case, and it does not re-implement authorization: it goes
6//! through [`visible_repo`](super::access::visible_repo), so a repository invisible on its page
7//! is invisible here.
8//!
9//! Blame is displayed in *groups* — consecutive lines that arrived in the same commit —
10//! because a file's blame is mostly runs, and repeating the same commit on forty
11//! adjacent lines is noise rather than information.
12
13use std::{
14 collections::HashMap,
15 time::{Duration, SystemTime, UNIX_EPOCH},
16};
17
18use crate::domain::{
19 Actor, ObjectId, OrgName, RefName, RepoName, RepoPath,
20 repository::{MembershipRepository, OrgRepository, RepoRepository},
21};
22
23use super::{
24 access::{Stores, visible_repo},
25 browse::MAX_BLOB_BYTES,
26 error::Result,
27 port::GitQuery,
28};
29
30/// How many steps of age the tint has.
31///
32/// Five, because the tint is texture rather than a heat map: it should say "this part of
33/// the file is older than that part" at a glance and nothing more precise. A continuous
34/// gradient would invite reading a value off it that blame cannot support.
35pub const AGE_STEPS: u8 = 5;
36
37/// One commit, as blame describes it.
38///
39/// The author rather than the committer, because blame answers "who wrote this line".
40/// A rebase rewrites committer information and leaves authorship alone, which is the
41/// behaviour that makes the answer stable.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct BlameCommit {
44 pub id: ObjectId,
45 pub summary: String,
46 pub author_name: String,
47 pub authored_at: SystemTime,
48 /// Whether git stopped walking here — the commit is at the edge of the range it was
49 /// given, so the lines it is credited with may well be older than it is.
50 pub boundary: bool,
51 /// What the file was called in that commit.
52 ///
53 /// git names it once per commit in the porcelain stream, so it is carried on the
54 /// commit rather than on the run of lines. Differs from the path being browsed
55 /// exactly when the file was renamed or the lines moved.
56 pub filename: String,
57}
58
59/// A run of consecutive lines that arrived in the same commit.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct BlameGroup {
62 pub commit: BlameCommit,
63 /// The 1-based line number this run starts at.
64 pub start_line: usize,
65 pub lines: Vec<String>,
66 /// `0` for the file's oldest commit, `AGE_STEPS - 1` for its newest.
67 ///
68 /// Decided here rather than in the view because it is arithmetic over the whole
69 /// file, which a component rendering one row cannot see.
70 pub age: u8,
71}
72
73/// A file, line by line, grouped by the commit each line came from.
74#[derive(Debug, Clone, Default, PartialEq, Eq)]
75pub struct Blame {
76 pub groups: Vec<BlameGroup>,
77}
78
79impl Blame {
80 /// An empty file blames to nothing at all, which the page says rather than showing
81 /// an empty table.
82 pub fn is_empty(&self) -> bool {
83 self.groups.is_empty()
84 }
85
86 pub fn line_count(&self) -> usize {
87 self.groups.iter().map(|group| group.lines.len()).sum()
88 }
89}
90
91/// What blaming a path produced.
92///
93/// The same three outcomes the blob page has, decided the same way and from the same
94/// cap, so the two views of a file agree about what they can show.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub enum BlameContent {
97 Ready(Blame),
98 /// Not valid UTF-8, so there are no lines to attribute.
99 Binary,
100 /// Larger than [`MAX_BLOB_BYTES`].
101 TooLarge,
102}
103
104/// A blamed file, with the size the page reports whatever the outcome.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct BlameFile {
107 pub size: u64,
108 pub content: BlameContent,
109}
110
111/// Blames a file at a revision.
112///
113/// `Ok(None)` means the repository is invisible, absent, or has nothing blameable at
114/// that path — an unknown revision, a path that is not there, and a directory are all
115/// one answer, for the reason [`visible_repo`](super::access::visible_repo) gives.
116///
117/// **Two `git` processes before blame itself.** The blob is read first, to decide
118/// binary, too-large and not-there exactly as the blob page decides them rather than
119/// with a second set of rules that could disagree. The alternative — deriving those from
120/// blame's own output — cannot tell a binary file from a text one, because the porcelain
121/// stream carries the bytes without saying what they are.
122pub async fn blame_file(
123 handle: &OrgName,
124 name: &RepoName,
125 rev: &RefName,
126 path: &RepoPath,
127 actor: &Actor,
128 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
129 queries: &impl GitQuery,
130) -> Result<Option<BlameFile>> {
131 if visible_repo(actor, handle, name, stores).await?.is_none() {
132 return Ok(None);
133 }
134
135 let Some(blob) = queries
136 .read_blob(handle, name, rev, path, MAX_BLOB_BYTES)
137 .await?
138 else {
139 return Ok(None);
140 };
141
142 let content = match &blob.content {
143 // The port reports the size and withholds the bytes past the cap, so this is
144 // "too large" rather than "unreadable".
145 None => BlameContent::TooLarge,
146 Some(bytes) if std::str::from_utf8(bytes).is_err() => BlameContent::Binary,
147 Some(_) => match queries.blame(handle, name, rev, path).await? {
148 Some(blame) => BlameContent::Ready(blame),
149 // The path resolved a moment ago, so this is a repository that changed
150 // underneath the request. A 404 is the honest answer to "blame what?".
151 None => return Ok(None),
152 },
153 };
154
155 Ok(Some(BlameFile {
156 size: blob.size,
157 content,
158 }))
159}
160
161/// What one line of the porcelain stream said, before lines are grouped.
162struct Attributed {
163 commit: ObjectId,
164 line: usize,
165 content: String,
166}
167
168/// The header block git writes once per commit.
169#[derive(Default, Clone)]
170struct CommitHeader {
171 summary: String,
172 author_name: String,
173 authored_at: i64,
174 boundary: bool,
175 filename: String,
176}
177
178/// Parses `git blame --porcelain` output into runs of lines.
179///
180/// The format is a header line — `<sha> <original line> <final line> [<run length>]` —
181/// then zero or more `<key> <value>` lines, then the line itself prefixed with a tab.
182/// The key block is written **in full only the first time a commit appears**, so commit
183/// details are accumulated by sha and looked up again for every later run.
184///
185/// Nothing here fails. A record git spells in a shape this does not recognise is skipped
186/// rather than turned into an error: blame is a view of a file that renders fine without
187/// one line's attribution, and refusing the whole page over an unexpected key would make
188/// a future git version an outage.
189///
190/// Content is decoded lossily for the same reason a tree listing is: a file that is
191/// almost text still blames usefully, and the alternative is a blank page.
192pub fn parse_blame(stdout: &[u8]) -> Blame {
193 let mut headers: HashMap<String, CommitHeader> = HashMap::new();
194 let mut attributed: Vec<Attributed> = Vec::new();
195 let mut pending: Option<(ObjectId, usize)> = None;
196
197 for record in stdout.split(|byte| *byte == b'\n') {
198 // The content line is the only one that starts with a tab, and it is what ends
199 // an entry. Checked first, because a line of code can look like anything.
200 if let Some((commit, line)) = pending.clone()
201 && record.first() == Some(&b'\t')
202 {
203 attributed.push(Attributed {
204 commit,
205 line,
206 content: String::from_utf8_lossy(&record[1..])
207 .trim_end_matches('\r')
208 .to_owned(),
209 });
210 pending = None;
211 continue;
212 }
213
214 let text = String::from_utf8_lossy(record);
215 let text = text.trim_end_matches('\r');
216
217 if text.is_empty() {
218 continue;
219 }
220
221 let Some((commit, _)) = pending.clone() else {
222 // A header line. Its first three fields are the sha and the line numbers;
223 // the fourth, when present, is the run length, which is re-derived from the
224 // grouping below rather than trusted.
225 let mut fields = text.split(' ');
226 let (Some(sha), Some(_original), Some(line)) =
227 (fields.next(), fields.next(), fields.next())
228 else {
229 continue;
230 };
231
232 let (Ok(sha), Ok(line)) = (ObjectId::new(sha), line.parse::<usize>()) else {
233 continue;
234 };
235
236 pending = Some((sha, line));
237 continue;
238 };
239
240 let (key, value) = text.split_once(' ').unwrap_or((text, ""));
241 let header = headers.entry(commit.as_str().to_owned()).or_default();
242
243 match key {
244 "author" => header.author_name = value.to_owned(),
245 "author-time" => header.authored_at = value.parse().unwrap_or_default(),
246 "summary" => header.summary = value.to_owned(),
247 // A valueless key, so it splits to nothing and is recognised by name alone.
248 "boundary" => header.boundary = true,
249 "filename" => header.filename = value.to_owned(),
250 _ => {}
251 }
252 }
253
254 group(attributed, &headers)
255}
256
257/// Collapses attributed lines into runs and tints them by age.
258fn group(attributed: Vec<Attributed>, headers: &HashMap<String, CommitHeader>) -> Blame {
259 let mut groups: Vec<BlameGroup> = Vec::new();
260 let mut times: Vec<i64> = Vec::new();
261
262 for line in attributed {
263 let continues = groups.last().is_some_and(|last| {
264 last.commit.id == line.commit && last.start_line + last.lines.len() == line.line
265 });
266
267 if continues {
268 groups
269 .last_mut()
270 .expect("a continued run has a last group")
271 .lines
272 .push(line.content);
273 continue;
274 }
275
276 let header = headers
277 .get(line.commit.as_str())
278 .cloned()
279 .unwrap_or_default();
280
281 times.push(header.authored_at);
282 groups.push(BlameGroup {
283 commit: BlameCommit {
284 id: line.commit,
285 summary: header.summary,
286 author_name: header.author_name,
287 authored_at: unix_time(header.authored_at),
288 boundary: header.boundary,
289 filename: header.filename,
290 },
291 start_line: line.line,
292 lines: vec![line.content],
293 age: 0,
294 });
295 }
296
297 tint(&mut groups, &times);
298
299 Blame { groups }
300}
301
302/// Assigns each run an age step between the file's oldest and newest commit.
303///
304/// Relative to *this file* rather than to wall-clock time: a file nobody has touched for
305/// two years still has a most-recently-changed part, and that is the thing worth seeing.
306///
307/// A file whose lines all come from one moment is uniformly as new as it gets, so it
308/// takes the top step rather than the bottom one — there is nothing older to contrast it
309/// with.
310fn tint(groups: &mut [BlameGroup], times: &[i64]) {
311 let (Some(oldest), Some(newest)) = (times.iter().min(), times.iter().max()) else {
312 return;
313 };
314
315 let span = newest - oldest;
316 let last = i64::from(AGE_STEPS - 1);
317
318 for (group, time) in groups.iter_mut().zip(times) {
319 group.age = if span == 0 {
320 AGE_STEPS - 1
321 } else {
322 // Integer arithmetic on seconds: the span of a file's history is far too
323 // small to overflow, and floats would only add rounding to argue about.
324 (((time - oldest) * i64::from(AGE_STEPS) / span).min(last)) as u8
325 };
326 }
327}
328
329/// A unix timestamp as a `SystemTime`, including the negative ones a rewritten or
330/// imported history can carry.
331fn unix_time(seconds: i64) -> SystemTime {
332 match u64::try_from(seconds) {
333 Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
334 Err(_) => UNIX_EPOCH - Duration::from_secs(seconds.unsigned_abs()),
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 /// Captured from `git blame --porcelain` on this repository and then trimmed: two
343 /// commits, a boundary commit, and a run whose lines were moved in under a different
344 /// filename by a rename.
345 const PORCELAIN: &[u8] = b"\
346af126c7704b91896c347742dbf91c9abac20cb99 1 1 2
347author Ada Lovelace
348author-mail <ada@example.com>
349author-time 1786485070
350author-tz +0100
351committer Ada Lovelace
352committer-mail <ada@example.com>
353committer-time 1786485070
354committer-tz +0100
355summary feat: the first components
356boundary
357filename components.toml
358\t# Topcoat UI install state.
359af126c7704b91896c347742dbf91c9abac20cb99 2 2
360\tversion = 1
361285f5fd29aabe8814c7b94bca3a89b3e176410e8 3 3 2
362author Grace Hopper
363author-mail <grace@example.com>
364author-time 1786614911
365author-tz +0100
366committer Grace Hopper
367committer-mail <grace@example.com>
368committer-time 1786614911
369committer-tz +0100
370summary feat: create and view repositories
371previous af126c7704b91896c347742dbf91c9abac20cb99 old-name.toml
372filename old-name.toml
373\t[theme]
374285f5fd29aabe8814c7b94bca3a89b3e176410e8 4 4
375\tname = \"neutral\"
376af126c7704b91896c347742dbf91c9abac20cb99 5 5 1
377filename components.toml
378\tregistry = \"topcoat\"
379";
380
381 fn blame() -> Blame {
382 parse_blame(PORCELAIN)
383 }
384
385 #[test]
386 fn consecutive_lines_from_one_commit_become_one_run() {
387 let blame = blame();
388
389 assert_eq!(blame.groups.len(), 3, "{:#?}", blame.groups);
390 assert_eq!(blame.line_count(), 5);
391 assert_eq!(blame.groups[0].start_line, 1);
392 assert_eq!(
393 blame.groups[0].lines,
394 vec!["# Topcoat UI install state.", "version = 1"]
395 );
396 assert_eq!(blame.groups[1].start_line, 3);
397 assert_eq!(blame.groups[2].start_line, 5);
398 }
399
400 #[test]
401 fn a_commit_returning_later_is_a_second_run_rather_than_a_continuation() {
402 // Lines 1-2 and line 5 are the same commit but not adjacent, so blame must not
403 // merge them — merging would credit line 5's position to the wrong place.
404 let blame = blame();
405
406 assert_eq!(blame.groups[0].commit.id, blame.groups[2].commit.id);
407 assert_eq!(blame.groups[2].lines, vec!["registry = \"topcoat\""]);
408 }
409
410 #[test]
411 fn commit_details_are_remembered_for_later_runs() {
412 // The header block is written once. The third run's record carries only a sha,
413 // so everything it shows has to come from the first appearance.
414 let blame = blame();
415 let third = &blame.groups[2].commit;
416
417 assert_eq!(third.author_name, "Ada Lovelace");
418 assert_eq!(third.summary, "feat: the first components");
419 assert_eq!(third.authored_at, unix_time(1_786_485_070));
420 }
421
422 #[test]
423 fn a_boundary_commit_is_marked_as_one() {
424 let blame = blame();
425
426 assert!(blame.groups[0].commit.boundary);
427 assert!(!blame.groups[1].commit.boundary);
428 }
429
430 #[test]
431 fn a_run_moved_by_a_rename_carries_the_name_it_had() {
432 // What makes the rename visible on the page: the lines are in `components.toml`
433 // now, but that commit changed them in `old-name.toml`.
434 let blame = blame();
435
436 assert_eq!(blame.groups[1].commit.filename, "old-name.toml");
437 assert_eq!(blame.groups[0].commit.filename, "components.toml");
438 }
439
440 #[test]
441 fn the_oldest_and_newest_runs_sit_at_the_ends_of_the_tint() {
442 let blame = blame();
443
444 assert_eq!(blame.groups[0].age, 0, "the oldest commit is the faintest");
445 assert_eq!(
446 blame.groups[2].age, 0,
447 "and so is the same commit's later run"
448 );
449 assert_eq!(
450 blame.groups[1].age,
451 AGE_STEPS - 1,
452 "the newest commit is the strongest"
453 );
454 }
455
456 #[test]
457 fn a_file_written_in_one_commit_is_uniformly_new() {
458 // Nothing to contrast with, so the whole file takes the top step rather than
459 // rendering as uniformly ancient.
460 let single = b"\
4611111111111111111111111111111111111111111 1 1 1
462author Ada Lovelace
463author-time 1786485070
464summary only
465filename notes.md
466\thello
467" as &[u8];
468
469 let blame = parse_blame(single);
470
471 assert_eq!(blame.groups.len(), 1);
472 assert_eq!(blame.groups[0].age, AGE_STEPS - 1);
473 }
474
475 #[test]
476 fn every_step_of_the_tint_is_reachable() {
477 // Five evenly spaced commits should land on five distinct steps; a formula that
478 // is off by one collapses the ends instead.
479 let mut porcelain = Vec::new();
480
481 for index in 0..5u32 {
482 let sha = format!("{index}").repeat(40);
483 let line = index as usize + 1;
484 porcelain.extend_from_slice(
485 format!(
486 "{} {line} {line} 1\nauthor Ada\nauthor-time {}\nsummary s\nfilename f\n\tline\n",
487 &sha[..40],
488 1_700_000_000 + index * 1000
489 )
490 .as_bytes(),
491 );
492 }
493
494 let ages: Vec<u8> = parse_blame(&porcelain)
495 .groups
496 .iter()
497 .map(|group| group.age)
498 .collect();
499
500 assert_eq!(ages, vec![0, 1, 2, 3, 4]);
501 }
502
503 #[test]
504 fn an_empty_file_blames_to_nothing() {
505 assert!(parse_blame(b"").is_empty());
506 }
507
508 #[test]
509 fn a_line_that_is_not_utf8_still_blames() {
510 let mut porcelain = b"\
5111111111111111111111111111111111111111111 1 1 1
512author Ada
513author-time 1786485070
514summary only
515filename notes.md
516\t"
517 .to_vec();
518 porcelain.extend_from_slice(&[0xff, 0xfe]);
519 porcelain.push(b'\n');
520
521 let blame = parse_blame(&porcelain);
522
523 assert_eq!(blame.groups.len(), 1);
524 assert_eq!(blame.groups[0].lines[0], "\u{fffd}\u{fffd}");
525 }
526
527 #[test]
528 fn a_line_of_code_that_looks_like_a_header_is_still_content() {
529 // The tab is what separates the two, and a file full of shas would otherwise
530 // reparse itself into nonsense.
531 let porcelain = b"\
5321111111111111111111111111111111111111111 1 1 1
533author Ada
534author-time 1786485070
535summary only
536filename notes.md
537\t2222222222222222222222222222222222222222 9 9 9
538" as &[u8];
539
540 let blame = parse_blame(porcelain);
541
542 assert_eq!(blame.groups.len(), 1);
543 assert_eq!(
544 blame.groups[0].lines[0],
545 "2222222222222222222222222222222222222222 9 9 9"
546 );
547 }
548
549 // --- the use case ------------------------------------------------------------
550
551 use crate::{
552 domain::{
553 Membership, MembershipId, OrgId, Organization, RepoId, Repository, UserId, Visibility,
554 },
555 infrastructure::{
556 git::InMemoryGitQuery,
557 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
558 },
559 };
560
561 struct Fixture {
562 orgs: InMemoryOrgRepo,
563 memberships: InMemoryMembershipRepo,
564 repos: InMemoryRepoRepo,
565 handle: OrgName,
566 owner: Actor,
567 stranger: Actor,
568 }
569
570 /// One organisation with an owner, and a `steid` repository of the given visibility.
571 async fn fixture(visibility: Visibility) -> Fixture {
572 let orgs = InMemoryOrgRepo::new();
573 let memberships = InMemoryMembershipRepo::new();
574 let repos = InMemoryRepoRepo::new();
575
576 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
577 orgs.save(&org).await.expect("save org");
578
579 let owner = UserId::generate();
580 memberships
581 .save(&Membership::new(
582 MembershipId::generate(),
583 org.id.clone(),
584 owner.clone(),
585 crate::domain::Role::Owner,
586 ))
587 .await
588 .expect("save membership");
589
590 repos
591 .save(
592 &Repository::new(
593 RepoId::generate(),
594 org.id.clone(),
595 "steid",
596 None,
597 visibility,
598 SystemTime::now(),
599 )
600 .expect("valid repository"),
601 )
602 .await
603 .expect("save repo");
604
605 Fixture {
606 orgs,
607 memberships,
608 repos,
609 handle: org.name,
610 owner: Actor::User(owner),
611 stranger: Actor::Anonymous,
612 }
613 }
614
615 impl Fixture {
616 async fn blame(
617 &self,
618 actor: &Actor,
619 path: &str,
620 queries: &InMemoryGitQuery,
621 ) -> Result<Option<BlameFile>> {
622 blame_file(
623 &self.handle,
624 &RepoName::new("steid").expect("valid repository name"),
625 &RefName::new("main").expect("valid revision"),
626 &RepoPath::new(path).expect("valid path"),
627 actor,
628 &Stores::new(&self.orgs, &self.memberships, &self.repos),
629 queries,
630 )
631 .await
632 }
633 }
634
635 fn one_line_blame() -> Blame {
636 parse_blame(
637 b"1111111111111111111111111111111111111111 1 1 1\nauthor Ada\nauthor-time 1786485070\nsummary only\nfilename notes.md\n\thello\n",
638 )
639 }
640
641 #[tokio::test]
642 async fn a_text_file_blames() {
643 let f = fixture(Visibility::Public).await;
644 let queries = InMemoryGitQuery::new()
645 .with_blob("main", "notes.md", b"hello\n")
646 .with_blame("main", "notes.md", one_line_blame());
647
648 let file = f
649 .blame(&f.owner, "notes.md", &queries)
650 .await
651 .expect("should read")
652 .expect("found");
653
654 assert_eq!(file.size, 6);
655 assert_eq!(file.content, BlameContent::Ready(one_line_blame()));
656 }
657
658 #[tokio::test]
659 async fn a_binary_file_has_no_lines_to_attribute() {
660 // Decided from the bytes, exactly as the blob page decides it — and decided
661 // *before* the expensive query, so nothing walks history for a PNG.
662 let f = fixture(Visibility::Public).await;
663 let queries = InMemoryGitQuery::new().with_blob("main", "logo.png", vec![0x00, 0xff, 0xfe]);
664
665 let file = f
666 .blame(&f.owner, "logo.png", &queries)
667 .await
668 .expect("should read")
669 .expect("found");
670
671 assert_eq!(file.content, BlameContent::Binary);
672 }
673
674 #[tokio::test]
675 async fn a_file_past_the_page_cap_says_so_rather_than_blaming() {
676 let f = fixture(Visibility::Public).await;
677 let size = MAX_BLOB_BYTES as usize + 1;
678 let queries = InMemoryGitQuery::new().with_blob("main", "big.txt", vec![b'x'; size]);
679
680 let file = f
681 .blame(&f.owner, "big.txt", &queries)
682 .await
683 .expect("should read")
684 .expect("found");
685
686 assert_eq!(file.content, BlameContent::TooLarge);
687 assert_eq!(file.size, size as u64);
688 }
689
690 #[tokio::test]
691 async fn a_path_that_is_not_a_file_is_not_found() {
692 let f = fixture(Visibility::Public).await;
693 let queries = InMemoryGitQuery::new().with_tree("main", "src", Vec::new());
694
695 for path in ["src", "nope.md"] {
696 assert!(
697 f.blame(&f.owner, path, &queries)
698 .await
699 .expect("should read")
700 .is_none(),
701 "{path} should not blame"
702 );
703 }
704 }
705
706 #[tokio::test]
707 async fn a_private_repositorys_blame_is_invisible_to_a_stranger() {
708 // Blame names commits, authors and every line of the file. Same answer as the
709 // page, for the same reason.
710 let f = fixture(Visibility::Private).await;
711 let queries = InMemoryGitQuery::new()
712 .with_blob("main", "notes.md", b"hello\n")
713 .with_blame("main", "notes.md", one_line_blame());
714
715 assert!(
716 f.blame(&f.stranger, "notes.md", &queries)
717 .await
718 .expect("should read")
719 .is_none()
720 );
721 assert!(
722 f.blame(&f.owner, "notes.md", &queries)
723 .await
724 .expect("should read")
725 .is_some()
726 );
727 }
728}