Skip to main content

fallow_output/
audit_worsened.rs

1//! Audit-mode attribution classes of complexity findings, and the measured
2//! metrics that grew against the matched base finding.
3
4/// Audit-mode class of a complexity finding against the base snapshot.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
6#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
7#[serde(rename_all = "kebab-case")]
8pub enum AuditFindingAttribution {
9    /// No base finding matches, or a grown metric now exceeds a threshold
10    /// that the base finding did not exceed, or the growth of an exceeded
11    /// metric moved the finding to a higher severity tier. A CRAP score from
12    /// estimated coverage does not count as growth.
13    Introduced,
14    /// A base finding matches and a measured metric grew, but the finding is
15    /// not introduced. Growth of an exceeded metric in the same severity tier
16    /// is worsened.
17    Worsened,
18    /// A base finding matches and no measured metric grew.
19    Inherited,
20}
21
22/// Audit-mode reason why a complexity finding does not gate the verdict.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
24#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
25#[serde(rename_all = "kebab-case")]
26pub enum AuditGateExemption {
27    /// The finding is in a test file: a spec, a test directory, an end-to-end
28    /// suite, a mock or a fixture. Its gate severity is `warn`.
29    TestFile,
30}
31
32impl AuditGateExemption {
33    /// The JSON value, also used in compact output and SARIF properties.
34    #[must_use]
35    pub const fn token(self) -> &'static str {
36        match self {
37            Self::TestFile => "test-file",
38        }
39    }
40}
41
42/// Audit facts of one finding that an inline review comment shows.
43///
44/// The CodeClimate builder sets the attribution and the gate exemption. The
45/// audit render sets `gate` from the gate policy of the run. The CodeClimate
46/// wire shape does not carry these facts.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct AuditReviewContext {
49    /// Class of the finding against the base snapshot.
50    pub attribution: AuditFindingAttribution,
51    /// Reason why the finding never gates, when it has one.
52    pub gate_exemption: Option<AuditGateExemption>,
53    /// Effect of the finding on the gate. `None` when the gate policy of the
54    /// run is not known: the comment then shows only the attribution.
55    pub gate: Option<AuditReviewGate>,
56}
57
58/// Effect of one audit finding on the gate of the run.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum AuditReviewGate {
61    /// The finding counts in the gate.
62    Gated,
63    /// `--gate new-only` does not count an inherited finding.
64    NotGatedNewOnly,
65    /// `--worsened warn` gives a warning for a worsened finding, not a failure.
66    NotGatedWorsenedWarn,
67    /// `--worsened off` does not count a worsened finding.
68    NotGatedWorsenedOff,
69    /// A finding in a test file does not gate.
70    NotGatedTestFile,
71}
72
73impl AuditReviewContext {
74    /// The label text after the severity, for example
75    /// `inherited, not gated: `--gate new-only``.
76    #[must_use]
77    pub fn label(&self) -> String {
78        let class = match self.attribution {
79            AuditFindingAttribution::Introduced => "introduced",
80            AuditFindingAttribution::Worsened => "worsened",
81            AuditFindingAttribution::Inherited => "inherited",
82        };
83        let reason = match self.gate {
84            None | Some(AuditReviewGate::Gated) => None,
85            Some(AuditReviewGate::NotGatedNewOnly) => Some("`--gate new-only`"),
86            Some(AuditReviewGate::NotGatedWorsenedWarn) => Some("`--worsened warn`"),
87            Some(AuditReviewGate::NotGatedWorsenedOff) => Some("`--worsened off`"),
88            Some(AuditReviewGate::NotGatedTestFile) => Some("test file"),
89        };
90        reason.map_or_else(
91            || class.to_owned(),
92            |reason| format!("{class}, not gated: {reason}"),
93        )
94    }
95}
96
97/// A measured metric of a complexity finding.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
99#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
100#[serde(rename_all = "snake_case")]
101pub enum WorsenedMetricKind {
102    /// Cyclomatic complexity.
103    Cyclomatic,
104    /// Cognitive complexity.
105    Cognitive,
106    /// CRAP score. Compared only when both sides have coverage data.
107    Crap,
108    /// Lines of code in the function body.
109    LineCount,
110}
111
112impl WorsenedMetricKind {
113    /// Short label for human output.
114    #[must_use]
115    pub const fn label(self) -> &'static str {
116        match self {
117            Self::Cyclomatic => "cyclomatic",
118            Self::Cognitive => "cognitive",
119            Self::Crap => "CRAP",
120            Self::LineCount => "lines",
121        }
122    }
123}
124
125/// One measured metric that is higher at head than in the matched base
126/// finding.
127#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
128#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
129pub struct WorsenedMetric {
130    /// The metric.
131    pub metric: WorsenedMetricKind,
132    /// Value in the matched base finding.
133    #[serde(serialize_with = "serialize_metric_value")]
134    pub base: f64,
135    /// Value in the head finding. Always higher than `base`.
136    #[serde(serialize_with = "serialize_metric_value")]
137    pub head: f64,
138}
139
140impl WorsenedMetric {
141    /// Human form, for example `cyclomatic 15 -> 40`.
142    #[must_use]
143    pub fn describe(&self) -> String {
144        format!(
145            "{} {} -> {}",
146            self.metric.label(),
147            format_metric_value(self.base),
148            format_metric_value(self.head)
149        )
150    }
151}
152
153/// The human form of a list of grown metrics, joined with `, `.
154#[must_use]
155pub fn describe_worsened_metrics(metrics: &[WorsenedMetric]) -> String {
156    metrics
157        .iter()
158        .map(WorsenedMetric::describe)
159        .collect::<Vec<_>>()
160        .join(", ")
161}
162
163/// Metric values of the base finding that an inherited complexity finding
164/// matches. The JSON output does not carry these values, so only a live audit
165/// run has them. A `report --from` re-render of a saved audit has no base
166/// values.
167#[derive(Debug, Clone, Copy, PartialEq, Default)]
168pub struct AuditBaseMetrics {
169    /// Cyclomatic complexity of the base finding.
170    pub cyclomatic: u16,
171    /// Cognitive complexity of the base finding.
172    pub cognitive: u16,
173    /// CRAP score of the base finding, when coverage data exists.
174    pub crap: Option<f64>,
175    /// Lines of code of the base finding.
176    pub line_count: u32,
177}
178
179impl AuditBaseMetrics {
180    /// The human form of each metric that `head` exceeds, with the base value
181    /// and the head value, for example `cognitive 21 -> 21`. A CRAP score
182    /// shows only when both sides have one. `None` when no exceeded metric
183    /// has a base value.
184    #[must_use]
185    pub fn describe_exceeded(&self, head: &crate::ComplexityViolation) -> Option<String> {
186        let exceeded = head.exceeded;
187        let mut parts = Vec::new();
188        let mut push = |kind: WorsenedMetricKind, base: f64, head: f64| {
189            parts.push(format!(
190                "{} {} -> {}",
191                kind.label(),
192                format_metric_value(base),
193                format_metric_value(head)
194            ));
195        };
196        if exceeded.includes_cyclomatic() {
197            push(
198                WorsenedMetricKind::Cyclomatic,
199                f64::from(self.cyclomatic),
200                f64::from(head.cyclomatic),
201            );
202        }
203        if exceeded.includes_cognitive() {
204            push(
205                WorsenedMetricKind::Cognitive,
206                f64::from(self.cognitive),
207                f64::from(head.cognitive),
208            );
209        }
210        if exceeded.includes_crap()
211            && let (Some(base), Some(head)) = (self.crap, head.crap)
212        {
213            push(WorsenedMetricKind::Crap, base, head);
214        }
215        if exceeded.is_file_lines() {
216            push(
217                WorsenedMetricKind::LineCount,
218                f64::from(self.line_count),
219                f64::from(head.line_count),
220            );
221        }
222        (!parts.is_empty()).then(|| parts.join(", "))
223    }
224}
225
226/// Largest magnitude that an `f64` holds as an exact whole number.
227const MAX_EXACT_WHOLE: f64 = 9_007_199_254_740_992.0;
228
229fn is_whole(value: f64) -> bool {
230    value.fract() == 0.0 && value.abs() < MAX_EXACT_WHOLE
231}
232
233/// Format a metric value: whole numbers without a fraction, CRAP scores with
234/// one decimal.
235#[must_use]
236pub fn format_metric_value(value: f64) -> String {
237    if is_whole(value) {
238        format!("{value:.0}")
239    } else {
240        format!("{value:.1}")
241    }
242}
243
244/// Write whole metric values as JSON integers, so `15` does not read `15.0`.
245#[expect(
246    clippy::trivially_copy_pass_by_ref,
247    reason = "serde serialize_with passes the field by reference"
248)]
249fn serialize_metric_value<S: serde::Serializer>(
250    value: &f64,
251    serializer: S,
252) -> Result<S::Ok, S::Error> {
253    if is_whole(*value) {
254        #[expect(
255            clippy::cast_possible_truncation,
256            reason = "is_whole keeps the value whole and inside the exact i64 range"
257        )]
258        serializer.serialize_i64(*value as i64)
259    } else {
260        serializer.serialize_f64(*value)
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn whole_values_serialize_as_integers() {
270        let metric = WorsenedMetric {
271            metric: WorsenedMetricKind::LineCount,
272            base: 80.0,
273            head: 300.0,
274        };
275        let json = serde_json::to_value(metric).expect("serialize");
276        assert_eq!(
277            json,
278            serde_json::json!({"metric": "line_count", "base": 80, "head": 300})
279        );
280    }
281
282    #[test]
283    fn crap_values_keep_their_fraction() {
284        let metric = WorsenedMetric {
285            metric: WorsenedMetricKind::Crap,
286            base: 31.5,
287            head: 42.25,
288        };
289        let json = serde_json::to_value(metric).expect("serialize");
290        assert_eq!(json["base"], 31.5);
291        assert_eq!(metric.describe(), "CRAP 31.5 -> 42.2");
292    }
293
294    fn violation(
295        exceeded: crate::ExceededThreshold,
296        crap: Option<f64>,
297    ) -> crate::ComplexityViolation {
298        crate::ComplexityViolation {
299            path: std::path::PathBuf::from("src/a.ts"),
300            name: "work".to_owned(),
301            line: 1,
302            col: 0,
303            cyclomatic: 19,
304            standard_cyclomatic: None,
305            cognitive: 18,
306            line_count: 40,
307            param_count: 1,
308            react_hook_count: 0,
309            react_jsx_max_depth: 0,
310            react_prop_count: 0,
311            react_hook_profile: None,
312            exceeded,
313            effective_severity: None,
314            severity: crate::FindingSeverity::High,
315            mutation: None,
316            coverage_pct: None,
317            crap,
318            coverage_tier: None,
319            coverage_source: None,
320            inherited_from: None,
321            component_rollup: None,
322            contributions: Vec::new(),
323            effective_thresholds: None,
324            threshold_source: None,
325            override_comment_line: None,
326            max_file_lines: None,
327        }
328    }
329
330    const BASE: AuditBaseMetrics = AuditBaseMetrics {
331        cyclomatic: 23,
332        cognitive: 18,
333        crap: Some(31.5),
334        line_count: 60,
335    };
336
337    #[test]
338    fn base_metrics_name_only_the_exceeded_metrics() {
339        let head = violation(crate::ExceededThreshold::Cyclomatic, None);
340        assert_eq!(
341            BASE.describe_exceeded(&head).as_deref(),
342            Some("cyclomatic 23 -> 19")
343        );
344        let head = violation(crate::ExceededThreshold::All, Some(30.0));
345        assert_eq!(
346            BASE.describe_exceeded(&head).as_deref(),
347            Some("cyclomatic 23 -> 19, cognitive 18 -> 18, CRAP 31.5 -> 30")
348        );
349        let head = violation(crate::ExceededThreshold::FileLines, None);
350        assert_eq!(
351            BASE.describe_exceeded(&head).as_deref(),
352            Some("lines 60 -> 40")
353        );
354    }
355
356    #[test]
357    fn base_metrics_skip_a_crap_score_that_one_side_lacks() {
358        let head = violation(crate::ExceededThreshold::Crap, None);
359        assert_eq!(BASE.describe_exceeded(&head), None);
360    }
361
362    #[test]
363    fn describe_joins_metrics() {
364        let metrics = [
365            WorsenedMetric {
366                metric: WorsenedMetricKind::Cyclomatic,
367                base: 15.0,
368                head: 40.0,
369            },
370            WorsenedMetric {
371                metric: WorsenedMetricKind::LineCount,
372                base: 80.0,
373                head: 300.0,
374            },
375        ];
376        assert_eq!(
377            describe_worsened_metrics(&metrics),
378            "cyclomatic 15 -> 40, lines 80 -> 300"
379        );
380    }
381}