use std::io;
use std::path::{Path, PathBuf};
pub use super::baseline::PendingRecord;
use super::baseline::file_hash;
#[derive(Debug, Clone, PartialEq)]
pub struct PendingSnapshot {
pub dir: PathBuf,
pub record: PendingRecord,
}
impl PendingSnapshot {
#[must_use]
pub fn actual(&self) -> PathBuf {
self.dir.join("actual.png")
}
#[must_use]
pub fn expected(&self) -> PathBuf {
self.dir.join("expected.png")
}
#[must_use]
pub fn diff(&self) -> PathBuf {
self.dir.join("diff.png")
}
}
#[cfg_attr(test, mockall::automock)]
pub trait PendingStore {
fn list(&self) -> io::Result<Vec<PendingSnapshot>>;
fn baseline_hash(&self, baseline: &Path) -> io::Result<Option<String>>;
fn accept(&self, entry: &PendingSnapshot) -> io::Result<()>;
fn reject(&self, entry: &PendingSnapshot) -> io::Result<()>;
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ReviewError {
#[error("baselines are not accepted with CI set; accept them on a developer's machine")]
Ci,
#[error("{} changed after the comparison; rerun the test and review again", baseline.display())]
BaselineChanged {
baseline: PathBuf,
},
#[error(transparent)]
Io(#[from] io::Error),
}
pub fn pending(store: &dyn PendingStore, filter: Option<&str>) -> io::Result<Vec<PendingSnapshot>> {
let mut entries: Vec<PendingSnapshot> = store
.list()?
.into_iter()
.filter(|entry| filter.is_none_or(|filter| entry.record.test.contains(filter)))
.collect();
entries.sort_by(|a, b| {
(a.record.test.as_str(), a.record.snapshot.as_str())
.cmp(&(b.record.test.as_str(), b.record.snapshot.as_str()))
});
Ok(entries)
}
pub fn accept(
store: &dyn PendingStore,
entry: &PendingSnapshot,
ci: bool,
) -> Result<(), ReviewError> {
if ci {
return Err(ReviewError::Ci);
}
if store.baseline_hash(&entry.record.baseline)? != entry.record.baseline_hash {
return Err(ReviewError::BaselineChanged {
baseline: entry.record.baseline.clone(),
});
}
Ok(store.accept(entry)?)
}
pub fn reject(store: &dyn PendingStore, entry: &PendingSnapshot) -> Result<(), ReviewError> {
Ok(store.reject(entry)?)
}
pub fn pending_insta(root: &Path) -> io::Result<usize> {
let mut count = 0;
let mut dirs = vec![root.to_path_buf()];
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(&dir)? {
let path = entry?.path();
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
if path.is_dir() {
if name != "target" && !name.starts_with('.') {
dirs.push(path);
}
continue;
}
if name.ends_with(".snap.new") || name.ends_with(".pending-snap") {
count += 1;
}
}
}
Ok(count)
}
#[derive(Debug, Clone)]
pub struct FsPendingStore {
root: PathBuf,
}
impl FsPendingStore {
#[must_use]
pub fn new(out_dir: &Path) -> Self {
Self {
root: out_dir.join("snapshots-failed"),
}
}
pub fn from_env() -> Result<Self, crate::error::ConfigError> {
Ok(Self::new(&super::SnapshotEnv::current()?.out_dir))
}
}
impl PendingStore for FsPendingStore {
fn list(&self) -> io::Result<Vec<PendingSnapshot>> {
let mut out = Vec::new();
if !self.root.is_dir() {
return Ok(out);
}
let mut dirs = vec![self.root.clone()];
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(&dir)? {
let path = entry?.path();
if path.is_dir() {
dirs.push(path);
continue;
}
if path.file_name().is_some_and(|name| name == "pending.json") {
let text = std::fs::read_to_string(&path)?;
let record: PendingRecord = serde_json::from_str(&text)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
out.push(PendingSnapshot {
dir: dir.clone(),
record,
});
}
}
}
Ok(out)
}
fn baseline_hash(&self, baseline: &Path) -> io::Result<Option<String>> {
match std::fs::read(baseline) {
Ok(bytes) => Ok(Some(file_hash(&bytes))),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
fn accept(&self, entry: &PendingSnapshot) -> io::Result<()> {
if let Some(parent) = entry.record.baseline.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(entry.actual(), &entry.record.baseline)?;
std::fs::remove_dir_all(&entry.dir)
}
fn reject(&self, entry: &PendingSnapshot) -> io::Result<()> {
std::fs::remove_dir_all(&entry.dir)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(test: &str, snapshot: &str, hash: Option<&str>) -> PendingSnapshot {
PendingSnapshot {
dir: PathBuf::from("/out/snapshots-failed")
.join(test)
.join(snapshot),
record: PendingRecord {
baseline: PathBuf::from("/src/tests/screenshots").join(format!("{snapshot}.png")),
test: test.to_owned(),
snapshot: snapshot.to_owned(),
variant: String::new(),
kind: "changed".to_owned(),
changed: Some(3),
total: Some(100),
max_diff_pixels: 0,
max_diff_ratio: 0.0,
baseline_hash: hash.map(str::to_owned),
},
}
}
#[test]
fn pending_filters_by_test_and_sorts() {
let mut store = MockPendingStore::new();
store.expect_list().returning(|| {
Ok(vec![
entry("ui::toolbar", "b", None),
entry("ui::reader", "z", None),
entry("ui::reader", "a", None),
])
});
let all = pending(&store, None).unwrap();
let names: Vec<(&str, &str)> = all
.iter()
.map(|e| (e.record.test.as_str(), e.record.snapshot.as_str()))
.collect();
assert_eq!(
names,
[
("ui::reader", "a"),
("ui::reader", "z"),
("ui::toolbar", "b")
]
);
assert_eq!(pending(&store, Some("toolbar")).unwrap().len(), 1);
}
#[test]
fn accepting_copies_when_the_baseline_is_unchanged() {
let mut store = MockPendingStore::new();
store
.expect_baseline_hash()
.returning(|_| Ok(Some("abc".to_owned())));
store.expect_accept().times(1).returning(|_| Ok(()));
accept(&store, &entry("t", "s", Some("abc")), false).unwrap();
}
#[test]
fn a_changed_baseline_or_ci_refuses() {
let mut store = MockPendingStore::new();
store
.expect_baseline_hash()
.returning(|_| Ok(Some("new".to_owned())));
store.expect_accept().never();
assert!(matches!(
accept(&store, &entry("t", "s", Some("old")), false),
Err(ReviewError::BaselineChanged { .. })
));
assert!(matches!(
accept(&store, &entry("t", "s", Some("new")), true),
Err(ReviewError::Ci)
));
}
#[test]
fn a_new_snapshot_is_accepted_while_no_baseline_exists() {
let mut store = MockPendingStore::new();
store.expect_baseline_hash().returning(|_| Ok(None));
store.expect_accept().times(1).returning(|_| Ok(()));
accept(&store, &entry("t", "s", None), false).unwrap();
}
#[test]
fn rejecting_leaves_the_baseline() {
let mut store = MockPendingStore::new();
store.expect_accept().never();
store.expect_reject().times(1).returning(|_| Ok(()));
reject(&store, &entry("t", "s", None)).unwrap();
}
}