use std::fmt::Display;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::process::Command;
pub enum Need {
Docker,
Helper,
}
impl Need {
fn missing(&self) -> Option<&'static str> {
match self {
Need::Docker => {
let up = matches!(Command::new("docker").arg("info").output(), Ok(o) if o.status.success());
(!up).then_some("docker unavailable")
}
Need::Helper => {
use crate::devsbd::{Arch, hash};
hash(Arch::host()).is_none().then_some("no devsbd helper embedded")
}
}
}
}
pub fn gated<E: Display>(test: &str, needs: &[Need], body: impl FnOnce() -> Result<(), E>) {
if let Some(why) = needs.iter().find_map(Need::missing) {
return skip(test, why);
}
if let Err(why) = body() {
skip(test, &why.to_string());
}
}
pub fn with_cleanup<T>(cleanup: impl FnOnce(), body: impl FnOnce() -> T) -> T {
let result = catch_unwind(AssertUnwindSafe(body));
cleanup();
result.unwrap_or_else(|panic| resume_unwind(panic))
}
fn skip(test: &str, why: &str) {
if on_ci() {
panic!("{test}: {why}; environment-gated tests must never skip on CI (`CI` is set)");
}
eprintln!("skipping {test}: {why}");
}
fn on_ci() -> bool {
std::env::var("CI").is_ok_and(|v| !v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false"))
}