pub fn dogfood(body: impl FnOnce()) {
if std::env::var_os("SHERD_DOGFOOD").is_some() {
body();
}
}
use std::path::{Path, PathBuf};
use std::process::Command;
pub struct TestRepo {
pub root: PathBuf,
}
impl Drop for TestRepo {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
impl TestRepo {
pub fn new(tag: &str) -> Result<Self, String> {
use std::sync::atomic::{AtomicUsize, Ordering};
static N: AtomicUsize = AtomicUsize::new(0);
let n = N.fetch_add(1, Ordering::Relaxed);
let root = std::env::temp_dir()
.join(format!("sherd-repo-{tag}-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).map_err(|e| format!("mkdir: {e}"))?;
let r = Self { root };
r.git(&["init", "-q", "-b", "main"])?;
r.git(&["config", "user.email", "t@example.invalid"])?;
r.git(&["config", "user.name", "test"])?;
r.write("SPEC.md", "# SPEC\n\n## \u{a7}G GOAL\n\nfixture\n")?;
r.commit("root")?;
Ok(r)
}
fn command(&self, args: &[&str]) -> Command {
crate::git::at(&self.root, args)
}
pub fn git(&self, args: &[&str]) -> Result<String, String> {
let out = self
.command(args)
.output()
.map_err(|e| format!("git {args:?}: {e}"))?;
if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
pub fn write(&self, rel: &str, body: &str) -> Result<(), String> {
let p = self.root.join(rel);
if let Some(d) = p.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("mkdir: {e}"))?;
}
std::fs::write(&p, body).map_err(|e| format!("write {rel}: {e}"))
}
pub fn commit(&self, msg: &str) -> Result<(), String> {
self.git(&["add", "-A"])?;
self.git(&["commit", "-q", "--no-verify", "-m", msg])
.map(|_| ())
}
#[must_use]
pub fn path(&self) -> &Path {
&self.root
}
}
#[cfg(test)]
mod tests {
use super::TestRepo;
#[test]
fn the_fixture_refuses_the_git_environment_a_hook_exports() {
let Ok(r) = TestRepo::new("env") else {
unreachable!("the fixture builds")
};
let c = r.command(&["status"]);
for k in crate::git::INHERITED {
let removed = c
.get_envs()
.any(|(name, value)| name == k && value.is_none());
assert!(
removed,
"`{k}` is still inherited -- an exported one aims this \
fixture's git at the repository the suite is running in"
);
}
}
#[test]
fn the_fixture_commits_land_in_its_own_repo() {
let Ok(r) = TestRepo::new("own") else {
unreachable!("the fixture builds")
};
let Ok(dir) = r.git(&["rev-parse", "--absolute-git-dir"]) else {
unreachable!("the fixture is a repository")
};
let Ok(root) = std::fs::canonicalize(&r.root) else {
unreachable!("the fixture root exists")
};
let Ok(dir) = std::fs::canonicalize(&dir) else {
unreachable!("the git dir exists")
};
assert!(
dir.starts_with(&root),
"the fixture's git dir is {}, outside its own root {}",
dir.display(),
root.display()
);
}
}