use std::fmt::Display;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::process::Command;
pub enum Need {
Runtime,
DockerOnly,
Helper,
}
impl Need {
fn missing(&self) -> Option<&'static str> {
match self {
Need::Runtime => {
let up = matches!(runtime_cmd().arg("info").output(), Ok(o) if o.status.success());
(!up).then_some("container runtime unavailable")
}
Need::DockerOnly => None,
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>) {
let runtime = crate::runtime::backend().name();
if needs.iter().any(|n| matches!(n, Need::DockerOnly)) && runtime != "docker" {
return eprintln!("{test}: docker only, not applicable under {runtime}");
}
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 runtime_cmd() -> Command {
Command::new(crate::runtime::backend().bin())
}
#[cfg(unix)]
pub fn share_runtime_dirs(data: &std::path::Path, runtime: &std::path::Path) {
use std::os::unix::fs::{DirBuilderExt, symlink};
std::fs::create_dir_all(data).unwrap();
std::fs::DirBuilder::new().recursive(true).mode(0o700).create(runtime).unwrap();
if crate::runtime::backend().name() != "podman" {
return;
}
let out = runtime_cmd().args(["info", "--format", "{{.Store.GraphRoot}}\n{{.Store.RunRoot}}"]).output().unwrap();
assert!(out.status.success(), "podman info: {}", String::from_utf8_lossy(&out.stderr));
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let mut lines = text.lines().map(std::path::Path::new);
let (Some(graph), Some(run)) = (lines.next(), lines.next()) else { panic!("podman info: {text}") };
let (Some(store), Some(run_dir)) = (graph.parent(), run.parent()) else { panic!("podman info: {text}") };
symlink(store, data.join("containers")).unwrap();
for name in ["containers", "libpod"] {
symlink(run_dir.join(name), runtime.join(name)).unwrap();
}
if let Some(bus) = std::env::var_os("XDG_RUNTIME_DIR").map(|d| std::path::PathBuf::from(d).join("bus")).filter(|b| b.exists()) {
symlink(bus, runtime.join("bus")).unwrap();
}
}
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"))
}