From a8531825a388765c6197510982053d4fce4ed6d9 Mon Sep 17 00:00:00 2001 From: danny Date: Wed, 28 Oct 2026 18:00:24 +0100 Subject: [PATCH] M4.6: Git log and file history - crates/vcs log.rs: Repo::log (topological, all refs, paging, literal message/author filters, a path's history with --follow), show_commit (message and files against the first parent, renames) and show_at (a file at any commit); parsers property-tested. - Engine git.log, git.showCommit, git.showAt in cmd/git_log.rs through the step-1 hook. - Log tab in the bottom panel: graph lanes carried across pages, ref badges, filters, lazy paging, keyboard; commit details whose files open a read-only diff at that commit in M4.3's viewer. - vcs.showLog and vcs.showHistory (menu, tree context menu, active editor tab), no default shortcuts. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/git_log.rs | 223 ++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/engine.rs | 3 + crates/engine/tests/git_log.rs | 177 +++++ crates/vcs/src/lib.rs | 2 + crates/vcs/src/log.rs | 502 ++++++++++++ crates/vcs/tests/log.rs | 284 +++++++ docs/architecture.md | 24 + docs/gaps.md | 3 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 3 +- docs/tooling-parity.md | 4 +- ui/src/commands/uiCommands.ts | 2 + ui/src/components/editor/EditorTabs.vue | 18 +- ui/src/components/layout/MainLayout.vue | 40 +- ui/src/components/project/TreeContextMenu.vue | 12 +- ui/src/components/vcs/diff/DiffView.vue | 8 +- ui/src/components/vcs/diff/diff.ts | 107 ++- ui/src/components/vcs/log/LogToolWindow.vue | 730 ++++++++++++++++++ ui/src/components/vcs/log/graph.ts | 145 ++++ ui/src/components/vcs/log/log.ts | 556 +++++++++++++ ui/src/i18n/en.json | 25 + ui/tests/i18n/catalog.test.ts | 1 + ui/tests/menu/AppMenu.test.ts | 2 + ui/tests/palette/CommandPalette.test.ts | 2 + ui/tests/vcs/DiffView.test.ts | 2 +- ui/tests/vcs/Log.test.ts | 483 ++++++++++++ 27 files changed, 3349 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/cmd/git_log.rs create mode 100644 crates/engine/tests/git_log.rs create mode 100644 crates/vcs/src/log.rs create mode 100644 crates/vcs/tests/log.rs create mode 100644 ui/src/components/vcs/log/LogToolWindow.vue create mode 100644 ui/src/components/vcs/log/graph.ts create mode 100644 ui/src/components/vcs/log/log.ts create mode 100644 ui/tests/vcs/Log.test.ts diff --git a/crates/engine/src/cmd/git_log.rs b/crates/engine/src/cmd/git_log.rs new file mode 100644 index 0000000..64022d2 --- /dev/null +++ b/crates/engine/src/cmd/git_log.rs @@ -0,0 +1,223 @@ +//! History commands (M4.6): `git.log`, `git.showCommit` and `git.showAt`, +//! read-only and run like every `git.*` command (a pending outcome off the +//! lock, git and the repository cached by [`super::git`]). + +use lutra_vcs::{CommitDetails, LOG_LIMIT, LogCommit, LogQuery}; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::git::{rel_path, start_with}; +use super::params::parse; +use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State}; + +/// Registers the history commands. +/// +/// # Errors +/// [`EngineError::Internal`] if an id is taken. +pub fn register(registry: &mut Registry) -> Result<(), EngineError> { + registry.register(Box::new(Log))?; + registry.register(Box::new(ShowCommit))?; + registry.register(Box::new(ShowAt))?; + Ok(()) +} + +/// One commit of `git.log`. +fn commit_json(commit: &LogCommit) -> Value { + json!({ + "hash": commit.hash, + "parents": commit.parents, + "author": commit.author, + "email": commit.email, + "date": commit.date, + "subject": commit.subject, + "refs": commit.refs, + }) +} + +/// `git.showCommit`'s value. +fn details_json(details: &CommitDetails) -> Value { + let files: Vec = details + .files + .iter() + .map(|f| { + let mut value = json!({"path": f.path, "status": f.status}); + if let (Some(orig), Some(map)) = (&f.orig_path, value.as_object_mut()) { + map.insert("origPath".into(), json!(orig)); + } + value + }) + .collect(); + json!({ + "hash": details.hash, + "parents": details.parents, + "author": details.author, + "email": details.email, + "date": details.date, + "message": details.message, + "files": files, + "truncated": details.truncated, + }) +} + +/// Params of `git.log`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct LogParams { + /// Commits to skip. + #[serde(default)] + skip: usize, + /// Commits to return, 1 to 500. + #[serde(default = "default_limit")] + limit: usize, + /// A file or folder whose history to list. + #[serde(default)] + path: Option, + /// Text the message must contain. + #[serde(default)] + query: Option, + /// Text the author name or email must contain. + #[serde(default)] + author: Option, +} + +/// The default page size of `git.log`. +fn default_limit() -> usize { + 100 +} + +/// `git.log`. +struct Log; + +impl Command for Log { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.log", + label: "Git: Log", + menu_path: None, + default_shortcut: None, + params: "{ skip?: number (0), limit?: 1..500 (100), path?: project-relative file or folder (HEAD's history, following renames for a file), query?: text in the message, author?: text in author name or email (both case-insensitive, literal) }; returns { commits: [{ hash, parents, author, email, date (ISO 8601), subject, refs }] } newest first in topological order over all branches, remote branches, tags and HEAD", + } + } + + 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: LogParams = parse(command, params)?; + if p.limit == 0 || p.limit > LOG_LIMIT { + return Err(EngineError::invalid_params( + command, + format!("limit must be 1 to {LOG_LIMIT}"), + )); + } + let path = match p.path.as_deref().map(str::trim) { + Some(path) if !path.is_empty() => Some(rel_path(state, command, path)?), + _ => None, + }; + let query = LogQuery { + skip: p.skip, + limit: p.limit, + path, + query: p.query, + author: p.author, + }; + start_with( + state, + command, + false, + Box::new(move |repo| { + let commits: Vec = repo.log(&query)?.iter().map(commit_json).collect(); + Ok(json!({"commits": commits})) + }), + ) + } +} + +/// Params of `git.showCommit`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ShowCommitParams { + /// The commit. + hash: String, +} + +/// `git.showCommit`. +struct ShowCommit; + +impl Command for ShowCommit { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.showCommit", + label: "Git: Show Commit", + menu_path: None, + default_shortcut: None, + params: "{ hash: 4 to 64 hex digits }; returns { hash, parents, author, email, date, message, files: [{ path, status: added|modified|deleted|renamed|copied, origPath? }], truncated } with the files changed against the first parent (renames detected), inside the project, at most 10,000", + } + } + + 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: ShowCommitParams = parse(command, params)?; + start_with( + state, + command, + false, + Box::new(move |repo| Ok(details_json(&repo.show_commit(&p.hash)?))), + ) + } +} + +/// Params of `git.showAt`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ShowAtParams { + /// The file. + path: String, + /// The commit or revision. + rev: String, +} + +/// `git.showAt`. +struct ShowAt; + +impl Command for ShowAt { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.showAt", + label: "Git: Show File at Commit", + menu_path: None, + default_shortcut: None, + params: "{ path: project-relative path, rev: commit hash or revision such as abc123^ }; returns { text: string | null, binary, tooLarge } like git.show (null when the path or revision does not exist there)", + } + } + + 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: ShowAtParams = parse(command, params)?; + let path = rel_path(state, command, &p.path)?; + let rev = p.rev; + start_with( + state, + command, + false, + Box::new(move |repo| { + let contents = repo.show_at(&path, &rev)?; + Ok(json!({ + "text": contents.text, + "binary": contents.binary, + "tooLarge": contents.too_large, + })) + }), + ) + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 110735e..97fa077 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -5,6 +5,7 @@ mod buffer; mod file; pub mod git; pub mod git_lines; +pub mod git_log; pub mod goto; mod lsp_assist; mod lsp_diagnostics; @@ -68,5 +69,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> { lsp_nav::register(registry)?; git::register(registry)?; git_lines::register(registry)?; + git_log::register(registry)?; Ok(()) } diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 3e08225..960e5a1 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -486,7 +486,10 @@ mod tests { "git.createBranch", "git.lastMessage", "git.lineChanges", + "git.log", "git.show", + "git.showAt", + "git.showCommit", "git.stage", "git.status", "git.unstage", diff --git a/crates/engine/tests/git_log.rs b/crates/engine/tests/git_log.rs new file mode 100644 index 0000000..fae0bad --- /dev/null +++ b/crates/engine/tests/git_log.rs @@ -0,0 +1,177 @@ +//! The history commands (M4.6) through the engine: `git.log` with paging +//! and filters, `git.showCommit`, `git.showAt`, bad params, and no +//! `gitChanged` from these reads. 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 with `message`. +fn commit(dir: &Path, path: &str, text: &str, message: &str) -> String { + std::fs::write(dir.join(path), text).unwrap(); + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-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) + } +} + +#[test] +fn log_show_commit_and_show_at() { + 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", " main"])); + assert_eq!(commits[1]["subject"], "Second"); + + let page = host.run("git.log", json!({"skip": 2, "limit": 5})).unwrap(); + assert_eq!(page["commits"][0]["hash"], first); + let file = host.run("git.log", json!({"path": "a.php"})).unwrap(); + assert_eq!(file["commits"].as_array().unwrap().len(), 2); + let absolute = host + .run("git.log", json!({"path": d.join("b.php")})) + .unwrap(); + assert_eq!(absolute["commits"][0]["hash"], second); + let text = host.run("git.log", json!({"query": "thi"})).unwrap(); + assert_eq!(text["commits"][0]["hash"], third); + let author = host.run("git.log", json!({"author": "nobody"})).unwrap(); + assert_eq!(author["commits"], json!([])); + + let details = host.run("git.showCommit", json!({"hash": second})).unwrap(); + assert_eq!(details["message"], "Second\n\nBody"); + assert_eq!(details["parents"], json!([first])); + assert_eq!( + details["files"], + json!([{"path": "b.php", "status": "added"}]) + ); + assert_eq!(details["truncated"], false); + + let at = host + .run("git.showAt", json!({"path": "a.php", "rev": first})) + .unwrap(); + assert_eq!( + at, + json!({"text": ", + /// Only commits whose message contains this text (case-insensitive). + pub query: Option, + /// Only commits whose author name or email contains this text + /// (case-insensitive). + pub author: Option, +} + +/// One commit of the log. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct LogCommit { + /// Full hash. + pub hash: String, + /// Parent hashes, first parent first; empty for a root commit. + pub parents: Vec, + /// Author name. + pub author: String, + /// Author email. + pub email: String, + /// Author date, strict ISO 8601 with offset. + pub date: String, + /// The subject line. + pub subject: String, + /// Ref names pointing here as git decorates them: `HEAD -> main`, + /// `origin/main`, `tag: v1.0`. + pub refs: Vec, +} + +/// How a file changed in a commit (against its first parent). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CommitFile { + /// Project-relative path after the change. + pub path: String, + /// `added`, `modified`, `deleted`, `renamed` or `copied`. + pub status: &'static str, + /// The path before a rename or copy (project-relative; `None` when it + /// lay outside the project). + pub orig_path: Option, +} + +/// One commit with its message and changed files. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CommitDetails { + /// Full hash. + pub hash: String, + /// Parent hashes, first parent first. + pub parents: Vec, + /// Author name. + pub author: String, + /// Author email. + pub email: String, + /// Author date, strict ISO 8601. + pub date: String, + /// The full message, trailing line breaks removed. + pub message: String, + /// Files changed against the first parent (against nothing for a root + /// commit), inside the project, at most [`COMMIT_FILES_CAP`]. + pub files: Vec, + /// More files changed than [`CommitDetails::files`] holds. + pub truncated: bool, +} + +impl Repo { + /// One page of history, newest first in topological order (children + /// before parents, so graph lanes can be drawn), over all local + /// branches, remote-tracking branches, tags and HEAD. With a path: + /// only HEAD's history of that path. Inside a repository whose root + /// lies above the project, only commits touching the project. + /// + /// # Errors + /// [`VcsError::InvalidPath`], or git's refusal. A repository without + /// commits has an empty log. + pub fn log(&self, query: &LogQuery) -> Result, VcsError> { + let limit = if query.limit == 0 { + LOG_LIMIT + } else { + query.limit.min(LOG_LIMIT) + }; + let pathspec = match query.path.as_deref() { + Some(path) => Some(self.to_repo_path(path)?), + None => Some(self.prefix().trim_end_matches('/').to_string()).filter(|p| !p.is_empty()), + }; + let follow = query.path.is_some() + && pathspec + .as_deref() + .is_some_and(|p| self.root().join(p).is_file()); + let skip = format!("--skip={}", query.skip); + let count = format!("--max-count={limit}"); + let grep = filter_text(query.query.as_deref()).map(|q| format!("--grep={q}")); + let author = filter_text(query.author.as_deref()).map(|a| format!("--author={a}")); + let mut args: Vec<&str> = vec![ + "log", + LOG_FORMAT, + "--topo-order", + "--decorate=short", + "--fixed-strings", + "--regexp-ignore-case", + &skip, + &count, + ]; + if follow { + args.push("--follow"); + } + args.extend(grep.as_deref()); + args.extend(author.as_deref()); + if query.path.is_none() { + args.extend(["--branches", "--remotes", "--tags"]); + } + args.extend(["--end-of-options", "HEAD"]); + if let Some(spec) = pathspec.as_deref() { + args.extend(["--", spec]); + } + let output = self.run(Call::read(self.root(), &args, SMALL_CAP))?; + if !output.success() { + let message = output.message(); + if message.contains("does not have any commits") || message.contains("unknown revision") + { + return Ok(Vec::new()); + } + return Err(VcsError::Git(message)); + } + Ok(parse_log(&output.stdout)) + } + + /// One commit's details: the full message and the files changed + /// against its first parent, renames detected. + /// + /// # Parameters + /// - `hash`: a commit hash (4 to 64 hex digits, abbreviations allowed + /// when unambiguous). + /// + /// # Errors + /// [`VcsError::InvalidName`] for something that is not a hash, + /// [`VcsError::Git`] when no such commit exists. + pub fn show_commit(&self, hash: &str) -> Result { + check_hash(hash)?; + let commit = format!("{hash}^{{commit}}"); + let output = self + .run(Call::read( + self.root(), + &["show", "-s", SHOW_FORMAT, "--end-of-options", &commit], + SMALL_CAP, + ))? + .checked()?; + let mut details = + parse_details(&output.stdout).ok_or_else(|| VcsError::BadOutput(hash.to_string()))?; + let mut args = vec![ + "diff-tree", + "--no-commit-id", + "-r", + "-z", + "-M", + "--name-status", + ]; + let parent = details.parents.first().cloned(); + if parent.is_none() { + args.push("--root"); + } + args.push("--end-of-options"); + if let Some(parent) = parent.as_deref() { + args.push(parent); + } + args.push(&details.hash); + let output = self + .run(Call::read(self.root(), &args, SMALL_CAP))? + .checked()?; + let mut files = Vec::new(); + for (status, path, orig) in parse_name_status(&output.stdout) { + let Some(path) = self.from_repo_path(&path) else { + continue; + }; + if files.len() == COMMIT_FILES_CAP { + details.truncated = true; + break; + } + files.push(CommitFile { + path, + status, + orig_path: orig.and_then(|o| self.from_repo_path(&o)), + }); + } + details.files = files; + Ok(details) + } + + /// A file's contents at a commit, as stored (no filters or line-ending + /// conversion), with the same rules as [`Repo::show`]. + /// + /// # Parameters + /// - `path`: project-relative path. + /// - `rev`: a commit hash or another revision (`main`, `abc123^`); + /// not starting with `-`, without `:` or control characters. + /// + /// # Errors + /// [`VcsError::InvalidPath`], [`VcsError::InvalidName`], or the + /// runner's errors. A path or revision that does not exist is empty + /// [`Contents`]. + pub fn show_at(&self, path: &str, rev: &str) -> Result { + let path = self.to_repo_path(path)?; + check_name(rev)?; + if rev.contains(':') || rev.trim() != rev { + return Err(VcsError::InvalidName(rev.to_string())); + } + let object = format!("{rev}:{path}\n"); + let output = self + .run( + Call::read(self.root(), &["cat-file", "--batch-check"], SMALL_CAP) + .stdin(object.into_bytes()), + )? + .checked()?; + let line = String::from_utf8_lossy(&output.stdout); + let fields: Vec<&str> = line.trim_end().rsplitn(3, ' ').collect(); + let [size, kind, oid] = fields.as_slice() else { + return Ok(Contents::default()); + }; + if *size == "missing" || *kind == "missing" || *kind == "ambiguous" || *kind == "tree" { + return Ok(Contents::default()); + } + if *kind != "blob" { + return Ok(Contents { + binary: true, + ..Contents::default() + }); + } + let size: usize = size + .parse() + .map_err(|_| VcsError::BadOutput(line.to_string()))?; + if size > FILE_CAP { + return Ok(Contents { + too_large: true, + ..Contents::default() + }); + } + let output = self + .run(Call::read( + self.root(), + &["cat-file", "blob", oid], + FILE_CAP, + ))? + .checked()?; + Ok(decode(output.stdout)) + } +} + +/// A filter text worth passing: trimmed, not empty, without control +/// characters (which git's pattern options cannot take anyway). +fn filter_text(text: Option<&str>) -> Option { + let text = text?.trim(); + if text.is_empty() { + return None; + } + Some(text.chars().filter(|c| !c.is_control()).collect()) +} + +/// Rejects anything but 4 to 64 hex digits. +fn check_hash(hash: &str) -> Result<(), VcsError> { + if (4..=64).contains(&hash.len()) && hash.bytes().all(|b| b.is_ascii_hexdigit()) { + Ok(()) + } else { + Err(VcsError::InvalidName(hash.to_string())) + } +} + +/// Splits git's space-separated parent list. +fn parents(field: &str) -> Vec { + field.split_whitespace().map(str::to_string).collect() +} + +/// Parses the [`LOG_FORMAT`] output. Records with too few fields or an +/// empty hash are skipped. +pub fn parse_log(bytes: &[u8]) -> Vec { + let mut commits = Vec::new(); + for record in bytes.split(|b| *b == RECORD) { + let text = String::from_utf8_lossy(record); + let text = text.trim_end_matches(['\n', '\r']); + let mut fields = text.split('\0'); + let ( + Some(hash), + Some(parent_list), + Some(author), + Some(email), + Some(date), + Some(subject), + Some(refs), + ) = ( + fields.next(), + fields.next(), + fields.next(), + fields.next(), + fields.next(), + fields.next(), + fields.next(), + ) + else { + continue; + }; + let hash = hash.trim(); + if hash.is_empty() { + continue; + } + commits.push(LogCommit { + hash: hash.to_string(), + parents: parents(parent_list), + author: author.to_string(), + email: email.to_string(), + date: date.to_string(), + subject: subject.to_string(), + refs: refs + .split(", ") + .map(str::trim) + .filter(|r| !r.is_empty()) + .map(str::to_string) + .collect(), + }); + } + commits +} + +/// Parses the [`SHOW_FORMAT`] output; `None` without a hash. +pub fn parse_details(bytes: &[u8]) -> Option { + let text = String::from_utf8_lossy(bytes); + let mut fields = text.splitn(6, '\0'); + let hash = fields.next()?.trim().to_string(); + if hash.is_empty() { + return None; + } + let parent_list = fields.next()?; + let author = fields.next()?.to_string(); + let email = fields.next()?.to_string(); + let date = fields.next()?.to_string(); + let message = fields + .next() + .unwrap_or_default() + .trim_end_matches(['\n', '\r']) + .to_string(); + Some(CommitDetails { + hash, + parents: parents(parent_list), + author, + email, + date, + message, + files: Vec::new(), + truncated: false, + }) +} + +/// Parses `diff-tree --name-status -z` into `(status, path, orig_path)` +/// with root-relative paths. Unknown letters count as `modified`; a +/// rename or copy without its second path (or an empty path) ends the +/// list. +pub fn parse_name_status(bytes: &[u8]) -> Vec<(&'static str, String, Option)> { + let mut entries = Vec::new(); + let mut fields = bytes + .split(|b| *b == 0) + .map(|f| String::from_utf8_lossy(f).into_owned()); + while let Some(code) = fields.next() { + let Some(letter) = code.bytes().next() else { + continue; + }; + let status = match letter { + b'A' => "added", + b'D' => "deleted", + b'R' => "renamed", + b'C' => "copied", + _ => "modified", + }; + let Some(first) = fields.next().filter(|f| !f.is_empty()) else { + break; + }; + if matches!(letter, b'R' | b'C') { + let Some(second) = fields.next().filter(|f| !f.is_empty()) else { + break; + }; + entries.push((status, second, Some(first))); + } else { + entries.push((status, first, None)); + } + } + entries +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::indexing_slicing)] + + use super::*; + use proptest::prelude::*; + + #[test] + fn log_records_parse() { + let bytes = b"\x1eaaa\0p1 p2\0Ann\0a@x\x002026-01-01T00:00:00+01:00\0Merge it\0HEAD -> main, tag: v1\n\x1ebbb\0\0Bo\0b@x\x002026-01-01T00:00:00Z\0Root\0\n"; + let commits = parse_log(bytes); + assert_eq!(commits.len(), 2); + assert_eq!(commits[0].parents, ["p1", "p2"]); + assert_eq!(commits[0].refs, ["HEAD -> main", "tag: v1"]); + assert_eq!(commits[1].parents, Vec::::new()); + assert!(commits[1].refs.is_empty()); + assert_eq!(commits[1].subject, "Root"); + } + + #[test] + fn short_records_are_skipped() { + assert!(parse_log(b"\x1eaaa\0p\0only three").is_empty()); + assert!(parse_log(b"").is_empty()); + } + + #[test] + fn details_keep_the_message_body() { + let d = parse_details(b"h\0p\0A\0e\0d\0Subject\n\nBody\0with nul\n\n").unwrap(); + assert_eq!(d.message, "Subject\n\nBody\0with nul"); + assert_eq!(d.parents, ["p"]); + assert!(parse_details(b"").is_none()); + } + + #[test] + fn name_status_reads_renames() { + let e = parse_name_status(b"M\0a.php\0R087\0old.php\0new.php\0A\0b\0D\0c\0T\0d\0"); + assert_eq!(e[0], ("modified", "a.php".into(), None)); + assert_eq!(e[1], ("renamed", "new.php".into(), Some("old.php".into()))); + assert_eq!(e[2].0, "added"); + assert_eq!(e[3].0, "deleted"); + assert_eq!(e[4].0, "modified"); + assert_eq!(parse_name_status(b"R100\0only\0").len(), 0); + } + + #[test] + fn hashes_are_checked() { + assert!(check_hash("abcd").is_ok()); + assert!(check_hash("abc").is_err()); + assert!(check_hash("HEAD").is_err()); + assert!(check_hash("-abcd").is_err()); + assert!(check_hash(&"a".repeat(65)).is_err()); + } + + #[test] + fn filter_text_drops_blanks_and_controls() { + assert_eq!(filter_text(Some(" ")), None); + assert_eq!(filter_text(Some(" a\nb ")), Some("ab".into())); + assert_eq!(filter_text(None), None); + } + + proptest! { + #[test] + fn parsers_never_panic(bytes in proptest::collection::vec(any::(), 0..512)) { + let _ = parse_log(&bytes); + let _ = parse_details(&bytes); + let _ = parse_name_status(&bytes); + } + + #[test] + fn log_fields_round_trip( + subject in "[^\0\x1e\n\r]{0,40}", + author in "[^\0\x1e\n\r]{0,20}", + ) { + let bytes = format!("\x1eh\0\0{author}\0e\0d\0{subject}\0\n"); + let commits = parse_log(bytes.as_bytes()); + prop_assert_eq!(commits.len(), 1); + prop_assert_eq!(&commits[0].subject, &subject); + prop_assert_eq!(&commits[0].author, &author); + } + } +} diff --git a/crates/vcs/tests/log.rs b/crates/vcs/tests/log.rs new file mode 100644 index 0000000..37ecc23 --- /dev/null +++ b/crates/vcs/tests/log.rs @@ -0,0 +1,284 @@ +//! History (M4.6) against real repositories in temp folders: paging, +//! filters, merges and refs, a file's history across a rename, commit +//! details and file contents at a commit. 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, LogQuery, Repo, VcsError}; + +/// 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 default author. +const ME: &str = "Lutra Test "; + +#[test] +fn an_empty_repository_has_no_history() { + let Some(cli) = installed() else { return }; + let dir = tempfile::tempdir().unwrap(); + init(dir.path()); + let repo = open(&cli, dir.path()); + assert!(repo.log(&LogQuery::default()).unwrap().is_empty()); +} + +#[test] +fn pages_filters_merges_and_refs() { + let Some(cli) = installed() else { return }; + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + init(d); + write(d, "a.php", ""); + git(d, &["switch", "-q", "main"]); + write(d, "a.php", " = all.iter().map(|c| c.hash.as_str()).collect(); + assert_eq!(hashes.len(), 4); + assert_eq!(hashes[0], merge); + assert_eq!(*hashes.last().unwrap(), root); + assert!(hashes.contains(&side.as_str()) && hashes.contains(&main_work.as_str())); + assert_eq!(all[0].parents, [main_work.clone(), side.clone()]); + assert!(all[0].refs.iter().any(|r| r == "HEAD -> main")); + assert!(all.last().unwrap().refs.iter().any(|r| r == "tag: v1")); + assert!(all[0].date.contains('T')); + assert_eq!(all[0].email, "test@lutra.invalid"); + + let page = repo + .log(&LogQuery { + skip: 1, + limit: 2, + ..LogQuery::default() + }) + .unwrap(); + assert_eq!(page.len(), 2); + assert_eq!(page[0].hash, all[1].hash); + + let by_text = repo + .log(&LogQuery { + query: Some("feature b".into()), + ..LogQuery::default() + }) + .unwrap(); + assert_eq!(by_text.len(), 1); + assert_eq!(by_text[0].hash, side); + + let regex_chars = repo + .log(&LogQuery { + query: Some("feature.*[".into()), + ..LogQuery::default() + }) + .unwrap(); + assert!(regex_chars.is_empty()); + + let by_author = repo + .log(&LogQuery { + author: Some("ADA".into()), + ..LogQuery::default() + }) + .unwrap(); + assert_eq!(by_author.len(), 1); + assert_eq!(by_author[0].author, "Ada Other"); +} + +#[test] +fn a_files_history_follows_renames() { + let Some(cli) = installed() else { return }; + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + init(d); + let body = " = history.iter().map(|c| c.hash.as_str()).collect(); + assert_eq!(hashes, [renamed.as_str(), first.as_str()]); + + let folder = repo + .log(&LogQuery { + path: Some("src".into()), + ..LogQuery::default() + }) + .unwrap(); + assert_eq!(folder.len(), 2); + + let details = repo.show_commit(renamed.get(..10).unwrap()).unwrap(); + assert_eq!(details.hash, renamed); + assert_eq!(details.message, "Rename"); + assert_eq!(details.files.len(), 1); + assert_eq!(details.files[0].status, "renamed"); + assert_eq!(details.files[0].path, "src/New.php"); + assert_eq!(details.files[0].orig_path.as_deref(), Some("src/Old.php")); + + let root = repo.show_commit(&first).unwrap(); + assert!(root.parents.is_empty()); + assert_eq!(root.files.len(), 2); + assert!(root.files.iter().all(|f| f.status == "added")); + + let old = repo.show_at("src/Old.php", &first).unwrap(); + assert_eq!(old.text.as_deref(), Some(body)); + let gone = repo.show_at("src/Old.php", &renamed).unwrap(); + assert!(gone.text.is_none() && !gone.binary); + let parent = repo.show_at("src/Old.php", &format!("{renamed}^")).unwrap(); + assert_eq!(parent.text.as_deref(), Some(body)); +} + +#[test] +fn bad_input_is_refused() { + let Some(cli) = installed() else { return }; + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + init(d); + write(d, "a.php", "/HEAD` left out), the subject, the author and the local date. Up/Down/Page/Home/End move the selection. + - **Graph:** one column per waiting lane. A commit takes the leftmost lane waiting for it, and the other lanes waiting for it join it. Its first parent continues in its column, and further parents join an existing lane or take the first free one. Lanes left after a page carry into the next, so rows already drawn never change. At most 24 columns, coloured from theme tokens only. With a text or author filter there is no graph (the parents are not listed), only dots. + - **Filters:** message and author fields apply 300 ms after typing or on Enter. A "History of " chip clears the path filter. `gitChanged` reloads only when HEAD or the branch moved (a commit or a checkout), not on staging. A project open or close clears the tab. + - **Details:** the selected commit's short hash, author, email, date, full message and changed files (state colours, "from " for renames). Enter or a double-click on a file opens its diff at that commit. +- **Diff at a commit (in M4.3's viewer):** `useDiffStore().openAtCommit(path, {hash, parent, origPath, deleted})` opens a "Diff: ()" tab. The left side is `git.showAt` of the old path at the first parent (empty for a root commit or an added file), the right side `git.showAt` at the commit (empty for a deleted file). Both sides are read-only texts with normalised line breaks; nothing is re-read on `gitChanged`, and no buffer is opened. +- **Checked in the app** (debug build with the bundled UI, Windows 11, git 2.47.1, control port 7946, a demo repository with a feature branch merged with `--no-ff`, a rename, a tag and an unmerged branch; screenshots only, no input): `git.log` 75–79 ms over the control channel; `vcs.showLog` showed the lanes branching at the merge and joining at the fork point, the badges (HEAD, main, feature, hotfix, v1.0) and the first commit's details; `vcs.showHistory {path: "Renamed.php"}` showed its three commits back to the import as `Old.php`, without the other branch. The diff at a commit needs a double-click, so it is covered by Vitest only. +- **Tests:** `crates/vcs/tests/log.rs` (5 tests against real temp repositories: empty repository, paging, merge parents and refs, tags, literal text filter, author filter, history across a rename, a folder's history, commit details and a root commit, contents at a commit and its parent, bad input, a project inside a repository); unit and property tests in `log.rs`; `crates/engine/tests/git_log.rs` (the command shapes, paging, filters, an absolute path, bad params, no `gitChanged`); Vitest `ui/tests/vcs/Log.test.ts` (21 tests: lanes for linear and merged histories, across pages and capped, parsers, badges, paging, filters with stale answers, reloads on `gitChanged`, errors, details, the window's rows, keyboard, filters and chip, the diff at a commit with both sides read-only, commands and the tree menu). + ### 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. @@ -654,6 +677,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 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-27 | minor | F3: `lutra_proc::spawn_suspended` (Phpactor) and `adopt` (ConPTY shell in a job), cancel superseded completions, syntax proptests compare leaf kinds | | 2026-10-27 | minor | C6 F1: remote branch checkout without a configured remote (`--no-track`), `git.lastMessage` and the Amend prefill, one shared git status store | | 2026-10-27 | minor | F2: `ui.screenshot` through WebView2 `CapturePreview` without focus; region fallback elsewhere; `--control` windows open unfocused | diff --git a/docs/gaps.md b/docs/gaps.md index c19a314..c8f69fd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -13,7 +13,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h | | G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h | -| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), log, blame, conflicts, stash, remotes | M4 | ~122 h | +| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), ~~log~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), blame, conflicts, stash, remotes | M4 | ~122 h | | G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h | | G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h | | G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h | @@ -54,6 +54,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin | Date | Change | Summary | |---|---|---| +| 2026-10-28 | patch | G8: log and file history (M4.6) | | 2026-10-27 | minor | G11 note: suspended Phpactor start, terminal shell in a job, completion cancel, syntax proptest (F3) | | 2026-10-27 | patch | G8: amend prefill, remote checkout fix, shared status store (C6 F1) | | 2026-10-27 | minor | Screenshot item shrunk: webview capture without focus on Windows (F2) | diff --git a/docs/roadmap.md b/docs/roadmap.md index da88df9..50258ec 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Milestones -> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours, diff viewer, branches) · **Last updated:** 2026-10-26 +> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours, diff viewer, branches; C6: log) · **Last updated:** 2026-10-28 Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 were scaled ×0.1 to ×0.15 (measured factors: C1 0.07, C2 0.10, C3 0.14, C4 0.17; next cycle ×0.18); M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value). @@ -10,7 +10,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t | M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) | | M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | done 2026-10-22 (C4: M3.1 PHP detection and Phpactor download, M3.2 LSP client, M3.3 engine wiring and diagnostics, M3.4 completion, hover and signature help, M3.5 definition, references and rename, M3.6 integrated terminal, M3.7 CLI and single instance, M3.8 MCP server, M3.9 app menu, M3.10 autosave; live check with real key presses pending) | ~14 (measured) | -| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer, M4.5 branches done) | ~122 | +| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer, M4.5 branches done; C6: M4.6 log done) | ~122 | | M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 | | M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 | | M7 | Workbench and tools: Deployment (FTP/SFTP/local mappings, upload/download, compare with server, save before deploy, optional upload on save per server), Local History, diff tool (files/folders), scratch files, macros, keymap editor, user themes, plug-in system, Database tools and SQL, HTTP Client, SSH/Docker/Vagrant/WSL, File Watchers, external tools, TODO view, tasks and contexts | not started | ~900 | @@ -34,6 +34,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati | Date | Change | Summary | |---|---|---| +| 2026-10-28 | minor | M4.6 log and file history | | 2026-10-26 | minor | M4.5 branch widget and popup | | 2026-10-26 | minor | M4.3 diff viewer | | 2026-10-25 | minor | M4.4 gutter markers and status colours | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0b453b6..c87abfe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -22,7 +22,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Inspections and quick-fixes | 8 | 5% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, the editor's problem counter and scrollbar marks, next/previous problem, a current-file Problems view and severity filters, external tools (PHPStan, Psalm, PHP_CodeSniffer) | ~287 (est.) | H3: PHP syntax errors on Windows from Lutra's own `php -l` (on open and save, off the engine lock, killed with Lutra), merged into the editor underlines and the Problems tab with source `php -l`; the language server's messages as notifications and its log as `lsp.log`. Tests: `crates/engine/tests/lsp_ux.rs`, unit tests incl. a parser proptest. M3.3: diagnostics from Phpactor (worse reflection: missing members, unknown classes, …) as wavy underlines, gutter markers and hover messages in the editor (`ui/src/components/editor/lint.ts`, tokens only), and a Problems tab in the bottom panel grouped by file with click to reveal (`ui/src/components/problems/`, `problems.open` `Mod+Alt+P`); engine `diagnosticsChanged`, `diagnostics.list`, `lspStatus` (`crates/engine/src/lsp/`). Tests: 10 engine tests against a fake server incl. a sync proptest, a TCP test, 16 Vitest tests, an ignored test against the real PHAR. Checked in the app on Windows 11 with the real Phpactor (port 7933): five errors underlined and listed; first diagnostics 2.7 s after `file.open`, 2.7–2.9 s after an edit (debug build, measured, incl. Phpactor's 1 s debounce). Graded against `plan/phpstorm/11-problems.md`: the depth comes from Phpactor, Lutra has no inspections of its own | | Refactoring | 7 | 3% (est.) | rename: preview of all changes, comments/strings and text occurrences, scope, renaming files with classes, one undo across files (closed files written on disk are not undone by the editor); extract variable/method/constant, inline, move, change signature, safe delete, pull up/push down, introduce parameter | ~244 (est.) | M3.5: Rename (`lsp.prepareRename` then `lsp.rename`, F2) through Phpactor with an inline field over the symbol that shows how many uses in how many files change. The workspace edit is checked completely first (inside the project, ranges fit, open buffers unchanged since the request, no file operations); then closed files are written atomically through the VFS (written ones restored if a later write fails), open buffers change through `buffer.edit` (dirty, one undo step each in the editor), Phpactor reindexes the written files (sent as `didOpen`/`didSave`/`didClose`; its index followed in 140 ms, measured) and a summary notification follows. Live: renaming a method used in 3 files took 28 ms (open buffer + 2 closed files, CRLF kept). Tests: `crates/engine/tests/lsp_nav.rs` (multi-file rename incl. a closed CRLF file, an edit outside the project refused, a bad range refused, a buffer edited meanwhile refused; ignored real-Phpactor rename and rename back), Vitest `ui/tests/nav/`. | | Code style and formatting | 4 | 0% | everything | ~120 (est.) | — | -| Git | 8 | 9% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~122 (est.) | C6 F1: Amend fills an empty message box with the last commit message (`git.lastMessage`); checking out a remote branch whose remote is not configured gives an untracked local branch and a clean tree instead of a half-done checkout; one shared status store, so a `gitChanged` costs one `git.status` for the Changes window, the colours and the branch item. M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: " tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, log, blame and remotes do not yet. | +| Git | 8 | 9% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log: date and branch filters, several selected commits, cherry-pick, revert, reset, checkout or new branch from a commit, compare two commits, history of a selection; blame, conflicts, stash, remotes (C6); ignored files in the status | ~122 (est.) | C6 M4.6: a Log tab in the bottom panel (`vcs.showLog`, menu Git › Log) lists all branches' commits in topological order with graph lanes, ref badges, author and date, 100 per page loaded as the list scrolls; message and author filters; the selected commit's message and changed files, each opening a read-only "Diff: ()" at that commit against its parent (renames followed); history of a file or folder (`vcs.showHistory`: menu, the tree's context menu, or the active editor tab) follows renames. Backend `git.log`, `git.showCommit`, `git.showAt`. Tests: `crates/vcs/tests/log.rs`, `crates/engine/tests/git_log.rs`, Vitest `ui/tests/vcs/Log.test.ts` (21). C6 F1: Amend fills an empty message box with the last commit message (`git.lastMessage`); checking out a remote branch whose remote is not configured gives an untracked local branch and a clean tree instead of a half-done checkout; one shared status store, so a `gitChanged` costs one `git.status` for the Changes window, the colours and the branch item. M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: " tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, log, blame and remotes do not yet. | | Terminal | 3 | 15% (est.) | renaming and splitting tabs, sessions kept across restarts, search in the output, clickable paths and links, drag and drop, command completion, terminal settings (shell path, start directory, environment, font, cursor shape, bell, copy on selection, middle-click paste), a key back to the editor, the PHP interpreter in `PATH`, a terminal in a file's directory, confirmation before killing a running process, moving a terminal into the editor | ~26 (est.) | M3.6: `crates/terminal` runs the shell in a pseudo terminal (`portable-pty`: ConPTY on Windows, Unix pty elsewhere) on its own reader, writer and waiter threads: UTF-8 split across reads joined, invalid bytes U+FFFD, a 1 MiB output buffer per session with backpressure (the shell waits, nothing is dropped while it runs), a non-blocking input queue, resize, kill, exit codes. Engine `terminal.create {cwd?, shell?, cols, rows}` / `terminal.input` / `terminal.resize` / `terminal.close`, events `terminalOutput` (≤ 64 KiB per terminal and 256 KiB per pump, round-robin) and `terminalExited {code}`; terminals close with the project and on `app.quit`. UI: a Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, several terminals as sub-tabs (Local, Local (2)…) with close and new buttons, output replayed after collapsing the panel, copy (`Mod+Shift+C`, `Ctrl+C` with a selection) and paste (`Mod+Shift+V`, `Ctrl+V`), a focus rule that leaves plain Ctrl keys to the shell, Lutra's own ANSI colours (`--lt-terminal-*`, all text colours ≥ 4.5:1), `terminal.open` `Mod+Shift+T`. Tests: 8 session tests with real `cmd.exe` (echo, exit code, input, 6,000 multibyte characters without U+FFFD, 30,000 lines through a full buffer without losing a line, resize, kill, spawn errors) and UTF-8 proptests (`crates/terminal`), 3 engine tests (`crates/engine/tests/terminal.rs`), a TCP control test create → output → input → exit (`crates/control/tests/terminal.rs`), 20 Vitest tests with a mocked xterm (`ui/tests/terminal/`). Live check (Windows 11, debug build with bundled UI, control port 7936, temp project): `terminal.open` showed a pwsh prompt in the project root, first `terminalOutput` 0.2–0.5 s after the command; `php -v` printed PHP 8.4.24 within 0.5–1.5 s; `dir` listed the project; resizing the window changed the shell's width 144 → 190 → 105 → 142 columns (pwsh `WindowSize`); a second terminal as sub-tab "Local (2)"; Find and Terminal as bottom tabs; dark and light screenshots read; `exit 3` gave `terminalExited {code: 3}`; `app.quit` ended the app and its shells (measured). The live check found two bugs, fixed before the commit: xterm's own black viewport background showed as a bar under the last row, and programs printing ANSI white (PSReadLine) were unreadable on the light theme, so xterm now enforces a 4.5:1 minimum contrast. Typing, clicking and copy/paste were not driven in the app (the control channel has no input method); Vitest covers them. Graded against `plan/phpstorm/10-terminal.md` | | Run configurations | 2 | 0% | everything | ~50 (est.) | — | | Debugger | 5 | 0% | everything | ~120 (est.) | — | @@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated); | Date | Change | Summary | |---|---|---| +| 2026-10-28 | patch | M4.6 evidence in the Git row (Log tab, commit details, diff at a commit, file history); score left to the PM | | 2026-10-27 | patch | C6 F1 evidence in the Git row (Amend prefill, remote checkout fix, shared status store) | | 2026-10-26 | minor | C5 review: breadth 35/155 | | 2026-10-26 | minor | M4.5: Git 8% → 9% (est.), branch widget and popup; hours 128 → 122 | diff --git a/docs/tooling-parity.md b/docs/tooling-parity.md index 190478b..6c5cb11 100644 --- a/docs/tooling-parity.md +++ b/docs/tooling-parity.md @@ -1,6 +1,6 @@ # Tooling checklist -> **Status:** integrated terminal partial (M3.6), Git backend, Changes window, diff viewer and branches partial (M4.1, M4.2, M4.3, M4.5) · **Last updated:** 2026-10-26 +> **Status:** integrated terminal partial (M3.6), Git backend, Changes window, diff viewer and branches, log partial (M4.1, M4.2, M4.3, M4.5, M4.6) · **Last updated:** 2026-10-28 - [ ] Integrated terminal with tabs - M3.6 (2026-10-18): PTY sessions (pwsh → powershell → cmd on Windows, `$SHELL` or `/bin/sh` on Unix; cwd = project root) in the bottom panel's Terminal tab, several terminals as sub-tabs, xterm.js rendering with Lutra's colours, copy/paste, resize, exit codes; closed with the project. Missing: settings, persistence across restarts, split tabs, search, links, the PHP interpreter in `PATH`. @@ -8,6 +8,7 @@ - M4.2 (2026-10-25): status, stage/unstage and commit (with amend) from the Changes tab, saving open files first. Missing: diff, gutter markers, branches UI, push/pull, log, blame, conflicts, stash. - M4.3 (2026-10-26): a side-by-side diff of the working copy against the staged version or the last commit, editable on the right, with next/previous change. Missing: comparing with other revisions or branches, a unified view, three-way merge for conflicts. - M4.5 (2026-10-26): current branch in the status bar, switch to a local or remote branch (saving open files first, git's refusal shown) and create a branch from HEAD in the branches popup. Missing: merge, rebase, rename, delete, push/pull, log, blame, conflicts, stash. + - M4.6 (2026-10-28): Log tab with graph lanes, message and author filters and lazy paging; commit details with each file's diff at that commit; history of a file from the tree, the editor or the menu. Missing: date and branch filters, actions on commits (cherry-pick, revert, reset, checkout), comparing two commits, blame, conflicts, stash, push/pull. - [ ] Composer: install, update, require, scripts - [ ] PHP interpreters: local, Docker - [ ] Xdebug via DAP: breakpoints, stepping, variables, watches @@ -21,6 +22,7 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-28 | minor | Git: log and file history (M4.6) | | 2026-10-26 | minor | Git: branch widget, checkout and new branch (M4.5) | | 2026-10-26 | minor | Git: diff viewer (M4.3) | | 2026-10-25 | minor | Git: status, staging and commit from the Changes tab (M4.2) | diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index d4fdf79..c95a827 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -41,6 +41,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [ { id: "vcs.newBranch", labelKey: "command.vcs.newBranch", menuPath: "Git/New Branch…" }, { id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" }, { id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" }, + { id: "vcs.showLog", labelKey: "command.vcs.showLog", menuPath: "Git/Log" }, + { id: "vcs.showHistory", labelKey: "command.vcs.showHistory", menuPath: "Git/Show History" }, { 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/EditorTabs.vue b/ui/src/components/editor/EditorTabs.vue index 15c8fb4..89b26a6 100644 --- a/ui/src/components/editor/EditorTabs.vue +++ b/ui/src/components/editor/EditorTabs.vue @@ -13,7 +13,8 @@ import { X } from "@lucide/vue"; import { t } from "../../i18n"; import { useEditorStore } from "../../stores/editor"; import { useVcsStatusStore } from "../../stores/vcsStatus"; -import { useDiffStore } from "../vcs/diff/diff"; +import { SHORT_HASH } from "../vcs/changes/changes"; +import { useDiffStore, type DiffTab } from "../vcs/diff/diff"; const editor = useEditorStore(); const vcs = useVcsStatusStore(); @@ -38,6 +39,19 @@ function activateTab(id: number): void { editor.activate(id); } +/** + * The title of a diff tab: the file name, marked for the staged view or + * with the short hash of a commit tab. + * + * @param tab - the diff tab. + */ +function diffTitle(tab: DiffTab): string { + if (tab.commit) { + return t("vcs.diff.tabTitleCommit", { name: tab.name, hash: tab.commit.hash.slice(0, SHORT_HASH) }); + } + return tab.staged ? t("vcs.diff.tabTitleStaged", { name: tab.name }) : t("vcs.diff.tabTitle", { name: tab.name }); +} + /** * Closes a diff tab on a middle click. * @@ -143,7 +157,7 @@ function onKeydown(event: KeyboardEvent): void { @mousedown.middle.prevent @auxclick="onDiffAuxClick($event, tab.key)" > - {{ tab.staged ? t("vcs.diff.tabTitleStaged", { name: tab.name }) : t("vcs.diff.tabTitle", { name: tab.name }) }} + {{ diffTitle(tab) }}