Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 21.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Blame: the changeset that last changed each line of a file, along first
5//! parents.
6//!
7//! The content of a file at a changeset `C` is the one the last changeset
8//! on `C`'s first-parent chain whose change list sets the file gave it. Its
9//! blame is derived data of that changeset and the path, computed from the
10//! blame at the previous changeset on the chain that names the path: when
11//! the path was a file there, a line diff between the two contents carries
12//! the lines that were kept over with their changesets, and the lines added
13//! or changed are the new changeset's. A file that a changeset creates,
14//! where there was nothing, a directory or a gitlink, is all its own:
15//! renames are not followed.
16//!
17//! The line diff, [`line_diff`], is imara-diff's Myers algorithm with its
18//! indentation heuristic, which is what git's blame uses by default, so the
19//! two agree line for line except in two ways. Git follows a file across
20//! whole-file renames, and braid does not. And the two diffs can differ:
21//! when a change has several shortest line diffs, they may keep different
22//! copies of lines that repeat, such as closing braces and blank lines; and
23//! neither always finds a shortest diff, so on some changes one inserts and
24//! deletes a few more lines than the other. Blame then gives those lines to
25//! different changesets.
26//!
27//! The derived function `blame`, version 1, of a changeset and a path (the
28//! argument of the key) is:
29//!
30//! ```text
31//! uv k, k × [32] changesets, in the order their first lines come
32//! uv r, r × (uv changeset index, uv lines) runs of lines, in order
33//! ```
34//!
35//! Runs are not empty, two runs in a row never have the same changeset, and
36//! every changeset listed has lines. A line ends after a `\n`, and a last
37//! line without one is a line too, as in three-way merges.
38
39use std::collections::HashMap;
40use std::ops::Range;
41use std::rc::Rc;
42
43use braid_format::codec::{Reader, put_id, put_uv};
44use braid_format::{ChangeOp, DecodeError, EntryKind, ObjectId, Objects};
45use imara_diff::sources::byte_lines;
46use imara_diff::{Algorithm, Diff, InternedInput};
47
48use crate::access::{entry_at, read_blob, read_changeset};
49use crate::bloom::PathHash;
50use crate::derived::{DerivedIndex, DerivedKey};
51use crate::error::Error;
52use crate::history::History;
53
54/// The derived function of blame records.
55const BLAME: &str = "blame";
56
57/// The version of its encoding.
58const BLAME_VERSION: u64 = 1;
59
60/// Content this long or longer is not diffed: a new version of it is all new
61/// lines.
62const MAX_DIFF_BYTES: usize = i32::MAX as usize;
63
64/// Who last changed each line of a file.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Blame {
67 /// The changeset the file's content comes from: the last one, on the
68 /// first-parent chain of the changeset blamed, whose change list sets the
69 /// file.
70 pub changeset: ObjectId,
71 /// The file's content.
72 pub content: Vec<u8>,
73 /// For each line of the content, in order, the changeset that last
74 /// changed it.
75 pub origins: Vec<ObjectId>,
76}
77
78impl Blame {
79 /// Each line, with its line ending if it has one, and the changeset that
80 /// last changed it.
81 pub fn lines(&self) -> impl Iterator<Item = (&[u8], ObjectId)> + '_ {
82 byte_lines(&self.content).zip(self.origins.iter().copied())
83 }
84}
85
86impl<O: Objects, I: DerivedIndex> History<'_, O, I> {
87 /// The blame of `path` at `changeset`: for each line of the file there,
88 /// the changeset on the first-parent chain that last changed it. `None`
89 /// when the path holds no file there: nothing, a directory or a gitlink.
90 /// A symlink's target is blamed as a file.
91 ///
92 /// Blame records are computed for the changesets that set the file and
93 /// lack one, back to the newest that has one or to where the file was
94 /// created; finding those changesets costs a walk down the chain with
95 /// changed-path filters.
96 pub fn blame(&mut self, changeset: ObjectId, path: &[u8]) -> Result<Option<Blame>, Error> {
97 let root = read_changeset(self.objects, changeset)?.root;
98 let blob = match entry_at(self.objects, root, path)? {
99 Some(
100 EntryKind::File { blob, .. }
101 | EntryKind::Executable { blob, .. }
102 | EntryKind::Symlink { blob, .. },
103 ) => blob,
104 _ => return Ok(None),
105 };
106 let hash = PathHash::of(path);
107 // The change list of some changeset on the chain must have set the
108 // file, unless derived data says otherwise.
109 let last = match self.last_change(Some(changeset), path, hash)? {
110 Some((last, op)) if file_blob(&op) == Some(blob) => last,
111 _ => return Err(Error::DerivedData { id: changeset }),
112 };
113 let (origins, content) = self.origins(last, blob, path, hash)?;
114 Ok(Some(Blame {
115 changeset: last,
116 content,
117 origins,
118 }))
119 }
120
121 /// The origins of the lines of `path` at `last`, which set it to `blob`,
122 /// and its content.
123 fn origins(
124 &mut self,
125 last: ObjectId,
126 blob: ObjectId,
127 path: &[u8],
128 hash: PathHash,
129 ) -> Result<(Vec<ObjectId>, Vec<u8>), Error> {
130 // The changesets that set the file without a blame record, newest
131 // first, down to one with a record or to the one that created it.
132 let mut chain: Vec<(ObjectId, ObjectId)> = Vec::new();
133 let mut base: Option<(Vec<ObjectId>, Vec<u8>)> = None;
134 let mut current = (last, blob);
135 loop {
136 if let Some(runs) = self.load_blame(current.0, path)? {
137 let content = read_blob(self.objects, current.1)?;
138 // A record that does not fit the content is ignored, and
139 // made again.
140 if runs.lines() == count_lines(&content) {
141 base = Some((runs.expand(), content));
142 break;
143 }
144 }
145 chain.push(current);
146 let parent = self.changed_paths(current.0)?.first_parent;
147 match self.last_change(parent, path, hash)? {
148 Some((id, op)) => match file_blob(&op) {
149 Some(blob) => current = (id, blob),
150 None => break,
151 },
152 None => break,
153 }
154 }
155
156 let (mut origins, mut content) = match base {
157 Some((origins, content)) => (origins, Some(content)),
158 None => (Vec::new(), None),
159 };
160 for (id, blob) in chain.into_iter().rev() {
161 let new = read_blob(self.objects, blob)?;
162 origins = match &content {
163 Some(old) => carry(old, &new, &origins, id),
164 None => vec![id; count_lines(&new)],
165 };
166 self.save_blame(id, path, &origins)?;
167 content = Some(new);
168 }
169 // The loop above ran at least once, or the base was found.
170 Ok((origins, content.unwrap_or_default()))
171 }
172
173 /// The blame record of `path` at `id`, if there is a valid one.
174 fn load_blame(&mut self, id: ObjectId, path: &[u8]) -> Result<Option<Rc<Runs>>, Error> {
175 let memo = (id, path.to_vec());
176 if let Some(runs) = self.blames.get(&memo) {
177 return Ok(Some(Rc::clone(runs)));
178 }
179 let key = DerivedKey::new(BLAME, BLAME_VERSION, &[id], path);
180 let Some(runs) = self.load(&key, Runs::decode)? else {
181 return Ok(None);
182 };
183 let runs = Rc::new(runs);
184 self.blames.insert(memo, Rc::clone(&runs));
185 Ok(Some(runs))
186 }
187
188 /// Stores the blame record of `path` at `id`.
189 fn save_blame(&mut self, id: ObjectId, path: &[u8], origins: &[ObjectId]) -> Result<(), Error> {
190 let runs = Runs::of(origins);
191 let key = DerivedKey::new(BLAME, BLAME_VERSION, &[id], path);
192 self.save(key, &runs.encode())?;
193 self.blames.insert((id, path.to_vec()), Rc::new(runs));
194 Ok(())
195 }
196}
197
198/// The blob a change sets, for the changes that set a file.
199fn file_blob(op: &ChangeOp) -> Option<ObjectId> {
200 match op {
201 ChangeOp::File { blob, .. }
202 | ChangeOp::Executable { blob, .. }
203 | ChangeOp::Symlink { blob, .. } => Some(*blob),
204 ChangeOp::Gitlink { .. } | ChangeOp::Delete => None,
205 }
206}
207
208/// The number of lines of `content`.
209fn count_lines(content: &[u8]) -> usize {
210 byte_lines(content).count()
211}
212
213/// One change of a line diff: lines of the old version, replaced by lines of
214/// the new one.
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct LineChange {
217 /// The lines of the old version it replaces, counted from 0, end
218 /// excluded; empty for an insertion, which goes before line `old.start`.
219 pub old: Range<usize>,
220 /// The lines of the new version it puts there; empty for a deletion.
221 pub new: Range<usize>,
222}
223
224/// The line diff blame uses between two versions of a file: its changes, in
225/// order. The lines between changes are kept: equal, in the same order.
226///
227/// It is imara-diff's Myers algorithm with its indentation heuristic, which
228/// is what git's blame uses by default. Like git's, it does not always find
229/// the shortest diff: it gives up on it where the search would cost too
230/// much, and its preprocessing, which sets aside lines that cannot be kept,
231/// can miss it too. So a diff may insert, and delete, a few more lines than
232/// the fewest possible, and not on the same changes as git's. Content of
233/// [`i32::MAX`] bytes or more is not diffed: all of it is replaced.
234pub fn line_diff(old: &[u8], new: &[u8]) -> Vec<LineChange> {
235 if old.len() >= MAX_DIFF_BYTES || new.len() >= MAX_DIFF_BYTES {
236 let (old_lines, new_lines) = (count_lines(old), count_lines(new));
237 if old_lines == 0 && new_lines == 0 {
238 return Vec::new();
239 }
240 return vec![LineChange {
241 old: 0..old_lines,
242 new: 0..new_lines,
243 }];
244 }
245 let input = InternedInput::new(old, new);
246 let mut diff = Diff::compute(Algorithm::Myers, &input);
247 diff.postprocess_lines(&input);
248 diff.hunks()
249 .map(|hunk| LineChange {
250 old: hunk.before.start as usize..hunk.before.end as usize,
251 new: hunk.after.start as usize..hunk.after.end as usize,
252 })
253 .collect()
254}
255
256/// The origins of the lines of `new`, a later version of `old` whose lines
257/// come from `old_origins`, when `id` made it: kept lines keep their origin,
258/// the others are `id`'s.
259fn carry(old: &[u8], new: &[u8], old_origins: &[ObjectId], id: ObjectId) -> Vec<ObjectId> {
260 let mut origins = Vec::with_capacity(old_origins.len());
261 // The next line of `old` that no change has reached yet.
262 let mut kept = 0;
263 for change in line_diff(old, new) {
264 origins.extend_from_slice(&old_origins[kept..change.old.start]);
265 origins.extend(std::iter::repeat_n(id, change.new.len()));
266 kept = change.old.end;
267 }
268 origins.extend_from_slice(&old_origins[kept..]);
269 debug_assert_eq!(origins.len(), count_lines(new));
270 origins
271}
272
273/// A blame record: the origins of the lines of a file, as runs.
274#[derive(Clone, Debug, PartialEq, Eq)]
275pub(crate) struct Runs {
276 /// The changesets, in the order their first lines come.
277 changesets: Vec<ObjectId>,
278 /// Runs of lines: an index into `changesets`, and how many lines.
279 runs: Vec<(usize, u64)>,
280}
281
282impl Runs {
283 /// The runs of these origins, line by line.
284 fn of(origins: &[ObjectId]) -> Runs {
285 let mut changesets = Vec::new();
286 let mut index: HashMap<ObjectId, usize> = HashMap::new();
287 let mut runs: Vec<(usize, u64)> = Vec::new();
288 for origin in origins {
289 let at = *index.entry(*origin).or_insert_with(|| {
290 changesets.push(*origin);
291 changesets.len() - 1
292 });
293 match runs.last_mut() {
294 Some((last, lines)) if *last == at => *lines += 1,
295 _ => runs.push((at, 1)),
296 }
297 }
298 Runs { changesets, runs }
299 }
300
301 /// The number of lines.
302 fn lines(&self) -> usize {
303 self.runs.iter().map(|(_, lines)| *lines as usize).sum()
304 }
305
306 /// The origin of each line.
307 fn expand(&self) -> Vec<ObjectId> {
308 let mut origins = Vec::with_capacity(self.lines());
309 for (at, lines) in &self.runs {
310 origins.extend(std::iter::repeat_n(self.changesets[*at], *lines as usize));
311 }
312 origins
313 }
314
315 fn encode(&self) -> Vec<u8> {
316 let mut out = Vec::new();
317 put_uv(&mut out, self.changesets.len() as u64);
318 for changeset in &self.changesets {
319 put_id(&mut out, changeset);
320 }
321 put_uv(&mut out, self.runs.len() as u64);
322 for (at, lines) in &self.runs {
323 put_uv(&mut out, *at as u64);
324 put_uv(&mut out, *lines);
325 }
326 out
327 }
328
329 /// Decodes a record, accepting only the encoding [`Runs::of`] makes.
330 fn decode(value: &[u8]) -> Option<Runs> {
331 let read = || -> Result<Runs, DecodeError> {
332 let mut reader = Reader::new(value);
333 let count = reader.count(ObjectId::LEN)?;
334 let mut changesets = Vec::with_capacity(count);
335 for _ in 0..count {
336 changesets.push(reader.id()?);
337 }
338 let run_count = reader.count(2)?;
339 let mut runs = Vec::with_capacity(run_count);
340 for _ in 0..run_count {
341 let at = reader.position();
342 let index = usize::try_from(reader.uv()?).ok();
343 let lines = reader.uv()?;
344 let invalid = DecodeError::Invalid { at, what: "run" };
345 let Some(index) = index.filter(|index| *index < count) else {
346 return Err(invalid);
347 };
348 // Changesets come in the order of their first runs, and two
349 // runs in a row have different changesets.
350 let seen = runs.iter().map(|(i, _)| i + 1).max().unwrap_or(0);
351 let repeats = runs.last().is_some_and(|(last, _)| *last == index);
352 if lines == 0 || index > seen || repeats {
353 return Err(invalid);
354 }
355 runs.push((index, lines));
356 }
357 reader.finish()?;
358 let used = runs.iter().map(|(i, _)| i + 1).max().unwrap_or(0);
359 if used != count {
360 return Err(DecodeError::Invalid {
361 at: 0,
362 what: "unused changeset",
363 });
364 }
365 Ok(Runs { changesets, runs })
366 };
367 read().ok()
368 }
369}
370
371#[cfg(test)]
372mod tests {
373 use super::*;
374 use crate::derived::MemoryIndex;
375 use crate::testing::{Repo, delete, gitlink};
376 use braid_format::Kind;
377
378 fn id(n: u8) -> ObjectId {
379 ObjectId::hash(Kind::Changeset, &[n])
380 }
381
382 #[test]
383 fn runs_round_trip_and_are_canonical() {
384 let origins = [id(1), id(1), id(2), id(1), id(3), id(3)];
385 let runs = Runs::of(&origins);
386 assert_eq!(runs.changesets, [id(1), id(2), id(3)]);
387 assert_eq!(runs.runs, [(0, 2), (1, 1), (0, 1), (2, 2)]);
388 assert_eq!(runs.lines(), 6);
389 assert_eq!(runs.expand(), origins);
390 assert_eq!(Runs::decode(&runs.encode()), Some(runs.clone()));
391 assert_eq!(Runs::of(&[]).encode(), [0, 0]);
392 assert_eq!(Runs::decode(&[0, 0]), Some(Runs::of(&[])));
393
394 let encode = |changesets: &[ObjectId], runs: &[(u64, u64)]| {
395 let mut out = Vec::new();
396 put_uv(&mut out, changesets.len() as u64);
397 for changeset in changesets {
398 put_id(&mut out, changeset);
399 }
400 put_uv(&mut out, runs.len() as u64);
401 for (at, lines) in runs {
402 put_uv(&mut out, *at);
403 put_uv(&mut out, *lines);
404 }
405 out
406 };
407 assert!(Runs::decode(&encode(&[id(1), id(2)], &[(0, 1), (1, 2)])).is_some());
408 for (changesets, runs) in [
409 // An empty run, two runs in a row from one changeset, an index
410 // out of range, changesets out of order, one never used.
411 (&[id(1)][..], &[(0, 0)][..]),
412 (&[id(1)], &[(0, 1), (0, 1)]),
413 (&[id(1)], &[(1, 1)]),
414 (&[id(1), id(2)], &[(1, 1), (0, 1)]),
415 (&[id(1), id(2)], &[(0, 1)]),
416 ] {
417 assert_eq!(Runs::decode(&encode(changesets, runs)), None, "{runs:?}");
418 }
419 }
420
421 #[test]
422 fn line_diffs_list_changes_between_kept_lines() {
423 let change = |old: Range<usize>, new: Range<usize>| LineChange { old, new };
424 assert_eq!(
425 line_diff(b"a\nb\nc\n", b"a\nB\nc\nd\n"),
426 [change(1..2, 1..2), change(3..3, 3..4)]
427 );
428 assert_eq!(line_diff(b"x\ny\n", b"x\ny\n"), []);
429 assert_eq!(line_diff(b"", b""), []);
430 assert_eq!(line_diff(b"", b"one\n"), [change(0..0, 0..1)]);
431 assert_eq!(line_diff(b"a\nb\n", b"b\n"), [change(0..1, 0..0)]);
432 }
433
434 #[test]
435 fn kept_lines_keep_their_origin() {
436 let old = b"a\nb\nc\nd\n";
437 let new = b"a\nB\nc\nd\ne\n";
438 let origins = [id(1), id(2), id(3), id(4)];
439 assert_eq!(
440 carry(old, new, &origins, id(9)),
441 [id(1), id(9), id(3), id(4), id(9)]
442 );
443 assert_eq!(carry(b"", b"x\ny", &[], id(9)), [id(9), id(9)]);
444 assert_eq!(carry(b"x\n", b"", &[id(1)], id(9)), []);
445 // A last line that gains its newline is a changed line.
446 assert_eq!(
447 carry(b"a\nb", b"a\nb\n", &[id(1), id(2)], id(9)),
448 [id(1), id(9)]
449 );
450 }
451
452 fn blame<O: Objects, I: DerivedIndex>(
453 history: &mut History<'_, O, I>,
454 at: ObjectId,
455 path: &str,
456 ) -> Vec<(String, ObjectId)> {
457 let blame = history.blame(at, path.as_bytes()).unwrap().unwrap();
458 blame
459 .lines()
460 .map(|(line, origin)| (String::from_utf8(line.to_vec()).unwrap(), origin))
461 .collect()
462 }
463
464 fn origins<O: Objects, I: DerivedIndex>(
465 history: &mut History<'_, O, I>,
466 at: ObjectId,
467 ) -> Vec<ObjectId> {
468 history.blame(at, b"f").unwrap().unwrap().origins
469 }
470
471 #[test]
472 fn lines_go_to_the_changeset_that_last_changed_them() {
473 let repo = Repo::new();
474 let one = repo.commit(&[], vec![repo.set("f", "a\nb\nc\n"), repo.set("g", "1\n")]);
475 let two = repo.commit(&[one], vec![repo.set("f", "a\nB\nc\n")]);
476 let other = repo.commit(&[two], vec![repo.set("g", "2\n")]);
477 // A side branch adds a line; the merge brings it in, so the line is
478 // the merge's along first parents.
479 let side = repo.commit(&[two], vec![repo.set("f", "a\nB\nc\nside\n")]);
480 let merge = repo.commit(&[other, side], vec![repo.set("f", "a\nB\nc\nside\n")]);
481 let exec = repo.commit(&[merge], vec![repo.exec("f", "a\nB\nc\nside\n")]);
482
483 let index = MemoryIndex::new();
484 let mut history = History::new(&repo.objects, &index);
485 let line = |text: &str, origin| (text.to_owned(), origin);
486 assert_eq!(
487 blame(&mut history, exec, "f"),
488 [
489 line("a\n", one),
490 line("B\n", two),
491 line("c\n", one),
492 line("side\n", merge)
493 ]
494 );
495 // Blamed at a changeset that did not touch the file.
496 assert_eq!(
497 blame(&mut history, other, "f"),
498 [line("a\n", one), line("B\n", two), line("c\n", one)]
499 );
500 assert_eq!(blame(&mut history, other, "g"), [line("2\n", other)]);
501 let whole = history.blame(exec, b"f").unwrap().unwrap();
502 assert_eq!(whole.changeset, exec);
503 assert_eq!(whole.content, b"a\nB\nc\nside\n");
504 // Records for the changesets that set f, once each.
505 let computed = history.computed();
506 history.blame(exec, b"f").unwrap();
507 assert_eq!(history.computed(), computed);
508
509 // Nothing to blame: a missing path, a directory.
510 assert_eq!(history.blame(exec, b"nothing").unwrap(), None);
511 let dir = repo.commit(&[exec], vec![repo.set("d/x", "1\n")]);
512 assert_eq!(history.blame(dir, b"d").unwrap(), None);
513 }
514
515 #[test]
516 fn a_file_created_again_starts_over() {
517 let repo = Repo::new();
518 let one = repo.commit(&[], vec![repo.set("f", "a\nb\n")]);
519 let gone = repo.commit(&[one], vec![delete("f")]);
520 let back = repo.commit(&[gone], vec![repo.set("f", "a\nb\nc\n")]);
521 let link = repo.commit(&[back], vec![gitlink("f", 7)]);
522 let file = repo.commit(&[link], vec![repo.set("f", "a\nb\nc\n")]);
523 let index = MemoryIndex::new();
524 let mut history = History::new(&repo.objects, &index);
525 assert_eq!(origins(&mut history, back), [back, back, back]);
526 assert_eq!(origins(&mut history, file), [file, file, file]);
527 assert_eq!(history.blame(link, b"f").unwrap(), None);
528 assert_eq!(history.blame(gone, b"f").unwrap(), None);
529 }
530
531 #[test]
532 fn records_made_in_any_order_are_the_same() {
533 let repo = Repo::new();
534 let mut at = repo.commit(&[], vec![repo.set("f", "1\n2\n3\n")]);
535 let mut chain = vec![at];
536 for (i, content) in ["1\n2\n3\n4\n", "0\n1\n3\n4\n", "0\n1\n3\n4\n5\n", "x\n"]
537 .iter()
538 .enumerate()
539 {
540 let other = repo.set(&format!("other{i}"), "x");
541 at = repo.commit(&[at], vec![repo.set("f", content), other]);
542 chain.push(at);
543 }
544 let forward = MemoryIndex::new();
545 let mut history = History::new(&repo.objects, &forward);
546 for at in &chain {
547 history.blame(*at, b"f").unwrap();
548 }
549 history.flush().unwrap();
550 let backward = MemoryIndex::new();
551 let mut history = History::new(&repo.objects, &backward);
552 for at in chain.iter().rev() {
553 history.blame(*at, b"f").unwrap();
554 }
555 history.flush().unwrap();
556 assert_eq!(forward.entries(), backward.entries());
557 }
558}