PM: merge M4.6 Git log and file history
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-28 18:07:13 +01:00
commit 48b892a6d5
27 changed files with 3349 additions and 16 deletions

View file

@ -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<Value> = 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<String>,
/// Text the message must contain.
#[serde(default)]
query: Option<String>,
/// Text the author name or email must contain.
#[serde(default)]
author: Option<String>,
}
/// 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<Outcome, EngineError> {
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<Value> = 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<Outcome, EngineError> {
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<Outcome, EngineError> {
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,
}))
}),
)
}
}

View file

@ -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(())
}

View file

@ -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",

View file

@ -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<Engine>,
/// Events published so far.
events: Mutex<Vec<Event>>,
}
impl Host {
/// Opens `root` as the project.
fn open(root: &Path) -> Self {
let host = Self {
engine: Mutex::new(Engine::new().unwrap()),
events: Mutex::new(Vec::new()),
};
host.run("project.open", json!({"path": root})).unwrap();
host
}
/// Runs a command the way hosts do.
fn run(&self, command: &str, params: Value) -> Result<Value, EngineError> {
run_waiting(
|| self.engine.lock().unwrap(),
command,
params,
|events| self.events.lock().unwrap().extend_from_slice(events),
)
.map(|o| o.value)
}
}
#[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", "<?php // 1\n", "First");
let second = commit(d, "b.php", "<?php // b\n", "Second\n\nBody");
let third = commit(d, "a.php", "<?php // 3\n", "Third");
let host = Host::open(d);
host.events.lock().unwrap().clear();
let log = host.run("git.log", Value::Null).unwrap();
let commits = log["commits"].as_array().unwrap();
assert_eq!(commits.len(), 3);
assert_eq!(commits[0]["hash"], third);
assert_eq!(commits[0]["parents"], json!([second]));
assert_eq!(commits[0]["author"], "Lutra Test");
assert_eq!(commits[0]["email"], "test@lutra.invalid");
assert_eq!(commits[0]["refs"], json!(["HEAD -> 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": "<?php // 1\n", "binary": false, "tooLarge": false})
);
let missing = host
.run("git.showAt", json!({"path": "b.php", "rev": first}))
.unwrap();
assert_eq!(missing["text"], Value::Null);
for (command, params) in [
("git.log", json!({"limit": 0})),
("git.log", json!({"limit": 501})),
("git.log", json!({"bogus": 1})),
("git.showCommit", json!({"hash": "HEAD"})),
("git.showCommit", json!({})),
("git.showAt", json!({"path": "a.php", "rev": "-p"})),
] {
let err = host.run(command, params.clone()).unwrap_err();
assert_eq!(err.code(), "invalid_params", "{command} {params}");
}
let err = host
.run("git.showCommit", json!({"hash": "abcdef12"}))
.unwrap_err();
assert_eq!(err.code(), "failed");
let changed = host
.events
.lock()
.unwrap()
.iter()
.filter(|e| matches!(e, Event::GitChanged(_)))
.count();
assert_eq!(changed, 0);
}

View file

@ -18,12 +18,14 @@
//! own threads, off its lock.
mod error;
pub mod log;
pub mod porcelain;
mod repo;
pub mod runner;
mod watch;
pub use error::VcsError;
pub use log::{CommitDetails, CommitFile, LOG_LIMIT, LogCommit, LogQuery};
pub use porcelain::{FileState, FileStatus, Head, Status, Version};
pub use repo::{
Branch, Branches, CommitInfo, Contents, FILE_CAP, Git, MIN_VERSION, Repo, Rev, STATUS_CAP,

502
crates/vcs/src/log.rs Normal file
View file

@ -0,0 +1,502 @@
//! History (M4.6): pages of the commit log, one commit's details and a
//! file's contents at any commit.
//!
//! Output is read from NUL-separated formats only (`--format` with `%x00`
//! between fields and `%x1e` before each record, `--name-status -z`). The
//! parsers take untrusted bytes: malformed records are skipped, never a
//! panic (property-tested).
use crate::repo::{SMALL_CAP, check_name};
use crate::runner::Call;
use crate::{Contents, FILE_CAP, Repo, VcsError, decode};
/// Most commits one [`Repo::log`] page returns.
pub const LOG_LIMIT: usize = 500;
/// Most changed files [`Repo::show_commit`] lists.
pub const COMMIT_FILES_CAP: usize = 10_000;
/// Separator before each record of the log format.
const RECORD: u8 = 0x1e;
/// The log format: hash, parents, author, email, author date (strict ISO
/// 8601), subject, ref names; fields NUL-separated, each record starting
/// with [`RECORD`].
const LOG_FORMAT: &str = "--format=%x1e%H%x00%P%x00%an%x00%ae%x00%aI%x00%s%x00%D";
/// The details format: hash, parents, author, email, author date, the raw
/// message.
const SHOW_FORMAT: &str = "--format=%H%x00%P%x00%an%x00%ae%x00%aI%x00%B";
/// What [`Repo::log`] lists.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LogQuery {
/// Commits to skip (paging).
pub skip: usize,
/// Commits to return; capped at [`LOG_LIMIT`], 0 means the cap.
pub limit: usize,
/// Only commits touching this project-relative file or folder (a file's
/// history follows renames).
pub path: Option<String>,
/// Only commits whose message contains this text (case-insensitive).
pub query: Option<String>,
/// Only commits whose author name or email contains this text
/// (case-insensitive).
pub author: Option<String>,
}
/// 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<String>,
/// 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<String>,
}
/// 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<String>,
}
/// 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<String>,
/// 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<CommitFile>,
/// 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<Vec<LogCommit>, 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<CommitDetails, VcsError> {
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<Contents, VcsError> {
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<String> {
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<String> {
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<LogCommit> {
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<CommitDetails> {
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<String>)> {
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::<String>::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::<u8>(), 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);
}
}
}

284
crates/vcs/tests/log.rs Normal file
View file

@ -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<Git> {
match Git::detect("") {
Ok(git) => Some(git),
Err(e) => {
eprintln!("skipped: no usable git installed ({e})");
None
}
}
}
/// Runs git in `dir` for test setup and asserts it succeeded.
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// A new repository on `main` with a local identity.
fn init(dir: &Path) {
git(dir, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Lutra Test"),
("user.email", "test@lutra.invalid"),
("commit.gpgsign", "false"),
("tag.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git(dir, &["config", key, value]);
}
}
/// Writes a file, creating its folders.
fn write(dir: &Path, path: &str, text: &str) {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
std::fs::write(full, text).unwrap();
}
/// Stages everything and commits as `author` (`Name <mail>`), returning
/// the hash.
fn commit(dir: &Path, message: &str, author: &str) -> String {
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "--author", author, "-m", message]);
git(dir, &["rev-parse", "HEAD"])
}
/// Opens the repository at `dir`.
fn open(git: &Git, dir: &Path) -> Repo {
git.open(dir).unwrap().expect("a repository")
}
/// The default author.
const ME: &str = "Lutra Test <test@lutra.invalid>";
#[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", "<?php\n");
let root = commit(d, "Initial import", ME);
git(d, &["tag", "v1"]);
git(d, &["switch", "-q", "-c", "feature"]);
write(d, "b.php", "<?php // b\n");
let side = commit(d, "Add feature B", "Ada Other <ada@other.invalid>");
git(d, &["switch", "-q", "main"]);
write(d, "a.php", "<?php // main\n");
let main_work = commit(d, "Tweak A on main", ME);
git(d, &["merge", "-q", "--no-ff", "--no-edit", "feature"]);
let merge = git(d, &["rev-parse", "HEAD"]);
let repo = open(&cli, d);
let all = repo.log(&LogQuery::default()).unwrap();
let hashes: Vec<&str> = 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 = "<?php\nfunction long_enough_to_detect_a_rename() {\n return 42;\n}\n";
write(d, "src/Old.php", body);
write(d, "other.php", "<?php\n");
let first = commit(d, "Add old", ME);
write(d, "other.php", "<?php // 2\n");
commit(d, "Unrelated", ME);
git(d, &["mv", "src/Old.php", "src/New.php"]);
let renamed = commit(d, "Rename", ME);
let repo = open(&cli, d);
let history = repo
.log(&LogQuery {
path: Some("src/New.php".into()),
..LogQuery::default()
})
.unwrap();
let hashes: Vec<&str> = 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", "<?php\n");
commit(d, "One", ME);
let repo = open(&cli, d);
assert!(matches!(
repo.show_commit("HEAD"),
Err(VcsError::InvalidName(_))
));
assert!(matches!(
repo.show_commit("--all"),
Err(VcsError::InvalidName(_))
));
assert!(matches!(
repo.show_commit("abcdef12"),
Err(VcsError::Git(_))
));
assert!(matches!(
repo.show_at("a.php", "-x"),
Err(VcsError::InvalidName(_))
));
assert!(matches!(
repo.show_at("a.php", "HEAD:b"),
Err(VcsError::InvalidName(_))
));
assert!(matches!(
repo.show_at("../a.php", "HEAD"),
Err(VcsError::InvalidPath(_))
));
assert!(matches!(
repo.log(&LogQuery {
path: Some("../x".into()),
..LogQuery::default()
}),
Err(VcsError::InvalidPath(_))
));
assert!(
repo.show_at("a.php", "nosuchbranch")
.unwrap()
.text
.is_none()
);
}
#[test]
fn a_project_inside_a_repository_sees_its_own_history() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let d = dir.path();
init(d);
write(d, "app/a.php", "<?php\n");
let inside = commit(d, "Inside", ME);
write(d, "elsewhere.txt", "x\n");
commit(d, "Outside", ME);
let repo = open(&cli, &d.join("app"));
let log = repo.log(&LogQuery::default()).unwrap();
assert_eq!(log.len(), 1);
assert_eq!(log[0].hash, inside);
let details = repo.show_commit(&inside).unwrap();
assert_eq!(details.files[0].path, "a.php");
assert_eq!(
repo.show_at("a.php", &inside).unwrap().text.as_deref(),
Some("<?php\n")
);
}

View file

