use std::path::Path;
use std::process::Command;
pub struct Oracle {
pub program: String,
pub version: String,
}
pub fn pinned_version(repo: &Path) -> Option<String> {
if let Ok(v) = std::env::var("TEX_VERSION_EXPECT") {
return Some(v);
}
let bugs = std::fs::read_to_string(repo.join("BUGS.md")).ok()?;
bugs.lines()
.find_map(|l| l.split("measured against **tex ").nth(1))
.and_then(|rest| rest.split("**").next())
.map(str::to_string)
}
pub fn oracle(repo: &Path) -> Result<Oracle, String> {
let program = std::env::var("TEX_ORACLE").unwrap_or_else(|_| "tex".to_string());
let out = Command::new(&program)
.arg("--version")
.output()
.map_err(|_| format!("no `{program}' on PATH — the harness has no oracle"))?;
if !out.status.success() {
return Err(format!("`{program} --version' failed"));
}
let banner = String::from_utf8_lossy(&out.stdout);
let version = banner
.lines()
.next()
.and_then(|l| l.split("TeX ").nth(1))
.and_then(|v| v.split_whitespace().next())
.ok_or_else(|| format!("`{program} --version' did not report a TeX version"))?
.to_string();
match pinned_version(repo) {
Some(want) if want != version => Err(format!(
"oracle is tex {version}, but everything here was measured against {want}.\n\
A mismatched oracle reports a different divergence set, not an error.\n\
Set TEX_VERSION_EXPECT={version} to accept this deliberately."
)),
Some(_) => Ok(Oracle { program, version }),
None => Err("no `measured against **tex X.Y**' line in BUGS.md".to_string()),
}
}
pub fn messages_of(out: &str) -> String {
let Some(at) = out.find("(./") else {
return String::new();
};
let rest = &out[at + 3..];
let Some((_, after)) = rest.split_once(".tex") else {
return String::new();
};
let body = match after.rfind(')') {
Some(end) => &after[..end],
None => after,
};
body.replace('\n', "").trim().to_string()
}
pub fn reference(oracle: &Oracle, case: &Path) -> String {
let dir = std::env::temp_dir().join(format!("texrs-oracle-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let dst = dir.join("case.tex");
if std::fs::copy(case, &dst).is_err() {
return String::new();
}
let out = Command::new(&oracle.program)
.args(["-interaction=nonstopmode", "case.tex"])
.env("max_print_line", "8000")
.current_dir(&dir)
.output();
let text = out
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
.unwrap_or_default();
let _ = std::fs::remove_dir_all(&dir);
messages_of(&text)
}
pub fn subject(src: &str) -> String {
match crate::run_messages_tex(src) {
Ok(m) => m,
Err(e) => format!("ERROR: {}", e.0),
}
}
pub enum Verdict {
Parity,
Diverges { want: String, got: String },
Known,
Stale,
}
pub fn verdict(oracle: &Oracle, case: &Path, known: &[String]) -> Verdict {
let want = reference(oracle, case);
let src = std::fs::read_to_string(case).unwrap_or_default();
let got = subject(&src);
let name = case
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let listed = known.contains(&name);
match (want == got, listed) {
(true, false) => Verdict::Parity,
(true, true) => Verdict::Stale,
(false, true) => Verdict::Known,
(false, false) => Verdict::Diverges { want, got },
}
}
pub const FREEZE_SEP: &str = "#==# ";
pub fn freeze(oracle: &Oracle, cases: &[std::path::PathBuf]) -> String {
let mut out = format!(
"# Frozen output of tex {}, written by `cargo run --bin parity -- --freeze`.\n\
# One block per case in tests/cases; tests/parity.rs replays these with\n\
# no TeX installed. Regenerate when a case changes, and read the diff:\n\
# a changed block is a changed claim about what the reference engine does.\n",
oracle.version
);
for case in cases {
let name = case
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
out.push_str(&format!(
"{FREEZE_SEP}{name}\n{}\n",
reference(oracle, case)
));
}
out
}
pub fn frozen_path(repo: &Path, dir_name: &str) -> std::path::PathBuf {
repo.join("tests/data")
.join(format!("{dir_name}_expected.txt"))
}
pub fn thawed(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
for block in text.split(FREEZE_SEP).skip(1) {
let Some((name, body)) = block.split_once('\n') else {
continue;
};
out.push((
name.trim().to_string(),
body.strip_suffix('\n').unwrap_or(body).to_string(),
));
}
out
}
pub fn known_gaps(repo: &Path) -> Vec<String> {
std::fs::read_to_string(repo.join("tests/known_gaps.txt"))
.unwrap_or_default()
.lines()
.filter(|l| !l.trim_start().starts_with('#') && !l.trim().is_empty())
.filter_map(|l| l.split_whitespace().next().map(str::to_string))
.collect()
}
pub fn cases_in(dir: &Path) -> Vec<std::path::PathBuf> {
let mut v: Vec<std::path::PathBuf> = std::fs::read_dir(dir)
.map(|entries| {
entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|x| x == "tex"))
.collect()
})
.unwrap_or_default();
v.sort();
v
}