use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
static COUNTER: AtomicUsize = AtomicUsize::new(0);
pub struct TempRepo {
root: PathBuf,
repo: PathBuf,
}
impl TempRepo {
pub fn new(commits: usize) -> TempRepo {
let repo = Self::bare_dirs();
repo.git(&["init", "-q", "-b", "main"]);
repo.git(&["config", "user.name", "Test User"]);
repo.git(&["config", "user.email", "test@example.com"]);
repo.git(&["config", "commit.gpgsign", "false"]);
repo.git(&["config", "core.autocrlf", "false"]);
for i in 1..=commits {
repo.write(&format!("f{i}.txt"), &format!("{i}\n"));
repo.git(&["add", "."]);
let date = format!("{} +0000", 1_704_110_400 + i * 60);
let output = repo
.command(&repo.repo, &["commit", "-q", "-m", &format!("commit {i}")])
.env("GIT_AUTHOR_DATE", &date)
.env("GIT_COMMITTER_DATE", &date)
.output()
.expect("git not runnable");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
repo
}
pub fn outside() -> TempRepo {
Self::bare_dirs()
}
fn bare_dirs() -> TempRepo {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos());
let temp = real_path(&std::env::temp_dir());
let root = temp.join(format!("gct-ut-{}-{n}-{nanos}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let repo = root.join("repo");
std::fs::create_dir_all(root.join("home")).unwrap();
std::fs::create_dir_all(&repo).unwrap();
std::fs::write(root.join("gitconfig"), "").unwrap();
TempRepo { root, repo }
}
pub fn with_remote(self) -> TempRepo {
let remote = self.root.join("remote.git");
let output = self
.command(
&self.root,
&["init", "-q", "--bare", "-b", "main", "remote.git"],
)
.output()
.expect("git not runnable");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
self.git(&["remote", "add", "origin", &remote.to_string_lossy()]);
if !self.git(&["rev-list", "-n1", "--all"]).is_empty() {
self.git(&["push", "-q", "-u", "origin", "main"]);
}
self
}
pub fn path(&self) -> &Path {
&self.repo
}
pub fn remote_path(&self) -> PathBuf {
self.root.join("remote.git")
}
pub fn write(&self, rel: &str, content: &str) {
let path = self.repo.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(path, content).unwrap();
}
pub fn git(&self, args: &[&str]) -> String {
let output = self
.command(&self.repo, args)
.output()
.expect("git not runnable");
assert!(
output.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout)
.trim_end()
.to_string()
}
pub fn run<T>(&self, f: impl FnOnce() -> T) -> T {
crate::git::with_ctx(&self.repo, self.env(), f)
}
pub fn env(&self) -> Vec<(String, String)> {
let home = self.root.join("home").to_string_lossy().into_owned();
vec![
("HOME".into(), home.clone()),
("USERPROFILE".into(), home.clone()),
("XDG_CONFIG_HOME".into(), format!("{home}/.config")),
("GIT_CONFIG_NOSYSTEM".into(), "1".into()),
(
"GIT_CONFIG_GLOBAL".into(),
self.root.join("gitconfig").to_string_lossy().into_owned(),
),
(
"GIT_CEILING_DIRECTORIES".into(),
self.root.to_string_lossy().into_owned(),
),
("GIT_TERMINAL_PROMPT".into(), "0".into()),
]
}
fn command(&self, dir: &Path, args: &[&str]) -> Command {
let mut command = Command::new("git");
command.args(args).current_dir(dir).envs(self.env());
command
}
}
fn real_path(dir: &Path) -> PathBuf {
match std::fs::canonicalize(dir) {
Ok(path) => strip_verbatim(path),
Err(_) => dir.to_path_buf(),
}
}
fn strip_verbatim(path: PathBuf) -> PathBuf {
let text = path.to_string_lossy();
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
PathBuf::from(format!(r"\\{rest}"))
} else if let Some(rest) = text.strip_prefix(r"\\?\") {
PathBuf::from(rest)
} else {
path
}
}
impl Drop for TempRepo {
fn drop(&mut self) {
for attempt in 0..5 {
if std::fs::remove_dir_all(&self.root).is_ok() || !self.root.exists() {
return;
}
make_writable(&self.root);
std::thread::sleep(std::time::Duration::from_millis(20 * (attempt + 1)));
}
if std::fs::remove_dir_all(&self.root).is_err() && self.root.exists() {
eprintln!("testutil: could not delete {}", self.root.display());
}
}
}
fn make_writable(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
make_writable(&path);
} else if let Ok(meta) = entry.metadata() {
let mut perms = meta.permissions();
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
let _ = std::fs::set_permissions(&path, perms);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn temp_repo_basics() {
let root;
{
let repo = TempRepo::new(3).with_remote();
root = repo.root.clone();
assert_eq!(repo.git(&["rev-list", "--count", "HEAD"]), "3");
assert_eq!(repo.git(&["log", "-1", "--format=%s"]), "commit 3");
assert_eq!(
repo.git(&["rev-parse", "--abbrev-ref", "@{u}"]),
"origin/main"
);
assert!(repo.remote_path().is_dir());
let count = repo.run(|| crate::git::run(&["rev-list", "--count", "HEAD"]).unwrap());
assert_eq!(count, "3");
let again = TempRepo::new(3);
assert_eq!(
again.git(&["rev-parse", "HEAD"]),
repo.git(&["rev-parse", "HEAD"])
);
}
assert!(!root.exists());
let empty = TempRepo::new(0);
assert!(empty.git(&["rev-list", "-n1", "--all"]).is_empty());
}
#[test]
fn outside_is_never_inside_a_repo() {
let outside = TempRepo::outside();
let root = outside.root.to_string_lossy().into_owned();
assert!(!root.starts_with(r"\\?\"), "{root}");
assert_eq!(
outside.root,
real_path(&outside.root),
"already the long, real path"
);
assert!(!outside.run(crate::repo_state::in_repo));
}
#[test]
fn verbatim_prefix_is_stripped() {
let cases = [
(r"\\?\C:\Users\x", r"C:\Users\x"),
(r"\\?\UNC\server\share\d", r"\\server\share\d"),
("/tmp/plain", "/tmp/plain"),
];
for (input, expected) in cases {
assert_eq!(
strip_verbatim(PathBuf::from(input)),
PathBuf::from(expected)
);
}
}
}