use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};
use super::SnapshotError;
use super::variant::theme_name;
use crate::testing::matrix::Theme;
pub const DIR: &str = "semantic-themes";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Disagreement {
pub snapshot: PathBuf,
pub yaml: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct RecordKey {
parts: Vec<String>,
}
fn safe(text: &str) -> String {
text.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'_'
}
})
.collect()
}
pub(crate) fn without_theme(test: &str) -> Vec<String> {
let mut parts: Vec<String> = test.split("::").map(str::to_owned).collect();
let Some(last) = parts.pop() else {
return parts;
};
let kept: Vec<&str> = last
.split('_')
.filter(|token| !matches!(*token, "light" | "dark"))
.collect();
if !kept.is_empty() {
parts.push(kept.join("_"));
}
parts
}
impl RecordKey {
pub(crate) fn new(crate_name: &str, test: &str, name: &str, suffix: &str) -> Self {
let mut parts = vec![safe(crate_name)];
parts.extend(without_theme(test).iter().map(|part| safe(part)));
let stem = if suffix.is_empty() {
safe(name)
} else {
format!("{}@{}", safe(name), safe(suffix))
};
parts.push(stem);
Self { parts }
}
fn dir(&self, out_dir: &Path) -> PathBuf {
let mut dir = out_dir.join(DIR);
dir.extend(&self.parts);
dir
}
}
type Seen = BTreeMap<(String, RecordKey), BTreeMap<&'static str, String>>;
fn seen() -> std::sync::MutexGuard<'static, Seen> {
static SEEN: Mutex<Seen> = Mutex::new(BTreeMap::new());
SEEN.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn check_within_test(
thread: &str,
key: &RecordKey,
display_name: &str,
theme: Theme,
yaml: &str,
) -> Result<(), SnapshotError> {
let theme = theme_name(theme);
let mut seen = seen();
let entry = seen.entry((thread.to_owned(), key.clone())).or_default();
if let Some((other, other_yaml)) = entry
.iter()
.find(|(other, other_yaml)| **other != theme && other_yaml.as_str() != yaml)
{
return Err(SnapshotError::ThemesDisagree {
name: display_name.to_owned(),
theme,
yaml: yaml.to_owned(),
other,
other_yaml: other_yaml.clone(),
});
}
entry.insert(theme, yaml.to_owned());
Ok(())
}
pub(crate) fn record(
out_dir: &Path,
key: &RecordKey,
theme: Theme,
yaml: &str,
) -> std::io::Result<()> {
let dir = key.dir(out_dir);
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join(format!("{}.yaml", theme_name(theme))), yaml)
}
#[must_use]
pub fn compare(records: impl IntoIterator<Item = (PathBuf, String, String)>) -> Vec<Disagreement> {
let mut by_snapshot: BTreeMap<PathBuf, BTreeMap<String, String>> = BTreeMap::new();
for (snapshot, theme, yaml) in records {
by_snapshot.entry(snapshot).or_default().insert(theme, yaml);
}
by_snapshot
.into_iter()
.filter(|(_, yaml)| {
let mut texts = yaml.values();
texts
.next()
.is_some_and(|first| texts.any(|other| other != first))
})
.map(|(snapshot, yaml)| Disagreement { snapshot, yaml })
.collect()
}
fn collect(
root: &Path,
dir: &Path,
out: &mut Vec<(PathBuf, String, String)>,
) -> std::io::Result<()> {
let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::io::Result<_>>()?;
entries.sort();
for path in entries {
if path.is_dir() {
collect(root, &path, out)?;
continue;
}
if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
continue;
}
let (Some(theme), Some(parent)) = (
path.file_stem().and_then(|s| s.to_str()),
path.parent().and_then(|p| p.strip_prefix(root).ok()),
) else {
continue;
};
out.push((
parent.to_path_buf(),
theme.to_owned(),
std::fs::read_to_string(&path)?,
));
}
Ok(())
}
pub fn disagreements(out_dir: &Path) -> std::io::Result<Vec<Disagreement>> {
let root = out_dir.join(DIR);
if !root.exists() {
return Ok(Vec::new());
}
let mut records = Vec::new();
collect(&root, &root, &mut records)?;
Ok(compare(records))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::snapshot::fonts::Fnv;
#[test]
fn theme_names_leave_the_test_path() {
assert_eq!(
without_theme("ui::board::dark_phone"),
["ui", "board", "phone"]
);
assert_eq!(
without_theme("ui::board::light_phone"),
["ui", "board", "phone"]
);
assert_eq!(without_theme("ui::board::dark"), ["ui", "board"]);
assert_eq!(without_theme("ui::darkness"), ["ui", "darkness"]);
}
#[test]
fn keys_are_file_safe_and_ignore_the_theme() {
let dark = RecordKey::new("app", "ui::t::dark", "role=list[name=\"Items\"]", "phone");
let light = RecordKey::new("app", "ui::t::light", "role=list[name=\"Items\"]", "phone");
assert_eq!(dark, light);
assert_eq!(
dark.dir(Path::new("/out")),
PathBuf::from("/out/semantic-themes/app/ui/t/role_list_name__Items__@phone")
);
}
#[test]
fn only_snapshots_whose_themes_differ_are_reported() {
let records = vec![
(PathBuf::from("a"), "light".to_owned(), "- list".to_owned()),
(PathBuf::from("a"), "dark".to_owned(), "- list".to_owned()),
(PathBuf::from("b"), "light".to_owned(), "- list".to_owned()),
(
PathBuf::from("b"),
"dark".to_owned(),
"- list \"Dark\"".to_owned(),
),
(
PathBuf::from("c"),
"dark".to_owned(),
"- only one".to_owned(),
),
];
let found = compare(records);
assert_eq!(found.len(), 1);
assert_eq!(found[0].snapshot, PathBuf::from("b"));
assert_eq!(found[0].yaml.len(), 2);
}
#[test]
fn a_second_harness_in_the_same_test_is_compared_at_once() {
let key = RecordKey::new("app", "within::test", "list", "");
let thread = "themes::tests::a_second_harness_in_the_same_test_is_compared_at_once";
check_within_test(thread, &key, "list", Theme::Light, "- list").unwrap();
check_within_test(thread, &key, "list", Theme::Light, "- list").unwrap();
let error =
check_within_test(thread, &key, "list", Theme::Dark, "- list \"x\"").unwrap_err();
let text = error.to_string();
assert!(text.contains("per_theme(true)"), "{text}");
assert!(text.contains("light") && text.contains("dark"), "{text}");
check_within_test("another::test", &key, "list", Theme::Dark, "- list \"x\"").unwrap();
}
#[test]
fn records_written_by_two_tests_are_compared_after_the_run() -> std::io::Result<()> {
let out = std::env::temp_dir().join(format!(
"icedwright-themes-{}",
Fnv::of(b"records_written_by_two_tests_are_compared_after_the_run")
));
if out.exists() {
std::fs::remove_dir_all(&out)?;
}
let key = RecordKey::new("app", "ui::board::dark", "items", "");
record(&out, &key, Theme::Dark, "- list \"Dark\"")?;
let other = RecordKey::new("app", "ui::board::light", "items", "");
record(&out, &other, Theme::Light, "- list")?;
let found = disagreements(&out)?;
std::fs::remove_dir_all(&out)?;
assert_eq!(found.len(), 1);
assert_eq!(found[0].snapshot, PathBuf::from("app/ui/board/items"));
Ok(())
}
}