1#[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 Introduced,
14 Worsened,
18 Inherited,
20}
21
22#[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 TestFile,
30}
31
32impl AuditGateExemption {
33 #[must_use]
35 pub const fn token(self) -> &'static str {
36 match self {
37 Self::TestFile => "test-file",
38 }
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct AuditReviewContext {
49 pub attribution: AuditFindingAttribution,
51 pub gate_exemption: Option<AuditGateExemption>,
53 pub gate: Option<AuditReviewGate>,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum AuditReviewGate {
61 Gated,
63 NotGatedNewOnly,
65 NotGatedWorsenedWarn,
67 NotGatedWorsenedOff,
69 NotGatedTestFile,
71}
72
73impl AuditReviewContext {
74 #[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#[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,
104 Cognitive,
106 Crap,
108 LineCount,
110}
111
112impl WorsenedMetricKind {
113 #[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#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
128#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
129pub struct WorsenedMetric {
130 pub metric: WorsenedMetricKind,
132 #[serde(serialize_with = "serialize_metric_value")]
134 pub base: f64,
135 #[serde(serialize_with = "serialize_metric_value")]
137 pub head: f64,
138}
139
140impl WorsenedMetric {
141 #[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#[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#[derive(Debug, Clone, Copy, PartialEq, Default)]
168pub struct AuditBaseMetrics {
169 pub cyclomatic: u16,
171 pub cognitive: u16,
173 pub crap: Option<f64>,
175 pub line_count: u32,
177}
178
179impl AuditBaseMetrics {
180 #[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
226const 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#[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#[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}