1use anyhow::Context;
6use anyhow::Result;
7use serde::Deserialize;
8use serde::Serialize;
9use serde_json::from_str;
10use serde_json::to_string_pretty;
11use std::collections::BTreeMap;
12use std::fs::read_to_string;
13use std::fs::write;
14use std::path::Path;
15
16use crate::baseline_outcome::BaselineOutcome;
17use crate::offence::Offence;
18use crate::offence_fingerprint::OffenceFingerprint;
19
20#[derive(Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
35pub struct Baseline {
36 offences: BTreeMap<String, usize>,
37}
38
39impl Baseline {
40 pub fn of(offences: &[Offence]) -> Self {
41 let mut counts: BTreeMap<String, usize> = BTreeMap::new();
42 for offence in offences {
43 *counts.entry(OffenceFingerprint::of(offence)).or_default() += 1;
44 }
45 Self { offences: counts }
46 }
47
48 pub fn load(path: &Path) -> Result<Self> {
49 let text = read_to_string(path)
50 .with_context(|| format!("{} could not be read", path.display()))?;
51 from_str(&text).with_context(|| format!("{} is not a valid baseline", path.display()))
52 }
53
54 pub fn save(&self, path: &Path) -> Result<()> {
55 let text = to_string_pretty(self)
56 .with_context(|| format!("{} could not be rendered", path.display()))?;
57 write(path, text).with_context(|| format!("{} could not be written", path.display()))
58 }
59
60 pub fn len(&self) -> usize {
61 self.offences.values().sum()
62 }
63
64 pub fn is_empty(&self) -> bool {
65 self.offences.is_empty()
66 }
67
68 pub fn apply(&self, offences: Vec<Offence>) -> BaselineOutcome {
73 let mut remaining = self.offences.clone();
74 let mut kept = Vec::new();
75 let mut suppressed = 0;
76 for offence in offences {
77 let fingerprint = OffenceFingerprint::of(&offence);
78 match remaining.get_mut(&fingerprint) {
79 Some(count) if *count > 0 => {
80 *count -= 1;
81 suppressed += 1;
82 }
83 _ => kept.push(offence),
84 }
85 }
86 BaselineOutcome::new(kept, suppressed, remaining.values().sum())
87 }
88}