@ -627,6 +627,29 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Look:** both sides use the Lutra editor theme and the file's language; changed lines are tinted with `color-mix` of `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right) into `--lt-editor-bg`, changed words more strongly, a change bar in each gutter, unchanged stretches over 8 lines collapse to a row (3 lines of context). No colour outside the tokens.
- **Tests:** `ui/tests/vcs/DiffView.test.ts` (21 Vitest tests against a fake engine: params and `git.show` parsing, EOL normalisation, index and HEAD sides, one tab per side, the palette without a path, bad params and no file as toasts, disabled without a project, edits on the right reaching `buffer.edit`, engine changes reaching the right side, the left side refresh on `gitChanged`, closing with the buffer, binary / too large / git error / deleted / new file, switching between diff and file tabs, next/previous change with wrap-around, the tree context menu by right click and by Shift+F10 with Escape).
### History (M4.6)
- **Backend (`crates/vcs/src/log.rs`, appended to `Repo`):**
- `log(LogQuery {skip, limit ≤ 500, path?, query?, author?})`: `git log --topo-order` (children before parents, so the UI can draw lanes) over `--branches --remotes --tags HEAD`; with a path, HEAD's history of that path, with `--follow` when it is a file. Text and author filters are literal and case-insensitive (`--fixed-strings --regexp-ignore-case`). In a repository whose root lies above the project, only commits touching the project. A repository without commits has an empty log.
- Format: `%x1e` before each record, NUL between hash, parents, author, email, strict ISO date, subject and decorations (`%D`); malformed records are skipped.
- `show_commit(hash)`: 4–64 hex digits only. Reads the full message (`show -s`) and the files against the first parent (`diff-tree --no-commit-id -r -z -M --name-status`, `--root` for a root commit), at most 10,000 inside the project, with `truncated`.
- `show_at(path, rev)`: `rev:path` through `cat-file --batch-check`, then the blob, with the same binary, size and BOM rules as `show`. A revision starting with `-`, holding `:` or control characters is refused; a missing path or revision is empty contents.
- The parsers are property-tested with random bytes.
- **Shared hook for new git commands (wave 2/3):** `Repo::run`, `check_name` and `SMALL_CAP` are `pub(crate)`. In `cmd/git.rs`, `Op::Custom {mutates, run}` and `start_with(state, id, mutates, run)` run a closure from another module exactly like the built-in commands: a pending outcome, git and the repository cached, and `gitChanged` after a change. `rel_path` resolves path params. M4.6's commands live in `crates/engine/src/cmd/git_log.rs`.
- **Commands** (read-only, pending, no `gitChanged`):
- `git.log {skip?, limit? (1–500, 100), path?, query?, author?}` → `{commits: [{hash, parents, author, email, date, subject, refs}]}`.
- `git.showCommit {hash}` → `{hash, parents, author, email, date, message, files: [{path, status, origPath?}], truncated}`. `email` and `truncated` are additions to the C6 contract.
- `git.showAt {path, rev}` → `{text|null, binary, tooLarge}` (the shape of `git.show`).
- A bad limit, hash, revision or path is `invalid_params`; an unknown commit is `failed` with git's message.
- **Log tab** (`ui/src/components/vcs/log/`): `log.ts` is the store, `graph.ts` the lane layout, `LogToolWindow.vue` the window. It is a tab of the bottom panel, opened by the UI commands `vcs.showLog` (menu Git › Log) and `vcs.showHistory {path?}` (menu Git › Show History, the project tree's context menu; without a path, the active editor tab's file). Neither has a default shortcut.
- **List:** pages of 100 through `runWaiting`. The next page loads when the list scrolls within 30 rows of its end, or when the keyboard selection gets there. One load at a time, a generation counter drops stale answers, at most 50,000 commits. Rows show the graph, ref badges (HEAD, branch, remote, tag; `<remote>/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 <path>" 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 <old path>" 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: <name> (<short hash>)" 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 |

View file

@ -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) |

View file

@ -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 |

File diff suppressed because one or more lines are too long

View file

@ -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) |

View file

@ -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+[" },

View file

@ -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)"
>
<span class="tabs__name">{{ tab.staged ? t("vcs.diff.tabTitleStaged", { name: tab.name }) : t("vcs.diff.tabTitle", { name: tab.name }) }}</span>
<span class="tabs__name">{{ diffTitle(tab) }}</span>
<button
class="tabs__close"
type="button"

View file

@ -30,7 +30,9 @@
* (`Mod+Alt+Shift+G`) and `vcs.commit` (`Mod+Alt+Shift+M`, which also
* focuses the commit message box); `vcs.refresh` re-reads the Git status.
* Its store reads the status from the start, so it is current when the
* tab opens.
* 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.
*
* A slim header bar along the top (M3.9) holds the app menu
* ({@link AppMenu}); its `header` slot can replace it.
@ -49,6 +51,10 @@ import ReferencesToolWindow from "../editor/nav/ReferencesToolWindow.vue";
import { useNavStore } from "../editor/nav/nav";
import ChangesToolWindow from "../vcs/changes/ChangesToolWindow.vue";
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 { useEditorStore } from "../../stores/editor";
import { useProjectStore } from "../../stores/project";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import StructureToolWindow from "../structure/StructureToolWindow.vue";
@ -96,9 +102,12 @@ const terminal = useTerminalStore();
const problems = useProblemsStore();
const nav = useNavStore();
const changes = useChangesStore();
const vcsLog = useLogStore();
const editor = useEditorStore();
const project = useProjectStore();
/** Tool windows of the bottom panel. */
type BottomTool = "find" | "terminal" | "problems" | "references" | "changes";
type BottomTool = "find" | "terminal" | "problems" | "references" | "changes" | "log";
/** The bottom tool window last chosen. */
const bottomTool = ref<BottomTool>("find");
/** Bottom tool windows that are shown, in tab order. */
@ -109,6 +118,7 @@ const bottomTools = computed(() => {
if (problems.visible) tools.push({ id: "problems", title: t("problems.toolWindow.title") });
if (nav.visible) tools.push({ id: "references", title: t("nav.references.title") });
if (changes.visible) tools.push({ id: "changes", title: t("vcs.changes.toolWindow.title") });
if (vcsLog.visible) tools.push({ id: "log", title: t("vcs.log.toolWindow.title") });
return tools;
});
/** The active bottom tool window: the chosen one if shown, else the first. */
@ -126,7 +136,9 @@ const bottomStore = computed(() =>
? nav
: bottomActive.value === "changes"
? changes
: find,
: bottomActive.value === "log"
? vcsLog
: find,
);
/** Expansion of the panel, kept per tool window by its store. */
const bottomOpen = computed({
@ -142,7 +154,7 @@ const bottomOpen = computed({
* @param id - the tool window id from the panel.
*/
function chooseBottom(id: string): void {
if (id === "find" || id === "terminal" || id === "problems" || id === "references" || id === "changes") {
if (id === "find" || id === "terminal" || id === "problems" || id === "references" || id === "changes" || id === "log") {
bottomTool.value = id;
}
}
@ -160,6 +172,7 @@ onMounted(() => {
terminal.start();
problems.start();
changes.start();
vcsLog.start();
withdraw = [
commands.provide("view.toggleProjectTree", {
run: () => {
@ -201,6 +214,20 @@ onMounted(() => {
run: () => changes.refresh(),
enabled: () => commands.isEnabled("git.status"),
}),
commands.provide(SHOW_LOG_COMMAND, {
run: () => {
bottomTool.value = "log";
return vcsLog.open();
},
enabled: () => project.root !== null,
}),
commands.provide(SHOW_HISTORY_COMMAND, {
run: (params) => {
bottomTool.value = "log";
return vcsLog.runShowHistory(params, editor.activeTab?.path ?? null);
},
enabled: () => project.root !== null,
}),
commands.provide("view.toggleStructure", {
run: () => {
toggleLeft("structure");
@ -218,6 +245,7 @@ onBeforeUnmount(() => {
terminal.stop();
problems.stop();
changes.stop();
vcsLog.stop();
});
</script>
@ -292,6 +320,10 @@ onBeforeUnmount(() => {
<ProblemsToolWindow v-show="bottomActive === 'problems'" />
<ReferencesToolWindow v-show="bottomActive === 'references'" />
<ChangesToolWindow v-show="bottomActive === 'changes'" />
<LogToolWindow
v-if="vcsLog.visible"
v-show="bottomActive === 'log'"
/>
</BottomPanel>
<StatusBar />
</div>

View file

@ -1,7 +1,8 @@
<script setup lang="ts">
/**
* The project tree's context menu for a file (M4.3): Open and Show Diff
* (`vcs.showDiff {path}`, dimmed while the command is disabled).
* The project tree's context menu for a file (M4.3): Open, Show Diff
* (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`,
* M4.6), the Git items dimmed while their command is disabled.
*
* Follows the WAI-ARIA menu pattern: it takes the focus when it opens,
* Up/Down move between items (wrapping), Enter or Space runs one, Escape,
@ -13,6 +14,7 @@ import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { SHOW_DIFF_COMMAND } from "../vcs/diff/diff";
import { SHOW_HISTORY_COMMAND } from "../vcs/log/log";
const props = defineProps<{
/** Project-relative path of the file. */
@ -66,6 +68,12 @@ const items = computed<MenuItem[]>(() => [
enabled: commands.isEnabled(SHOW_DIFF_COMMAND),
run: () => commands.execute(SHOW_DIFF_COMMAND, { path: props.path }),
},
{
id: "showHistory",
label: t("project.tree.menu.showHistory"),
enabled: commands.isEnabled(SHOW_HISTORY_COMMAND),
run: () => commands.execute(SHOW_HISTORY_COMMAND, { path: props.path }),
},
]);
/** The menu's position, kept inside the window. */

View file

