use std::collections::BTreeMap;
use std::fmt;
use codeint_model::SourceSet;
use serde::{Deserialize, Serialize};
use crate::baseline::{Baseline, BaselineEntry};
use crate::finding_anchor::match_anchors_with_renames;
use crate::ratchet::{Ratchet, RatchetEntry, round_ratchet_ratio};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StateCheckViolation {
RatchetFileDeleted {
path: String,
},
RatchetEntryRemoved {
#[serde(default, skip_serializing_if = "Option::is_none")]
source_set: Option<String>,
metric: String,
base_ceiling: f64,
metric_version: u32,
},
RatchetCeilingRaised {
#[serde(default, skip_serializing_if = "Option::is_none")]
source_set: Option<String>,
metric: String,
base_ceiling: f64,
head_ceiling: f64,
metric_version: u32,
},
BaselineFindingsAdded {
#[serde(default, skip_serializing_if = "Option::is_none")]
source_set: Option<String>,
metric: String,
base_count: usize,
head_count: usize,
added_count: usize,
added_ids: Vec<String>,
metric_version: u32,
},
}
impl StateCheckViolation {
pub fn metric_label(&self) -> Option<String> {
match self {
StateCheckViolation::RatchetFileDeleted { .. } => None,
StateCheckViolation::RatchetEntryRemoved {
source_set, metric, ..
}
| StateCheckViolation::RatchetCeilingRaised {
source_set, metric, ..
}
| StateCheckViolation::BaselineFindingsAdded {
source_set, metric, ..
} => Some(format_metric_label(source_set.as_deref(), metric)),
}
}
}
impl fmt::Display for StateCheckViolation {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StateCheckViolation::RatchetFileDeleted { path } => {
write!(formatter, "Ratchet file {path} was deleted")
}
StateCheckViolation::RatchetEntryRemoved {
source_set,
metric,
base_ceiling,
metric_version,
} => write!(
formatter,
"Ratchet entry {} (ceiling {base_ceiling}, Metric version {metric_version}) was removed",
format_metric_label(source_set.as_deref(), metric)
),
StateCheckViolation::RatchetCeilingRaised {
source_set,
metric,
base_ceiling,
head_ceiling,
metric_version,
} => write!(
formatter,
"Ratchet ceiling for {} was raised from {base_ceiling} to {head_ceiling} (Metric version {metric_version})",
format_metric_label(source_set.as_deref(), metric)
),
StateCheckViolation::BaselineFindingsAdded {
source_set,
metric,
base_count,
head_count,
added_count,
metric_version,
..
} => {
let noun = if *added_count == 1 {
"Finding"
} else {
"Findings"
};
write!(
formatter,
"Baseline for {} added {added_count} {noun} ({base_count} to {head_count}, Metric version {metric_version})",
format_metric_label(source_set.as_deref(), metric)
)
}
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StateCheckComparison {
pub violations: Vec<StateCheckViolation>,
}
impl StateCheckComparison {
pub fn passed(&self) -> bool {
self.violations.is_empty()
}
}
pub fn compare_state(
ratchet_path: &str,
base_ratchet: Option<&Ratchet>,
head_ratchet: Option<&Ratchet>,
base_baseline: Option<&Baseline>,
head_baseline: Option<&Baseline>,
renames: &BTreeMap<String, String>,
) -> StateCheckComparison {
let mut violations = Vec::new();
compare_ratchet(ratchet_path, base_ratchet, head_ratchet, &mut violations);
compare_baseline(base_baseline, head_baseline, renames, &mut violations);
StateCheckComparison { violations }
}
fn compare_ratchet(
ratchet_path: &str,
base_ratchet: Option<&Ratchet>,
head_ratchet: Option<&Ratchet>,
violations: &mut Vec<StateCheckViolation>,
) {
let Some(base) = base_ratchet else {
return;
};
let Some(head) = head_ratchet else {
violations.push(StateCheckViolation::RatchetFileDeleted {
path: ratchet_path.to_owned(),
});
return;
};
for (source_set, entries) in base.source_sets.iter() {
for (metric, &base_entry) in entries {
compare_ratchet_entry(
Some(source_set),
metric,
base_entry,
head.entry(Some(source_set), metric),
violations,
);
}
}
for (metric, &base_entry) in &base.dependencies {
compare_ratchet_entry(
None,
metric,
base_entry,
head.entry(None, metric),
violations,
);
}
}
fn compare_ratchet_entry(
source_set: Option<SourceSet>,
metric: &str,
base_entry: RatchetEntry,
head_entry: Option<RatchetEntry>,
violations: &mut Vec<StateCheckViolation>,
) {
let source_set_key = source_set.map(|set| set.key().to_owned());
let base_ceiling = round_ratchet_ratio(base_entry.ceiling);
let Some(head_entry) = head_entry else {
violations.push(StateCheckViolation::RatchetEntryRemoved {
source_set: source_set_key,
metric: metric.to_owned(),
base_ceiling,
metric_version: base_entry.metric_version,
});
return;
};
if head_entry.metric_version != base_entry.metric_version {
return;
}
let head_ceiling = round_ratchet_ratio(head_entry.ceiling);
if head_ceiling > base_ceiling {
violations.push(StateCheckViolation::RatchetCeilingRaised {
source_set: source_set_key,
metric: metric.to_owned(),
base_ceiling,
head_ceiling,
metric_version: base_entry.metric_version,
});
}
}
fn compare_baseline(
base_baseline: Option<&Baseline>,
head_baseline: Option<&Baseline>,
renames: &BTreeMap<String, String>,
violations: &mut Vec<StateCheckViolation>,
) {
let (Some(base), Some(head)) = (base_baseline, head_baseline) else {
return;
};
for (source_set, entries) in head.source_sets.iter() {
for (metric, head_entry) in entries {
compare_baseline_entry(
Some(source_set),
metric,
base.entry(Some(source_set), metric),
head_entry,
renames,
violations,
);
}
}
for (metric, head_entry) in &head.dependencies {
compare_baseline_entry(
None,
metric,
base.entry(None, metric),
head_entry,
renames,
violations,
);
}
}
fn compare_baseline_entry(
source_set: Option<SourceSet>,
metric: &str,
base_entry: Option<&BaselineEntry>,
head_entry: &BaselineEntry,
renames: &BTreeMap<String, String>,
violations: &mut Vec<StateCheckViolation>,
) {
let source_set_key = source_set.map(|set| set.key().to_owned());
let Some(base_entry) = base_entry else {
if !head_entry.findings.is_empty() {
let mut added_ids: Vec<String> = head_entry
.findings
.iter()
.map(|finding| finding.id.clone())
.collect();
added_ids.sort();
violations.push(StateCheckViolation::BaselineFindingsAdded {
source_set: source_set_key,
metric: metric.to_owned(),
base_count: 0,
head_count: head_entry.findings.len(),
added_count: added_ids.len(),
added_ids,
metric_version: head_entry.metric_version,
});
}
return;
};
if head_entry.metric_version != base_entry.metric_version {
return;
}
let matched = match_anchors_with_renames(&base_entry.findings, &head_entry.findings, renames);
let mut matched_head = vec![None; head_entry.findings.len()];
for (base, head) in matched.matched_pairs {
matched_head[head] = Some(&base_entry.findings[base]);
}
let covered_clone_lines = base_entry.covered_clone_lines(renames);
let mut added_ids: Vec<String> = head_entry
.findings
.iter()
.enumerate()
.filter(|&(index, finding)| {
if finding.clone_lines.is_empty() {
return matched_head[index].is_none_or(|old| !old.clone_lines.is_empty());
}
matched_head[index].is_none()
|| finding
.clone_lines
.iter()
.any(|line| !covered_clone_lines.contains(line))
})
.map(|(_, finding)| finding.id.clone())
.collect();
if !added_ids.is_empty() {
added_ids.sort();
violations.push(StateCheckViolation::BaselineFindingsAdded {
source_set: source_set_key,
metric: metric.to_owned(),
base_count: base_entry.findings.len(),
head_count: head_entry.findings.len(),
added_count: added_ids.len(),
added_ids,
metric_version: head_entry.metric_version,
});
}
}
fn format_metric_label(source_set: Option<&str>, metric: &str) -> String {
match source_set {
Some(source_set) => format!("{source_set}.{metric}"),
None => metric.to_owned(),
}
}