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

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