Skip to main content

fallow_report_protocol/
gate.rs

1//! The verdict of one gate on one run.
2//!
3//! A gate is a rule that can fail a run. Each fallow tool keys these values by
4//! its own gate names.
5
6use std::borrow::Borrow;
7use std::collections::BTreeMap;
8
9use serde::Serialize;
10
11/// What a gate concluded on this run.
12///
13/// The status has four values, not two. A verdict can have a warn tier that
14/// does not fail the run, and a gate can stand down without a pass. A change
15/// from a boolean to a wider type later would change the type of a required
16/// member and the version of each envelope that carries it.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
18#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
19#[serde(rename_all = "kebab-case")]
20pub enum GateStatus {
21    /// The gate ran and its condition did not hold.
22    Pass,
23    /// The gate ran and reached a warn tier that does not fail the run. Only a
24    /// gate with a warn tier reports this value.
25    Warn,
26    /// The gate ran and its condition held.
27    Fail,
28    /// The gate could not judge this run and stood down on purpose. For
29    /// example, the run was told never to fail, or a different gate decides
30    /// the run. This is not `pass`: `pass` says that the gate evaluated the
31    /// condition and the condition did not hold.
32    Skipped,
33}
34
35/// One gate's verdict on one run.
36///
37/// `status` and `enforced` answer different questions, and they can disagree.
38/// `status` is what the rule concluded. `enforced` tells if a `fail` from this
39/// gate makes the run exit non-zero. A run that was told never to fail reports
40/// a failed gate as `status: fail` with `enforced: false`.
41///
42/// **A gate fails the build when `status` is `fail` AND `enforced` is true.**
43/// One member alone does not decide it. `enforced` is true on every armed
44/// gate, also on a gate that passed. Thus a gate rule on `enforced` alone
45/// fails every run that armed a gate. Read `status` alone to decide what to
46/// say. `warn` and `skipped` are not a pass and not a failure.
47#[derive(Debug, Clone, PartialEq, Serialize)]
48#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
49pub struct GateOutcome {
50    /// What the rule concluded.
51    pub status: GateStatus,
52    /// True when a `fail` from this gate makes the run exit non-zero. False
53    /// when the tool publishes the verdict for information only: no flag or
54    /// config armed the gate, the run was told never to fail, or the output
55    /// format exits 0 for the gate.
56    pub enforced: bool,
57    /// The measured value that the gate compared, when there is one: for
58    /// example a percentage, a score, a number of findings, or the number of
59    /// files in `files`. A whole number is a JSON number, so a count of three
60    /// reads as `3.0`. Absent for a gate that compares no number.
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub observed: Option<f64>,
63    /// The configured limit that the gate compared `observed` against, when
64    /// there is one. Absent for a gate that compares no number.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub threshold: Option<f64>,
67    /// How the limit was spelled, for a gate whose `threshold` number does not
68    /// carry its unit. Examples are a severity floor such as `high`, the rule
69    /// severity that the gate counts such as `error`, or a tolerance as the
70    /// user wrote it, such as `"50%"`. Each gate name documents its label.
71    /// Absent for a gate whose numbers have a clear meaning without a label.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub threshold_label: Option<String>,
74    /// The files that the gate judged, for a gate that judges files and not a
75    /// number. One item for each file, sorted by path. Absent when the list is
76    /// empty.
77    #[serde(default, skip_serializing_if = "Vec::is_empty")]
78    pub files: Vec<GateFile>,
79}
80
81/// One file that a file-judging gate names, with the reason that the gate
82/// counted it.
83///
84/// A gate that counts files that did not parse cleanly writes this item. When
85/// `reason` is set, `error_count` and `panicked` hold fixed values.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
87#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
88pub struct GateFile {
89    /// The file path, relative to the project root, with `/` separators.
90    pub path: String,
91    /// The number of parser errors for the file. `1` when `reason` is set.
92    pub error_count: u32,
93    /// True when the parser stopped in the file and did not recover, so the
94    /// analysis saw only the part before the error. `true` when `reason` is set.
95    pub panicked: bool,
96    /// Why the file counts when it is not a parser error. Absent for a parser
97    /// error, the only reason before this field existed.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub reason: Option<GateFileReason>,
100}
101
102/// Why a file counts for a parse gate, other than a parser error.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
104#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
105#[serde(rename_all = "kebab-case")]
106pub enum GateFileReason {
107    /// The file nests too deep to parse, so the tool did not parse it.
108    NestingTooDeep,
109}
110
111impl GateOutcome {
112    /// A gate that ran, compared no number, and was armed.
113    #[must_use]
114    pub const fn new(status: GateStatus, enforced: bool) -> Self {
115        Self {
116            status,
117            enforced,
118            observed: None,
119            threshold: None,
120            threshold_label: None,
121            files: Vec::new(),
122        }
123    }
124
125    /// A gate that compared `observed` against `threshold`.
126    #[must_use]
127    pub const fn measured(
128        status: GateStatus,
129        enforced: bool,
130        observed: f64,
131        threshold: f64,
132    ) -> Self {
133        Self {
134            status,
135            enforced,
136            observed: Some(observed),
137            threshold: Some(threshold),
138            threshold_label: None,
139            files: Vec::new(),
140        }
141    }
142
143    /// A gate that counted `observed` items at or above a named floor.
144    #[must_use]
145    pub fn counted(
146        status: GateStatus,
147        enforced: bool,
148        observed: f64,
149        threshold_label: &str,
150    ) -> Self {
151        Self {
152            status,
153            enforced,
154            observed: Some(observed),
155            threshold: None,
156            threshold_label: Some(threshold_label.to_owned()),
157            files: Vec::new(),
158        }
159    }
160
161    /// A gate that judged files: `observed` is the number of files it named.
162    #[must_use]
163    pub fn with_files(status: GateStatus, enforced: bool, files: Vec<GateFile>) -> Self {
164        #[expect(
165            clippy::cast_precision_loss,
166            reason = "a file count never approaches the f64 integer limit"
167        )]
168        let observed = files.len() as f64;
169        Self {
170            status,
171            enforced,
172            observed: Some(observed),
173            threshold: None,
174            threshold_label: None,
175            files,
176        }
177    }
178
179    /// Whether this outcome should make the run exit non-zero.
180    #[must_use]
181    pub const fn fails_run(&self) -> bool {
182        self.enforced && matches!(self.status, GateStatus::Fail)
183    }
184}
185
186/// The verdict of every gate that a run evaluated, keyed by gate name.
187///
188/// Each tool defines its own gate names. The name of a gate is the JSON member
189/// name, and the members are in the order of the names. A tool never writes an
190/// empty object. When no gate ran, the member is absent.
191///
192/// The key set is OPEN. A name that a consumer does not recognize means "some
193/// gate", not an error.
194#[derive(Debug, Clone, PartialEq, Serialize)]
195#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
196#[cfg_attr(feature = "schema", schemars(rename = "GateOutcomes"))]
197#[serde(transparent)]
198pub struct GateOutcomes<K: Ord>(BTreeMap<K, GateOutcome>);
199
200impl<K: Ord> Default for GateOutcomes<K> {
201    fn default() -> Self {
202        Self::new()
203    }
204}
205
206impl<K: Ord> GateOutcomes<K> {
207    /// An empty set. [`Self::into_option`] makes it absent.
208    #[must_use]
209    pub const fn new() -> Self {
210        Self(BTreeMap::new())
211    }
212
213    /// Record the outcome of one gate. A previous entry for that name goes.
214    pub fn insert(&mut self, name: K, outcome: GateOutcome) {
215        self.0.insert(name, outcome);
216    }
217
218    /// Record the outcome of one gate when the gate ran.
219    pub fn insert_if(&mut self, name: K, outcome: Option<GateOutcome>) {
220        if let Some(outcome) = outcome {
221            self.0.insert(name, outcome);
222        }
223    }
224
225    /// Read the outcome of one gate.
226    #[must_use]
227    pub fn get<Q>(&self, name: &Q) -> Option<&GateOutcome>
228    where
229        K: Borrow<Q>,
230        Q: Ord + ?Sized,
231    {
232        self.0.get(name)
233    }
234
235    /// Whether a gate of the set fails the run: its status is `fail` and it
236    /// is enforced.
237    #[must_use]
238    pub fn fails_run(&self) -> bool {
239        self.0.values().any(GateOutcome::fails_run)
240    }
241
242    /// Whether the set holds no gate.
243    #[must_use]
244    pub fn is_empty(&self) -> bool {
245        self.0.is_empty()
246    }
247
248    /// Make an empty set `None`. This keeps the member absent on a run that
249    /// evaluated no gate.
250    #[must_use]
251    pub fn into_option(self) -> Option<Self> {
252        if self.0.is_empty() { None } else { Some(self) }
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn an_unenforced_failure_does_not_fail_the_run() {
262        let outcome = GateOutcome::new(GateStatus::Fail, false);
263        assert!(!outcome.fails_run());
264        let enforced = GateOutcome::new(GateStatus::Fail, true);
265        assert!(enforced.fails_run());
266    }
267
268    #[test]
269    fn a_skipped_gate_never_fails_the_run() {
270        assert!(!GateOutcome::new(GateStatus::Skipped, true).fails_run());
271        assert!(!GateOutcome::new(GateStatus::Warn, true).fails_run());
272    }
273}