From 2f758d76b98b6feffcd7723b78987375db38dfc7 Mon Sep 17 00:00:00 2001 From: danny Date: Fri, 30 Oct 2026 17:52:44 +0100 Subject: [PATCH] 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 --- crates/engine/src/cmd/git_blame.rs | 116 ++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/engine.rs | 1 + crates/engine/tests/git_blame.rs | 230 ++++++++ crates/vcs/src/blame.rs | 343 ++++++++++++ crates/vcs/src/lib.rs | 4 + crates/vcs/tests/blame.rs | 190 +++++++ docs/architecture.md | 10 + ui/src/commands/uiCommands.ts | 2 + ui/src/components/editor/blame.ts | 702 ++++++++++++++++++++++++ ui/src/components/editor/extensions.ts | 5 +- ui/src/components/layout/MainLayout.vue | 29 + ui/src/i18n/en.json | 6 + ui/src/stores/vcsStatus.ts | 8 +- ui/tests/editor/blame.test.ts | 321 +++++++++++ ui/tests/menu/AppMenu.test.ts | 1 + ui/tests/palette/CommandPalette.test.ts | 2 + ui/tests/vcs/Log.test.ts | 34 +- 18 files changed, 2003 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/git_blame.rs create mode 100644 crates/engine/tests/git_blame.rs create mode 100644 crates/vcs/src/blame.rs create mode 100644 crates/vcs/tests/blame.rs create mode 100644 ui/src/components/editor/blame.ts create mode 100644 ui/tests/editor/blame.test.ts diff --git a/crates/engine/src/cmd/git_blame.rs b/crates/engine/src/cmd/git_blame.rs new file mode 100644 index 0000000..72fc4c4 --- /dev/null +++ b/crates/engine/src/cmd/git_blame.rs @@ -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, +} + +/// `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 { + 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 = 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), + })) + }), + ) + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index e3a2e3d..1b82e60 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -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)?; diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 9f1c713..51f856b 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -481,6 +481,7 @@ mod tests { "file.open", "file.save", "file.saveAll", + "git.blame", "git.branches", "git.cancel", "git.checkout", diff --git a/crates/engine/tests/git_blame.rs b/crates/engine/tests/git_blame.rs new file mode 100644 index 0000000..69f4a83 --- /dev/null +++ b/crates/engine/tests/git_blame.rs @@ -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, + /// Events published so far. + events: Mutex>, +} + +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 { + 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 { + 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", + "", + ); + let second = commit( + d, + "a.php", + "", + ); + std::fs::write(d.join("bom.php"), "\u{feff}= 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"), " []`), 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, 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, + /// Author offset, `+hhmm` / `-hhmm`. + tz: String, + /// Subject line. + summary: String, +} + +/// Parses `git blame --porcelain` output into one entry per line. +/// Headers that are not ` …` and content lines +/// without a header before them are skipped. +pub fn parse_blame(bytes: &[u8]) -> Vec { + let mut commits: HashMap = 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 ` []`. +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::().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 { + 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 \nauthor-time 1700000000\nauthor-tz +0100\nsummary First\nfilename f.php\n\t(), 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)); + } + } +} diff --git a/crates/vcs/src/lib.rs b/crates/vcs/src/lib.rs index 44ac9ed..d6fbe4a 100644 --- a/crates/vcs/src/lib.rs +++ b/crates/vcs/src/lib.rs @@ -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}; diff --git a/crates/vcs/tests/blame.rs b/crates/vcs/tests/blame.rs new file mode 100644 index 0000000..d7e2520 --- /dev/null +++ b/crates/vcs/tests/blame.rs @@ -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 { + 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 `), 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 { + 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", ""); + write(d, "a.php", ""); + 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(""); + assert_ne!(renamed, second); + assert_eq!( + hashes(&repo, "b.php", None, None), + [first.clone(), first, second] + ); + + // Untracked and bad input. + write(d, "new.php", ""); + 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", " []`, the commit's fields once per hash, the line after a tab), skips malformed headers and is property-tested with random bytes. Dates are the author time in the author's offset as ISO 8601 (`civil_from_days`, no date crate). Lines not committed yet carry git's all-zero hash (`is_uncommitted`). +- **Command** (`crates/engine/src/cmd/git_blame.rs`, through `start_with`; read-only, pending, no `gitChanged`): `git.blame {path, rev?}` → `{lines: [{hash, author, date, summary, origLine}], version}`, one entry per line in file order, `origLine` 1-based in that commit. Without `rev`, an open buffer for the path is blamed as it stands: under the lock only its rope is cloned, and the git thread builds the saved text (buffer line ending, BOM again in front when the file has one). `version` is that buffer's version, `null` when no buffer was used (an addition to the C6 contract, like `git.lineChanges`). A bad path or revision is `invalid_params`; an unknown revision is `failed` with git's message. +- **Gutter** (`ui/src/components/editor/blame.ts`, appended to `editorExtensions` for buffers): annotations per file, toggled by the UI command `vcs.toggleBlame {path?}` (menu Git › Annotate with Git Blame; without a path, the active tab's file; no default shortcut). Every editor of the file shows them until toggled off or the project changes. The first line of a run from one commit shows the short local date and the author (22 characters wide, cut with an ellipsis); every annotated line has a 3 px bar mixed from `--lt-accent` by age (a day, a week, a month, a year, older), and uncommitted lines a `--lt-vcs-modified` bar and "Not committed yet". Queries go through `runWaiting` when shown, 500 ms after the last edit and on every `gitChanged` (the status store calls `refreshBlame`); like the change markers they wait for the buffer sync's `idle()` and drop answers for a changed document. Between answers the annotations move with the text (a line inserted at a line start pushes the annotation down); new lines stay blank. Failures keep the annotations. +- **Hover and click:** resting on an annotation for 300 ms shows a card with the short hash, author, local date and the subject, replaced by the full message from `git.showCommit` (cached per hash, at most 200); leaving the gutter and the card hides it. A click on a committed line runs the UI command `vcs.showCommit {hash}` (no menu entry, no default shortcut), which shows the Log tab (M4.6) with that commit selected, even one outside the loaded pages. +- **Checked in the app** (debug build with the bundled UI, Windows 11, git 2.47.1, control port 7947, a demo repository with three authors from 2024, August 2026 and three hours ago; screenshots only, no input): `git.blame` 210 ms for the first call (git detection, opening the repository), then 68 ms; `vcs.toggleBlame` showed date and author on each run with the strongest bar on today's lines and the faintest on 2024's; an unsaved line inserted through `buffer.edit` showed "Not committed yet" and pushed the others down; `vcs.showCommit` opened the Log with the commit selected and its full message. Hover and click need the mouse, so they are covered by Vitest only. +- **Tests:** `crates/vcs/tests/blame.rs` (2 tests against real temp repositories: authors and summaries, buffer contents with CRLF under autocrlf, revisions, a rename, untracked files, bad input, a project inside a repository, an empty repository); unit and property tests in `blame.rs` (groups, content that looks like a header, header checks, dates and offsets); `crates/engine/tests/git_blame.rs` (2 tests: the working copy, a buffer with an unsaved line, a revision, a CRLF buffer with a BOM, untracked, bad params, an unknown revision, no `gitChanged`, no commits, no project); Vitest `ui/tests/editor/blame.test.ts` (11: parsing, age levels, runs and clamping, labels, the toggle, debounce and mapping, stale answers, failures, `refreshBlame`/`clearBlame`, click, hover with the full message, commands, tokens only) and one layout test in `ui/tests/vcs/Log.test.ts` (`vcs.showCommit` selects the commit, `vcs.toggleBlame`). + ### Branches (M4.5) - **Where:** `ui/src/components/vcs/branches/`: `branches.ts` is the Pinia store, `BranchStatusItem.vue` the status-bar item (one line in `StatusBar.vue`, after H3's progress item), `BranchPopup.vue` the popup. The item supplies the UI commands, so they exist wherever the status bar is. @@ -747,6 +756,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | M4.7: blame (`git.blame` with `--contents` from the buffer, the annotation gutter by age, hover with the commit message, `vcs.toggleBlame`, `vcs.showCommit`) | | 2026-10-28 | minor | M4.6: history backend (`git.log`, `git.showCommit`, `git.showAt`), the shared hook for new git commands, the Log tab, diffs at a commit | | 2026-10-28 | minor | M4.10: remotes (`Call::network` with progress and cancel, URL redaction, `git.fetch/pull/push/clone/cancel/remotes/remoteAdd/remoteSetUrl/remoteRemove`, `gitProgress`, `git.pull.mode`, the clone and remotes dialogs) | | 2026-10-28 | minor | M4.8: merge conflicts (`git.merge`, `git.mergeAbort`, `git.conflictVersions`, `git.markResolved`, the merge dialog with a three-pane resolve view) | diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index bc811cb..04a6957 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -53,6 +53,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [ { id: "vcs.showHistory", labelKey: "command.vcs.showHistory", menuPath: "Git/Show History" }, { id: "vcs.stash", labelKey: "command.vcs.stash", menuPath: "Git/Stash Changes…" }, { id: "vcs.showStashes", labelKey: "command.vcs.showStashes", menuPath: "Git/Stashes…" }, + { id: "vcs.showCommit", labelKey: "command.vcs.showCommit" }, + { id: "vcs.toggleBlame", labelKey: "command.vcs.toggleBlame", menuPath: "Git/Annotate with Git Blame" }, { id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" }, { id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" }, { id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" }, diff --git a/ui/src/components/editor/blame.ts b/ui/src/components/editor/blame.ts new file mode 100644 index 0000000..6d3c52d --- /dev/null +++ b/ui/src/components/editor/blame.ts @@ -0,0 +1,702 @@ +/** + * Git blame annotations in the editor gutter (M4.7): beside each line the + * date and author of the commit that last changed it, with a bar coloured + * by the commit's age. + * + * - **Toggle:** per file ({@link toggleBlame}, the UI command + * `vcs.toggleBlame` on the active tab). Every editor of that file shows + * or hides the annotations; the choice lasts until the project changes + * ({@link clearBlame}). + * - **Source:** `git.blame {path}` (a pending outcome, so through + * `runWaiting`). The engine blames the open buffer as it stands, so + * unsaved lines show as not committed. Asked when shown, 500 ms after + * the last edit ({@link BLAME_DEBOUNCE_MS}) and on {@link refreshBlame} + * (every `gitChanged`, from the status store). Like the change markers, + * the plugin waits for the buffer sync to be idle and drops answers for + * a document that changed meanwhile. Between answers the annotations + * move with the text; new lines stay blank until the next answer. + * - **Look:** the first line of each run of lines from one commit shows + * `date author`; the following lines only the bar. The bar's strength + * follows the age (today, a week, a month, a year, older), mixed from + * `--lt-accent`; lines not committed yet take `--lt-vcs-modified`. + * - **Hover** shows hash, author, date and the commit message (the + * subject at once, the full message from `git.showCommit`, cached per + * hash). **Click** opens the commit in the Log (`vcs.showCommit`). + * - Failures leave the annotations as they are. + */ +import { RangeSet, RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state"; +import { EditorView, GutterMarker, ViewPlugin, gutter, showTooltip, type PluginValue, type Tooltip, type ViewUpdate } from "@codemirror/view"; +import { runWaiting, type JsonValue } from "../../ipc"; +import { t } from "../../i18n"; +import type { AssistBuffer } from "./assist"; + +/** Delay between the last edit and the query. */ +export const BLAME_DEBOUNCE_MS = 500; + +/** Delay before the hover card shows. */ +export const BLAME_HOVER_MS = 300; + +/** The UI command that opens a commit in the Log. */ +export const SHOW_COMMIT_COMMAND = "vcs.showCommit"; + +/** The UI command that shows or hides the annotations of the active file. */ +export const TOGGLE_BLAME_COMMAND = "vcs.toggleBlame"; + +/** Most commit messages cached for the hover card. */ +const MAX_MESSAGES = 200; + +/** One line of `git.blame`. */ +export interface BlameLine { + /** Full hash; all zeros for a line not committed yet. */ + hash: string; + /** Author name. */ + author: string; + /** Author date, ISO 8601. */ + date: string; + /** Subject line. */ + summary: string; + /** Line number in that commit, 1-based. */ + origLine: number; +} + +/** How the annotations reach the engine and the Log; replaced in tests. */ +export interface BlameTransport { + /** Runs a command and resolves with its untrusted result. */ + query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }>; + /** Opens a commit in the Log. */ + openCommit(hash: string): void; +} + +/** Opens commits through the UI command; set by the layout. */ +let commitOpener: (hash: string) => void = () => undefined; + +/** + * Sets how a click opens a commit (the layout runs `vcs.showCommit`). + * + * @param open - the opener. + */ +export function setCommitOpener(open: (hash: string) => void): void { + commitOpener = open; +} + +/** The transport through the engine IPC. */ +export const engineBlameTransport: BlameTransport = { + query: (command, params) => runWaiting(command, params), + openCommit: (hash) => { + commitOpener(hash); + }, +}; + +/** + * Whether a hash is git's all-zero hash of lines not committed yet. + * + * @param hash - a hash from `git.blame`. + */ +export function isUncommitted(hash: string): boolean { + return hash !== "" && /^0+$/.test(hash); +} + +/** + * Reads the lines of a `git.blame` result. A malformed line becomes an + * empty entry, so the others keep their line numbers. + * + * @param value - the untrusted result. + * @returns one entry per line (null for a malformed one), or null when + * the result has no list. + */ +export function readBlame(value: unknown): (BlameLine | null)[] | null { + if (typeof value !== "object" || value === null) { + return null; + } + const lines = (value as Record).lines; + if (!Array.isArray(lines)) { + return null; + } + return (lines as unknown[]).map((line) => { + if (typeof line !== "object" || line === null) { + return null; + } + const { hash, author, date, summary, origLine } = line as Record; + if (typeof hash !== "string" || !/^[0-9a-f]{4,64}$/i.test(hash) || typeof author !== "string" || typeof date !== "string") { + return null; + } + return { + hash, + author, + date, + summary: typeof summary === "string" ? summary : "", + origLine: typeof origLine === "number" && Number.isInteger(origLine) && origLine > 0 ? origLine : 0, + }; + }); +} + +/** One day in milliseconds. */ +const DAY = 86_400_000; + +/** Upper bounds of the age levels 0 to 3; older is level 4. */ +const AGE_BOUNDS = [DAY, 7 * DAY, 31 * DAY, 365 * DAY]; + +/** + * The age level of a commit date: 0 within a day, 1 a week, 2 a month, + * 3 a year, 4 older (and for an unreadable date). + * + * @param iso - ISO 8601 date. + * @param now - the current time in milliseconds. + */ +export function ageLevel(iso: string, now: number): number { + const time = Date.parse(iso); + if (Number.isNaN(time)) { + return AGE_BOUNDS.length; + } + const age = Math.max(0, now - time); + const level = AGE_BOUNDS.findIndex((bound) => age < bound); + return level === -1 ? AGE_BOUNDS.length : level; +} + +/** + * A short local date, `YYYY-MM-DD`. + * + * @param iso - ISO 8601 date. + * @returns the date, or the input when it cannot be read. + */ +export function shortDate(iso: string): string { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) { + return iso; + } + const pad = (n: number): string => String(n).padStart(2, "0"); + return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; +} + +/** The text and look of one annotated line. */ +class BlameMarker extends GutterMarker { + /** + * @param line - the blame of the line. + * @param first - the first line of a run from one commit (shows text). + * @param level - the age level, or `"new"` for uncommitted lines. + */ + constructor( + readonly line: BlameLine, + readonly first: boolean, + readonly level: number | "new", + ) { + super(); + } + + /** Text inserted at the line's start pushes the annotation down with the line. */ + override startSide = 1; + + /** Same side as the start, so the empty range survives mapping. */ + override endSide = 1; + + override eq(other: GutterMarker): boolean { + return other instanceof BlameMarker && other.line.hash === this.line.hash && other.first === this.first && other.level === this.level; + } + + override toDOM(): Node { + const element = document.createElement("div"); + element.className = `lt-blame-marker lt-blame-marker--age-${String(this.level)}`; + element.dataset.test = "blame-marker"; + element.dataset.hash = this.line.hash; + if (this.first) { + element.textContent = this.level === "new" ? t("editor.blame.notCommitted") : `${shortDate(this.line.date)} ${this.line.author}`; + } + return element; + } +} + +/** + * Builds the annotations of `lines` in `doc`: line `i` of the blame is + * line `i + 1` of the document; lines past the document are ignored. + * + * @param doc - the document the blame was made for. + * @param lines - the blame, in line order. + * @param now - the current time in milliseconds. + */ +export function buildBlameMarkers(doc: Text, lines: readonly (BlameLine | null)[], now: number): RangeSet { + const builder = new RangeSetBuilder(); + let previous: string | null = null; + const count = Math.min(lines.length, doc.lines); + for (let index = 0; index < count; index += 1) { + const line = lines[index] ?? null; + if (line === null) { + previous = null; + continue; + } + const level = isUncommitted(line.hash) ? "new" : ageLevel(line.date, now); + const at = doc.line(index + 1).from; + builder.add(at, at, new BlameMarker(line, line.hash !== previous, level)); + previous = line.hash; + } + return builder.finish(); +} + +/** Replaces the annotations of a state. */ +const setBlame = StateEffect.define>(); + +/** The annotations of a state, mapped through edits between answers. */ +const blameMarkers = StateField.define>({ + create: () => RangeSet.empty, + update(value, tr) { + let next = value.map(tr.changes); + for (const effect of tr.effects) { + if (effect.is(setBlame)) { + next = effect.value; + } + } + return next; + }, +}); + +/** + * The blame of the line at `pos`, if annotated. + * + * @param state - an editor state built with {@link blameExtensions}. + * @param pos - a position on the line. + */ +function blameAt(state: EditorState, pos: number): BlameLine | null { + const set = state.field(blameMarkers, false); + if (set === undefined) { + return null; + } + const line = state.doc.lineAt(pos); + let found: BlameLine | null = null; + set.between(line.from, line.from, (_from, _to, marker) => { + if (marker instanceof BlameMarker) { + found = marker.line; + return false; + } + return undefined; + }); + return found; +} + +/** + * The annotations a state carries, for tests and inspection. + * + * @param state - an editor state built with {@link blameExtensions}. + * @returns by 1-based line number: hash, whether it shows text, the age + * level; empty without the extension. + */ +export function blameMarkerLines(state: EditorState): Record { + const out: Record = {}; + const set = state.field(blameMarkers, false); + if (set === undefined) { + return out; + } + const cursor = set.iter(); + while (cursor.value !== null) { + if (cursor.value instanceof BlameMarker) { + const { line, first, level } = cursor.value; + out[state.doc.lineAt(cursor.from).number] = { hash: line.hash, first, level }; + } + cursor.next(); + } + return out; +} + +/** What the hover card shows: a line's blame at a document position. */ +interface Hover { + /** Start of the hovered line. */ + pos: number; + /** Its blame. */ + line: BlameLine; +} + +/** Shows (or, with null, hides) the hover card. */ +const setHover = StateEffect.define(); + +/** Full commit messages by hash, for the hover card. */ +const messages = new Map(); + +/** + * Remembers a commit message, dropping the oldest beyond the cap. + * + * @param hash - the commit. + * @param message - its full message. + */ +function rememberMessage(hash: string, message: string): void { + if (messages.size >= MAX_MESSAGES) { + const oldest = messages.keys().next().value; + if (oldest !== undefined) { + messages.delete(oldest); + } + } + messages.set(hash, message); +} + +/** + * Builds the hover card of a line. + * + * @param line - the line's blame. + * @returns the card's DOM and the element that holds the message. + */ +function hoverCard(line: BlameLine): { dom: HTMLElement; message: HTMLElement } { + const dom = document.createElement("div"); + dom.className = "lt-blame-tooltip"; + dom.dataset.test = "blame-tooltip"; + const head = document.createElement("div"); + head.className = "lt-blame-tooltip__head"; + const message = document.createElement("div"); + message.className = "lt-blame-tooltip__message"; + if (isUncommitted(line.hash)) { + head.textContent = t("editor.blame.notCommitted"); + message.textContent = t("editor.blame.notCommittedHint"); + } else { + const date = new Date(line.date); + const when = Number.isNaN(date.getTime()) ? line.date : date.toLocaleString(); + head.textContent = t("editor.blame.byLine", { hash: line.hash.slice(0, 8), author: line.author, date: when }); + message.textContent = messages.get(line.hash) ?? line.summary; + const hint = document.createElement("div"); + hint.className = "lt-blame-tooltip__hint"; + hint.textContent = t("editor.blame.clickHint"); + dom.append(head, message, hint); + return { dom, message }; + } + dom.append(head, message); + return { dom, message }; +} + +/** How each view reaches the engine, for its hover card. */ +const transports = new WeakMap(); + +/** The hover card; the card loads the full message once shown. */ +const hoverState = StateField.define({ + create: () => null, + update(value, tr) { + let next = value; + if (next !== null && tr.docChanged) { + next = null; + } + for (const effect of tr.effects) { + if (effect.is(setHover)) { + next = effect.value; + } + } + return next; + }, + provide: (field) => + showTooltip.from(field, (hover): Tooltip | null => { + if (hover === null) { + return null; + } + return { + pos: hover.pos, + above: false, + create: (view) => { + const { dom, message } = hoverCard(hover.line); + const { hash } = hover.line; + const transport = transports.get(view); + if (transport !== undefined && !isUncommitted(hash) && !messages.has(hash)) { + void transport.query("git.showCommit", { hash }).then((result) => { + if (!result.ok || typeof result.value !== "object" || result.value === null) { + return; + } + const text = (result.value as Record).message; + if (typeof text === "string") { + rememberMessage(hash, text); + message.textContent = text; + } + }); + } + return { dom }; + }, + }; + }), +}); + +/** Paths whose annotations are shown. */ +const shown = new Set(); + +/** Live plugins, refreshed when the toggle or the repository changes. */ +const live = new Set<{ path: string; schedule(delay: number): void }>(); + +/** + * Whether the annotations of a file are shown. + * + * @param path - project-relative path. + */ +export function isBlameShown(path: string): boolean { + return shown.has(path); +} + +/** + * Shows or hides the annotations of a file in every editor of it. + * + * @param path - project-relative path. + * @param on - show (true) or hide. + */ +export function setBlameShown(path: string, on: boolean): void { + if (on) { + shown.add(path); + } else { + shown.delete(path); + } + for (const plugin of live) { + if (plugin.path === path) { + plugin.schedule(0); + } + } +} + +/** + * Toggles the annotations of a file. + * + * @param path - project-relative path. + * @returns whether they are shown now. + */ +export function toggleBlame(path: string): boolean { + const on = !shown.has(path); + setBlameShown(path, on); + return on; +} + +/** Asks every annotated editor to query again (`gitChanged`). */ +export function refreshBlame(): void { + for (const plugin of live) { + if (shown.has(plugin.path)) { + plugin.schedule(0); + } + } +} + +/** Hides every annotation and forgets the messages (a project change). */ +export function clearBlame(): void { + const paths = [...shown]; + shown.clear(); + messages.clear(); + for (const plugin of live) { + if (paths.includes(plugin.path)) { + plugin.schedule(0); + } + } +} + +/** + * The plugin that queries the annotations of one view and runs its hover + * card. + * + * @param path - the file. + * @param buffer - the engine buffer the state shows. + * @param transport - how to reach the engine. + */ +function blamePlugin(path: string, buffer: AssistBuffer, transport: BlameTransport): Extension { + return ViewPlugin.define((view): PluginValue => { + const life = { alive: true }; + let timer: ReturnType | null = null; + let hoverTimer: ReturnType | null = null; + let asked = 0; + + /** + * Whether the plugin still lives and the view still shows `doc`. + * + * @param doc - the document a query was made for. + */ + function current(doc: Text): boolean { + return life.alive && view.state.doc === doc; + } + + /** Queries the annotations (or clears them when hidden). */ + async function run(): Promise { + asked += 1; + const mine = asked; + if (!shown.has(path)) { + if (view.state.field(blameMarkers).size > 0) { + view.dispatch({ effects: [setBlame.of(RangeSet.empty as RangeSet), setHover.of(null)] }); + } + return; + } + const doc = view.state.doc; + await buffer.idle(); + if (!current(doc) || mine !== asked) { + return; + } + const result = await transport.query("git.blame", { path }); + if (!current(doc) || mine !== asked || !result.ok || !shown.has(path)) { + return; + } + const lines = readBlame(result.value); + if (lines !== null) { + view.dispatch({ effects: setBlame.of(buildBlameMarkers(doc, lines, Date.now())) }); + } + } + + /** Hides the hover card, if any. */ + function hideHover(): void { + if (hoverTimer !== null) { + clearTimeout(hoverTimer); + hoverTimer = null; + } + if (life.alive && (view.state.field(hoverState, false) ?? null) !== null) { + view.dispatch({ effects: setHover.of(null) }); + } + } + + /** + * Hides the card when the pointer leaves the gutter and the card. + * + * @param event - the pointer event. + */ + function onPointer(event: Event): void { + const target = event.target; + if (target instanceof Element && (target.closest(".lt-blame-gutter") || target.closest(".lt-blame-tooltip"))) { + return; + } + hideHover(); + } + + const handle = { + path, + schedule(delay: number): void { + if (!life.alive) { + return; + } + if (timer !== null) { + clearTimeout(timer); + } + timer = setTimeout(() => { + timer = null; + void run(); + }, delay); + }, + hover(pos: number): void { + const line = blameAt(view.state, pos); + const now = view.state.field(hoverState, false); + if (line === null) { + hideHover(); + return; + } + if (now !== undefined && now !== null && now.pos === pos) { + return; + } + if (hoverTimer !== null) { + clearTimeout(hoverTimer); + } + hoverTimer = setTimeout(() => { + hoverTimer = null; + if (life.alive && blameAt(view.state, pos) === line) { + view.dispatch({ effects: setHover.of({ pos, line }) }); + } + }, BLAME_HOVER_MS); + }, + }; + live.add(handle); + plugins.set(view, handle); + transports.set(view, transport); + view.dom.addEventListener("mouseover", onPointer); + handle.schedule(0); + return { + update(update: ViewUpdate): void { + if (update.docChanged && shown.has(path)) { + handle.schedule(BLAME_DEBOUNCE_MS); + } + }, + destroy(): void { + life.alive = false; + live.delete(handle); + plugins.delete(view); + transports.delete(view); + view.dom.removeEventListener("mouseover", onPointer); + for (const pending of [timer, hoverTimer]) { + if (pending !== null) { + clearTimeout(pending); + } + } + timer = null; + hoverTimer = null; + }, + }; + }); +} + +/** The plugin handle of each view, for the gutter's pointer handlers. */ +const plugins = new WeakMap(); + +/** Annotation styles from the theme tokens. */ +const blameTheme: Extension = EditorView.theme({ + ".lt-blame-gutter .cm-gutterElement": { + padding: "0", + cursor: "pointer", + }, + ".lt-blame-marker": { + boxSizing: "border-box", + width: "22ch", + height: "100%", + padding: "0 6px 0 5px", + overflow: "hidden", + whiteSpace: "nowrap", + textOverflow: "ellipsis", + fontSize: "0.85em", + color: "var(--lt-editor-gutter-fg)", + borderLeft: "3px solid transparent", + }, + ".lt-blame-marker--age-0": { borderLeftColor: "var(--lt-accent)" }, + ".lt-blame-marker--age-1": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 75%, var(--lt-editor-gutter-bg))" }, + ".lt-blame-marker--age-2": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 50%, var(--lt-editor-gutter-bg))" }, + ".lt-blame-marker--age-3": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 30%, var(--lt-editor-gutter-bg))" }, + ".lt-blame-marker--age-4": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 15%, var(--lt-editor-gutter-bg))" }, + ".lt-blame-marker--age-new": { borderLeftColor: "var(--lt-vcs-modified)", fontStyle: "italic" }, + ".lt-blame-tooltip": { + maxWidth: "60ch", + padding: "6px 8px", + }, + ".lt-blame-tooltip__head": { + color: "var(--lt-fg-muted)", + marginBottom: "4px", + }, + ".lt-blame-tooltip__message": { + whiteSpace: "pre-wrap", + overflowWrap: "anywhere", + maxHeight: "16em", + overflowY: "auto", + }, + ".lt-blame-tooltip__hint": { + color: "var(--lt-fg-muted)", + marginTop: "6px", + fontSize: "0.9em", + }, +}); + +/** + * The blame annotation extensions of an editor state. + * + * @param path - the file's project-relative path. + * @param buffer - the buffer it shows; none for states without one. + * @param transport - how to reach the engine. + * @returns the extensions; empty without a buffer or path. + */ +export function blameExtensions( + path: string, + buffer: AssistBuffer | undefined, + transport: BlameTransport = engineBlameTransport, +): Extension { + if (buffer === undefined || path === "") { + return []; + } + return [ + blameMarkers, + hoverState, + gutter({ + class: "lt-blame-gutter", + markers: (view) => view.state.field(blameMarkers), + domEventHandlers: { + click(view, line, event) { + const target = event.target instanceof HTMLElement ? event.target.closest(".lt-blame-marker") : null; + const hash = target?.dataset.hash ?? blameAt(view.state, line.from)?.hash; + if (hash === undefined || isUncommitted(hash)) { + return false; + } + view.dispatch({ effects: setHover.of(null) }); + transport.openCommit(hash); + return true; + }, + mousemove(view, line) { + plugins.get(view)?.hover(line.from); + return false; + }, + }, + }), + blameTheme, + blamePlugin(path, buffer, transport), + ]; +} diff --git a/ui/src/components/editor/extensions.ts b/ui/src/components/editor/extensions.ts index 58ad50f..2bb944e 100644 --- a/ui/src/components/editor/extensions.ts +++ b/ui/src/components/editor/extensions.ts @@ -6,7 +6,8 @@ * the editor tokens (`--lt-editor-selection-bg`, `--lt-editor-active-line-bg`, * `--lt-editor-cursor`, `--lt-editor-gutter-bg`, `--lt-editor-gutter-fg`, * `--lt-editor-match-bg`, `--lt-font-size-editor`). Buffers also get Git - * change markers in the gutter (`gitGutter.ts`). + * change markers in the gutter (`gitGutter.ts`) and, when toggled, blame + * annotations (`blame.ts`). */ import { EditorView } from "@codemirror/view"; import type { Extension } from "@codemirror/state"; @@ -15,6 +16,7 @@ import { languageExtensions, type SYNTAX_CLASS, type SyntaxToken } from "./langu import { lintExtensions } from "./lint"; import { assistExtensions, type AssistBuffer } from "./assist"; import { navExtensions } from "./nav/navExtension"; +import { blameExtensions } from "./blame"; import { gitGutterExtensions } from "./gitGutter"; /** @@ -125,5 +127,6 @@ export function editorExtensions(path = "", buffer?: AssistBuffer): Extension { assistExtensions(path, buffer), navExtensions(), gitGutterExtensions(buffer), + blameExtensions(path, buffer), ]; } diff --git a/ui/src/components/layout/MainLayout.vue b/ui/src/components/layout/MainLayout.vue index abf5762..7a19b3d 100644 --- a/ui/src/components/layout/MainLayout.vue +++ b/ui/src/components/layout/MainLayout.vue @@ -33,6 +33,10 @@ * tab opens. The Log tab (M4.6) appears with `vcs.showLog` and with * `vcs.showHistory {path?}` (the history of a file or folder; without a * path, of the active editor tab's file); neither has a default shortcut. + * `vcs.showCommit {hash}` (M4.7) shows the Log with that commit selected + * (a click on a blame annotation); `vcs.toggleBlame {path?}` shows or + * hides the blame annotations of a file (default: the active tab's). No + * default shortcuts. * * A slim header bar along the top (M3.9) holds the app menu * ({@link AppMenu}); its `header` slot can replace it. @@ -54,6 +58,7 @@ import { useChangesStore } from "../vcs/changes/changes"; import LogToolWindow from "../vcs/log/LogToolWindow.vue"; import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log"; import StashDialog from "../vcs/stash/StashDialog.vue"; +import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame"; import { useEditorStore } from "../../stores/editor"; import { useProjectStore } from "../../stores/project"; import ProjectToolWindow from "../project/ProjectToolWindow.vue"; @@ -174,6 +179,7 @@ onMounted(() => { problems.start(); changes.start(); vcsLog.start(); + setCommitOpener((hash) => void commands.execute(SHOW_COMMIT_COMMAND, { hash })); withdraw = [ commands.provide("view.toggleProjectTree", { run: () => { @@ -229,6 +235,28 @@ onMounted(() => { }, enabled: () => project.root !== null, }), + commands.provide(SHOW_COMMIT_COMMAND, { + run: async (params) => { + const hash = (params as { hash?: unknown } | null)?.hash; + if (typeof hash !== "string" || !/^[0-9a-f]{4,64}$/i.test(hash)) { + return; + } + bottomTool.value = "log"; + await vcsLog.open(); + await vcsLog.select(hash); + }, + enabled: () => project.root !== null, + }), + commands.provide(TOGGLE_BLAME_COMMAND, { + run: (params) => { + const given = (params as { path?: unknown } | null)?.path; + const path = typeof given === "string" && given !== "" ? given : editor.activeTab?.path; + if (path !== undefined) { + toggleBlame(path); + } + }, + enabled: () => project.root !== null, + }), commands.provide("view.toggleStructure", { run: () => { toggleLeft("structure"); @@ -242,6 +270,7 @@ onBeforeUnmount(() => { fn(); } withdraw = []; + setCommitOpener(() => undefined); find.stop(); terminal.stop(); problems.stop(); diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index c5374cd..09a6b9b 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -35,11 +35,13 @@ "command.vcs.push": "Push", "command.vcs.refresh": "Refresh Changes", "command.vcs.resolveConflicts": "Resolve Conflicts…", + "command.vcs.showCommit": "Show Commit in Log", "command.vcs.showDiff": "Show Diff", "command.vcs.showHistory": "Show History", "command.vcs.showLog": "Log", "command.vcs.showStashes": "Stashes…", "command.vcs.stash": "Stash Changes…", + "command.vcs.toggleBlame": "Annotate with Git Blame", "command.view.toggleProjectTree": "Show or Hide Project", "command.view.toggleStructure": "Show or Hide Structure", "common.cancel": "Cancel", @@ -81,6 +83,10 @@ "editor.assist.kind.value": "Value", "editor.assist.kind.variable": "Variable", "editor.assist.signature.count": "{index} of {count}", + "editor.blame.byLine": "{hash} · {author} · {date}", + "editor.blame.clickHint": "Click to show this commit in the Log", + "editor.blame.notCommitted": "Not committed yet", + "editor.blame.notCommittedHint": "This line has changes that are not committed.", "editor.closePrompt.question": "Save changes to {name} before closing?", "editor.gitGutter.added": "Added since the staged version", "editor.gitGutter.deleted": "Lines deleted here since the staged version", diff --git a/ui/src/stores/vcsStatus.ts b/ui/src/stores/vcsStatus.ts index ce3def0..21a2e85 100644 --- a/ui/src/stores/vcsStatus.ts +++ b/ui/src/stores/vcsStatus.ts @@ -20,7 +20,9 @@ * `git.status`; the tree colours its ignored entries itself while a * repository is open. * - **Gutters:** every `gitChanged` also asks the editors' change markers - * to refresh (`refreshGitGutters`), since the index may have changed. + * to refresh (`refreshGitGutters`), since the index may have changed, + * and the blame annotations (`refreshBlame`); a project change hides + * them (`clearBlame`). * - **Lifetime:** {@link start} / {@link stop} are counted, so `App.vue` * and the main layout can both hold the store; the subscription ends * with the last holder. @@ -28,6 +30,7 @@ import { defineStore } from "pinia"; import { computed, ref, shallowRef } from "vue"; import { onEngineEvent, runWaiting, type EngineEventPayload } from "../ipc"; +import { clearBlame, refreshBlame } from "../components/editor/blame"; import { refreshGitGutters } from "../components/editor/gitGutter"; /** Most files kept from one status. */ @@ -387,14 +390,17 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => { switch (event.kind) { case "projectOpened": clear(); + clearBlame(); void refresh(); break; case "projectClosed": clear(); + clearBlame(); break; case "gitChanged": void refresh(); refreshGitGutters(); + refreshBlame(); break; default: break; diff --git a/ui/tests/editor/blame.test.ts b/ui/tests/editor/blame.test.ts new file mode 100644 index 0000000..b5b3d81 --- /dev/null +++ b/ui/tests/editor/blame.test.ts @@ -0,0 +1,321 @@ +/** + * Tests of the blame annotations (M4.7, `blame.ts`): reading `git.blame`, + * age levels, building annotations (runs, uncommitted lines, clamping), + * the per-file toggle, the query when shown, the debounce after edits, + * dropping answers for an old document, `refreshBlame` and `clearBlame`, + * annotations mapped through edits, the hover card with the full message, + * a click opening the commit, the commands, and colours from tokens only. + */ +import { EditorState, Text } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + BLAME_DEBOUNCE_MS, + BLAME_HOVER_MS, + SHOW_COMMIT_COMMAND, + TOGGLE_BLAME_COMMAND, + ageLevel, + blameExtensions, + blameMarkerLines, + buildBlameMarkers, + clearBlame, + isBlameShown, + isUncommitted, + readBlame, + refreshBlame, + setBlameShown, + shortDate, + toggleBlame, + type BlameLine, + type BlameTransport, +} from "../../src/components/editor/blame"; +import { UI_COMMANDS } from "../../src/commands/uiCommands"; +import type { JsonValue } from "../../src/ipc"; + +const A = "a".repeat(40); +const B = "b".repeat(40); +const ZERO = "0".repeat(40); +const NOW = Date.parse("2026-10-29T12:00:00Z"); + +/** Views created by a test, destroyed after it. */ +let views: EditorView[] = []; + +/** A blame line. */ +function line(hash: string, date = "2026-10-29T10:00:00+01:00", author = "Ann", summary = "Subject"): BlameLine { + return { hash, author, date, summary, origLine: 1 }; +} + +/** A fake engine answering `git.blame` and `git.showCommit`. */ +class FakeEngine implements BlameTransport { + /** Every query, in order. */ + readonly calls: { command: string; params: JsonValue }[] = []; + /** What `git.blame` answers. */ + answer: unknown = { lines: [], version: 1 }; + /** Whether queries fail. */ + fail = false; + /** Commits opened. */ + readonly opened: string[] = []; + + query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }> { + this.calls.push({ command, params }); + if (this.fail) { + return Promise.resolve({ ok: false }); + } + if (command === "git.showCommit") { + return Promise.resolve({ ok: true, value: { message: "Subject\n\nThe full body." } }); + } + expect(command).toBe("git.blame"); + return Promise.resolve({ ok: true, value: this.answer }); + } + + openCommit(hash: string): void { + this.opened.push(hash); + } + + /** The `git.blame` queries. */ + blames(): JsonValue[] { + return this.calls.filter((c) => c.command === "git.blame").map((c) => c.params); + } +} + +/** + * A view of `src/a.php` (buffer 7) showing `doc`. + * + * @param doc - the text. + * @param engine - the fake engine. + */ +function viewOf(doc: string, engine: FakeEngine): EditorView { + const view = new EditorView({ + state: EditorState.create({ + doc, + extensions: blameExtensions("src/a.php", { id: 7, idle: () => Promise.resolve() }, engine), + }), + parent: document.body, + }); + views.push(view); + return view; +} + +/** Hashes of the annotations a view shows, by 1-based line. */ +function hashes(view: EditorView): Record { + const out: Record = {}; + for (const [number, marker] of Object.entries(blameMarkerLines(view.state))) { + out[Number(number)] = marker.hash; + } + return out; +} + +/** Lets timers and promises run. */ +async function flush(ms = 0): Promise { + await vi.advanceTimersByTimeAsync(ms); + for (let i = 0; i < 5; i += 1) { + await Promise.resolve(); + } +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(NOW); +}); + +afterEach(() => { + for (const view of views) { + view.destroy(); + } + views = []; + clearBlame(); + vi.useRealTimers(); +}); + +describe("reading", () => { + it("keeps line positions and drops malformed entries", () => { + expect( + readBlame({ + lines: [line(A), { hash: "nothex!", author: "x", date: "d" }, null, { hash: B, author: "Bo", date: "d", origLine: -2 }], + }), + ).toEqual([line(A), null, null, { hash: B, author: "Bo", date: "d", summary: "", origLine: 0 }]); + expect(readBlame({})).toBeNull(); + expect(readBlame("x")).toBeNull(); + }); + + it("knows uncommitted hashes, ages and short dates", () => { + expect(isUncommitted(ZERO)).toBe(true); + expect(isUncommitted(A)).toBe(false); + expect(isUncommitted("")).toBe(false); + expect(ageLevel("2026-10-29T08:00:00Z", NOW)).toBe(0); + expect(ageLevel("2026-10-25T08:00:00Z", NOW)).toBe(1); + expect(ageLevel("2026-10-10T08:00:00Z", NOW)).toBe(2); + expect(ageLevel("2026-03-01T08:00:00Z", NOW)).toBe(3); + expect(ageLevel("2020-01-01T08:00:00Z", NOW)).toBe(4); + expect(ageLevel("not a date", NOW)).toBe(4); + expect(ageLevel("2027-01-01T00:00:00Z", NOW)).toBe(0); + expect(shortDate("2026-10-29T12:00:00")).toBe("2026-10-29"); + expect(shortDate("garbage")).toBe("garbage"); + }); +}); + +describe("buildBlameMarkers", () => { + it("shows text on the first line of each run and clamps to the document", () => { + const doc = Text.of(["a", "b", "c", "d"]); + const set = buildBlameMarkers(doc, [line(A), line(A), null, line(A), line(ZERO), line(B)], NOW); + const out: Record = {}; + const cursor = set.iter(); + while (cursor.value !== null) { + const marker = cursor.value as unknown as { first: boolean; level: number | string }; + out[doc.lineAt(cursor.from).number] = [marker.first, marker.level]; + cursor.next(); + } + expect(out).toEqual({ 1: [true, 0], 2: [false, 0], 4: [true, 0] }); + const withNew = buildBlameMarkers(Text.of(["x", "y"]), [line(A), line(ZERO)], NOW); + const levels: (number | string)[] = []; + withNew.between(0, 3, (_f, _t, m) => { + levels.push((m as unknown as { level: number | string }).level); + }); + expect(levels).toEqual([0, "new"]); + }); + + it("renders date and author, or a not-committed label", () => { + const view = viewOf("a\nb\nc", new FakeEngine()); + const doc = view.state.doc; + const set = buildBlameMarkers(doc, [line(A, "2026-10-29T10:00:00", "Ann"), line(A), line(ZERO)], NOW); + const texts: string[] = []; + set.between(0, doc.length, (_f, _t, marker) => { + texts.push((marker.toDOM?.(view) as HTMLElement).textContent); + }); + expect(texts).toEqual(["2026-10-29 Ann", "", "Not committed yet"]); + }); +}); + +describe("the gutter", () => { + it("queries only while the file's annotations are shown", async () => { + const engine = new FakeEngine(); + engine.answer = { lines: [line(A), line(B)], version: 1 }; + const view = viewOf("x\ny", engine); + await flush(); + expect(engine.blames()).toEqual([]); + expect(isBlameShown("src/a.php")).toBe(false); + + expect(toggleBlame("src/a.php")).toBe(true); + await flush(); + expect(engine.blames()).toEqual([{ path: "src/a.php" }]); + expect(hashes(view)).toEqual({ 1: A, 2: B }); + expect(view.dom.querySelectorAll("[data-test=blame-marker]")).toHaveLength(2); + + setBlameShown("src/other.php", true); + await flush(); + expect(engine.blames()).toHaveLength(1); + + expect(toggleBlame("src/a.php")).toBe(false); + await flush(); + expect(hashes(view)).toEqual({}); + expect(engine.blames()).toHaveLength(1); + }); + + it("debounces edits, maps annotations through them and drops stale answers", async () => { + const engine = new FakeEngine(); + engine.answer = { lines: [line(A), line(B)], version: 1 }; + setBlameShown("src/a.php", true); + const view = viewOf("x\ny", engine); + await flush(); + expect(hashes(view)).toEqual({ 1: A, 2: B }); + + view.dispatch({ changes: { from: 0, insert: "new\n" } }); + expect(hashes(view)).toEqual({ 2: A, 3: B }); + await flush(BLAME_DEBOUNCE_MS - 1); + expect(engine.blames()).toHaveLength(1); + engine.answer = { lines: [line(ZERO), line(A), line(B)], version: 2 }; + await flush(1); + expect(engine.blames()).toHaveLength(2); + expect(hashes(view)).toEqual({ 1: ZERO, 2: A, 3: B }); + + // An answer for a document that changed meanwhile is dropped. + let release: () => void = () => undefined; + const original = engine.query.bind(engine); + engine.query = (command, params) => + new Promise((resolve) => { + release = () => { + void original(command, params).then(resolve); + }; + }); + refreshBlame(); + await flush(); + view.dispatch({ changes: { from: 0, insert: "z" } }); + engine.answer = { lines: [line(B), line(B), line(B)], version: 3 }; + release(); + await flush(); + expect(hashes(view)).toEqual({ 1: ZERO, 2: A, 3: B }); + }); + + it("keeps annotations when a query fails and refreshes on gitChanged", async () => { + const engine = new FakeEngine(); + engine.answer = { lines: [line(A)], version: 1 }; + setBlameShown("src/a.php", true); + const view = viewOf("x", engine); + await flush(); + engine.fail = true; + refreshBlame(); + await flush(); + expect(engine.blames()).toHaveLength(2); + expect(hashes(view)).toEqual({ 1: A }); + + clearBlame(); + await flush(); + expect(hashes(view)).toEqual({}); + expect(isBlameShown("src/a.php")).toBe(false); + refreshBlame(); + await flush(); + expect(engine.blames()).toHaveLength(2); + }); + + it("opens the commit on click, but not for uncommitted lines", async () => { + const engine = new FakeEngine(); + engine.answer = { lines: [line(A), line(ZERO)], version: 1 }; + setBlameShown("src/a.php", true); + const view = viewOf("x\ny", engine); + await flush(); + const markers = view.dom.querySelectorAll("[data-test=blame-marker]"); + markers[1]?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + markers[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(engine.opened).toEqual([A]); + }); + + it("shows a hover card with the full message after a delay", async () => { + const engine = new FakeEngine(); + engine.answer = { lines: [line(A, "2026-10-29T10:00:00+01:00", "Ann", "Subject")], version: 1 }; + setBlameShown("src/a.php", true); + const view = viewOf("x", engine); + await flush(); + const marker = view.dom.querySelector("[data-test=blame-marker]"); + marker?.dispatchEvent(new MouseEvent("mousemove", { bubbles: true })); + await flush(BLAME_HOVER_MS - 1); + expect(document.querySelector("[data-test=blame-tooltip]")).toBeNull(); + await flush(1); + const card = document.querySelector("[data-test=blame-tooltip]"); + expect(card?.textContent).toContain(`${A.slice(0, 8)} · Ann`); + expect(card?.textContent).toContain("The full body."); + expect(engine.calls.filter((c) => c.command === "git.showCommit")).toEqual([{ command: "git.showCommit", params: { hash: A } }]); + + view.contentDOM.dispatchEvent(new MouseEvent("mouseover", { bubbles: true })); + await flush(); + expect(document.querySelector("[data-test=blame-tooltip]")).toBeNull(); + }); +}); + +describe("commands", () => { + it("registers Show Commit and Annotate without default shortcuts", () => { + const specs = UI_COMMANDS.filter((c) => c.id === SHOW_COMMIT_COMMAND || c.id === TOGGLE_BLAME_COMMAND); + expect(specs.map((c) => [c.id, c.menuPath, c.defaultShortcut])).toEqual([ + ["vcs.showCommit", undefined, undefined], + ["vcs.toggleBlame", "Git/Annotate with Git Blame", undefined], + ]); + }); +}); + +describe("colours", () => { + it("come from tokens only", () => { + const source = readFileSync(join(__dirname, "../../src/components/editor/blame.ts"), "utf8"); + expect(source).not.toMatch(/#[0-9a-f]{3,8}\b|rgba?\(/i); + }); +}); diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index 62906fe..2943641 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -276,6 +276,7 @@ describe("AppMenu", () => { "goto.classOpen", "goto.symbolOpen", "vcs.abortMerge", + "vcs.toggleBlame", "vcs.branches", "vcs.openChanges", "vcs.clone", diff --git a/ui/tests/palette/CommandPalette.test.ts b/ui/tests/palette/CommandPalette.test.ts index 66f3cd0..e771e54 100644 --- a/ui/tests/palette/CommandPalette.test.ts +++ b/ui/tests/palette/CommandPalette.test.ts @@ -259,6 +259,7 @@ describe("CommandPalette", () => { expect(document.activeElement).toBe(wrapper.find("[data-test=palette-input]").element); expect(rows(wrapper)).toEqual([ "vcs.abortMerge", + "vcs.toggleBlame", "vcs.branches", "vcs.openChanges", "vcs.checkout", @@ -290,6 +291,7 @@ describe("CommandPalette", () => { "vcs.resolveConflicts", "editor.reveal", "settings.open", + "vcs.showCommit", "vcs.showDiff", "vcs.showHistory", "view.toggleProjectTree", diff --git a/ui/tests/vcs/Log.test.ts b/ui/tests/vcs/Log.test.ts index 667c6ad..0a68b8d 100644 --- a/ui/tests/vcs/Log.test.ts +++ b/ui/tests/vcs/Log.test.ts @@ -4,7 +4,8 @@ * `gitChanged` when HEAD moves, commit details, the Log window (rows, * badges, keyboard, filters, history chip), a file's diff at a commit in * the diff viewer (both sides read-only), `vcs.showHistory` and the tree's - * context menu. The engine is a fake behind the mocked Tauri `invoke` and + * context menu, and `vcs.showCommit` / `vcs.toggleBlame` from the main + * layout (M4.7). The engine is a fake behind the mocked Tauri `invoke` and * `listen`. */ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; @@ -18,7 +19,9 @@ vi.mock("@tauri-apps/api/event", () => ({ listen })); import { useCommandsStore } from "../../src/commands/store"; import { UI_COMMANDS } from "../../src/commands/uiCommands"; +import { isBlameShown, SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND } from "../../src/components/editor/blame"; import EditorArea from "../../src/components/editor/EditorArea.vue"; +import MainLayout from "../../src/components/layout/MainLayout.vue"; import TreeContextMenu from "../../src/components/project/TreeContextMenu.vue"; import { commitDiffKey, useDiffStore } from "../../src/components/vcs/diff/diff"; import { currentMerge } from "../../src/components/vcs/diff/navigation"; @@ -481,3 +484,32 @@ describe("commands", () => { expect(run).toHaveBeenCalledWith({ path: "src/a.php" }); }); }); + +describe("blame commands in the main layout (M4.7)", () => { + it("shows a commit in the Log and toggles a file's annotations", async () => { + useProjectStore(pinia).root = { path: "/p", name: "p" }; + const wrapper = mount(MainLayout, { + attachTo: document.body, + global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } }, + }); + mounted.push(wrapper); + const commands = useCommandsStore(pinia); + await commands.start(); + await flushPromises(); + + await commands.execute(SHOW_COMMIT_COMMAND, { hash: "a" }); + await flushPromises(); + expect(callsOf("git.showCommit")).toEqual([]); + await commands.execute(SHOW_COMMIT_COMMAND, { hash: "abcd" }); + await flushPromises(); + const log = useLogStore(pinia); + expect(log.visible).toBe(true); + expect(log.selected).toBe("abcd"); + expect(callsOf("git.showCommit").at(-1)).toEqual({ hash: "abcd" }); + + await commands.execute(TOGGLE_BLAME_COMMAND, { path: "src/a.php" }); + expect(isBlameShown("src/a.php")).toBe(true); + await commands.execute(TOGGLE_BLAME_COMMAND, { path: "src/a.php" }); + expect(isBlameShown("src/a.php")).toBe(false); + }); +});