M4.6: Git log and file history

- crates/vcs log.rs: Repo::log (topological, all refs, paging, literal
  message/author filters, a path's history with --follow), show_commit
  (message and files against the first parent, renames) and show_at
  (a file at any commit); parsers property-tested.
- Engine git.log, git.showCommit, git.showAt in cmd/git_log.rs through
  the step-1 hook.
- Log tab in the bottom panel: graph lanes carried across pages, ref
  badges, filters, lazy paging, keyboard; commit details whose files open
  a read-only diff at that commit in M4.3's viewer.
- vcs.showLog and vcs.showHistory (menu, tree context menu, active
  editor tab), no default shortcuts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-28 18:00:24 +01:00
parent b814c49733
commit a8531825a3
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);
}