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

View file

@ -0,0 +1,116 @@
//! `git.blame` (M4.7): which commit last changed each line of a file, for
//! the editor's annotation gutter. Read-only and run like every `git.*`
//! command (a pending outcome off the lock, git and the repository cached
//! by [`super::git`]).
//!
//! Without `rev` an open buffer for the path is blamed as it stands
//! (`--contents -`, the text as it would be saved, BOM included), so
//! unsaved edits show as not committed and the lines match the editor.
//! Under the lock only the buffer's rope is cloned (shared chunks); the
//! text is built on the git thread.
use lutra_text::Buffer;
use lutra_vcs::BlameLine;
use serde::Deserialize;
use serde_json::{Value, json};
use super::git::start_with;
use super::params::{parse, project_path};
use crate::workspace::path_string;
use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State};
/// The UTF-8 byte order mark.
const BOM: &str = "\u{feff}";
/// Registers `git.blame`.
///
/// # Errors
/// [`EngineError::Internal`] if the id is taken.
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(Blame))
}
/// One line of `git.blame`.
fn line_json(line: &BlameLine) -> Value {
json!({
"hash": line.hash,
"author": line.author,
"date": line.date,
"summary": line.summary,
"origLine": line.orig_line,
})
}
/// Params of `git.blame`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct BlameParams {
/// The file.
path: String,
/// A revision to blame the file at instead of the working copy.
#[serde(default)]
rev: Option<String>,
}
/// `git.blame`.
struct Blame;
impl Command for Blame {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.blame",
label: "Git: Blame",
menu_path: None,
default_shortcut: None,
params: "{ path: project-relative path, rev?: commit hash or revision (default: the working copy, an open buffer's unsaved text included) }; returns { lines: [{ hash, author, date (ISO 8601), summary, origLine }], version } with one entry per line in file order (hash all zeros for lines not committed yet; origLine 1-based in that commit); no lines when the file is untracked or the repository has no commits; version is the blamed buffer's version, null when no buffer was used",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: BlameParams = parse(command, params)?;
let rel = project_path(state, command, &p.path)?;
let path = path_string(&rel);
let rev = p
.rev
.map(|r| r.trim().to_string())
.filter(|r| !r.is_empty());
let buffer: Option<(Buffer, bool, u64)> = if rev.is_none() {
state
.buffers
.find(&rel)
.and_then(|id| state.buffers.get(id))
.map(|open| (open.buffer.clone(), open.bom, open.version))
} else {
None
};
start_with(
state,
command,
false,
Box::new(move |repo| {
let contents = buffer.as_ref().map(|(buffer, bom, _)| {
let text = buffer.save_text();
if *bom { format!("{BOM}{text}") } else { text }
});
let lines: Vec<Value> = repo
.blame(
&path,
rev.as_deref(),
contents.as_deref().map(str::as_bytes),
)?
.iter()
.map(line_json)
.collect();
Ok(json!({
"lines": lines,
"version": buffer.as_ref().map(|(_, _, version)| *version),
}))
}),
)
}
}

View file

@ -4,6 +4,7 @@ mod app;
mod buffer;
mod file;
pub mod git;
pub mod git_blame;
pub mod git_lines;
pub mod git_log;
pub mod git_merge;
@ -72,6 +73,7 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
lsp_nav::register(registry)?;
git::register(registry)?;
git_lines::register(registry)?;
git_blame::register(registry)?;
git_log::register(registry)?;
git_remote::register(registry)?;
git_merge::register(registry)?;

View file

