use anyhow::Context;
use anyhow::Result;
use serde::Deserialize;
use serde::Serialize;
use serde_json::from_str;
use serde_json::to_string_pretty;
use std::collections::BTreeMap;
use std::fs::read_to_string;
use std::fs::write;
use std::path::Path;
use crate::adoption::baseline_outcome::BaselineOutcome;
use crate::reporting::offence::Offence;
use crate::reporting::offence_fingerprint::OffenceFingerprint;
#[derive(Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct Baseline {
offences: BTreeMap<String, usize>,
}
impl Baseline {
pub fn of(offences: &[Offence]) -> Self {
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
for offence in offences {
*counts.entry(OffenceFingerprint::of(offence)).or_default() += 1;
}
Self { offences: counts }
}
pub fn load(path: &Path) -> Result<Self> {
let text = read_to_string(path)
.with_context(|| format!("{} could not be read", path.display()))?;
from_str(&text).with_context(|| format!("{} is not a valid baseline", path.display()))
}
pub fn save(&self, path: &Path) -> Result<()> {
let text = to_string_pretty(self)
.with_context(|| format!("{} could not be rendered", path.display()))?;
write(path, text).with_context(|| format!("{} could not be written", path.display()))
}
pub fn len(&self) -> usize {
self.offences.values().sum()
}
pub fn is_empty(&self) -> bool {
self.offences.is_empty()
}
pub fn apply(&self, offences: Vec<Offence>) -> BaselineOutcome {
let mut remaining = self.offences.clone();
let mut kept = Vec::new();
let mut suppressed = 0;
for offence in offences {
let fingerprint = OffenceFingerprint::of(&offence);
match remaining.get_mut(&fingerprint) {
Some(count) if *count > 0 => {
*count -= 1;
suppressed += 1;
}
_ => kept.push(offence),
}
}
BaselineOutcome::new(kept, suppressed, remaining.values().sum())
}
}