M4.7: blame annotations in the editor gutter

- crates/vcs: blame.rs (git blame --porcelain, --contents - from a
  buffer, revisions, untracked files and empty repositories give no
  lines; property-tested parser, ISO dates without a date crate)
- engine: git.blame {path, rev?} -> {lines, version} through start_with;
  an open buffer is blamed as it would be saved (line ending, BOM)
- ui: blame.ts gutter toggled per file (vcs.toggleBlame, Git menu, no
  shortcut), date + author per run, bar coloured by age from tokens,
  hover card with the full commit message, click opens the commit in
  the Log (vcs.showCommit); refreshed on edits and gitChanged
- docs: architecture "Blame (M4.7)"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-30 17:52:44 +01:00
parent dc4a00ea0b
commit 2f758d76b9
18 changed files with 2003 additions and 3 deletions

343
crates/vcs/src/blame.rs Normal file
View file

@ -0,0 +1,343 @@
//! Blame (M4.7): which commit last changed each line of a file, for the
//! editor's annotation gutter.
//!
//! Output is read from `git blame --porcelain` only: a header line per
//! group of lines (`<hash> <orig> <final> [<count>]`), the commit's fields
//! the first time a hash appears, and each line's content after a tab.
//! The parser takes untrusted bytes: malformed headers are skipped, never
//! a panic (property-tested).
use std::collections::HashMap;
use crate::repo::check_name;
use crate::runner::Call;
use crate::{FILE_CAP, Repo, STATUS_CAP, VcsError};
/// The author git names for lines that are not committed yet.
pub const UNCOMMITTED_AUTHOR: &str = "Not Committed Yet";
/// One line of a blame, in file order.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlameLine {
/// Full hash of the commit that last changed the line; all zeros for
/// a line that is not committed yet.
pub hash: String,
/// Author name.
pub author: String,
/// Author date, ISO 8601 with the author's offset
/// (`2026-10-29T14:03:00+01:00`); empty when git gave none.
pub date: String,
/// The commit's subject line.
pub summary: String,
/// The line's number in that commit (1-based).
pub orig_line: u32,
}
/// Whether `hash` is git's all-zero hash of uncommitted lines.
pub fn is_uncommitted(hash: &str) -> bool {
!hash.is_empty() && hash.bytes().all(|b| b == b'0')
}
impl Repo {
/// Blames a file.
///
/// # Parameters
/// - `path`: project-relative path.
/// - `rev`: blame the file as it is at this revision (a hash, `main`,
/// `abc123^`); `None` blames the working copy.
/// - `contents`: with `rev` `None`, the working copy's text to blame
/// instead of the file on disk (an editor buffer with unsaved
/// edits); git converts its line endings as for a commit.
///
/// # Errors
/// [`VcsError::InvalidPath`], [`VcsError::InvalidName`], or git's
/// refusal. A file git does not know at that revision (untracked, or a
/// repository without commits) has no lines, not an error; so does
/// `contents` larger than [`FILE_CAP`].
pub fn blame(
&self,
path: &str,
rev: Option<&str>,
contents: Option<&[u8]>,
) -> Result<Vec<BlameLine>, VcsError> {
let path = self.to_repo_path(path)?;
if let Some(rev) = rev {
check_name(rev)?;
if rev.contains(':') || rev.trim() != rev {
return Err(VcsError::InvalidName(rev.to_string()));
}
}
let contents = if rev.is_none() { contents } else { None };
if contents.is_some_and(|c| c.len() > FILE_CAP) {
return Ok(Vec::new());
}
let mut args = vec!["blame", "--porcelain"];
if contents.is_some() {
args.extend(["--contents", "-"]);
}
// No `--end-of-options`: blame then reads the revision as a path
// ("bad revision"). `check_name` already refused a leading `-`.
args.extend(rev);
args.extend(["--", &path]);
let mut call = Call::read(self.root(), &args, STATUS_CAP);
if let Some(contents) = contents {
call = call.stdin(contents.to_vec());
}
let output = self.run(call)?;
if !output.success() {
let message = output.message();
if unknown_to_git(&message) {
return Ok(Vec::new());
}
return Err(VcsError::Git(message));
}
Ok(parse_blame(&output.stdout))
}
}
/// Whether git's refusal means the file has no history to blame there.
fn unknown_to_git(message: &str) -> bool {
[
"no such path",
"no such ref",
"does not have any commits",
"bad revision 'HEAD'",
]
.iter()
.any(|m| message.contains(m))
}
/// A commit's fields as blame prints them once per hash.
#[derive(Debug, Clone, Default)]
struct Commit {
/// Author name.
author: String,
/// Author time, seconds since the epoch.
time: Option<i64>,
/// Author offset, `+hhmm` / `-hhmm`.
tz: String,
/// Subject line.
summary: String,
}
/// Parses `git blame --porcelain` output into one entry per line.
/// Headers that are not `<hash> <orig> <final>…` and content lines
/// without a header before them are skipped.
pub fn parse_blame(bytes: &[u8]) -> Vec<BlameLine> {
let mut commits: HashMap<String, Commit> = HashMap::new();
let mut lines = Vec::new();
let mut current: Option<(String, u32)> = None;
for raw in bytes.split(|b| *b == b'\n') {
if raw.first() == Some(&b'\t') {
if let Some((hash, orig_line)) = current.take() {
let commit = commits.get(&hash).cloned().unwrap_or_default();
lines.push(BlameLine {
date: commit
.time
.map(|t| iso_date(t, &commit.tz))
.unwrap_or_default(),
author: commit.author,
summary: commit.summary,
hash,
orig_line,
});
}
continue;
}
let text = String::from_utf8_lossy(raw);
let text = text.trim_end_matches('\r');
if let Some(header) = parse_header(text) {
commits.entry(header.0.clone()).or_default();
current = Some(header);
continue;
}
let Some((hash, _)) = current.as_ref() else {
continue;
};
let Some(commit) = commits.get_mut(hash) else {
continue;
};
let (key, value) = text.split_once(' ').unwrap_or((text, ""));
match key {
"author" => commit.author = value.to_string(),
"author-time" => commit.time = value.trim().parse().ok(),
"author-tz" => commit.tz = value.trim().to_string(),
"summary" => commit.summary = value.to_string(),
_ => {}
}
}
lines
}
/// Reads a group header `<hash> <orig> <final> [<count>]`.
fn parse_header(text: &str) -> Option<(String, u32)> {
let mut parts = text.split(' ');
let hash = parts.next()?;
if !matches!(hash.len(), 40 | 64) || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let orig: u32 = parts.next()?.parse().ok()?;
let _final: u32 = parts.next()?.parse().ok()?;
match parts.next() {
None => {}
Some(count) => {
count.parse::<u32>().ok()?;
}
}
if parts.next().is_some() {
return None;
}
Some((hash.to_ascii_lowercase(), orig))
}
/// Formats seconds since the epoch in the offset `tz` (`+0100`) as ISO
/// 8601; a malformed offset counts as UTC.
fn iso_date(seconds: i64, tz: &str) -> String {
let offset = parse_offset(tz).unwrap_or(0);
let local = seconds.saturating_add(offset);
let days = local.div_euclid(86_400);
let secs = local.rem_euclid(86_400);
let (year, month, day) = civil_from_days(days);
let sign = if offset < 0 { '-' } else { '+' };
let off = offset.unsigned_abs() / 60;
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}{sign}{:02}:{:02}",
secs / 3600,
secs % 3600 / 60,
secs % 60,
off / 60,
off % 60
)
}
/// `+hhmm` / `-hhmm` in seconds.
fn parse_offset(tz: &str) -> Option<i64> {
let (sign, digits) = match tz.as_bytes().first()? {
b'+' => (1, tz.get(1..)?),
b'-' => (-1, tz.get(1..)?),
_ => return None,
};
if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let hours: i64 = digits.get(..2)?.parse().ok()?;
let minutes: i64 = digits.get(2..)?.parse().ok()?;
Some(sign * (hours * 3600 + minutes * 60))
}
/// The proleptic Gregorian date of a day count since 1970-01-01 (Howard
/// Hinnant's public-domain `civil_from_days`).
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
(
year,
u32::try_from(month).unwrap_or(1),
u32::try_from(day).unwrap_or(1),
)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::indexing_slicing)]
use super::*;
use proptest::prelude::*;
const A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
#[test]
fn porcelain_groups_parse_with_commit_fields_once() {
let text = format!(
"{A} 1 1 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 1700000000\nauthor-tz +0100\nsummary First\nfilename f.php\n\t<?php\n{A} 2 2\n\techo 1;\n{B} 1 3 1\nauthor Bo\nauthor-time 0\nauthor-tz -0230\nsummary Second one\nprevious {A} f.php\nfilename f.php\n\techo 2;\r\n"
);
let lines = parse_blame(text.as_bytes());
assert_eq!(lines.len(), 3);
assert_eq!(lines[0].hash, A);
assert_eq!(lines[0].author, "Ann");
assert_eq!(lines[0].date, "2023-11-14T23:13:20+01:00");
assert_eq!(lines[1].summary, "First");
assert_eq!(lines[1].orig_line, 2);
assert_eq!(lines[2].author, "Bo");
assert_eq!(lines[2].summary, "Second one");
assert_eq!(lines[2].date, "1969-12-31T21:30:00-02:30");
assert_eq!(lines[2].orig_line, 1);
}
#[test]
fn content_that_looks_like_a_header_is_content() {
let text = format!("{A} 1 1 1\nauthor X\nsummary s\n\t{B} 1 1 1\n");
let lines = parse_blame(text.as_bytes());
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].hash, A);
}
#[test]
fn headers_are_checked() {
assert!(parse_header(&format!("{A} 1 1 1")).is_some());
assert!(parse_header(&format!("{A} 1 1")).is_some());
assert!(parse_header("abc 1 1").is_none());
assert!(parse_header(&format!("{A} x 1")).is_none());
assert!(parse_header(&format!("{A} 1 1 1 1")).is_none());
assert!(parse_header("author-time 12").is_none());
assert!(parse_blame(b"\tstray content\n").is_empty());
}
#[test]
fn dates_and_offsets() {
assert_eq!(iso_date(0, "+0000"), "1970-01-01T00:00:00+00:00");
assert_eq!(iso_date(951_782_400, "bad"), "2000-02-29T00:00:00+00:00");
assert_eq!(iso_date(-1, "+0000"), "1969-12-31T23:59:59+00:00");
assert_eq!(parse_offset("+0530"), Some(19_800));
assert_eq!(parse_offset("-0100"), Some(-3600));
assert_eq!(parse_offset("0100"), None);
assert_eq!(parse_offset("+01"), None);
}
#[test]
fn uncommitted_hashes() {
assert!(is_uncommitted(&"0".repeat(40)));
assert!(!is_uncommitted(A));
assert!(!is_uncommitted(""));
}
#[test]
fn unknown_files_are_recognised() {
assert!(unknown_to_git("fatal: no such path 'a.php' in HEAD"));
assert!(unknown_to_git("fatal: no such ref: HEAD"));
assert!(!unknown_to_git("fatal: bad revision 'nope'"));
}
proptest! {
#[test]
fn the_parser_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
let _ = parse_blame(&bytes);
}
#[test]
fn every_content_line_after_a_header_counts(
count in 1usize..20,
author in "[^\n\r]{0,20}",
time in -10_000_000_000i64..10_000_000_000,
) {
let mut text = format!("{A} 1 1 {count}\nauthor {author}\nauthor-time {time}\nauthor-tz +0000\nsummary s\n");
for i in 0..count {
if i > 0 {
text.push_str(&format!("{A} {} {} \n", i + 1, i + 1).replace(" \n", "\n"));
}
text.push_str("\tline\n");
}
let lines = parse_blame(text.as_bytes());
prop_assert_eq!(lines.len(), count);
prop_assert!(lines.iter().all(|l| l.author == author && l.date.len() >= 25));
}
}
}

View file

@ -10,6 +10,8 @@
//! - Remotes (M4.10, owner decision D23): fetch, pull, push, clone and
//! remote management, with progress and cancel; credentials stay with
//! git's credential helper and the ssh agent (see `remote.rs`).
//! - Blame (M4.7): who last changed each line, of the working copy or an
//! editor buffer (`blame.rs`).
//! - [`RepoWatch`] notices changes inside `.git` (HEAD, index, refs).
//!
//! Every call goes through [`runner::run`]: arguments as an array, never a
@ -21,6 +23,7 @@
//! Calls block for as long as git runs, so the engine runs them on their
//! own threads, off its lock.
pub mod blame;
mod error;
pub mod log;
pub mod porcelain;
@ -30,6 +33,7 @@ pub mod runner;
pub mod stash;
mod watch;
pub use blame::{BlameLine, UNCOMMITTED_AUTHOR, is_uncommitted};
pub use error::VcsError;
pub use log::{CommitDetails, CommitFile, LOG_LIMIT, LogCommit, LogQuery};
pub use porcelain::{FileState, FileStatus, Head, Status, Version};