@ -12,6 +12,8 @@
* from disk, an agent's edit) come back through `bufferChanged`: once the
* sync has taken them over, the difference is applied to the right
* editor outside its undo history.
* - **Commit tabs (M4.6):** both sides are read-only texts from the store:
* the file at the commit's parent (left) and at the commit (right).
* - **Left side:** replaced in place when the store re-reads it
* (`gitChanged` after staging).
* - **Colours:** only `--lt-*` tokens; changed lines are tinted with
@ -32,6 +34,7 @@ import type { BufferSync } from "../../editor/bufferSync";
import { diffDocs } from "../../editor/engineText";
import { editorExtensions, lutraEditorTheme } from "../../editor/extensions";
import { languageExtensions } from "../../editor/language";
import { SHORT_HASH } from "../changes/changes";
import { refFor, useDiffStore } from "./diff";
import { setNavigator } from "./navigation";
@ -89,6 +92,9 @@ const caption = computed(() => {
if (!tab) {
return "";
}
if (tab.commit) {
return t("vcs.diff.captionCommit", { path: tab.path, hash: tab.commit.hash.slice(0, SHORT_HASH) });
}
return refFor(tab.staged) === "HEAD"
? t("vcs.diff.captionHead", { path: tab.path })
: t("vcs.diff.captionIndex", { path: tab.path });
@ -181,7 +187,7 @@ function build(): void {
: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly];
merge = new MergeView({
a: { doc: content.left, extensions: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly] },
b: sync ? { doc: sync.state.doc, selection: sync.state.selection, extensions: right } : { doc: "", extensions: right },
b: sync ? { doc: sync.state.doc, selection: sync.state.selection, extensions: right } : { doc: content.right ?? "", extensions: right },
parent: host.value,
gutter: true,
highlightChanges: true,

View file

@ -27,6 +27,10 @@
* - **Refresh:** `gitChanged` re-reads the left side of every text tab
* (staging changes the index). A project open or close drops every tab;
* closing the working copy's buffer closes its diff tabs.
* - **Commit tabs (M4.6):** {@link openAtCommit} compares a file at a commit
* (right, `git.showAt {path, rev: hash}`) with its first parent (left, the
* old path of a rename). Both sides are read-only texts; nothing is
* re-read on `gitChanged` (commits do not change).
* - **Untrusted input:** `git.show` results are checked field by field.
*/
import { defineStore } from "pinia";
@ -55,6 +59,18 @@ export interface ShowDiffParams {
staged: boolean;
}
/** The commit a commit tab shows (M4.6). */
export interface DiffCommit {
/** The commit's full hash (the right side). */
hash: string;
/** Its first parent (the left side); null for a root commit. */
parent: string | null;
/** The file's path in the parent when it was renamed or copied. */
origPath: string | null;
/** The file was deleted by the commit (no right side). */
deleted: boolean;
}
/** One diff tab. */
export interface DiffTab {
/** Stable key: side and path. */
@ -65,6 +81,8 @@ export interface DiffTab {
staged: boolean;
/** File name shown on the tab. */
name: string;
/** For a commit tab: what it compares; absent for working-copy diffs. */
commit?: DiffCommit;
}
/** What a diff tab shows. */
@ -82,6 +100,9 @@ export interface DiffContent {
bufferId: number | null;
/** Error text, or why the working copy is missing; null if none. */
message: string | null;
/** A commit tab's right text with `
` breaks (absent otherwise). */
right?: string;
}
/** A `git.show` result, checked. */
@ -122,6 +143,16 @@ export function diffKey(path: string, staged: boolean): string {
return `${staged ? "staged" : "work"}:${path}`;
}
/**
* The key of a commit tab.
*
* @param path - project-relative path.
* @param hash - the commit.
*/
export function commitDiffKey(path: string, hash: string): string {
return `commit:${hash}:${path}`;
}
/**
* Reads the params of `vcs.showDiff`; null when malformed.
*
@ -292,6 +323,55 @@ export const useDiffStore = defineStore("diff", () => {
}
}
/**
* Reads a file at a revision with `git.showAt`.
*
* @param path - project-relative path.
* @param rev - the commit.
* @returns the checked result, or the error text.
*/
async function readAt(path: string, rev: string): Promise<ShowResult | string> {
const result = await runWaiting("git.showAt", { path, rev });
if (!result.ok) {
return result.error.message;
}
return toShowResult(result.value) ?? t("common.error.unexpectedResult", { command: "git.showAt" });
}
/**
* Loads both sides of a commit tab.
*
* @param tab - the tab.
* @param commit - what it compares.
* @param current - whether this load is still the newest.
*/
async function loadCommit(tab: DiffTab, commit: DiffCommit, current: () => boolean): Promise<void> {
const missing: ShowResult = { text: null, binary: false, tooLarge: false };
const [left, right] = await Promise.all([
commit.parent === null ? Promise.resolve(missing) : readAt(commit.origPath ?? tab.path, commit.parent),
commit.deleted ? Promise.resolve(missing) : readAt(tab.path, commit.hash),
]);
if (!current()) {
return;
}
if (typeof left === "string" || typeof right === "string") {
setContent(tab.key, { ...LOADING, phase: "error", message: typeof left === "string" ? left : typeof right === "string" ? right : null });
return;
}
if (left.binary || right.binary || left.tooLarge || right.tooLarge) {
setContent(tab.key, { ...LOADING, phase: left.binary || right.binary ? "binary" : "tooLarge" });
return;
}
setContent(tab.key, {
phase: "ready",
left: normaliseEol(left.text ?? ""),
leftMissing: left.text === null,
bufferId: null,
message: null,
right: normaliseEol(right.text ?? ""),
});
}
/**
* Loads both sides of a tab.
*
@ -302,6 +382,10 @@ export const useDiffStore = defineStore("diff", () => {
generations.set(tab.key, generation);
const current = (): boolean => generations.get(tab.key) === generation && tabs.value.some((t) => t.key === tab.key);
setContent(tab.key, LOADING);
if (tab.commit) {
await loadCommit(tab, tab.commit, current);
return;
}
const left = await readLeft(tab);
if (!current()) {
return;
@ -344,6 +428,26 @@ export const useDiffStore = defineStore("diff", () => {
await load(tab);
}
/**
* Opens (or activates) the diff of a file at a commit against the
* commit's first parent.
*
* @param path - project-relative path at the commit.
* @param commit - the commit, its parent and the file's old path.
*/
async function openAtCommit(path: string, commit: DiffCommit): Promise<void> {
const key = commitDiffKey(path, commit.hash);
let tab = tabs.value.find((t) => t.key === key);
if (!tab) {
tab = { key, path, staged: false, name: baseName(path), commit };
tabs.value.push(tab);
}
activate(key);
if (contents.value[key]?.phase !== "ready") {
await load(tab);
}
}
/**
* Re-reads the left side of every loaded text tab; a changed text
* replaces the left document (`gitChanged`).
@ -352,7 +456,7 @@ export const useDiffStore = defineStore("diff", () => {
await Promise.all(
tabs.value.map(async (tab) => {
const before = contents.value[tab.key];
if (before?.phase !== "ready") {
if (before?.phase !== "ready" || tab.commit) {
return;
}
const generation = generations.get(tab.key);
@ -464,6 +568,7 @@ export const useDiffStore = defineStore("diff", () => {
activate,
deactivate,
open,
openAtCommit,
showDiff,
refreshLeft,
close,

View file

@ -0,0 +1,730 @@
<script setup lang="ts">
/**
* The Log tool window (M4.6), a tab of the bottom panel: the commit list
* with graph lanes on the left, the selected commit's details on the right.
*
* - **Toolbar:** a text filter (message) and an author filter, applied
* 300 ms after the last keystroke or at once on Enter; a chip with the
* path while a file's or folder's history shows (its button clears it);
* a refresh button.
* - **List:** graph, subject with ref badges, author, date. Up/Down,
* Page Up/Down, Home and End move the selection; scrolling near the end
* loads the next page.
* - **Details:** hash, author, date, the full message and the changed
* files; Enter or a double-click on a file opens its diff at that commit
* in the editor area.
* - **Colours:** lanes cycle through theme tokens only.
*/
import { RefreshCw, X } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, ref } from "vue";
import { t } from "../../../i18n";
import { useProjectStore } from "../../../stores/project";
import { SHORT_HASH } from "../changes/changes";
import { refBadges, useLogStore, type CommitFile, type CommitFileStatus } from "./log";
import type { GraphRow } from "./graph";
const log = useLogStore();
const project = useProjectStore();
/** Width of a lane in pixels. */
const LANE = 12;
/** Height of a row in pixels. */
const ROW = 22;
/** Rows from the end at which the next page loads. */
const PRELOAD_ROWS = 30;
/** Delay before a typed filter applies. */
const FILTER_DELAY_MS = 300;
/** Lane colours, theme tokens only. */
const LANE_COLOURS = [
"var(--lt-accent)",
"var(--lt-vcs-added)",
"var(--lt-vcs-modified)",
"var(--lt-syntax-keyword)",
"var(--lt-syntax-string)",
"var(--lt-syntax-function)",
"var(--lt-syntax-type)",
"var(--lt-syntax-number)",
];
/** Labels of the file states, from the catalog. */
const STATE_LABELS: Record<CommitFileStatus, () => string> = {
added: () => t("vcs.state.added"),
modified: () => t("vcs.state.modified"),
deleted: () => t("vcs.state.deleted"),
renamed: () => t("vcs.state.renamed"),
copied: () => t("vcs.state.copied"),
};
/** The list element. */
const listEl = ref<HTMLElement | null>(null);
/** The text filter as typed. */
const query = ref(log.filters.query);
/** The author filter as typed. */
const author = ref(log.filters.author);
/** Index of the focused file in the details. */
const fileIndex = ref(0);
/** Pending filter timer. */
let timer: ReturnType<typeof setTimeout> | null = null;
/** Width of the graph column: the widest loaded row. */
const graphWidth = computed(() => {
if (!log.graphShown) {
return LANE;
}
let lanes = 1;
for (const row of log.rows) {
lanes = Math.max(lanes, row.width);
}
return lanes * LANE + LANE / 2;
});
/** The status line: loading, an error or an empty result; null otherwise. */
const status = computed(() => {
if (!project.root) {
return t("vcs.log.noProject");
}
if (log.error !== null) {
return t("vcs.log.failed", { reason: log.error });
}
if (log.commits.length === 0) {
return log.loading || !log.loaded ? t("vcs.log.loading") : t("vcs.log.empty");
}
return null;
});
/**
* Colour of a lane.
*
* @param lane - lane index.
*/
function laneColour(lane: number): string {
return LANE_COLOURS[lane % LANE_COLOURS.length] ?? "var(--lt-accent)";
}
/**
* The x coordinate of a column's centre.
*
* @param column - column index.
*/
function x(column: number): number {
return column * LANE + LANE / 2;
}
/**
* SVG path of a segment.
*
* @param from - column at the start.
* @param to - column at the end.
* @param top - whether it runs from the top edge to the middle.
*/
function segmentPath(from: number, to: number, top: boolean): string {
const y0 = top ? 0 : ROW / 2;
const y1 = top ? ROW / 2 : ROW;
if (from === to) {
return ["M", x(from), y0, "L", x(to), y1].join(" ");
}
const mid = (y0 + y1) / 2;
return ["M", x(from), y0, "C", x(from), mid, x(to), mid, x(to), y1].join(" ");
}
/**
* The graph row of a commit, or null when the graph is hidden.
*
* @param index - row index.
*/
function rowAt(index: number): GraphRow | null {
return log.graphShown ? (log.rows[index] ?? null) : null;
}
/**
* A date for the list: the local date and time, short.
*
* @param iso - ISO 8601 date.
*/
function shortDate(iso: string): string {
const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return iso;
}
return date.toLocaleString(undefined, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
}
/** Applies the typed filters now. */
function applyFilters(): void {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
if (query.value === log.filters.query && author.value === log.filters.author) {
return;
}
void log.setFilters({ query: query.value, author: author.value });
}
/** Applies the typed filters after {@link FILTER_DELAY_MS}. */
function scheduleFilters(): void {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(applyFilters, FILTER_DELAY_MS);
}
/** Clears the path filter. */
function clearPath(): void {
void log.setFilters({ path: null });
}
/** Loads the next page when the list is scrolled near its end. */
function onScroll(): void {
const el = listEl.value;
if (el && el.scrollTop + el.clientHeight >= el.scrollHeight - PRELOAD_ROWS * ROW) {
void log.loadMore();
}
}
/**
* Selects the commit at an index and keeps it in view.
*
* @param index - row index (clamped).
*/
function selectAt(index: number): void {
const count = log.commits.length;
if (count === 0) {
return;
}
const clamped = Math.max(0, Math.min(count - 1, index));
fileIndex.value = 0;
void log.select(log.commits[clamped]?.hash ?? null);
void nextTick(() => {
listEl.value?.querySelector(`[data-index="${String(clamped)}"]`)?.scrollIntoView({ block: "nearest" });
});
if (clamped >= count - PRELOAD_ROWS) {
void log.loadMore();
}
}
/**
* Keyboard handling of the list.
*
* @param event - the key press.
*/
function onListKey(event: KeyboardEvent): void {
const index = log.commits.findIndex((c) => c.hash === log.selected);
const page = Math.max(1, Math.floor((listEl.value?.clientHeight ?? ROW * 10) / ROW) - 1);
const moves: Record<string, number> = {
ArrowDown: index + 1,
ArrowUp: index - 1,
PageDown: index + page,
PageUp: index - page,
Home: 0,
End: log.commits.length - 1,
};
const target = moves[event.key];
if (target === undefined) {
return;
}
event.preventDefault();
selectAt(target);
}
/**
* Opens a file's diff at the selected commit.
*
* @param file - the file.
*/
function openFile(file: CommitFile): void {
void log.openFile(file);
}
/**
* Keyboard handling of the file list.
*
* @param event - the key press.
*/
function onFilesKey(event: KeyboardEvent): void {
const files = log.details?.files ?? [];
if (files.length === 0) {
return;
}
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
fileIndex.value = Math.max(0, Math.min(files.length - 1, fileIndex.value + (event.key === "ArrowDown" ? 1 : -1)));
} else if (event.key === "Enter") {
event.preventDefault();
const file = files[fileIndex.value];
if (file) {
openFile(file);
}
}
}
onBeforeUnmount(() => {
if (timer !== null) {
clearTimeout(timer);
}
});
</script>
<template>
<div
class="log"
data-test="log-window"
>
<div class="log__toolbar">
<input
v-model="query"
class="log__filter"
type="search"
:placeholder="t('vcs.log.filterText')"
:aria-label="t('vcs.log.filterText')"
data-test="log-filter-text"
@input="scheduleFilters"
@keydown.enter="applyFilters"
>
<input
v-model="author"
class="log__filter log__filter--author"
type="search"
:placeholder="t('vcs.log.filterAuthor')"
:aria-label="t('vcs.log.filterAuthor')"
data-test="log-filter-author"
@input="scheduleFilters"
@keydown.enter="applyFilters"
>
<span
v-if="log.filters.path !== null"
class="log__chip"
data-test="log-path"
>
{{ t("vcs.log.historyOf", { path: log.filters.path }) }}
<button
type="button"
class="log__icon-button"
:aria-label="t('vcs.log.clearPath')"
:title="t('vcs.log.clearPath')"
data-test="log-path-clear"
@click="clearPath"
>
<X :size="12" />
</button>
</span>
<button
type="button"
class="log__icon-button log__refresh"
:aria-label="t('vcs.log.refresh')"
:title="t('vcs.log.refresh')"
data-test="log-refresh"
@click="log.reload()"
>
<RefreshCw :size="14" />
</button>
</div>
<div class="log__body">
<div
ref="listEl"
class="log__list"
role="listbox"
tabindex="0"
:aria-label="t('vcs.log.listLabel')"
:aria-activedescendant="log.selected ? `log-row-${log.selected}` : undefined"
data-test="log-list"
@scroll="onScroll"
@keydown="onListKey"
>
<div
v-if="status"
class="log__status"
data-test="log-status"
>
{{ status }}
</div>
<div
v-for="(commit, index) in log.commits"
:id="`log-row-${commit.hash}`"
:key="commit.hash"
class="log__row"
:class="{ 'log__row--selected': commit.hash === log.selected }"
role="option"
:aria-selected="commit.hash === log.selected"
:data-index="index"
:data-hash="commit.hash"
data-test="log-row"
@click="selectAt(index)"
>
<svg
class="log__graph"
:width="graphWidth"
:height="ROW"
aria-hidden="true"
>
<template v-if="rowAt(index)">
<path
v-for="(seg, i) in rowAt(index)?.up ?? []"
:key="`u${i}`"
:d="segmentPath(seg.from, seg.to, true)"
:stroke="laneColour(seg.lane)"
fill="none"
stroke-width="1.5"
/>
<path
v-for="(seg, i) in rowAt(index)?.down ?? []"
:key="`d${i}`"
:d="segmentPath(seg.from, seg.to, false)"
:stroke="laneColour(seg.lane)"
fill="none"
stroke-width="1.5"
/>
</template>
<circle
:cx="x(rowAt(index)?.column ?? 0)"
:cy="ROW / 2"
:r="rowAt(index)?.merge ? 3 : 3.5"
:fill="rowAt(index)?.merge ? 'var(--lt-bg)' : laneColour(rowAt(index)?.column ?? 0)"
:stroke="laneColour(rowAt(index)?.column ?? 0)"
stroke-width="1.5"
data-test="log-dot"
/>
</svg>
<span class="log__subject">
<span
v-for="badge in refBadges(commit.refs)"
:key="`${badge.kind}:${badge.name}`"
class="log__badge"
:class="`log__badge--${badge.kind}`"
data-test="log-badge"
>{{ badge.name }}</span>
{{ commit.subject }}
</span>
<span class="log__author">{{ commit.author }}</span>
<span class="log__date">{{ shortDate(commit.date) }}</span>
</div>
<div
v-if="log.loading && log.commits.length > 0"
class="log__status"
>
{{ t("vcs.log.loadingMore") }}
</div>
</div>
<section
class="log__details"
:aria-label="t('vcs.log.details')"
data-test="log-details"
>
<div
v-if="log.detailsLoading"
class="log__status"
>
{{ t("vcs.log.detailsLoading") }}
</div>
<div
v-else-if="log.detailsError !== null"
class="log__status log__status--error"
>
{{ t("vcs.log.detailsFailed", { reason: log.detailsError }) }}
</div>
<template v-else-if="log.details">
<div
class="log__meta"
data-test="log-meta"
>
<span class="log__hash">{{ log.details.hash.slice(0, SHORT_HASH) }}</span>
{{ t("vcs.log.byLine", { author: log.details.author, email: log.details.email, date: shortDate(log.details.date) }) }}
</div>
<pre
class="log__message"
data-test="log-message"
>{{ log.details.message }}</pre>
<div
class="log__files"
role="listbox"
tabindex="0"
:aria-label="t('vcs.log.files', { count: log.details.files.length })"
data-test="log-files"
@keydown="onFilesKey"
>
<div class="log__files-title">
{{ t("vcs.log.files", { count: log.details.files.length }) }}
</div>
<div
v-for="(file, i) in log.details.files"
:key="file.path"
class="log__file"
:class="[`log__file--${file.status}`, { 'log__file--focused': i === fileIndex }]"
role="option"
:aria-selected="i === fileIndex"
:title="t('vcs.log.openDiff')"
data-test="log-file"
@click="fileIndex = i"
@dblclick="openFile(file)"
>
<span class="log__file-path">{{ file.path }}</span>
<span
v-if="file.origPath"
class="log__file-from"
>{{ t("vcs.changes.renamedFrom", { path: file.origPath }) }}</span>
<span class="log__file-state">{{ STATE_LABELS[file.status]() }}</span>
</div>
<div
v-if="log.details.truncated"
class="log__status"
>
{{ t("vcs.log.truncated") }}
</div>
</div>
</template>
</section>
</div>
</div>
</template>
<style scoped>
.log {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
color: var(--lt-fg);
font-size: var(--lt-font-size-ui);
}
.log__toolbar {
display: flex;
align-items: center;
gap: var(--lt-space-s, 4px);
flex: none;
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px);
border-bottom: 1px solid var(--lt-border);
}
.log__filter {
width: 220px;
padding: 2px 6px;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
}
.log__filter--author {
width: 140px;
}
.log__filter:focus-visible {
outline: 2px solid var(--lt-accent);
}
.log__chip {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 0 2px 0 8px;
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
border-radius: var(--lt-radius, 4px);
white-space: nowrap;
}
.log__icon-button {
display: inline-flex;
align-items: center;
padding: 2px;
color: var(--lt-fg-muted);
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.log__icon-button:hover {
color: var(--lt-fg);
}
.log__icon-button:focus-visible {
outline: 2px solid var(--lt-accent);
}
.log__refresh {
margin-left: auto;
}
.log__body {
display: flex;
flex: 1;
min-height: 0;
}
.log__list {
flex: 3;
min-width: 0;
overflow: auto;
outline: none;
}
.log__list:focus-visible {
box-shadow: inset 0 0 0 1px var(--lt-accent);
}
.log__row {
display: flex;
align-items: center;
gap: var(--lt-space-m, 8px);
height: 22px;
padding: 0 var(--lt-space-m, 8px) 0 var(--lt-space-s, 4px);
white-space: nowrap;
cursor: default;
}
.log__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.log__row--selected,
.log__row--selected:hover {
background: var(--lt-editor-selection-bg);
}
.log__graph {
flex: none;
}
.log__subject {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.log__badge {
margin-right: 4px;
padding: 0 4px;
font-size: var(--lt-font-size-small);
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
}
.log__badge--head {
color: var(--lt-accent);
border-color: var(--lt-accent);
}
.log__badge--branch {
color: var(--lt-vcs-added);
border-color: var(--lt-vcs-added);
}
.log__badge--remote {
color: var(--lt-vcs-modified);
border-color: var(--lt-vcs-modified);
}
.log__badge--tag {
color: var(--lt-syntax-string);
border-color: var(--lt-syntax-string);
}
.log__author {
flex: none;
width: 140px;
overflow: hidden;
text-overflow: ellipsis;
color: var(--lt-fg-muted);
}
.log__date {
flex: none;
color: var(--lt-fg-muted);
font-variant-numeric: tabular-nums;
}
.log__details {
flex: 2;
min-width: 0;
overflow: auto;
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
border-left: 1px solid var(--lt-border);
}
.log__status {
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
color: var(--lt-fg-muted);
}
.log__status--error {
color: var(--lt-error);
}
.log__meta {
color: var(--lt-fg-muted);
}
.log__hash {
margin-right: 6px;
color: var(--lt-fg);
font-family: var(--lt-font-mono);
}
.log__message {
margin: var(--lt-space-s, 4px) 0;
font-family: var(--lt-font-mono);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.log__files {
outline: none;
}
.log__files:focus-visible {
box-shadow: inset 0 0 0 1px var(--lt-accent);
}
.log__files-title {
margin-top: var(--lt-space-s, 4px);
color: var(--lt-fg-muted);
}
.log__file {
display: flex;
gap: var(--lt-space-s, 4px);
padding: 1px 4px;
white-space: nowrap;
cursor: default;
}
.log__file--focused {
background: var(--lt-editor-selection-bg);
}
.log__file-path {
overflow: hidden;
text-overflow: ellipsis;
}
.log__file--added .log__file-path {
color: var(--lt-vcs-added);
}
.log__file--modified .log__file-path,
.log__file--renamed .log__file-path {
color: var(--lt-vcs-modified);
}
.log__file--copied .log__file-path {
color: var(--lt-vcs-added);
}
.log__file--deleted .log__file-path {
color: var(--lt-vcs-deleted);
text-decoration: line-through;
}
.log__file-from,
.log__file-state {
color: var(--lt-fg-muted);
}
.log__file-state {
margin-left: auto;
}
</style>

View file

@ -0,0 +1,145 @@
/**
* Graph lanes of the Log (M4.6): which column each commit sits in and the
* line segments drawn above and below its dot.
*
* Commits arrive newest first in topological order (`git.log`), so every
* child comes before its parents. A lane is a column waiting for a commit:
* - A commit takes the leftmost lane waiting for it (or the first free one)
* and every other lane waiting for it joins it from above.
* - Its first parent continues in its column, even when another lane
* waits for that parent too (both join when the parent comes); further
* parents (merges) join a lane already waiting for them, or take the
* first free column.
* - Lanes that pass by run straight down.
*
* Pages extend the layout: {@link layoutGraph} takes the lanes left by
* the previous page, so loading more never redraws rows already shown.
* Lanes are capped at {@link MAX_LANES}; commits beyond that share the
* last column (rare, and only the picture suffers).
*/
/** Most columns drawn. */
export const MAX_LANES = 24;
/** The commit fields the layout needs. */
export interface GraphCommit {
/** Full hash. */
hash: string;
/** Parent hashes, first parent first. */
parents: readonly string[];
}
/** A line inside one row, from a column at one edge to a column at the dot's height. */
export interface Segment {
/** Column at the row's top (for `up`) or at the dot's height (for `down`). */
from: number;
/** Column at the dot's height (for `up`) or at the row's bottom (for `down`). */
to: number;
/** Colour index of the lane. */
lane: number;
}
/** The drawing of one row. */
export interface GraphRow {
/** Column of the commit's dot. */
column: number;
/** Lines from the top edge to the dot's height. */
up: Segment[];
/** Lines from the dot's height to the bottom edge. */
down: Segment[];
/** Columns used by the row (for its width). */
width: number;
/** The commit is a merge (more than one parent). */
merge: boolean;
}
/** Lanes waiting for commits, carried from one page to the next. */
export type Lanes = (string | null)[];
/**
* Lays out rows for a page of commits.
*
* @param commits - the page, newest first in topological order.
* @param carried - lanes left by the previous page (not changed).
* @returns the rows and the lanes for the next page.
*/
export function layoutGraph(commits: readonly GraphCommit[], carried: Lanes = []): { rows: GraphRow[]; lanes: Lanes } {
const lanes: Lanes = carried.slice(0, MAX_LANES);
const rows: GraphRow[] = [];
for (const commit of commits) {
const before = lanes.slice();
let column = lanes.indexOf(commit.hash);
if (column < 0) {
column = freeColumn(lanes);
}
const up: Segment[] = [];
before.forEach((waiting, i) => {
if (waiting === null) {
return;
}
if (waiting === commit.hash) {
up.push({ from: i, to: column, lane: i });
lanes[i] = null;
} else {
up.push({ from: i, to: i, lane: i });
}
});
const targets: number[] = [];
commit.parents.forEach((parent, k) => {
if (k === 0 && lanes[column] === null) {
lanes[column] = parent;
targets.push(column);
return;
}
const existing = lanes.indexOf(parent);
if (existing >= 0) {
targets.push(existing);
return;
}
const slot = freeColumn(lanes);
lanes[slot] = parent;
targets.push(slot);
});
while (lanes.length > 0 && lanes[lanes.length - 1] === null) {
lanes.pop();
}
const down: Segment[] = [];
lanes.forEach((waiting, i) => {
if (waiting === null) {
return;
}
if (before[i] !== null && before[i] !== undefined && before[i] !== commit.hash) {
down.push({ from: i, to: i, lane: i });
}
});
for (const target of new Set(targets)) {
down.push({ from: column, to: target, lane: target });
}
rows.push({
column,
up,
down,
width: Math.max(before.length, lanes.length, column + 1),
merge: commit.parents.length > 1,
});
}
return { rows, lanes };
}
/**
* The first free column, appending one when all are taken (up to
* {@link MAX_LANES}; past it, the last column).
*
* @param lanes - the lanes; extended in place when a column is appended.
*/
function freeColumn(lanes: Lanes): number {
const free = lanes.indexOf(null);
if (free >= 0) {
return free;
}
if (lanes.length < MAX_LANES) {
lanes.push(null);
return lanes.length - 1;
}
return MAX_LANES - 1;
}

View file

@ -0,0 +1,556 @@
/**
* The Log tool window's state (M4.6): pages of `git.log`, the filters, the
* selected commit and its details.
*
* - **Pages:** {@link PAGE_SIZE} commits per `git.log` call (a pending
* outcome, so through `runWaiting`); {@link LogStore.loadMore} asks for
* the next page when the list is scrolled near its end. A page shorter
* than asked for ends the history. One load runs at a time; a filter
* change or a refresh starts over (a generation counter drops answers
* of older loads). At most {@link MAX_COMMITS} commits are kept.
* - **Filters:** text in the message, author, and a path (a file's or
* folder's history: `vcs.showHistory`). Text and author filters are
* applied by git; the graph is drawn only without them, because the
* filtered commits' parents are not in the list.
* - **Details:** selecting a commit reads `git.showCommit`; a file of it
* opens in the diff viewer at that commit (`useDiffStore().openAtCommit`).
* - **Refresh:** `gitChanged` reloads the first page when the HEAD or the
* branch moved (a commit, a checkout), not on every index change;
* opening a project clears everything, closing one too.
* - **Untrusted input:** results are checked field by field; malformed
* commits and files are dropped.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { t } from "../../../i18n";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { useNotificationsStore } from "../../../stores/notifications";
import { useDiffStore } from "../diff/diff";
import { layoutGraph, type GraphRow, type Lanes } from "./graph";
/** Commits per `git.log` page. */
export const PAGE_SIZE = 100;
/** Most commits kept in the list. */
export const MAX_COMMITS = 50_000;
/** Most files of a commit shown. */
export const MAX_FILES = 10_000;
/** Command id that shows the Log tab. */
export const SHOW_LOG_COMMAND = "vcs.showLog";
/** Command id that shows the history of a file or folder. */
export const SHOW_HISTORY_COMMAND = "vcs.showHistory";
/** One commit of the list. */
export interface LogCommit {
/** Full hash. */
hash: string;
/** Parent hashes, first parent first. */
parents: string[];
/** Author name. */
author: string;
/** Author email. */
email: string;
/** Author date, ISO 8601. */
date: string;
/** Subject line. */
subject: string;
/** Decorations: `HEAD -> main`, `origin/main`, `tag: v1`. */
refs: string[];
}
/** How a file changed in a commit. */
export type CommitFileStatus = "added" | "modified" | "deleted" | "renamed" | "copied";
/** A file changed by a commit. */
export interface CommitFile {
/** Project-relative path after the commit. */
path: string;
/** How it changed. */
status: CommitFileStatus;
/** Its path before a rename or copy. */
origPath: string | null;
}
/** A commit's details. */
export interface CommitDetails {
/** Full hash. */
hash: string;
/** Parent hashes. */
parents: string[];
/** Author name. */
author: string;
/** Author email. */
email: string;
/** Author date, ISO 8601. */
date: string;
/** The full message. */
message: string;
/** Changed files against the first parent. */
files: CommitFile[];
/** More files changed than listed. */
truncated: boolean;
}
/** The filters of the list. */
export interface LogFilters {
/** Text in the message. */
query: string;
/** Text in the author name or email. */
author: string;
/** A file or folder; null for the whole project. */
path: string | null;
}
/** The kind of a ref decoration, for its badge. */
export type RefKind = "head" | "branch" | "remote" | "tag";
/** A decoration, split for display. */
export interface RefBadge {
/** The name shown. */
name: string;
/** Its kind. */
kind: RefKind;
}
/** Statuses `git.showCommit` may report. */
const FILE_STATUSES: readonly CommitFileStatus[] = ["added", "modified", "deleted", "renamed", "copied"];
/**
* Narrows to a plain object.
*
* @param raw - anything.
*/
function record(raw: unknown): Record<string, unknown> | null {
return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : null;
}
/**
* A list of strings, or null when it is not one.
*
* @param raw - untrusted.
*/
function strings(raw: unknown): string[] | null {
return Array.isArray(raw) && raw.every((item) => typeof item === "string") ? raw : null;
}
/**
* Reads one commit of `git.log`; null when malformed.
*
* @param raw - untrusted.
*/
export function toCommit(raw: unknown): LogCommit | null {
const r = record(raw);
if (!r) {
return null;
}
const parents = strings(r.parents);
const refs = strings(r.refs);
const { hash, author, email, date, subject } = r;
if (
typeof hash !== "string" ||
hash === "" ||
parents === null ||
refs === null ||
typeof author !== "string" ||
typeof email !== "string" ||
typeof date !== "string" ||
typeof subject !== "string"
) {
return null;
}
return { hash, parents, author, email, date, subject, refs };
}
/**
* Reads a `git.log` result; null when malformed. Malformed commits are
* dropped.
*
* @param raw - untrusted.
*/
export function toCommits(raw: unknown): LogCommit[] | null {
const list = record(raw)?.commits;
if (!Array.isArray(list)) {
return null;
}
return list.map(toCommit).filter((c): c is LogCommit => c !== null);
}
/**
* Reads a `git.showCommit` result; null when malformed.
*
* @param raw - untrusted.
*/
export function toDetails(raw: unknown): CommitDetails | null {
const r = record(raw);
const parents = strings(r?.parents);
if (!r || parents === null || !Array.isArray(r.files)) {
return null;
}
const { hash, author, email, date, message } = r;
if (typeof hash !== "string" || typeof author !== "string" || typeof date !== "string" || typeof message !== "string") {
return null;
}
const files: CommitFile[] = [];
for (const item of r.files.slice(0, MAX_FILES)) {
const f = record(item);
const status = FILE_STATUSES.find((s) => s === f?.status);
if (!f || typeof f.path !== "string" || f.path === "" || status === undefined) {
continue;
}
files.push({ path: f.path, status, origPath: typeof f.origPath === "string" ? f.origPath : null });
}
return {
hash,
parents,
author,
email: typeof email === "string" ? email : "",
date,
message,
files,
truncated: r.truncated === true || r.files.length > MAX_FILES,
};
}
/**
* Splits git's decorations into badges.
*
* @param refs - `HEAD -> main`, `origin/main`, `tag: v1`, `HEAD`; a name
* with a `/` counts as a remote branch, `<remote>/HEAD` is left out.
*/
export function refBadges(refs: readonly string[]): RefBadge[] {
const badges: RefBadge[] = [];
for (const ref of refs) {
if (ref.startsWith("HEAD -> ")) {
badges.push({ name: "HEAD", kind: "head" }, { name: ref.slice("HEAD -> ".length), kind: "branch" });
} else if (ref === "HEAD") {
badges.push({ name: "HEAD", kind: "head" });
} else if (ref.startsWith("tag: ")) {
badges.push({ name: ref.slice("tag: ".length), kind: "tag" });
} else if (ref.endsWith("/HEAD")) {
continue;
} else {
badges.push({ name: ref, kind: ref.includes("/") ? "remote" : "branch" });
}
}
return badges;
}
/**
* The `git.log` params of a page.
*
* @param filters - the filters.
* @param skip - commits already loaded.
*/
export function logParams(filters: LogFilters, skip: number): Record<string, JsonValue> {
const params: Record<string, JsonValue> = { skip, limit: PAGE_SIZE };
if (filters.query.trim() !== "") {
params.query = filters.query.trim();
}
if (filters.author.trim() !== "") {
params.author = filters.author.trim();
}
if (filters.path !== null) {
params.path = filters.path;
}
return params;
}
/** The Log store. */
export const useLogStore = defineStore("log", () => {
const notifications = useNotificationsStore();
const diff = useDiffStore();
/** Whether the Log tab is shown. */
const visible = ref(false);
/** Whether the panel is expanded while the Log is shown. */
const expanded = ref(true);
/** The filters. */
const filters = ref<LogFilters>({ query: "", author: "", path: null });
/** Loaded commits, newest first. */
const commits = shallowRef<LogCommit[]>([]);
/** Graph rows, one per commit (empty while filtered by text or author). */
const rows = shallowRef<GraphRow[]>([]);
/** A page is loading. */
const loading = ref(false);
/** The history ended (the last page was short). */
const complete = ref(false);
/** The error of the last load; null if it worked. */
const error = ref<string | null>(null);
/** Hash of the selected commit. */
const selected = ref<string | null>(null);
/** The selected commit's details. */
const details = shallowRef<CommitDetails | null>(null);
/** The details are loading. */
const detailsLoading = ref(false);
/** Why the details could not be read; null if they could. */
const detailsError = ref<string | null>(null);
/** Something has been loaded since the last reset. */
const loaded = ref(false);
/** Lanes left after the loaded commits. */
let lanes: Lanes = [];
/** Bumped on every reset; answers of older loads are dropped. */
let generation = 0;
/** Bumped on every selection; answers for older ones are dropped. */
let detailsGeneration = 0;
/** HEAD and branch of the last `gitChanged`, to reload only when they move. */
let lastHead: string | null = null;
/** Whether the graph is drawn (no text or author filter). */
const graphShown = computed(() => filters.value.query.trim() === "" && filters.value.author.trim() === "");
/** The selected commit, null when none or not loaded. */
const selectedCommit = computed(() => commits.value.find((c) => c.hash === selected.value) ?? null);
/** Drops the list and starts over with the first page. */
async function reload(): Promise<void> {
generation += 1;
commits.value = [];
rows.value = [];
lanes = [];
complete.value = false;
error.value = null;
loading.value = false;
loaded.value = false;
await loadMore();
}
/** Loads the next page, unless one is loading or the history ended. */
async function loadMore(): Promise<void> {
if (loading.value || complete.value || commits.value.length >= MAX_COMMITS) {
return;
}
const mine = generation;
loading.value = true;
const result = await runWaiting("git.log", logParams(filters.value, commits.value.length));
if (mine !== generation) {
return;
}
loading.value = false;
loaded.value = true;
if (!result.ok) {
error.value = result.error.message;
complete.value = true;
return;
}
const page = toCommits(result.value);
if (page === null) {
error.value = t("common.error.unexpectedResult", { command: "git.log" });
complete.value = true;
return;
}
error.value = null;
if (graphShown.value) {
const laid = layoutGraph(page, lanes);
lanes = laid.lanes;
rows.value = [...rows.value, ...laid.rows];
}
commits.value = [...commits.value, ...page];
complete.value = page.length < PAGE_SIZE || commits.value.length >= MAX_COMMITS;
if (selected.value === null && commits.value.length > 0) {
void select(commits.value[0]?.hash ?? null);
}
}
/**
* Selects a commit and reads its details.
*
* @param hash - the commit, or null for none.
*/
async function select(hash: string | null): Promise<void> {
if (hash === selected.value && (details.value?.hash === hash || detailsLoading.value)) {
return;
}
selected.value = hash;
detailsGeneration += 1;
const mine = detailsGeneration;
details.value = null;
detailsError.value = null;
if (hash === null) {
detailsLoading.value = false;
return;
}
detailsLoading.value = true;
const result = await runWaiting("git.showCommit", { hash });
if (mine !== detailsGeneration) {
return;
}
detailsLoading.value = false;
if (!result.ok) {
detailsError.value = result.error.message;
return;
}
const read = toDetails(result.value);
if (read === null) {
detailsError.value = t("common.error.unexpectedResult", { command: "git.showCommit" });
return;
}
details.value = read;
}
/**
* Opens a file of the selected commit in the diff viewer.
*
* @param file - a file of {@link details}.
*/
async function openFile(file: CommitFile): Promise<void> {
const commit = details.value;
if (!commit) {
return;
}
await diff.openAtCommit(file.path, {
hash: commit.hash,
parent: commit.parents[0] ?? null,
origPath: file.origPath,
deleted: file.status === "deleted",
});
}
/**
* Changes the filters and reloads.
*
* @param change - the filters to change.
*/
async function setFilters(change: Partial<LogFilters>): Promise<void> {
filters.value = { ...filters.value, ...change };
selected.value = null;
details.value = null;
await reload();
}
/** Shows the tab (expanded) and loads the first page if nothing is loaded. */
async function open(): Promise<void> {
visible.value = true;
expanded.value = true;
if (!loaded.value && !loading.value) {
await reload();
}
}
/**
* Shows the history of a file or folder.
*
* @param path - project-relative path.
*/
async function showHistory(path: string): Promise<void> {
visible.value = true;
expanded.value = true;
await setFilters({ path, query: "", author: "" });
}
/** Hides the tab. */
function hide(): void {
visible.value = false;
}
/** Forgets everything (a project opened or closed). */
function clear(): void {
generation += 1;
detailsGeneration += 1;
commits.value = [];
rows.value = [];
lanes = [];
loading.value = false;
loaded.value = false;
complete.value = false;
error.value = null;
selected.value = null;
details.value = null;
detailsLoading.value = false;
detailsError.value = null;
filters.value = { query: "", author: "", path: null };
lastHead = null;
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "projectOpened" || event.kind === "projectClosed") {
clear();
return;
}
if (event.kind !== "gitChanged") {
return;
}
const repo = record(event.repo);
const text = (value: unknown): string => (typeof value === "string" ? value : "");
const head = repo ? `${text(repo.head)}|${text(repo.branch)}` : null;
const moved = head !== lastHead;
lastHead = head;
if (moved && loaded.value) {
void reload();
}
}
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events; calling it again has no effect. */
function start(): void {
unsubscribe ??= onEngineEvent(onEvent);
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/**
* Runs `vcs.showHistory {path?}`: the given path, else the active
* editor tab's file.
*
* @param params - untrusted params.
* @param fallback - the path to use without one (the active file);
* with neither, a warning toast says so.
*/
async function runShowHistory(params: JsonValue, fallback: string | null): Promise<void> {
const p = record(params) ?? {};
const path = typeof p.path === "string" && p.path !== "" ? p.path : fallback;
if (path === null) {
notifications.notify({ level: "warning", messageKey: "notification.vcs.historyNoFile" });
return;
}
await showHistory(path);
}
return {
visible,
expanded,
filters,
commits,
rows,
loading,
complete,
error,
loaded,
selected,
selectedCommit,
details,
detailsLoading,
detailsError,
graphShown,
reload,
loadMore,
select,
openFile,
setFilters,
open,
showHistory,
runShowHistory,
hide,
clear,
onEvent,
start,
stop,
};
});
/** The Log store's type. */
export type LogStore = ReturnType<typeof useLogStore>;

View file

@ -28,6 +28,8 @@
"command.vcs.previousChange": "Previous Change",
"command.vcs.refresh": "Refresh Changes",
"command.vcs.showDiff": "Show Diff",
"command.vcs.showHistory": "Show History",
"command.vcs.showLog": "Log",
"command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure",
"common.cancel": "Cancel",
@ -161,6 +163,7 @@
"notification.vcs.checkoutNotSaved": "Checkout of {branch} cancelled: not every file could be saved first.",
"notification.vcs.commitNotSaved": "Commit cancelled: not every file could be saved first.",
"notification.vcs.committed": "Committed {hash}: {summary}",
"notification.vcs.historyNoFile": "Open a file or pass a path to show its history",
"notification.vcs.newBranchFailed": "Branch {branch} was not created: {reason}",
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
@ -191,6 +194,7 @@
"project.tree.menu.label": "Actions for {name}",
"project.tree.menu.open": "Open",
"project.tree.menu.showDiff": "Show Diff",
"project.tree.menu.showHistory": "Show History",
"project.tree.truncated": "Listing truncated: more entries than can be shown",
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
"recovery.dialog.discard": "Discard",
@ -323,6 +327,7 @@
"vcs.commit.messageLabel": "Commit message",
"vcs.commit.placeholder": "Commit message",
"vcs.diff.binary": "Binary file: no text diff to show.",
"vcs.diff.captionCommit": "{path}: before (left) and after (right) commit {hash}",
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
"vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)",
"vcs.diff.closeTab": "Close the diff of {name}",
@ -331,9 +336,29 @@
"vcs.diff.loading": "Reading the file from Git…",
"vcs.diff.noFile": "Open a file or pass a path to show its diff",
"vcs.diff.tabTitle": "Diff: {name}",
"vcs.diff.tabTitleCommit": "Diff: {name} ({hash})",
"vcs.diff.tabTitleStaged": "Diff: {name} (staged)",
"vcs.diff.tooLarge": "The file is too large to compare.",
"vcs.diff.workingCopyMissing": "The working copy cannot be opened ({reason}); it may have been deleted.",
"vcs.log.byLine": "{author} <{email}>, {date}",
"vcs.log.clearPath": "Show the whole project's history",
"vcs.log.details": "Commit details",
"vcs.log.detailsFailed": "The commit cannot be read: {reason}",
"vcs.log.detailsLoading": "Reading the commit…",
"vcs.log.empty": "No commits match",
"vcs.log.failed": "The history cannot be read: {reason}",
"vcs.log.files": "Changed files: {count}",
"vcs.log.filterAuthor": "Author",
"vcs.log.filterText": "Filter by message",
"vcs.log.historyOf": "History of {path}",
"vcs.log.listLabel": "Commits",
"vcs.log.loading": "Reading the history…",
"vcs.log.loadingMore": "Reading more commits…",
"vcs.log.noProject": "Open a project to see its history",
"vcs.log.openDiff": "Double-click or press Enter to open the diff at this commit",
"vcs.log.refresh": "Reload the history",
"vcs.log.toolWindow.title": "Log",
"vcs.log.truncated": "More files changed than are listed here.",
"vcs.state.added": "added",
"vcs.state.conflicted": "conflicted",
"vcs.state.copied": "copied",

View file

@ -64,6 +64,7 @@ const RUNTIME_KEYS = new Set([
"notification.vcs.checkedOut",
"notification.vcs.checkoutFailed",
"notification.vcs.checkoutNotSaved",
"notification.vcs.historyNoFile",
"notification.vcs.commitNotSaved",
"notification.vcs.committed",
"notification.vcs.newBranchFailed",

View file

@ -278,11 +278,13 @@ describe("AppMenu", () => {
"vcs.branches",
"vcs.openChanges",
"vcs.commit",
"vcs.showLog",
"vcs.newBranch",
"vcs.nextChange",
"vcs.previousChange",
"vcs.refresh",
"vcs.showDiff",
"vcs.showHistory",
"app.about",
]);
const close = document.querySelector("[data-command='buffer.close']");

View file

@ -269,6 +269,7 @@ describe("CommandPalette", () => {
"goto.classOpen",
"goto.fileOpen",
"goto.symbolOpen",
"vcs.showLog",
"vcs.newBranch",
"vcs.nextChange",
"project.openDialog",
@ -282,6 +283,7 @@ describe("CommandPalette", () => {
"editor.reveal",
"settings.open",
"vcs.showDiff",
"vcs.showHistory",
"view.toggleProjectTree",
"view.toggleStructure",
"terminal.open",

View file

@ -475,7 +475,7 @@ describe("project tree context menu", () => {
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
const menu = document.querySelector("[data-test=tree-menu]");
expect(menu).not.toBeNull();
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff"]);
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History"]);
(document.querySelector("[data-item=showDiff]") as HTMLElement).click();
await flushPromises();
await flushPromises();

483
ui/tests/vcs/Log.test.ts Normal file
View file

@ -0,0 +1,483 @@
/**
* Tests of the Log (M4.6): graph lanes, reading the untrusted `git.log`
* and `git.showCommit` results, ref badges, paging, filters, reloading on
* `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
* `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useCommandsStore } from "../../src/commands/store";
import { UI_COMMANDS } from "../../src/commands/uiCommands";
import EditorArea from "../../src/components/editor/EditorArea.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";
import { layoutGraph, MAX_LANES } from "../../src/components/vcs/log/graph";
import {
logParams,
PAGE_SIZE,
refBadges,
SHOW_HISTORY_COMMAND,
SHOW_LOG_COMMAND,
toCommits,
toDetails,
useLogStore,
} from "../../src/components/vcs/log/log";
import LogToolWindow from "../../src/components/vcs/log/LogToolWindow.vue";
import { useNotificationsStore } from "../../src/stores/notifications";
import { useProjectStore } from "../../src/stores/project";
/** A commit of the fake history. */
interface FakeCommit {
hash: string;
parents: string[];
author: string;
email: string;
date: string;
subject: string;
refs: string[];
}
/** The fake history, newest first. */
let history: FakeCommit[];
/** What `git.showAt` answers, by `rev:path`. */
let blobs: Record<string, string>;
/** Errors to throw, by command id. */
let failures: Record<string, { code: string; message: string }>;
/** Every engine call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** Engine event callbacks. */
let listeners: ((event: { payload: unknown }) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components. */
let mounted: VueWrapper[];
/**
* A fake commit.
*
* @param hash - its hash.
* @param parents - its parents.
* @param refs - its decorations.
*/
function fake(hash: string, parents: string[], refs: string[] = []): FakeCommit {
return { hash, parents, author: `A ${hash}`, email: `${hash}@x`, date: "2026-10-27T10:00:00+01:00", subject: `Subject ${hash}`, refs };
}
/**
* A linear history of `count` commits, newest first.
*
* @param count - how many.
*/
function linear(count: number): FakeCommit[] {
return Array.from({ length: count }, (_, i) => {
const n = count - i;
return fake(`c${String(n)}`, n > 1 ? [`c${String(n - 1)}`] : []);
});
}
/**
* Sends an engine event.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of [...listeners]) {
listener({ payload });
}
await flushPromises();
}
/**
* The fake engine.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const failure = failures[command];
if (failure) {
return Promise.reject(Object.assign(new Error(failure.message), failure));
}
switch (command) {
case "git.log": {
const query = typeof p.query === "string" ? p.query.toLowerCase() : null;
const matching = history.filter((c) => query === null || c.subject.toLowerCase().includes(query));
const skip = Number(p.skip ?? 0);
return Promise.resolve({ commits: matching.slice(skip, skip + Number(p.limit ?? 100)) });
}
case "git.showCommit": {
const commit = history.find((c) => c.hash === p.hash);
if (!commit) {
return Promise.reject(Object.assign(new Error("no such commit"), { code: "failed", message: "no such commit" }));
}
return Promise.resolve({
hash: commit.hash,
parents: commit.parents,
author: commit.author,
email: commit.email,
date: commit.date,
message: `${commit.subject}\n\nBody`,
files: [
{ path: "src/New.php", status: "renamed", origPath: "src/Old.php" },
{ path: "gone.php", status: "deleted" },
{ path: "bad", status: "exploded" },
],
truncated: false,
});
}
case "git.showAt": {
const text = blobs[`${String(p.rev)}:${String(p.path)}`];
return Promise.resolve({ text: text ?? null, binary: false, tooLarge: false });
}
default:
return Promise.resolve({});
}
}
/**
* The calls of a command.
*
* @param command - the command id.
*/
function callsOf(command: string): Record<string, unknown>[] {
return calls.filter((c) => c.command === command).map((c) => c.params);
}
/** Mounts the Log window with an open project. */
async function mountLog(): Promise<VueWrapper> {
useProjectStore(pinia).root = { path: "/p", name: "p" };
const wrapper = mount(LogToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
beforeEach(() => {
Range.prototype.getClientRects = () => Object.assign([] as DOMRect[], { item: () => null });
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
Element.prototype.scrollIntoView = () => undefined;
pinia = createPinia();
setActivePinia(pinia);
history = [fake("m", ["a", "b"], ["HEAD -> main", "tag: v2"]), fake("b", ["r"], ["origin/feature", "origin/HEAD"]), fake("a", ["r"]), fake("r", [], ["tag: v1"])];
blobs = {};
failures = {};
calls = [];
listeners = [];
mounted = [];
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
calls.push({ command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.resolve(null);
});
});
afterEach(async () => {
await flushPromises();
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
document.body.innerHTML = "";
});
describe("graph", () => {
it("draws a straight line for a linear history", () => {
const { rows, lanes } = layoutGraph(linear(3));
expect(rows.map((r) => r.column)).toEqual([0, 0, 0]);
expect(rows[0]?.up).toEqual([]);
expect(rows[0]?.down).toEqual([{ from: 0, to: 0, lane: 0 }]);
expect(rows[2]?.down).toEqual([]);
expect(lanes).toEqual([]);
});
it("branches out at a merge and joins again at the fork point", () => {
const { rows } = layoutGraph(history);
expect(rows[0]).toMatchObject({ column: 0, merge: true });
expect(rows[0]?.down).toEqual([
{ from: 0, to: 0, lane: 0 },
{ from: 0, to: 1, lane: 1 },
]);
expect(rows[1]?.column).toBe(1);
expect(rows[2]?.column).toBe(0);
expect(rows[3]?.column).toBe(0);
expect(rows[3]?.up).toEqual([
{ from: 0, to: 0, lane: 0 },
{ from: 1, to: 0, lane: 1 },
]);
expect(rows[3]?.width).toBe(2);
});
it("continues across pages without redrawing", () => {
const all = layoutGraph(history).rows;
const first = layoutGraph(history.slice(0, 2));
const second = layoutGraph(history.slice(2), first.lanes);
expect([...first.rows, ...second.rows]).toEqual(all);
});
it("caps the lanes", () => {
const tips = Array.from({ length: MAX_LANES + 5 }, (_, i) => ({ hash: `t${String(i)}`, parents: [`p${String(i)}`] }));
const { rows, lanes } = layoutGraph(tips);
expect(Math.max(...rows.map((r) => r.column))).toBe(MAX_LANES - 1);
expect(lanes.length).toBeLessThanOrEqual(MAX_LANES);
});
});
describe("parsing", () => {
it("reads commits and drops malformed ones", () => {
expect(toCommits({ commits: [history[0], { hash: "x" }, null, { ...history[1], refs: [1] }] })).toEqual([history[0]]);
expect(toCommits({ commits: "no" })).toBeNull();
expect(toCommits(null)).toBeNull();
});
it("reads details and drops unknown file states", () => {
const d = toDetails({ hash: "h", parents: ["p"], author: "A", email: "e", date: "d", message: "m", files: [{ path: "a", status: "added" }, { path: "b", status: "?" }, { path: "c", status: "renamed", origPath: "o" }] });
expect(d?.files).toEqual([
{ path: "a", status: "added", origPath: null },
{ path: "c", status: "renamed", origPath: "o" },
]);
expect(toDetails({ hash: "h" })).toBeNull();
});
it("splits decorations into badges", () => {
expect(refBadges(["HEAD -> main", "origin/main", "origin/HEAD", "tag: v1", "HEAD", "dev"])).toEqual([
{ name: "HEAD", kind: "head" },
{ name: "main", kind: "branch" },
{ name: "origin/main", kind: "remote" },
{ name: "v1", kind: "tag" },
{ name: "HEAD", kind: "head" },
{ name: "dev", kind: "branch" },
]);
});
it("builds git.log params from the filters", () => {
expect(logParams({ query: " fix ", author: "", path: null }, 200)).toEqual({ skip: 200, limit: PAGE_SIZE, query: "fix" });
expect(logParams({ query: "", author: "ada", path: "a.php" }, 0)).toEqual({ skip: 0, limit: PAGE_SIZE, author: "ada", path: "a.php" });
});
});
describe("store", () => {
it("pages lazily and stops at a short page", async () => {
history = linear(PAGE_SIZE + 20);
const log = useLogStore(pinia);
await log.open();
expect(log.commits).toHaveLength(PAGE_SIZE);
expect(log.complete).toBe(false);
expect(log.selected).toBe(history[0]?.hash);
await log.loadMore();
expect(log.commits).toHaveLength(PAGE_SIZE + 20);
expect(log.rows).toHaveLength(PAGE_SIZE + 20);
expect(log.complete).toBe(true);
await log.loadMore();
expect(callsOf("git.log").map((p) => p.skip)).toEqual([0, PAGE_SIZE]);
});
it("filters by text without a graph, and drops stale answers", async () => {
const log = useLogStore(pinia);
await log.open();
const first = log.setFilters({ query: "subject b" });
const second = log.setFilters({ query: "subject a" });
await Promise.all([first, second]);
expect(log.commits.map((c) => c.hash)).toEqual(["a"]);
expect(log.graphShown).toBe(false);
expect(log.rows).toEqual([]);
});
it("reloads on gitChanged only when HEAD or the branch moved", async () => {
const log = useLogStore(pinia);
log.start();
await log.open();
await emit({ kind: "gitChanged", available: true, repo: { head: "m", branch: "main" }, filesChanged: true });
const before = callsOf("git.log").length;
await emit({ kind: "gitChanged", available: true, repo: { head: "m", branch: "main" }, filesChanged: true });
expect(callsOf("git.log")).toHaveLength(before);
history.unshift(fake("n", ["m"], ["HEAD -> main"]));
await emit({ kind: "gitChanged", available: true, repo: { head: "n", branch: "main" }, filesChanged: true });
expect(callsOf("git.log")).toHaveLength(before + 1);
expect(log.commits[0]?.hash).toBe("n");
await emit({ kind: "projectClosed" });
expect(log.commits).toEqual([]);
log.stop();
});
it("shows git's error", async () => {
failures["git.log"] = { code: "failed", message: "the project is not inside a Git repository" };
const log = useLogStore(pinia);
await log.open();
expect(log.error).toBe("the project is not inside a Git repository");
expect(log.complete).toBe(true);
});
it("reads the selected commit's details", async () => {
const log = useLogStore(pinia);
await log.open();
expect(log.details?.message).toBe("Subject m\n\nBody");
expect(log.details?.files.map((f) => f.status)).toEqual(["renamed", "deleted"]);
failures["git.showCommit"] = { code: "failed", message: "gone" };
await log.select("b");
expect(log.detailsError).toBe("gone");
});
it("shows a file's history, or warns without a file", async () => {
const log = useLogStore(pinia);
await log.runShowHistory({ path: "src/a.php" }, null);
expect(log.visible).toBe(true);
expect(log.filters.path).toBe("src/a.php");
expect(callsOf("git.log").at(-1)).toMatchObject({ path: "src/a.php" });
await log.runShowHistory({}, "b.php");
expect(log.filters.path).toBe("b.php");
await log.runShowHistory({}, null);
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("history");
});
});
describe("window", () => {
it("lists commits with badges, dots and details", async () => {
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
const rows = wrapper.findAll("[data-test=log-row]");
expect(rows).toHaveLength(4);
expect(rows[0]?.text()).toContain("Subject m");
expect(rows[0]?.findAll("[data-test=log-badge]").map((b) => b.text())).toEqual(["HEAD", "main", "v2"]);
expect(rows[1]?.findAll("[data-test=log-badge]").map((b) => b.text())).toEqual(["origin/feature"]);
expect(wrapper.findAll("[data-test=log-dot]")).toHaveLength(4);
expect(wrapper.find("[data-test=log-message]").text()).toBe("Subject m\n\nBody");
expect(wrapper.findAll("[data-test=log-file]").map((f) => f.text())).toEqual([
expect.stringContaining("from src/Old.php"),
expect.stringContaining("gone.php"),
]);
});
it("moves the selection with the keyboard", async () => {
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
const list = wrapper.find("[data-test=log-list]");
await list.trigger("keydown", { key: "ArrowDown" });
await flushPromises();
expect(log.selected).toBe("b");
await list.trigger("keydown", { key: "End" });
await flushPromises();
expect(log.selected).toBe("r");
await list.trigger("keydown", { key: "Home" });
await flushPromises();
expect(log.selected).toBe("m");
expect(callsOf("git.showCommit").map((p) => p.hash)).toEqual(["m", "b", "r", "m"]);
});
it("applies the text filter on Enter and clears a history's path", async () => {
const log = useLogStore(pinia);
await log.showHistory("a.php");
const wrapper = await mountLog();
expect(wrapper.find("[data-test=log-path]").text()).toContain("a.php");
const input = wrapper.find("[data-test=log-filter-text]");
await input.setValue("subject r");
await input.trigger("keydown", { key: "Enter" });
await flushPromises();
expect(callsOf("git.log").at(-1)).toMatchObject({ query: "subject r", path: "a.php" });
await wrapper.find("[data-test=log-path-clear]").trigger("click");
await flushPromises();
expect(log.filters.path).toBeNull();
expect(wrapper.find("[data-test=log-path]").exists()).toBe(false);
});
it("says when nothing matches or git fails", async () => {
history = [];
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
expect(wrapper.find("[data-test=log-status]").text()).toBe("No commits match");
failures["git.log"] = { code: "failed", message: "boom" };
await log.reload();
await flushPromises();
expect(wrapper.find("[data-test=log-status]").text()).toContain("boom");
});
});
describe("diff at a commit", () => {
it("compares the file at the commit with its parent, read-only", async () => {
blobs = { "a:src/Old.php": "<?php\r\nold();\r\n", "m:src/New.php": "<?php\nnew();\n" };
await useCommandsStore(pinia).start();
useProjectStore(pinia).root = { path: "/p", name: "p" };
const area = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } });
mounted.push(area);
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
const file = wrapper.findAll("[data-test=log-file]")[0];
await file?.trigger("dblclick");
await vi.dynamicImportSettled();
await flushPromises();
const diff = useDiffStore(pinia);
expect(diff.activeKey).toBe(commitDiffKey("src/New.php", "m"));
expect(callsOf("git.showAt")).toEqual([
{ path: "src/Old.php", rev: "a" },
{ path: "src/New.php", rev: "m" },
]);
const merge = currentMerge();
expect(merge?.a.state.doc.toString()).toBe("<?php\nold();\n");
expect(merge?.b.state.doc.toString()).toBe("<?php\nnew();\n");
expect(merge?.b.state.readOnly).toBe(true);
expect(area.find("[data-test=diff-tab]").text()).toBe("Diff: New.php (m)");
expect(area.find("[data-test=diff-caption]").text()).toContain("commit m");
expect(callsOf("file.open")).toEqual([]);
await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true });
expect(callsOf("git.showAt")).toHaveLength(2);
await log.openFile({ path: "gone.php", status: "deleted", origPath: null });
await flushPromises();
expect(callsOf("git.showAt").at(-1)).toEqual({ path: "gone.php", rev: "a" });
});
});
describe("commands", () => {
it("registers Log and Show History without default shortcuts", () => {
const specs = UI_COMMANDS.filter((c) => c.id === SHOW_LOG_COMMAND || c.id === SHOW_HISTORY_COMMAND);
expect(specs.map((c) => [c.id, c.menuPath, c.defaultShortcut])).toEqual([
["vcs.showLog", "Git/Log", undefined],
["vcs.showHistory", "Git/Show History", undefined],
]);
});
it("offers Show History in the tree's context menu", async () => {
const commands = useCommandsStore(pinia);
const run = vi.fn();
commands.provide(SHOW_HISTORY_COMMAND, { run });
const wrapper = mount(TreeContextMenu, {
attachTo: document.body,
props: { path: "src/a.php", name: "a.php", x: 0, y: 0 },
global: { plugins: [pinia] },
});
mounted.push(wrapper);
await flushPromises();
const item = wrapper.findAll("[data-test=tree-menu-item]").find((i) => i.text() === "Show History");
await item?.trigger("click");
await flushPromises();
expect(run).toHaveBeenCalledWith({ path: "src/a.php" });
});
});