Lutra/crates/engine/tests/git_log.rs
danny a8531825a3 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>
2026-10-28 18:00:24 +01:00

177 lines
5.6 KiB
Rust

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