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 fn write_script(path: &Path, body: &str) -> Result<String, String> {
let named = |e: std::io::Error| format!("{}: {e}", path.display());
std::fs::write(path, body).map_err(named)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, PermissionsExt::from_mode(0o755))
.map_err(named)?;
}
let probe = || Command::new(path).arg("--sherd-probe").output().map(drop);
once_it_runs(probe, 100).map_err(named)?;
Ok(path.display().to_string())
}
fn once_it_runs(
mut probe: impl FnMut() -> std::io::Result<()>,
tries: u32,
) -> std::io::Result<()> {
let mut last = probe();
for _ in 1..tries {
match &last {
Err(e) if e.kind() == std::io::ErrorKind::ExecutableFileBusy => {
std::thread::sleep(std::time::Duration::from_millis(10));
last = probe();
}
_ => break,
}
}
last
}
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()
);
}
}
#[cfg(test)]
mod script_tests {
use super::once_it_runs;
use std::io::{Error, ErrorKind};
fn failing(
n: u32,
kind: ErrorKind,
) -> (
impl FnMut() -> std::io::Result<()>,
std::rc::Rc<std::cell::Cell<u32>>,
) {
let calls = std::rc::Rc::new(std::cell::Cell::new(0));
let seen = std::rc::Rc::clone(&calls);
let probe = move || {
seen.set(seen.get() + 1);
if seen.get() <= n {
Err(Error::from(kind))
} else {
Ok(())
}
};
(probe, calls)
}
#[test]
fn a_busy_file_is_retried_until_it_runs() {
let (probe, calls) = failing(2, ErrorKind::ExecutableFileBusy);
assert!(once_it_runs(probe, 100).is_ok());
assert_eq!(calls.get(), 3);
}
#[test]
fn a_file_busy_on_every_try_is_that_error() {
let (probe, calls) = failing(u32::MAX, ErrorKind::ExecutableFileBusy);
let err = once_it_runs(probe, 3).err().map(|e| e.kind());
assert_eq!(err, Some(ErrorKind::ExecutableFileBusy));
assert_eq!(calls.get(), 3);
}
#[test]
fn another_failure_returns_at_once() {
let (probe, calls) = failing(u32::MAX, ErrorKind::NotFound);
let err = once_it_runs(probe, 100).err().map(|e| e.kind());
assert_eq!(err, Some(ErrorKind::NotFound));
assert_eq!(calls.get(), 1);
}
}