use std::path::{Path, PathBuf};
use std::process::Command;
pub(crate) fn run(root: &Path, args: &[&str]) -> Option<String> {
git(root, args)
}
fn git(root: &Path, args: &[&str]) -> Option<String> {
let output = Command::new("git")
.arg("-C")
.arg(root)
.args(args)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
}
#[must_use]
pub fn is_repo(root: &Path) -> bool {
git(root, &["rev-parse", "--is-inside-work-tree"]).is_some_and(|s| s.trim() == "true")
}
#[must_use]
pub fn resolve_commit(root: &Path, reference: &str) -> Option<String> {
let spec = format!("{reference}^{{commit}}");
git(root, &["rev-parse", "--verify", "--quiet", &spec]).and_then(|s| {
let sha = s.trim().to_string();
(!sha.is_empty()).then_some(sha)
})
}
#[must_use]
pub fn head_commit(root: &Path) -> Option<String> {
resolve_commit(root, "HEAD")
}
#[must_use]
pub fn changed_paths(root: &Path, from: &str, to: &str) -> Vec<PathBuf> {
let range = format!("{from}..{to}");
let Some(out) = git(root, &["diff", "--name-only", &range]) else {
return Vec::new();
};
out.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(PathBuf::from)
.collect()
}
#[must_use]
pub fn list_files_at(root: &Path, reference: &str) -> Vec<PathBuf> {
let spec = format!("{reference}^{{tree}}");
let Some(out) = git(root, &["ls-tree", "-r", "--name-only", "-z", &spec]) else {
return Vec::new();
};
out.split('\0')
.filter(|l| !l.is_empty())
.map(PathBuf::from)
.collect()
}
#[must_use]
pub fn read_blob_at(root: &Path, reference: &str, path: &Path) -> Option<String> {
let spec = format!("{reference}:{}", path.display());
git(root, &["show", &spec])
}
#[must_use]
pub fn origin_repo_name(root: &Path) -> Option<String> {
git(root, &["remote", "get-url", "origin"]).and_then(|s| repo_name_from_url(s.trim()))
}
#[must_use]
pub fn repo_root_containing(path: &Path) -> Option<PathBuf> {
let mut dir = if path.is_dir() {
Some(path)
} else {
path.parent()
};
while let Some(d) = dir {
if d.is_dir() {
break;
}
dir = d.parent();
}
let top = git(dir?, &["rev-parse", "--show-toplevel"])?;
let top = top.trim();
(!top.is_empty()).then(|| PathBuf::from(top))
}
fn repo_name_from_url(url: &str) -> Option<String> {
let trimmed = url.trim_end_matches('/');
let base = match trimmed.rsplit('/').next() {
Some(seg) if seg != trimmed => seg,
_ => trimmed.rsplit(':').next().unwrap_or(trimmed),
};
let name = base.strip_suffix(".git").unwrap_or(base);
(!name.is_empty()).then(|| name.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
fn init_repo(dir: &Path) -> bool {
let run = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.is_ok_and(|o| o.status.success())
};
if !run(&["init", "-q"]) {
return false; }
run(&["config", "user.email", "t@t.test"]);
run(&["config", "user.name", "t"]);
std::fs::write(dir.join("a.txt"), "one\n").unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "first"])
}
#[test]
fn a_files_repo_is_its_own_not_the_callers() {
let session = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
if !init_repo(session.path()) || !init_repo(other.path()) {
return; }
let other_root = repo_root_containing(&other.path().join("a.txt")).expect("in a repo");
let _cwd_is_elsewhere = session.path();
let resolved = repo_root_containing(&other.path().join("a.txt")).expect("in a repo");
assert_eq!(resolved, other_root);
assert_ne!(
resolved,
repo_root_containing(&session.path().join("a.txt")).expect("in a repo"),
"two distinct repos must not collapse to one root"
);
let unborn = other.path().join("deep/er/still/new.md");
assert_eq!(
repo_root_containing(&unborn).expect("unborn file still has a repo"),
other_root
);
}
#[test]
fn a_path_outside_any_repo_has_no_root() {
let bare = tempfile::tempdir().unwrap();
if repo_root_containing(bare.path()).is_some() {
return; }
assert_eq!(repo_root_containing(&bare.path().join("x.md")), None);
}
#[test]
fn resolves_head_and_detects_repo() {
let dir = tempfile::tempdir().unwrap();
if !init_repo(dir.path()) {
return; }
assert!(is_repo(dir.path()));
let head = head_commit(dir.path()).expect("HEAD resolves");
assert_eq!(head.len(), 40, "full SHA");
assert!(resolve_commit(dir.path(), "no-such-ref").is_none());
}
#[test]
fn diffs_changed_paths_between_commits() {
let dir = tempfile::tempdir().unwrap();
if !init_repo(dir.path()) {
return; }
let first = head_commit(dir.path()).unwrap();
std::fs::write(dir.path().join("b.txt"), "two\n").unwrap();
let run = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(dir.path())
.args(args)
.output()
.unwrap();
};
run(&["add", "."]);
run(&["commit", "-q", "-m", "second"]);
let second = head_commit(dir.path()).unwrap();
let changed = changed_paths(dir.path(), &first, &second);
assert_eq!(changed, vec![PathBuf::from("b.txt")]);
}
#[test]
fn degrades_gracefully_outside_repo() {
let dir = tempfile::tempdir().unwrap();
assert!(!is_repo(dir.path()));
assert!(head_commit(dir.path()).is_none());
assert!(resolve_commit(dir.path(), "main").is_none());
assert!(changed_paths(dir.path(), "a", "b").is_empty());
assert!(list_files_at(dir.path(), "HEAD").is_empty());
assert!(read_blob_at(dir.path(), "HEAD", Path::new("a.txt")).is_none());
}
#[test]
fn reads_tree_content_at_a_ref() {
let dir = tempfile::tempdir().unwrap();
if !init_repo(dir.path()) {
return; }
let first = head_commit(dir.path()).unwrap();
std::fs::write(dir.path().join("a.txt"), "changed\n").unwrap();
std::fs::write(dir.path().join("b.txt"), "two\n").unwrap();
let run = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(dir.path())
.args(args)
.output()
.unwrap();
};
run(&["add", "."]);
run(&["commit", "-q", "-m", "second"]);
let files = list_files_at(dir.path(), &first);
assert_eq!(files, vec![PathBuf::from("a.txt")]);
assert_eq!(
read_blob_at(dir.path(), &first, Path::new("a.txt")).as_deref(),
Some("one\n"),
"reads the historical blob, not the working tree"
);
assert!(read_blob_at(dir.path(), &first, Path::new("b.txt")).is_none());
let head_files = list_files_at(dir.path(), "HEAD");
assert!(head_files.contains(&PathBuf::from("a.txt")));
assert!(head_files.contains(&PathBuf::from("b.txt")));
assert_eq!(
read_blob_at(dir.path(), "HEAD", Path::new("a.txt")).as_deref(),
Some("changed\n")
);
}
#[test]
fn repo_name_from_every_remote_url_shape() {
for (url, want) in [
("https://github.com/scbrown/hank.git", "hank"),
("https://example.com/group/sub/proj", "proj"),
("git@github.com:scbrown/hank.git", "hank"),
("ssh://git.example/owner/thing.git", "thing"),
("ssh://git.example/owner/thing/", "thing"),
("host:solo.git", "solo"),
("/home/someone/checkouts/hank", "hank"),
] {
assert_eq!(repo_name_from_url(url).as_deref(), Some(want), "url: {url}");
}
assert_eq!(repo_name_from_url(""), None);
assert_eq!(repo_name_from_url(".git"), None);
}
#[test]
fn origin_repo_name_reads_the_remote_not_the_dir() {
let dir = tempfile::tempdir().unwrap();
if !init_repo(dir.path()) {
return; }
assert_eq!(origin_repo_name(dir.path()), None);
Command::new("git")
.args([
"remote",
"add",
"origin",
"https://example.com/owner/realname.git",
])
.current_dir(dir.path())
.status()
.unwrap();
assert_eq!(origin_repo_name(dir.path()).as_deref(), Some("realname"));
}
}