use std::path::PathBuf;
use std::process::Command;
pub fn ensure_test_plugin_built() -> PathBuf {
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let output = Command::new(&cargo)
.args(["build", "--example", "test_plugin"])
.output()
.unwrap_or_else(|e| panic!("failed to spawn `{cargo:?} build --example test_plugin`: {e}"));
if !output.status.success() {
panic!(
"`cargo build --example test_plugin` failed (exit {:?}):\n\
--- stdout ---\n{}\n\
--- stderr ---\n{}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
find_test_plugin_artifact().unwrap_or_else(|| {
panic!(
"test_plugin artifact not found after a successful \
`cargo build --example test_plugin`; verify the example declares \
`crate-type = [\"cdylib\"]` in Cargo.toml and that the target dir \
layout matches the search roots probed in `find_test_plugin_artifact`"
)
})
}
fn find_test_plugin_artifact() -> Option<PathBuf> {
let (prefix, suffix) = platform_prefix_suffix();
let file_name = format!("{prefix}test_plugin{suffix}");
let mut roots = Vec::new();
if let Some(td) = std::env::var_os("CARGO_TARGET_DIR") {
roots.push(PathBuf::from(td));
}
if let Some(md) = std::env::var_os("CARGO_MANIFEST_DIR") {
roots.push(PathBuf::from(md).join("target"));
}
roots.push(PathBuf::from("target"));
let profiles: [&str; 2] = if cfg!(debug_assertions) {
["debug", "release"]
} else {
["release", "debug"]
};
for root in &roots {
for profile in profiles {
let candidate = root.join(profile).join("examples").join(&file_name);
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
fn platform_prefix_suffix() -> (&'static str, &'static str) {
if cfg!(target_os = "windows") {
("", ".dll")
} else if cfg!(target_os = "macos") {
("lib", ".dylib")
} else {
("lib", ".so")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn platform_prefix_suffix_matches_cargo_convention() {
let (prefix, suffix) = platform_prefix_suffix();
if cfg!(target_os = "windows") {
assert_eq!((prefix, suffix), ("", ".dll"));
} else if cfg!(target_os = "macos") {
assert_eq!((prefix, suffix), ("lib", ".dylib"));
} else {
assert_eq!((prefix, suffix), ("lib", ".so"));
}
}
}