@ -481,6 +481,7 @@ mod tests {
"file.open",
"file.save",
"file.saveAll",
"git.blame",
"git.branches",
"git.cancel",
"git.checkout",

View file

@ -0,0 +1,230 @@
//! `git.blame` (M4.7) through the engine: the working copy, an open
//! buffer with unsaved edits and a BOM, a revision, an untracked file, bad
//! params, and no `gitChanged` from it. Skips with a message when git is
//! not installed.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::path::Path;
use std::process::Command;
use std::sync::Mutex;
use lutra_engine::{Engine, EngineError, Event, run_waiting};
use serde_json::{Value, json};
/// Whether git is installed; prints why a test is skipped.
fn have_git() -> bool {
let ok = Command::new("git")
.arg("--version")
.output()
.is_ok_and(|o| o.status.success());
if !ok {
eprintln!("skipped: git is not installed");
}
ok
}
/// Runs git for test setup.
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// Writes `text` to `path` and commits everything as `author`.
fn commit(dir: &Path, path: &str, text: &str, message: &str, author: &str) -> String {
std::fs::write(dir.join(path), text).unwrap();
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "--author", author, "-m", message]);
git(dir, &["rev-parse", "HEAD"])
}
/// An engine with `root` open, recording events.
struct Host {
/// The engine.
engine: Mutex<Engine>,
/// Events published so far.
events: Mutex<Vec<Event>>,
}
impl Host {
/// Opens `root` as the project.
fn open(root: &Path) -> Self {
let host = Self {
engine: Mutex::new(Engine::new().unwrap()),
events: Mutex::new(Vec::new()),
};
host.run("project.open", json!({"path": root})).unwrap();
host
}
/// Runs a command the way hosts do.
fn run(&self, command: &str, params: Value) -> Result<Value, EngineError> {
run_waiting(
|| self.engine.lock().unwrap(),
command,
params,
|events| self.events.lock().unwrap().extend_from_slice(events),
)
.map(|o| o.value)
}
}
/// The hashes of a blame's lines.
fn hashes(blame: &Value) -> Vec<String> {
blame["lines"]
.as_array()
.unwrap()
.iter()
.map(|l| l["hash"].as_str().unwrap().to_string())
.collect()
}
#[test]
fn blame_working_copy_buffer_and_revision() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
let d = dir.path();
git(d, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Lutra Test"),
("user.email", "test@lutra.invalid"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git(d, &["config", key, value]);
}
let first = commit(
d,
"a.php",
"<?php\n// one\n",
"First",
"Ann <ann@x.invalid>",
);
let second = commit(
d,
"a.php",
"<?php\n// one\n// two\n",
"Second\n\nBody",
"Bo <bo@x.invalid>",
);
std::fs::write(d.join("bom.php"), "\u{feff}<?php\r\n// bom\r\n").unwrap();
git(d, &["add", "-A"]);
git(d, &["commit", "-q", "-m", "Bom"]);
let bom_commit = git(d, &["rev-parse", "HEAD"]);
let host = Host::open(d);
host.events.lock().unwrap().clear();
let blame = host.run("git.blame", json!({"path": "a.php"})).unwrap();
assert_eq!(
hashes(&blame),
[first.as_str(), first.as_str(), second.as_str()]
);
assert_eq!(blame["version"], Value::Null);
let line = &blame["lines"][2];
assert_eq!(line["author"], "Bo");
assert_eq!(line["summary"], "Second");
assert_eq!(line["origLine"], 3);
assert!(line["date"].as_str().unwrap().len() >= 25, "{line}");
// An open buffer with an unsaved line: that line is not committed.
let opened = host.run("file.open", json!({"path": "a.php"})).unwrap();
let id = opened["id"].clone();
host.run(
"buffer.edit",
json!({"id": id, "baseVersion": opened["version"], "edits": [{"from": 6, "to": 6, "insert": "// new\n"}]}),
)
.unwrap();
let blame = host.run("git.blame", json!({"path": "a.php"})).unwrap();
let zeros = "0".repeat(first.len());
assert_eq!(
hashes(&blame),
[
first.as_str(),
zeros.as_str(),
first.as_str(),
second.as_str()
]
);
assert_ne!(blame["version"], Value::Null);
assert_eq!(blame["lines"][2]["origLine"], 2);
// A revision ignores the buffer.
let at = host
.run("git.blame", json!({"path": "a.php", "rev": first}))
.unwrap();
assert_eq!(hashes(&at), [first.as_str(), first.as_str()]);
assert_eq!(at["version"], Value::Null);
// A CRLF buffer with a BOM matches its blob.
host.run("file.open", json!({"path": "bom.php"})).unwrap();
let blame = host.run("git.blame", json!({"path": "bom.php"})).unwrap();
assert_eq!(hashes(&blame), [bom_commit.as_str(), bom_commit.as_str()]);
// Untracked: no lines.
std::fs::write(d.join("new.php"), "<?php\n").unwrap();
let untracked = host.run("git.blame", json!({"path": "new.php"})).unwrap();
assert_eq!(untracked["lines"], json!([]));
for params in [
json!({}),
json!({"path": "a.php", "bogus": 1}),
json!({"path": "a.php", "rev": "-L1"}),
json!({"path": "../x.php"}),
] {
let err = host.run("git.blame", params.clone()).unwrap_err();
assert_eq!(err.code(), "invalid_params", "{params}");
}
let err = host
.run("git.blame", json!({"path": "a.php", "rev": "nope"}))
.unwrap_err();
assert_eq!(err.code(), "failed");
let changed = host
.events
.lock()
.unwrap()
.iter()
.filter(|e| matches!(e, Event::GitChanged(_)))
.count();
assert_eq!(changed, 0);
}
#[test]
fn blame_without_commits_or_project() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
git(dir.path(), &["init", "-q", "-b", "main"]);
std::fs::write(dir.path().join("a.php"), "<?php\n").unwrap();
let host = Host::open(dir.path());
let blame = host.run("git.blame", json!({"path": "a.php"})).unwrap();
assert_eq!(blame["lines"], json!([]));
host.run("file.open", json!({"path": "a.php"})).unwrap();
let blame = host.run("git.blame", json!({"path": "a.php"})).unwrap();
assert_eq!(blame["lines"], json!([]));
let bare = Host {
engine: Mutex::new(Engine::new().unwrap()),
events: Mutex::new(Vec::new()),
};
let err = bare.run("git.blame", json!({"path": "a.php"})).unwrap_err();
assert_eq!(err.code(), "disabled");
}

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};

190
crates/vcs/tests/blame.rs Normal file
View file

