1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//! Audit-mode attribution classes of complexity findings, and the measured
//! metrics that grew against the matched base finding.
/// Audit-mode class of a complexity finding against the base snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum AuditFindingAttribution {
/// No base finding matches, or a grown metric now exceeds a threshold
/// that the base finding did not exceed, or the growth of an exceeded
/// metric moved the finding to a higher severity tier. A CRAP score from
/// estimated coverage does not count as growth.
Introduced,
/// A base finding matches and a measured metric grew, but the finding is
/// not introduced. Growth of an exceeded metric in the same severity tier
/// is worsened.
Worsened,
/// A base finding matches and no measured metric grew.
Inherited,
}
/// Audit-mode reason why a complexity finding does not gate the verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum AuditGateExemption {
/// The finding is in a test file: a spec, a test directory, an end-to-end
/// suite, a mock or a fixture. Its gate severity is `warn`.
TestFile,
}
impl AuditGateExemption {
/// The JSON value, also used in compact output and SARIF properties.
#[must_use]
pub const fn token(self) -> &'static str {
match self {
Self::TestFile => "test-file",
}
}
}
/// Audit facts of one finding that an inline review comment shows.
///
/// The CodeClimate builder sets the attribution and the gate exemption. The
/// audit render sets `gate` from the gate policy of the run. The CodeClimate
/// wire shape does not carry these facts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditReviewContext {
/// Class of the finding against the base snapshot.
pub attribution: AuditFindingAttribution,
/// Reason why the finding never gates, when it has one.
pub gate_exemption: Option<AuditGateExemption>,
/// Effect of the finding on the gate. `None` when the gate policy of the
/// run is not known: the comment then shows only the attribution.
pub gate: Option<AuditReviewGate>,
}
/// Effect of one audit finding on the gate of the run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditReviewGate {
/// The finding counts in the gate.
Gated,
/// `--gate new-only` does not count an inherited finding.
NotGatedNewOnly,
/// `--worsened warn` gives a warning for a worsened finding, not a failure.
NotGatedWorsenedWarn,
/// `--worsened off` does not count a worsened finding.
NotGatedWorsenedOff,
/// A finding in a test file does not gate.
NotGatedTestFile,
}
impl AuditReviewContext {
/// The label text after the severity, for example
/// `inherited · not gated (`--gate new-only`)`.
#[must_use]
pub fn label(&self) -> String {
let class = match self.attribution {
AuditFindingAttribution::Introduced => "introduced",
AuditFindingAttribution::Worsened => "worsened",
AuditFindingAttribution::Inherited => "inherited",
};
let reason = match self.gate {
None | Some(AuditReviewGate::Gated) => None,
Some(AuditReviewGate::NotGatedNewOnly) => Some("`--gate new-only`"),
Some(AuditReviewGate::NotGatedWorsenedWarn) => Some("`--worsened warn`"),
Some(AuditReviewGate::NotGatedWorsenedOff) => Some("`--worsened off`"),
Some(AuditReviewGate::NotGatedTestFile) => Some("test file"),
};
reason.map_or_else(
|| class.to_owned(),
|reason| format!("{class} \u{00b7} not gated ({reason})"),
)
}
}
/// A measured metric of a complexity finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorsenedMetricKind {
/// Cyclomatic complexity.
Cyclomatic,
/// Cognitive complexity.
Cognitive,
/// CRAP score. Compared only when both sides have coverage data.
Crap,
/// Lines of code in the function body.
LineCount,
}
impl WorsenedMetricKind {
/// Short label for human output.
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Cyclomatic => "cyclomatic",
Self::Cognitive => "cognitive",
Self::Crap => "CRAP",
Self::LineCount => "lines",
}
}
}
/// One measured metric that is higher at head than in the matched base
/// finding.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorsenedMetric {
/// The metric.
pub metric: WorsenedMetricKind,
/// Value in the matched base finding.
#[serde(serialize_with = "serialize_metric_value")]
pub base: f64,
/// Value in the head finding. Always higher than `base`.
#[serde(serialize_with = "serialize_metric_value")]
pub head: f64,
}
impl WorsenedMetric {
/// Human form, for example `cyclomatic 15 -> 40`.
#[must_use]
pub fn describe(&self) -> String {
format!(
"{} {} -> {}",
self.metric.label(),
format_metric_value(self.base),
format_metric_value(self.head)
)
}
}
/// The human form of a list of grown metrics, joined with `, `.
#[must_use]
pub fn describe_worsened_metrics(metrics: &[WorsenedMetric]) -> String {
metrics
.iter()
.map(WorsenedMetric::describe)
.collect::<Vec<_>>()
.join(", ")
}
/// Largest magnitude that an `f64` holds as an exact whole number.
const MAX_EXACT_WHOLE: f64 = 9_007_199_254_740_992.0;
fn is_whole(value: f64) -> bool {
value.fract() == 0.0 && value.abs() < MAX_EXACT_WHOLE
}
/// Format a metric value: whole numbers without a fraction, CRAP scores with
/// one decimal.
#[must_use]
pub fn format_metric_value(value: f64) -> String {
if is_whole(value) {
format!("{value:.0}")
} else {
format!("{value:.1}")
}
}
/// Write whole metric values as JSON integers, so `15` does not read `15.0`.
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde serialize_with passes the field by reference"
)]
fn serialize_metric_value<S: serde::Serializer>(
value: &f64,
serializer: S,
) -> Result<S::Ok, S::Error> {
if is_whole(*value) {
#[expect(
clippy::cast_possible_truncation,
reason = "is_whole keeps the value whole and inside the exact i64 range"
)]
serializer.serialize_i64(*value as i64)
} else {
serializer.serialize_f64(*value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn whole_values_serialize_as_integers() {
let metric = WorsenedMetric {
metric: WorsenedMetricKind::LineCount,
base: 80.0,
head: 300.0,
};
let json = serde_json::to_value(metric).expect("serialize");
assert_eq!(
json,
serde_json::json!({"metric": "line_count", "base": 80, "head": 300})
);
}
#[test]
fn crap_values_keep_their_fraction() {
let metric = WorsenedMetric {
metric: WorsenedMetricKind::Crap,
base: 31.5,
head: 42.25,
};
let json = serde_json::to_value(metric).expect("serialize");
assert_eq!(json["base"], 31.5);
assert_eq!(metric.describe(), "CRAP 31.5 -> 42.2");
}
#[test]
fn describe_joins_metrics() {
let metrics = [
WorsenedMetric {
metric: WorsenedMetricKind::Cyclomatic,
base: 15.0,
head: 40.0,
},
WorsenedMetric {
metric: WorsenedMetricKind::LineCount,
base: 80.0,
head: 300.0,
},
];
assert_eq!(
describe_worsened_metrics(&metrics),
"cyclomatic 15 -> 40, lines 80 -> 300"
);
}
}