use std::fmt::Write as _;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
const UPDATE: &str = "PARITY_UPDATE";
fn parity() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/parity")
}
fn directory() -> PathBuf {
parity().join("engine")
}
fn baselines() -> PathBuf {
parity().join("baseline")
}
fn updating() -> bool {
std::env::var_os(UPDATE).is_some_and(|value| !value.is_empty())
}
pub(crate) fn check(name: &str, actual: &str) -> Option<String> {
let path = directory().join(name);
let stored = match fs::read_to_string(&path) {
Ok(text) => Some(text),
Err(error) if error.kind() == ErrorKind::NotFound => None,
Err(error) => panic!("read {}: {error}", path.display()),
};
if stored.as_deref() == Some(actual) {
return None;
}
if updating() {
fs::create_dir_all(directory())
.unwrap_or_else(|error| panic!("create {}: {error}", directory().display()));
fs::write(&path, actual)
.unwrap_or_else(|error| panic!("write {}: {error}", path.display()));
return None;
}
Some(match stored {
None => format!("{name}: no engine file; write it with {UPDATE}=1"),
Some(stored) => format!(
"{name}: differs from its engine file\n{}",
diff(&stored, actual)
),
})
}
pub(crate) fn without_baseline() -> Vec<String> {
let Ok(entries) = fs::read_dir(directory()) else {
return Vec::new();
};
let mut reports = entries
.map(|entry| {
entry
.unwrap_or_else(|error| panic!("read {}: {error}", directory().display()))
.file_name()
})
.filter(|name| !baselines().join(name).is_file())
.map(|name| format!("{}: no baseline of the same name", name.to_string_lossy()))
.collect::<Vec<_>>();
reports.sort();
reports
}
fn diff(stored: &str, actual: &str) -> String {
let stored = stored.split('\n').collect::<Vec<_>>();
let actual = actual.split('\n').collect::<Vec<_>>();
let mut report = String::new();
for index in 0..stored.len().max(actual.len()) {
match (stored.get(index), actual.get(index)) {
(Some(left), Some(right)) if left == right => {
let _ = writeln!(report, " {left}");
}
(left, right) => {
if let Some(left) = left {
let _ = writeln!(report, "- {left}");
}
if let Some(right) = right {
let _ = writeln!(report, "+ {right}");
}
}
}
}
report
}