@ -0,0 +1,190 @@
//! Blame (M4.7) against real repositories in temp folders: the working
//! copy, buffer contents under `core.autocrlf`, a revision, a rename, a
//! project inside a larger repository, untracked files and an empty
//! repository. Every test skips with a message when git is not installed.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::path::Path;
use std::process::Command;
use lutra_vcs::{Git, Repo, VcsError, is_uncommitted};
/// The installed git, or `None` (with a message) when there is none.
fn installed() -> Option<Git> {
match Git::detect("") {
Ok(git) => Some(git),
Err(e) => {
eprintln!("skipped: no usable git installed ({e})");
None
}
}
}
/// Runs git in `dir` for test setup and asserts it succeeded.
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// A new repository on `main` with a local identity.
fn init(dir: &Path) {
git(dir, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Lutra Test"),
("user.email", "test@lutra.invalid"),
("commit.gpgsign", "false"),
("tag.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git(dir, &["config", key, value]);
}
}
/// Writes a file, creating its folders.
fn write(dir: &Path, path: &str, text: &str) {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
std::fs::write(full, text).unwrap();
}
/// Stages everything and commits as `author` (`Name <mail>`), returning
/// the hash.
fn commit(dir: &Path, message: &str, author: &str) -> String {
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "--author", author, "-m", message]);
git(dir, &["rev-parse", "HEAD"])
}
/// Opens the repository at `dir`.
fn open(git: &Git, dir: &Path) -> Repo {
git.open(dir).unwrap().expect("a repository")
}
/// The hashes of a blame.
fn hashes(repo: &Repo, path: &str, rev: Option<&str>, contents: Option<&str>) -> Vec<String> {
repo.blame(path, rev, contents.map(str::as_bytes))
.unwrap()
.into_iter()
.map(|l| l.hash)
.collect()
}
#[test]
fn working_copy_contents_and_revisions() {
let Some(g) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let d = dir.path();
init(d);
write(d, "a.php", "<?php\nfunction a() {}\n");
let first = commit(d, "First", "Ann <ann@x.invalid>");
write(d, "a.php", "<?php\nfunction a() {}\nfunction b() {}\n");
let second = commit(d, "Second", "Bo <bo@x.invalid>");
let repo = open(&g, d);
let lines = repo.blame("a.php", None, None).unwrap();
assert_eq!(lines.len(), 3);
assert_eq!(lines[0].hash, first);
assert_eq!(lines[0].author, "Ann");
assert_eq!(lines[2].hash, second);
assert_eq!(lines[2].summary, "Second");
assert_eq!(lines[2].orig_line, 3);
// Unsaved text with CRLF under autocrlf: only the new line is new.
git(d, &["config", "core.autocrlf", "true"]);
let blamed = hashes(
&repo,
"a.php",
None,
Some("<?php\r\nfunction a() {}\r\n// new\r\nfunction b() {}\r\n"),
);
assert_eq!(blamed.len(), 4);
assert_eq!(blamed[0], first);
assert!(is_uncommitted(&blamed[2]));
assert_eq!(blamed[3], second);
// A revision ignores the contents.
assert_eq!(
hashes(&repo, "a.php", Some(&first), Some("x\n")),
[first.clone(), first.clone()]
);
assert_eq!(
hashes(&repo, "a.php", Some("HEAD^"), None),
[first.clone(), first.clone()]
);
// Renamed: blame follows the file.
git(d, &["mv", "a.php", "b.php"]);
let renamed = commit(d, "Rename", "Cy <cy@x.invalid>");
assert_ne!(renamed, second);
assert_eq!(
hashes(&repo, "b.php", None, None),
[first.clone(), first, second]
);
// Untracked and bad input.
write(d, "new.php", "<?php\n");
assert!(repo.blame("new.php", None, None).unwrap().is_empty());
assert!(
repo.blame("new.php", None, Some(b"<?php\n"))
.unwrap()
.is_empty()
);
assert!(matches!(
repo.blame("b.php", Some("-L1"), None),
Err(VcsError::InvalidName(_))
));
assert!(matches!(
repo.blame("b.php", Some("HEAD:b.php"), None),
Err(VcsError::InvalidName(_))
));
assert!(matches!(
repo.blame("../b.php", None, None),
Err(VcsError::InvalidPath(_))
));
assert!(matches!(
repo.blame("b.php", Some("nope"), None),
Err(VcsError::Git(_))
));
}
#[test]
fn a_project_inside_a_repository_and_an_empty_one() {
let Some(g) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let d = dir.path();
init(d);
write(d, "app/src/a.php", "<?php\n");
let hash = commit(d, "First", "Ann <ann@x.invalid>");
let repo = open(&g, &d.join("app"));
assert_eq!(hashes(&repo, "src/a.php", None, None), [hash]);
let empty = tempfile::tempdir().unwrap();
init(empty.path());
write(empty.path(), "a.php", "<?php\n");
let repo = open(&g, empty.path());
assert!(repo.blame("a.php", None, None).unwrap().is_empty());
assert!(
repo.blame("a.php", None, Some(b"<?php\n"))
.unwrap()
.is_empty()
);
}