#[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 {
Introduced,
Worsened,
Inherited,
}
#[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 {
TestFile,
}
impl AuditGateExemption {
#[must_use]
pub const fn token(self) -> &'static str {
match self {
Self::TestFile => "test-file",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditReviewContext {
pub attribution: AuditFindingAttribution,
pub gate_exemption: Option<AuditGateExemption>,
pub gate: Option<AuditReviewGate>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditReviewGate {
Gated,
NotGatedNewOnly,
NotGatedWorsenedWarn,
NotGatedWorsenedOff,
NotGatedTestFile,
}
impl AuditReviewContext {
#[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}, not gated: {reason}"),
)
}
}
#[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,
Cognitive,
Crap,
LineCount,
}
impl WorsenedMetricKind {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Cyclomatic => "cyclomatic",
Self::Cognitive => "cognitive",
Self::Crap => "CRAP",
Self::LineCount => "lines",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorsenedMetric {
pub metric: WorsenedMetricKind,
#[serde(serialize_with = "serialize_metric_value")]
pub base: f64,
#[serde(serialize_with = "serialize_metric_value")]
pub head: f64,
}
impl WorsenedMetric {
#[must_use]
pub fn describe(&self) -> String {
format!(
"{} {} -> {}",
self.metric.label(),
format_metric_value(self.base),
format_metric_value(self.head)
)
}
}
#[must_use]
pub fn describe_worsened_metrics(metrics: &[WorsenedMetric]) -> String {
metrics
.iter()
.map(WorsenedMetric::describe)
.collect::<Vec<_>>()
.join(", ")
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct AuditBaseMetrics {
pub cyclomatic: u16,
pub cognitive: u16,
pub crap: Option<f64>,
pub line_count: u32,
}
impl AuditBaseMetrics {
#[must_use]
pub fn describe_exceeded(&self, head: &crate::ComplexityViolation) -> Option<String> {
let exceeded = head.exceeded;
let mut parts = Vec::new();
let mut push = |kind: WorsenedMetricKind, base: f64, head: f64| {
parts.push(format!(
"{} {} -> {}",
kind.label(),
format_metric_value(base),
format_metric_value(head)
));
};
if exceeded.includes_cyclomatic() {
push(
WorsenedMetricKind::Cyclomatic,
f64::from(self.cyclomatic),
f64::from(head.cyclomatic),
);
}
if exceeded.includes_cognitive() {
push(
WorsenedMetricKind::Cognitive,
f64::from(self.cognitive),
f64::from(head.cognitive),
);
}
if exceeded.includes_crap()
&& let (Some(base), Some(head)) = (self.crap, head.crap)
{
push(WorsenedMetricKind::Crap, base, head);
}
if exceeded.is_file_lines() {
push(
WorsenedMetricKind::LineCount,
f64::from(self.line_count),
f64::from(head.line_count),
);
}
(!parts.is_empty()).then(|| parts.join(", "))
}
}
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
}
#[must_use]
pub fn format_metric_value(value: f64) -> String {
if is_whole(value) {
format!("{value:.0}")
} else {
format!("{value:.1}")
}
}
#[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");
}
fn violation(
exceeded: crate::ExceededThreshold,
crap: Option<f64>,
) -> crate::ComplexityViolation {
crate::ComplexityViolation {
path: std::path::PathBuf::from("src/a.ts"),
name: "work".to_owned(),
line: 1,
col: 0,
cyclomatic: 19,
standard_cyclomatic: None,
cognitive: 18,
line_count: 40,
param_count: 1,
react_hook_count: 0,
react_jsx_max_depth: 0,
react_prop_count: 0,
react_hook_profile: None,
exceeded,
effective_severity: None,
severity: crate::FindingSeverity::High,
mutation: None,
coverage_pct: None,
crap,
coverage_tier: None,
coverage_source: None,
inherited_from: None,
component_rollup: None,
contributions: Vec::new(),
effective_thresholds: None,
threshold_source: None,
override_comment_line: None,
max_file_lines: None,
}
}
const BASE: AuditBaseMetrics = AuditBaseMetrics {
cyclomatic: 23,
cognitive: 18,
crap: Some(31.5),
line_count: 60,
};
#[test]
fn base_metrics_name_only_the_exceeded_metrics() {
let head = violation(crate::ExceededThreshold::Cyclomatic, None);
assert_eq!(
BASE.describe_exceeded(&head).as_deref(),
Some("cyclomatic 23 -> 19")
);
let head = violation(crate::ExceededThreshold::All, Some(30.0));
assert_eq!(
BASE.describe_exceeded(&head).as_deref(),
Some("cyclomatic 23 -> 19, cognitive 18 -> 18, CRAP 31.5 -> 30")
);
let head = violation(crate::ExceededThreshold::FileLines, None);
assert_eq!(
BASE.describe_exceeded(&head).as_deref(),
Some("lines 60 -> 40")
);
}
#[test]
fn base_metrics_skip_a_crap_score_that_one_side_lacks() {
let head = violation(crate::ExceededThreshold::Crap, None);
assert_eq!(BASE.describe_exceeded(&head), None);
}
#[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"
);
}
}