use std::path::Path;
const GIT_ENV: &[&str] = &[
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_COMMON_DIR",
"GIT_CEILING_DIRECTORIES",
"GIT_NAMESPACE",
"GIT_PREFIX",
];
pub(crate) fn git(root: &Path) -> std::process::Command {
let mut cmd = std::process::Command::new("git");
cmd.arg("-C").arg(root);
for key in GIT_ENV {
cmd.env_remove(key);
}
cmd
}
pub(crate) fn blob(root: &Path, commit: &str, path: &str) -> Option<String> {
let spec = format!("{commit}:{path}");
let out = git(root).args(["cat-file", "-p", &spec]).output().ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
pub(crate) fn count_at(
root: &Path,
commit: &str,
path: &str,
bpe: bool,
) -> Option<u64> {
blob(root, commit, path).map(|text| count_text(&text, bpe))
}
fn count_text(text: &str, bpe: bool) -> u64 {
#[cfg(feature = "bpe")]
if bpe {
return crate::bpe::count(text);
}
let _ = bpe;
crate::estimate::dummy(u64::try_from(text.len()).unwrap_or(u64::MAX))
}
pub(crate) fn changed_in(root: &Path, commit: &str) -> Vec<String> {
let Some(n) = parents(root, commit) else {
return Vec::new();
};
if n == 0 {
return root_diff(root, commit);
}
let first = format!("{commit}^1");
names(root, &["diff", "--name-only", &first, commit])
}
fn root_diff(root: &Path, commit: &str) -> Vec<String> {
names(
root,
&[
"diff-tree",
"--root",
"--no-commit-id",
"--name-only",
"-r",
commit,
],
)
}
fn parents(root: &Path, commit: &str) -> Option<usize> {
let out = git(root)
.args(["rev-list", "--parents", "-n", "1", commit])
.output()
.ok()?;
if !out.status.success() {
return None;
}
String::from_utf8_lossy(&out.stdout)
.split_whitespace()
.count()
.checked_sub(1)
}
pub(crate) fn changed_between(root: &Path, a: &str, b: &str) -> Vec<String> {
names(root, &["diff", "--name-only", a, b])
}
pub(crate) fn changed_working(root: &Path, refspec: &str) -> Vec<String> {
names(root, &["diff", "--name-only", refspec])
}
pub(crate) fn staged(root: &Path) -> Vec<String> {
names(root, &["diff", "--cached", "--name-only"])
}
fn names(root: &Path, args: &[&str]) -> Vec<String> {
let Ok(out) = git(root).args(args).output() else {
return Vec::new();
};
String::from_utf8_lossy(&out.stdout)
.lines()
.map(str::to_owned)
.collect()
}
pub(crate) fn commits(
root: &Path,
extra: &[String],
) -> Vec<(String, String, String)> {
let mut args = vec![
"log".to_owned(),
"--format=%h%x1f%ad%x1f%s".to_owned(),
"--date=short".to_owned(),
];
args.extend(extra.iter().cloned());
output(root, &args).lines().filter_map(triple).collect()
}
fn output(root: &Path, args: &[String]) -> String {
git(root)
.args(args)
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
.unwrap_or_default()
}
fn triple(line: &str) -> Option<(String, String, String)> {
let mut p = line.split('\u{1f}');
Some((
p.next()?.to_owned(),
p.next()?.to_owned(),
p.next()?.to_owned(),
))
}
pub(crate) fn subject(root: &Path, commit: &str) -> Option<String> {
let out = git(root)
.args(["show", "-s", "--format=%h %s", commit])
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
#[cfg(test)]
mod tests {
const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
use super::*;
use std::path::PathBuf;
const FIXTURE_INIT: &[&[&str]] = &[
&["init", "-q", "."],
&["config", "user.email", "fixture@example.invalid"],
&["config", "user.name", "fixture"],
];
const FIXTURE_STEPS: &[(&str, &[&str])] = &[
("root.txt", &["commit", "-qm", "root"]),
("", &["checkout", "-qb", "side"]),
("side.txt", &["commit", "-qm", "side"]),
("", &["checkout", "-q", "-"]),
("main.txt", &["commit", "-qm", "mainline"]),
("", &["merge", "-q", "--no-ff", "side", "-m", "merge"]),
];
fn repo() -> PathBuf {
PathBuf::from(crate::testutil::repo_root())
}
#[test]
fn blob_reads_a_file_at_head() {
if !crate::testutil::dogfood() {
return;
}
let f = crate::testutil::crate_path("Cargo.toml");
let b = blob(&repo(), "HEAD", &f).unwrap_or_default();
assert!(b.contains("[package]"), "got: {b:.40}");
}
#[test]
fn a_missing_path_at_head_is_none() {
assert_eq!(blob(&repo(), "HEAD", "no/such/file.xyz"), None);
}
#[test]
fn count_at_head_is_positive() {
if !crate::testutil::dogfood() {
return;
}
assert!(
count_at(&repo(), "HEAD", "Cargo.toml", false).unwrap_or(0) > 0
);
}
#[test]
fn count_of_a_missing_path_is_none() {
assert_eq!(count_at(&repo(), "HEAD", "no/such.xyz", false), None);
}
#[test]
fn a_commit_changed_some_files() {
if !crate::testutil::dogfood() {
return;
}
assert!(!changed_in(&repo(), "HEAD").is_empty());
}
fn merge_fixture(name: &str) -> PathBuf {
let dir = fixture_dir(name);
for (file, args) in FIXTURE_STEPS {
if !file.is_empty() {
let w = std::fs::write(dir.join(file), "x\n");
assert!(w.is_ok(), "fixture write {file}");
assert!(fgit(&dir, &["add", "--", file]), "fixture add {file}");
}
assert!(fgit(&dir, args), "fixture step {args:?}");
}
dir
}
fn fixture_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("itok-gitref-{name}"));
assert!(dir.is_absolute(), "fixture path must be absolute: {dir:?}");
let _ = std::fs::remove_dir_all(&dir);
assert!(std::fs::create_dir_all(&dir).is_ok(), "fixture dir");
for args in FIXTURE_INIT {
assert!(fgit(&dir, args), "fixture needs a working `git`");
}
assert_own_repo(&dir);
dir
}
fn assert_own_repo(dir: &Path) {
let top =
PathBuf::from(fgit_out(dir, &["rev-parse", "--show-toplevel"]));
let (want, got) = (dir.canonicalize().ok(), top.canonicalize().ok());
assert!(
want.is_some() && want == got,
"fixture must be its OWN repo -- wanted {want:?}, git says \
{got:?}. An ambient GIT_DIR/GIT_WORK_TREE leaked past the \
scrub, and the commits would have gone into the repo under test."
);
}
fn fgit(dir: &Path, args: &[&str]) -> bool {
git(dir)
.args(args)
.output()
.is_ok_and(|o| o.status.success())
}
fn fgit_out(dir: &Path, args: &[&str]) -> String {
git(dir)
.args(args)
.output()
.ok()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
.unwrap_or_default()
}
#[test]
fn a_merge_commit_reports_what_it_merged() {
let dir = merge_fixture("merge");
let changed = changed_in(&dir, "HEAD");
assert_eq!(
changed,
vec!["side.txt".to_owned()],
"first-parent semantics: the merge brought in side.txt, and \
main.txt was already on the first parent"
);
}
#[test]
fn the_root_commit_reports_everything_it_added() {
let dir = merge_fixture("root");
let root = fgit_out(&dir, &["rev-list", "--max-parents=0", "HEAD"]);
assert!(!root.is_empty(), "fixture must have a root commit");
assert_eq!(changed_in(&dir, &root), vec!["root.txt".to_owned()]);
}
#[test]
fn an_ordinary_commit_is_unchanged_by_the_fix() {
let dir = merge_fixture("ordinary");
assert_eq!(
changed_in(&dir, "HEAD^1"),
vec!["main.txt".to_owned()],
"the mainline commit, diffed against its one parent"
);
}
#[test]
fn an_unresolvable_ref_is_empty_for_now() {
assert!(changed_in(&repo(), "no-such-ref-xyz").is_empty());
}
#[test]
fn a_range_lists_changed_files() {
if !crate::testutil::dogfood() {
return;
}
assert!(!changed_between(&repo(), EMPTY_TREE, "HEAD").is_empty());
}
#[test]
fn commits_lists_history() {
if !crate::testutil::dogfood() {
return;
}
let c = commits(&repo(), &["-n".to_owned(), "3".to_owned()]);
assert!(!c.is_empty());
assert!(c.iter().all(|(h, d, s)| {
!h.is_empty() && !d.is_empty() && !s.is_empty()
}));
}
#[test]
fn working_and_staged_listers_run() {
let _ = changed_working(&repo(), "HEAD");
let _ = staged(&repo());
}
#[test]
fn subject_has_a_hash_and_text() {
if !crate::testutil::dogfood() {
return;
}
let s = subject(&repo(), "HEAD").unwrap_or_default();
assert!(s.contains(' '), "hash + subject: {s:?}");
}
#[cfg(feature = "bpe")]
#[test]
fn bpe_tier_counts_a_blob() {
if !crate::testutil::dogfood() {
return;
}
assert!(count_at(&repo(), "HEAD", "Cargo.toml", true).unwrap_or(0) > 0);
}
}