Lutra/crates/vcs/tests/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

284 lines
8.6 KiB
Rust

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