Skip to main content

stern4rust/
baseline.rs

1// Copyright 2025 Umberto Gotti <umberto.gotti@umbertogotti.dev>
2// Licensed under the MIT License
3// SPDX-License-Identifier: MIT
4
5use 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// The offences a repository has already agreed to live with.
21//
22// `--rule` gives a codebase a way in by enforcing one rule at a time. What it
23// cannot express is "every rule, against new code only", which is what a
24// codebase with six hundred existing offences actually needs -- otherwise the
25// choice is between a gate that fails forever and no gate at all.
26//
27// Counts, not a set. Two identical offences in one file share a fingerprint, so
28// the baseline records that there were two: fixing one and introducing another
29// leaves the total unchanged and must still pass, while introducing a third
30// must not.
31//
32// Sorted on the way out, because this file is checked in and a diff that
33// reorders itself between runs is a diff nobody reviews.
34#[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    // Each fingerprint is forgiven up to the number of times the baseline
69    // recorded it, and every occurrence beyond that is reported. Which of two
70    // identical offences is forgiven does not matter -- they differ only by
71    // line, and the one that survives carries a real line either way.
72    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}