use std::path::{Path, PathBuf};
use crate::registry::{non_empty, system_data_dirs, user_data_dir};
use crate::resolved_path;
include!(concat!(env!("OUT_DIR"), "/embedded_fixtures.rs"));
const INSTALL_SUBDIR: &str = "stegobench";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
Explicit(PathBuf),
WorkingDirectory(PathBuf),
BesideExecutable(PathBuf),
UserData(PathBuf),
SystemData(PathBuf),
BuiltIn,
}
impl Source {
pub fn tag(&self) -> &'static str {
match self {
Source::Explicit(_) => "explicit",
Source::WorkingDirectory(_) => "working-directory",
Source::BesideExecutable(_) => "beside-executable",
Source::UserData(_) => "user-data",
Source::SystemData(_) => "system-data",
Source::BuiltIn => "built-in",
}
}
}
#[derive(Debug)]
pub struct Fixtures {
source: Source,
dir: PathBuf,
_scratch: Option<tempfile::TempDir>,
}
impl Fixtures {
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn source(&self) -> &Source {
&self.source
}
pub fn line(&self) -> String {
match &self.source {
Source::BuiltIn => "fixtures built in".to_string(),
_ => format!("fixtures {}", resolved_path(&self.dir).display()),
}
}
}
#[derive(Debug)]
pub enum Error {
NamedButMissing(PathBuf),
CouldNotUnpack(String),
NoneAnywhere,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::NamedButMissing(p) => write!(
f,
"no fixture directory at {}.\n\
It was named with --fixtures or STEGOBENCH_FIXTURES, so nothing \
else was tried: a typo that quietly self-tested against a \
different set of images would not show up in the result.",
p.display()
),
Error::CouldNotUnpack(why) => write!(
f,
"the fixtures compiled into this binary could not be unpacked: {why}.\n\
Self-tests need the images on disk. Point --fixtures at a copy, \
or run `stegobench doctor --no-selftest` to skip the checks."
),
Error::NoneAnywhere => write!(
f,
"this build carries no self-test fixtures and none were found on disk.\n\
Point --fixtures at the `fixtures` directory from the source tree, \
or run `stegobench doctor --no-selftest`."
),
}
}
}
type Candidate = (PathBuf, fn(PathBuf) -> Source);
pub fn search_path() -> Vec<Candidate> {
let mut out: Vec<Candidate> = vec![(PathBuf::from("fixtures"), Source::WorkingDirectory)];
for dir in beside_executable() {
out.push((dir, Source::BesideExecutable));
}
if let Some(d) = user_data_dir() {
out.push((d.join(INSTALL_SUBDIR).join("fixtures"), Source::UserData));
}
for d in system_data_dirs() {
out.push((d.join(INSTALL_SUBDIR).join("fixtures"), Source::SystemData));
}
out
}
fn beside_executable() -> Vec<PathBuf> {
let Ok(exe) = std::env::current_exe() else {
return Vec::new();
};
let Some(dir) = exe.parent() else {
return Vec::new();
};
vec![
dir.join("fixtures"),
dir.join("..")
.join("share")
.join(INSTALL_SUBDIR)
.join("fixtures"),
]
}
pub fn resolve(explicit: Option<&Path>) -> Result<Fixtures, Error> {
resolve_with(explicit, non_empty("STEGOBENCH_FIXTURES").as_deref())
}
pub fn resolve_with(explicit: Option<&Path>, from_env: Option<&str>) -> Result<Fixtures, Error> {
let named = explicit
.map(PathBuf::from)
.or_else(|| from_env.filter(|v| !v.is_empty()).map(PathBuf::from));
if let Some(p) = named {
if p.is_dir() {
return Ok(Fixtures {
source: Source::Explicit(p.clone()),
dir: p,
_scratch: None,
});
}
return Err(Error::NamedButMissing(p));
}
for (p, make) in search_path() {
if !p.is_dir() {
continue;
}
return Ok(Fixtures {
source: make(p.clone()),
dir: p,
_scratch: None,
});
}
unpack_built_in()
}
fn unpack_built_in() -> Result<Fixtures, Error> {
if EMBEDDED_FIXTURES.is_empty() {
return Err(Error::NoneAnywhere);
}
let scratch = tempfile::Builder::new()
.prefix("stegobench-fixtures-")
.tempdir()
.map_err(|e| Error::CouldNotUnpack(e.to_string()))?;
for (name, bytes) in EMBEDDED_FIXTURES {
if name.contains('/') || name.contains('\\') || name.contains("..") {
return Err(Error::CouldNotUnpack(format!(
"built-in fixture {name:?} is not a plain file name"
)));
}
std::fs::write(scratch.path().join(name), bytes)
.map_err(|e| Error::CouldNotUnpack(format!("writing {name}: {e}")))?;
}
Ok(Fixtures {
source: Source::BuiltIn,
dir: scratch.path().to_path_buf(),
_scratch: Some(scratch),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_binary_carries_its_own_fixtures() {
assert!(
!EMBEDDED_FIXTURES.is_empty(),
"no fixtures were compiled in; build.rs found none beside the workspace"
);
}
#[test]
fn every_built_in_fixture_has_a_plain_name_and_some_bytes() {
for (name, bytes) in EMBEDDED_FIXTURES {
assert!(!name.contains('/'), "{name} carries a separator");
assert!(!name.contains(".."), "{name} carries a parent reference");
assert!(!bytes.is_empty(), "{name} is empty");
}
}
#[test]
fn unpacking_writes_every_image_and_removes_them_afterwards() {
let dir;
{
let f = unpack_built_in().expect("the built-in copy unpacks");
assert_eq!(f.source(), &Source::BuiltIn);
dir = f.dir().to_path_buf();
for (name, bytes) in EMBEDDED_FIXTURES {
let written = std::fs::read(dir.join(name)).expect("fixture written");
assert_eq!(&written, bytes, "{name} round trips byte for byte");
}
}
assert!(!dir.exists(), "the scratch directory outlived its handle");
}
#[test]
fn a_named_directory_that_is_absent_is_an_error_not_a_fall_through() {
let missing = Path::new("definitely-not-a-fixture-directory-xyzzy");
match resolve(Some(missing)) {
Err(Error::NamedButMissing(p)) => assert_eq!(p, missing),
other => panic!("expected NamedButMissing, got {other:?}"),
}
}
#[test]
fn a_named_directory_that_exists_is_taken_as_given() {
let tmp = tempfile::tempdir().expect("scratch");
let f = resolve(Some(tmp.path())).expect("an existing directory resolves");
assert_eq!(f.dir(), tmp.path());
assert_eq!(f.source().tag(), "explicit");
}
#[test]
fn the_search_path_starts_at_the_checkout_and_ends_at_the_system() {
let path = search_path();
assert_eq!(path.first().unwrap().0, Path::new("fixtures"));
assert!(
path.len() > 1,
"nothing but the working directory was searched"
);
}
#[test]
fn the_environment_names_a_fixture_directory_only_when_it_has_something_in_it() {
let tmp = tempfile::tempdir().expect("scratch");
let from_env = tmp.path().join("from-env");
let from_flag = tmp.path().join("from-flag");
for dir in [&from_env, &from_flag] {
std::fs::create_dir_all(dir).expect("dirs");
}
let f = resolve_with(None, Some(&from_env.display().to_string())).expect("resolves");
assert_eq!(f.dir(), from_env);
assert_eq!(f.source().tag(), "explicit");
let f = resolve_with(Some(&from_flag), Some(&from_env.display().to_string()))
.expect("resolves");
assert_eq!(
f.dir(),
from_flag,
"the environment overrode an explicit --fixtures"
);
let missing = resolve_with(None, Some(&tmp.path().join("nope").display().to_string()));
assert!(
matches!(missing, Err(Error::NamedButMissing(_))),
"a named fixture directory that is absent fell through"
);
resolve_with(None, Some("")).expect("an empty variable is ignored");
}
#[test]
fn the_line_names_the_directory_or_says_built_in() {
let f = unpack_built_in().expect("unpacks");
assert_eq!(f.line(), "fixtures built in");
let tmp = tempfile::tempdir().expect("scratch");
let g = resolve(Some(tmp.path())).expect("resolves");
assert!(g.line().starts_with("fixtures "));
assert!(g.line().contains(&tmp.path().display().to_string()));
}
#[test]
fn a_relative_directory_is_printed_as_a_place_a_reader_can_go() {
let f = Fixtures {
source: Source::WorkingDirectory(PathBuf::from("fixtures")),
dir: PathBuf::from("fixtures"),
_scratch: None,
};
let line = f.line();
assert_ne!(line, "fixtures fixtures", "{line}");
let path = line.strip_prefix("fixtures ").expect("the usual shape");
assert!(Path::new(path).is_absolute(), "{line}");
}
}