use std::collections::BTreeMap;
use std::path::Path;
use crate::error::WasmCheckError;
use crate::size::SizeReport;
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Baseline {
entries: BTreeMap<String, SizeReport>,
}
impl Baseline {
#[must_use]
pub const fn new() -> Self {
Self {
entries: BTreeMap::new(),
}
}
#[must_use]
pub const fn from_entries(entries: BTreeMap<String, SizeReport>) -> Self {
Self { entries }
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &SizeReport)> {
self.entries
.iter()
.map(|(key, report)| (key.as_str(), report))
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&SizeReport> {
self.entries.get(key)
}
pub fn set(&mut self, key: impl Into<String>, report: SizeReport) {
self.entries.insert(key.into(), report);
}
pub fn remove(&mut self, key: &str) -> Option<SizeReport> {
self.entries.remove(key)
}
pub fn prune(&mut self, pattern: &str, keep: &[String]) {
if !crate::config::is_glob(pattern) {
return;
}
let Ok(glob) = glob::Pattern::new(pattern) else {
return;
};
self.entries.retain(|key, _| {
keep.iter().any(|kept| kept == key) || key == pattern || !glob.matches(key)
});
}
pub fn load(path: impl AsRef<Path>) -> Result<Self, WasmCheckError> {
let path = path.as_ref();
let text = std::fs::read_to_string(path).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
WasmCheckError::BaselineNotFound(path.to_path_buf())
} else {
WasmCheckError::Io(e)
}
})?;
serde_json::from_str(&text).map_err(|source| WasmCheckError::ConfigParse {
path: path.to_path_buf(),
source,
})
}
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), WasmCheckError> {
let path = path.as_ref();
let mut json = serde_json::to_string_pretty(self)?;
json.push('\n');
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
&& !parent.exists()
{
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, json).map_err(WasmCheckError::Io)
}
}
impl From<BTreeMap<String, SizeReport>> for Baseline {
fn from(entries: BTreeMap<String, SizeReport>) -> Self {
Self::from_entries(entries)
}
}