1use std::path::Path;
36
37use fallow_output::{
38 AuditFindingAttribution, AuditGateExemption, CoverageSource, DEFAULT_COGNITIVE_CRITICAL,
39 DEFAULT_COGNITIVE_HIGH, DEFAULT_CYCLOMATIC_CRITICAL, DEFAULT_CYCLOMATIC_HIGH,
40 ExceededThreshold, FindingSeverity, WorsenedMetric, WorsenedMetricKind,
41 compute_finding_severity,
42};
43use fallow_types::output_dead_code::EffectiveSeverity;
44use rustc_hash::{FxHashMap, FxHashSet};
45
46use crate::audit_keys::{health_finding_key, remap_key_for_renames};
47
48#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct ComplexityMetrics {
51 pub line: u32,
53 pub cyclomatic: u16,
55 pub cognitive: u16,
57 pub crap: Option<f64>,
59 pub line_count: u32,
61 pub exceeded: ExceededThreshold,
63 pub severity: FindingSeverity,
65 pub crap_estimated: bool,
67}
68
69impl ComplexityMetrics {
70 #[must_use]
72 pub const fn of(finding: &fallow_output::ComplexityViolation) -> Self {
73 Self {
74 line: finding.line,
75 cyclomatic: finding.cyclomatic,
76 cognitive: finding.cognitive,
77 crap: finding.crap,
78 line_count: finding.line_count,
79 exceeded: finding.exceeded,
80 severity: finding.severity,
81 crap_estimated: crap_is_estimated(finding),
82 }
83 }
84
85 fn same_values(&self, other: &Self) -> bool {
88 self.cyclomatic == other.cyclomatic
89 && self.cognitive == other.cognitive
90 && self.crap.map(f64::to_bits) == other.crap.map(f64::to_bits)
91 }
92
93 fn same_values_and_lines(&self, other: &Self) -> bool {
96 self.same_values(other) && self.line_count == other.line_count
97 }
98
99 const fn same_structure(&self, other: &Self) -> bool {
103 self.cyclomatic == other.cyclomatic && self.cognitive == other.cognitive
104 }
105
106 const fn same_structure_and_lines(&self, other: &Self) -> bool {
109 self.same_structure(other) && self.line_count == other.line_count
110 }
111}
112
113#[derive(Debug, Clone, PartialEq, Default)]
115pub struct ComplexityClass {
116 pub introduced: bool,
119 pub worsened_metrics: Vec<WorsenedMetric>,
122 pub exceeded_metric_grew: bool,
126}
127
128impl ComplexityClass {
129 #[must_use]
132 pub fn is_worsened(&self) -> bool {
133 !self.introduced && !self.worsened_metrics.is_empty()
134 }
135
136 #[must_use]
138 pub fn attribution(&self) -> AuditFindingAttribution {
139 if self.introduced {
140 AuditFindingAttribution::Introduced
141 } else if self.worsened_metrics.is_empty() {
142 AuditFindingAttribution::Inherited
143 } else {
144 AuditFindingAttribution::Worsened
145 }
146 }
147
148 pub fn clear_worsened_for_off(&mut self) {
153 if !self.introduced && !self.exceeded_metric_grew {
154 self.worsened_metrics.clear();
155 }
156 }
157
158 fn of_match(
159 head: &fallow_output::ComplexityViolation,
160 base: Option<&ComplexityMetrics>,
161 ) -> Self {
162 base.map_or(
163 Self {
164 introduced: true,
165 worsened_metrics: Vec::new(),
166 exceeded_metric_grew: false,
167 },
168 |base| {
169 let exceeded_metric_grew = exceeded_metric_increased(head, base);
170 Self {
171 introduced: newly_exceeded_metric_grew(head, base)
172 || (exceeded_metric_grew && severity_tier_rose(head, base)),
173 worsened_metrics: grown_metrics(head, base),
174 exceeded_metric_grew,
175 }
176 },
177 )
178 }
179}
180
181fn grown_metrics(
187 head: &fallow_output::ComplexityViolation,
188 base: &ComplexityMetrics,
189) -> Vec<WorsenedMetric> {
190 let mut grown = Vec::new();
191 let mut push = |metric, base: f64, head: f64| {
192 if head > base {
193 grown.push(WorsenedMetric { metric, base, head });
194 }
195 };
196 push(
197 WorsenedMetricKind::Cyclomatic,
198 f64::from(base.cyclomatic),
199 f64::from(head.cyclomatic),
200 );
201 push(
202 WorsenedMetricKind::Cognitive,
203 f64::from(base.cognitive),
204 f64::from(head.cognitive),
205 );
206 if let (Some(base_crap), Some(head_crap)) = (base.crap, head.crap) {
207 push(WorsenedMetricKind::Crap, base_crap, head_crap);
208 }
209 if line_count_grew(base.line_count, head.line_count) {
210 grown.push(WorsenedMetric {
211 metric: WorsenedMetricKind::LineCount,
212 base: f64::from(base.line_count),
213 head: f64::from(head.line_count),
214 });
215 }
216 grown
217}
218
219const LINE_COUNT_MIN_GROWTH_LINES: u32 = 5;
221
222fn line_count_grew(base: u32, head: u32) -> bool {
230 head.saturating_sub(base) >= LINE_COUNT_MIN_GROWTH_LINES
231}
232
233pub type ComplexityBaseline = FxHashMap<String, Vec<ComplexityMetrics>>;
236
237#[must_use]
239pub fn complexity_baseline(
240 report: &fallow_output::HealthReport,
241 root: &Path,
242) -> ComplexityBaseline {
243 let mut baseline = ComplexityBaseline::default();
244 for finding in &report.findings {
245 baseline
246 .entry(health_finding_key(finding, root))
247 .or_default()
248 .push(ComplexityMetrics::of(finding));
249 }
250 sort_by_line(&mut baseline);
251 baseline
252}
253
254#[must_use]
256pub fn complexity_baseline_keys(baseline: &ComplexityBaseline) -> FxHashSet<String> {
257 baseline.keys().cloned().collect()
258}
259
260#[must_use]
266#[expect(
267 clippy::implicit_hasher,
268 reason = "fallow standardizes on FxHashMap across audit attribution keys"
269)]
270pub fn remap_complexity_baseline_for_renames(
271 baseline: ComplexityBaseline,
272 renames: &FxHashMap<String, String>,
273) -> ComplexityBaseline {
274 let mut remapped = ComplexityBaseline::default();
275 for (key, findings) in baseline {
276 remapped
277 .entry(remap_key_for_renames(&key, renames))
278 .or_default()
279 .extend(findings);
280 }
281 sort_by_line(&mut remapped);
282 remapped
283}
284
285fn sort_by_line(baseline: &mut ComplexityBaseline) {
286 for findings in baseline.values_mut() {
287 findings.sort_by_key(|metrics| metrics.line);
288 }
289}
290
291fn exceeded_metric_increased(
296 head: &fallow_output::ComplexityViolation,
297 base: &ComplexityMetrics,
298) -> bool {
299 let exceeded = head.exceeded;
300 (exceeded.includes_cyclomatic() && head.cyclomatic > base.cyclomatic)
301 || (exceeded.includes_cognitive() && head.cognitive > base.cognitive)
302 || (exceeded.includes_crap() && measured_crap_grew(head, base))
303 || (exceeded.is_file_lines() && line_count_grew(base.line_count, head.line_count))
304}
305
306fn newly_exceeded_metric_grew(
310 head: &fallow_output::ComplexityViolation,
311 base: &ComplexityMetrics,
312) -> bool {
313 let (now, before) = (head.exceeded, base.exceeded);
314 (now.includes_cyclomatic()
315 && !before.includes_cyclomatic()
316 && head.cyclomatic > base.cyclomatic)
317 || (now.includes_cognitive()
318 && !before.includes_cognitive()
319 && head.cognitive > base.cognitive)
320 || (now.includes_crap() && !before.includes_crap() && measured_crap_grew(head, base))
321}
322
323fn measured_crap_grew(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
327 crap_is_comparable(head, base)
328 && matches!((head.crap, base.crap), (Some(head), Some(base)) if head > base)
329}
330
331fn crap_is_comparable(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
332 head.crap.is_some() && base.crap.is_some() && !crap_is_estimated(head) && !base.crap_estimated
333}
334
335fn severity_tier_rose(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
341 if crap_is_comparable(head, base) {
342 return head.severity > base.severity;
343 }
344 complexity_tier(head.cognitive, head.cyclomatic)
345 > complexity_tier(base.cognitive, base.cyclomatic)
346}
347
348fn complexity_tier(cognitive: u16, cyclomatic: u16) -> FindingSeverity {
349 compute_finding_severity(
350 cognitive,
351 cyclomatic,
352 None,
353 DEFAULT_COGNITIVE_HIGH,
354 DEFAULT_COGNITIVE_CRITICAL,
355 DEFAULT_CYCLOMATIC_HIGH,
356 DEFAULT_CYCLOMATIC_CRITICAL,
357 )
358}
359
360#[must_use]
363pub const fn crap_is_estimated(finding: &fallow_output::ComplexityViolation) -> bool {
364 matches!(
365 finding.coverage_source,
366 Some(CoverageSource::Estimated | CoverageSource::EstimatedComponentInherited)
367 )
368}
369
370#[must_use]
373pub const fn exceeds_only_estimated_crap(finding: &fallow_output::ComplexityViolation) -> bool {
374 matches!(finding.exceeded, ExceededThreshold::Crap) && crap_is_estimated(finding)
375}
376
377pub fn demote_estimated_crap_gates(findings: &mut [fallow_output::HealthFinding]) {
385 for finding in findings {
386 if exceeds_only_estimated_crap(finding)
387 && finding.effective_severity == Some(EffectiveSeverity::Error)
388 {
389 finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
390 }
391 }
392}
393
394pub fn exempt_test_file_gates(findings: &mut [fallow_output::HealthFinding], root: &Path) {
402 for finding in findings {
403 let relative = finding.path.strip_prefix(root).unwrap_or(&finding.path);
404 if fallow_engine::test_paths::is_test_path(root, relative) {
405 finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
406 finding.gate_exemption = Some(AuditGateExemption::TestFile);
407 }
408 }
409}
410
411#[must_use]
414pub fn classify_complexity_findings(
415 findings: &[fallow_output::HealthFinding],
416 root: &Path,
417 base: &ComplexityBaseline,
418) -> Vec<bool> {
419 classify_complexity_attribution(findings, root, base)
420 .into_iter()
421 .map(|class| class.introduced)
422 .collect()
423}
424
425#[must_use]
457pub fn classify_complexity_attribution(
458 findings: &[fallow_output::HealthFinding],
459 root: &Path,
460 base: &ComplexityBaseline,
461) -> Vec<ComplexityClass> {
462 let mut groups: FxHashMap<String, Vec<usize>> = FxHashMap::default();
463 for (index, finding) in findings.iter().enumerate() {
464 groups
465 .entry(health_finding_key(finding, root))
466 .or_default()
467 .push(index);
468 }
469 let mut matches: Vec<Option<&ComplexityMetrics>> = vec![None; findings.len()];
470 for (key, mut heads) in groups {
471 let Some(bases) = base.get(&key) else {
472 continue;
473 };
474 heads.sort_by_key(|&index| (findings[index].line, findings[index].col));
475 let mut unmatched_bases: Vec<Option<&ComplexityMetrics>> = bases.iter().map(Some).collect();
476 let rules: [fn(&ComplexityMetrics, &ComplexityMetrics) -> bool; 4] = [
477 ComplexityMetrics::same_values_and_lines,
478 ComplexityMetrics::same_values,
479 ComplexityMetrics::same_structure_and_lines,
480 ComplexityMetrics::same_structure,
481 ];
482 for rule in rules {
483 for &index in &heads {
484 if matches[index].is_some() {
485 continue;
486 }
487 let head = ComplexityMetrics::of(&findings[index]);
488 if let Some(slot) = unmatched_bases
489 .iter_mut()
490 .find(|slot| slot.is_some_and(|base| rule(base, &head)))
491 {
492 matches[index] = slot.take();
493 }
494 }
495 }
496 let mut remaining_bases = unmatched_bases.into_iter().flatten();
497 for &index in &heads {
498 if matches[index].is_none() {
499 matches[index] = remaining_bases.next();
500 }
501 }
502 }
503 findings
504 .iter()
505 .zip(matches)
506 .map(|(finding, base)| ComplexityClass::of_match(finding, base))
507 .collect()
508}
509
510#[must_use]
514pub fn classify_complexity_findings_against_all<'a>(
515 findings: &[fallow_output::HealthFinding],
516 root: &Path,
517 bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
518) -> Vec<bool> {
519 classify_complexity_attribution_against_all(findings, root, bases)
520 .into_iter()
521 .map(|class| class.introduced)
522 .collect()
523}
524
525#[must_use]
534pub fn classify_complexity_attribution_against_all<'a>(
535 findings: &[fallow_output::HealthFinding],
536 root: &Path,
537 bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
538) -> Vec<ComplexityClass> {
539 let per_base: Vec<Vec<ComplexityClass>> = bases
540 .into_iter()
541 .map(|base| classify_complexity_attribution(findings, root, base))
542 .collect();
543 (0..findings.len())
544 .map(|index| {
545 let classes = per_base.iter().map(|classes| &classes[index]);
546 let inherited = classes
547 .clone()
548 .filter(|class| !class.introduced)
549 .min_by_key(|class| class.worsened_metrics.len());
550 inherited.cloned().unwrap_or_else(|| ComplexityClass {
551 introduced: true,
552 exceeded_metric_grew: false,
553 worsened_metrics: classes
554 .map(|class| &class.worsened_metrics)
555 .find(|metrics| !metrics.is_empty())
556 .cloned()
557 .unwrap_or_default(),
558 })
559 })
560 .collect()
561}
562
563#[must_use]
569pub fn complexity_ledger_keys(
570 findings: &[fallow_output::HealthFinding],
571 root: &Path,
572) -> Vec<String> {
573 let mut seen: FxHashMap<String, usize> = FxHashMap::default();
574 findings
575 .iter()
576 .map(|finding| {
577 let key = health_finding_key(finding, root);
578 let occurrence = seen.entry(key.clone()).or_default();
579 *occurrence += 1;
580 if *occurrence == 1 {
581 key
582 } else {
583 format!("{key}#{occurrence}")
584 }
585 })
586 .collect()
587}
588
589#[cfg(test)]
590mod tests {
591 use std::path::PathBuf;
592
593 use fallow_output::{
594 ComplexityViolation, ExceededThreshold, FindingSeverity, HealthFinding, HealthReport,
595 };
596
597 use super::*;
598
599 const MAX: u16 = 15;
600
601 fn root() -> PathBuf {
602 PathBuf::from("/project")
603 }
604
605 fn finding(name: &str, line: u32, cyclomatic: u16, cognitive: u16) -> HealthFinding {
606 HealthFinding::from(ComplexityViolation {
607 path: root().join("src/index.js"),
608 name: name.to_string(),
609 line,
610 col: 0,
611 cyclomatic,
612 standard_cyclomatic: None,
613 cognitive,
614 line_count: 30,
615 param_count: 1,
616 react_hook_count: 0,
617 react_jsx_max_depth: 0,
618 react_prop_count: 0,
619 react_hook_profile: None,
620 exceeded: ExceededThreshold::from_bools(cyclomatic > MAX, cognitive > MAX, false),
621 effective_severity: None,
622 severity: FindingSeverity::High,
623 crap: None,
624 mutation: None,
625 coverage_pct: None,
626 coverage_tier: None,
627 coverage_source: None,
628 inherited_from: None,
629 component_rollup: None,
630 contributions: Vec::new(),
631 effective_thresholds: None,
632 threshold_source: None,
633 max_file_lines: None,
634 })
635 }
636
637 fn baseline(findings: Vec<HealthFinding>) -> ComplexityBaseline {
638 complexity_baseline(
639 &HealthReport {
640 findings,
641 ..HealthReport::default()
642 },
643 &root(),
644 )
645 }
646
647 fn classify(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<bool> {
648 classify_complexity_findings(head, &root(), &baseline(base))
649 }
650
651 #[test]
652 fn identity_key_excludes_category_and_line() {
653 let key = health_finding_key(&finding("hotspot", 4, 17, 16), &root());
654 assert_eq!(key, "complexity:src/index.js:hotspot");
655 }
656
657 #[test]
658 fn issue_cases() {
659 assert_eq!(
661 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 17, 16)]),
662 [false]
663 );
664 assert_eq!(
666 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 18, 17)]),
667 [false]
668 );
669 assert_eq!(
671 classify(vec![finding("f", 1, 18, 17)], &[finding("f", 1, 17, 16)]),
672 [false]
673 );
674 assert_eq!(
676 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 16, 15)]),
677 [false]
678 );
679 assert_eq!(classify(vec![], &[finding("f", 1, 17, 16)]), [true]);
681 }
682
683 #[test]
684 fn only_exceeded_metrics_can_introduce() {
685 assert_eq!(
688 classify(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]),
689 [false]
690 );
691 assert_eq!(
693 classify(vec![finding("f", 1, 20, 14)], &[finding("f", 1, 19, 16)]),
694 [true]
695 );
696 }
697
698 #[test]
699 fn a_finding_that_any_base_has_is_inherited() {
700 let primary = baseline(vec![]);
701 let merged = baseline(vec![finding("f", 1, 17, 16)]);
702 let head = [finding("f", 1, 17, 16), finding("g", 9, 17, 16)];
703 assert_eq!(
704 classify_complexity_findings_against_all(&head, &root(), [&primary, &merged]),
705 [false, true]
706 );
707 assert_eq!(
710 classify_complexity_findings_against_all(
711 &[finding("f", 1, 31, 17)],
712 &root(),
713 [&baseline(vec![finding("f", 1, 17, 16)]), &merged]
714 ),
715 [true]
716 );
717 }
718
719 #[test]
720 fn line_shift_keeps_the_match() {
721 assert_eq!(
722 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 40, 17, 16)]),
723 [false]
724 );
725 }
726
727 fn crap_finding(crap: Option<f64>, source: Option<CoverageSource>) -> HealthFinding {
728 let mut finding = finding("f", 1, 16, 5);
729 finding.violation.exceeded = ExceededThreshold::Crap;
730 finding.violation.crap = crap;
731 finding.violation.coverage_source = source;
732 finding.violation.effective_severity = Some(EffectiveSeverity::Error);
733 finding
734 }
735
736 #[test]
737 fn crap_without_base_value_is_not_an_increase() {
738 let head = crap_finding(Some(50.0), Some(CoverageSource::Istanbul));
741 assert_eq!(
742 classify(vec![crap_finding(None, None)], std::slice::from_ref(&head)),
743 [false]
744 );
745 assert_eq!(
747 classify(
748 vec![crap_finding(Some(40.0), Some(CoverageSource::Istanbul))],
749 std::slice::from_ref(&head)
750 ),
751 [false]
752 );
753 assert_eq!(
754 classify(
755 vec![crap_finding(Some(60.0), Some(CoverageSource::Istanbul))],
756 &[head]
757 ),
758 [false]
759 );
760 }
761
762 #[test]
763 fn estimated_crap_growth_is_worsened_not_introduced() {
764 let estimated = Some(CoverageSource::Estimated);
765 let classes = attribution(
766 vec![crap_finding(Some(40.0), estimated)],
767 &[crap_finding(Some(50.0), estimated)],
768 );
769 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
770 assert_eq!(
771 classes[0].worsened_metrics,
772 [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
773 );
774 let mut base = crap_finding(Some(40.0), estimated);
776 base.violation.exceeded = ExceededThreshold::CognitiveCrap;
777 base.violation.cognitive = 20;
778 let mut head = base.clone();
779 head.violation.cognitive = 21;
780 head.violation.crap = Some(50.0);
781 assert_eq!(classify(vec![base.clone()], &[head.clone()]), [false]);
782 head.violation.cognitive = 25;
784 assert_eq!(classify(vec![base], &[head]), [true]);
785 }
786
787 #[test]
788 fn test_file_findings_get_warn_gate_severity_and_the_exemption() {
789 let project = root().join("tests").join("project");
792 let at = |relative: &str| {
793 let mut finding = finding("f", 1, 16, 5);
794 finding.violation.path = project.join(relative);
795 finding.violation.effective_severity = Some(EffectiveSeverity::Error);
796 finding
797 };
798 let mut findings = [
799 at("src/__tests__/app.js"),
800 at("src/app.spec.ts"),
801 at("src/app.test.tsx"),
802 at("src/__mocks__/api.js"),
803 at("src/app.js"),
804 at("src/latest.js"),
805 ];
806 exempt_test_file_gates(&mut findings, &project);
807 let marks: Vec<_> = findings
808 .iter()
809 .map(|finding| (finding.effective_severity, finding.gate_exemption))
810 .collect();
811 let exempt = (
812 Some(EffectiveSeverity::Warn),
813 Some(AuditGateExemption::TestFile),
814 );
815 let gated = (Some(EffectiveSeverity::Error), None);
816 assert_eq!(marks, [exempt, exempt, exempt, exempt, gated, gated]);
817 }
818
819 #[test]
820 fn estimated_crap_only_findings_get_warn_gate_severity() {
821 let mut both = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
822 both.violation.exceeded = ExceededThreshold::CognitiveCrap;
823 let mut warn_rule = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
824 warn_rule.violation.effective_severity = Some(EffectiveSeverity::Warn);
825 let mut findings = [
826 crap_finding(Some(50.0), Some(CoverageSource::Estimated)),
827 crap_finding(
828 Some(50.0),
829 Some(CoverageSource::EstimatedComponentInherited),
830 ),
831 crap_finding(Some(50.0), Some(CoverageSource::Istanbul)),
832 both,
833 warn_rule,
834 ];
835 demote_estimated_crap_gates(&mut findings);
836 let severities: Vec<_> = findings
837 .iter()
838 .map(|finding| finding.effective_severity)
839 .collect();
840 assert_eq!(
841 severities,
842 [
843 Some(EffectiveSeverity::Warn),
844 Some(EffectiveSeverity::Warn),
845 Some(EffectiveSeverity::Error),
846 Some(EffectiveSeverity::Error),
847 Some(EffectiveSeverity::Warn),
848 ]
849 );
850 }
851
852 #[test]
853 fn same_named_findings_match_unchanged_values_first() {
854 let base = vec![finding("run", 1, 17, 16), finding("run", 30, 21, 20)];
855 assert_eq!(
857 classify(
858 base.clone(),
859 &[finding("run", 1, 17, 16), finding("run", 30, 21, 20)]
860 ),
861 [false, false]
862 );
863 assert_eq!(
865 classify(base.clone(), &[finding("run", 1, 21, 20)]),
866 [false]
867 );
868 assert_eq!(
870 classify(
871 base.clone(),
872 &[
873 finding("run", 1, 30, 30),
874 finding("run", 20, 17, 16),
875 finding("run", 50, 21, 20)
876 ]
877 ),
878 [true, false, false]
879 );
880 assert_eq!(
882 classify(
883 base.clone(),
884 &[finding("run", 1, 18, 17), finding("run", 30, 21, 20)]
885 ),
886 [false, false]
887 );
888 assert_eq!(
890 classify(
891 base,
892 &[finding("run", 1, 30, 17), finding("run", 30, 21, 20)]
893 ),
894 [true, false]
895 );
896 }
897
898 fn arrow(
900 line: u32,
901 cyclomatic: u16,
902 cognitive: u16,
903 crap: Option<f64>,
904 source: CoverageSource,
905 ) -> HealthFinding {
906 let mut finding = finding("<arrow>", line, MAX + 1, MAX + 1);
907 finding.violation.cyclomatic = cyclomatic;
908 finding.violation.cognitive = cognitive;
909 finding.violation.crap = crap;
910 finding.violation.coverage_source = crap.map(|_| source);
911 finding.violation.exceeded = ExceededThreshold::from_bools(
912 cyclomatic > MAX,
913 cognitive > MAX,
914 crap.is_some_and(|crap| crap >= 30.0),
915 );
916 finding
917 }
918
919 #[test]
920 fn unchanged_arrow_keeps_its_base_when_only_crap_changes() {
921 let estimated = CoverageSource::Estimated;
926 let measured = CoverageSource::Istanbul;
927 let base = [
928 (122, 36, 37, 1332.0),
929 (284, 26, 28, 702.0),
930 (352, 9, 6, 90.0),
931 (560, 7, 6, 56.0),
932 (637, 30, 42, 930.0),
933 (732, 13, 5, 182.0),
934 (872, 13, 12, 182.0),
935 (889, 6, 2, 42.0),
936 (945, 5, 3, 30.0),
937 (972, 16, 4, 272.0),
938 (1017, 11, 13, 132.0),
939 (1184, 14, 15, 210.0),
940 (1202, 12, 5, 156.0),
941 ]
942 .into_iter()
943 .map(|(line, cyclomatic, cognitive, crap)| {
944 arrow(line, cyclomatic, cognitive, Some(crap), estimated)
945 })
946 .collect();
947 let head = [
948 arrow(128, 36, 37, Some(36.0), measured),
949 arrow(294, 27, 29, None, measured),
950 arrow(663, 30, 42, Some(30.0), measured),
951 ];
952 let classes = attribution(base, &head);
953 assert!(!classes[0].introduced);
954 assert!(!classes[2].introduced, "{:?}", classes[2]);
955 assert!(classes[2].worsened_metrics.is_empty());
956 }
957
958 #[test]
959 fn crap_growth_of_an_unchanged_arrow_still_compares() {
960 let measured = CoverageSource::Istanbul;
961 let classes = attribution(
962 vec![
963 arrow(10, 9, 6, Some(40.0), measured),
964 arrow(40, 30, 42, Some(30.0), measured),
965 ],
966 &[arrow(40, 30, 42, Some(60.0), measured)],
967 );
968 assert_eq!(
969 classes[0].worsened_metrics,
970 [metric(WorsenedMetricKind::Crap, 30.0, 60.0)]
971 );
972 }
973
974 fn with_lines(mut finding: HealthFinding, line_count: u32) -> HealthFinding {
975 finding.violation.line_count = line_count;
976 finding
977 }
978
979 fn attribution(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<ComplexityClass> {
980 classify_complexity_attribution(head, &root(), &baseline(base))
981 }
982
983 fn metric(kind: WorsenedMetricKind, base: f64, head: f64) -> WorsenedMetric {
984 WorsenedMetric {
985 metric: kind,
986 base,
987 head,
988 }
989 }
990
991 #[test]
992 fn grown_line_count_is_worsened_not_introduced() {
993 let classes = attribution(
994 vec![with_lines(finding("f", 1, 17, 16), 80)],
995 &[with_lines(finding("f", 1, 17, 16), 300)],
996 );
997 assert!(!classes[0].introduced);
998 assert!(classes[0].is_worsened());
999 assert_eq!(
1000 classes[0].worsened_metrics,
1001 [metric(WorsenedMetricKind::LineCount, 80.0, 300.0)]
1002 );
1003 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1004 }
1005
1006 #[test]
1007 fn grown_metric_that_the_finding_does_not_exceed_is_worsened() {
1008 let classes = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1010 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1011 assert_eq!(
1012 classes[0].worsened_metrics,
1013 [metric(WorsenedMetricKind::Cognitive, 5.0, 9.0)]
1014 );
1015 }
1016
1017 #[test]
1018 fn grown_exceeded_metric_in_the_same_tier_is_worsened() {
1019 let classes = attribution(vec![finding("f", 1, 100, 16)], &[finding("f", 1, 103, 16)]);
1021 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1022 assert!(classes[0].exceeded_metric_grew);
1023 assert_eq!(
1024 classes[0].worsened_metrics,
1025 [metric(WorsenedMetricKind::Cyclomatic, 100.0, 103.0)]
1026 );
1027 let below = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1029 assert!(!below[0].exceeded_metric_grew);
1030 }
1031
1032 #[test]
1033 fn severity_tier_uses_the_base_values_not_todays_thresholds() {
1034 let mut head = finding("f", 1, 18, 10);
1038 head.violation.exceeded = ExceededThreshold::Both;
1039 assert_eq!(
1040 classify(vec![finding("f", 1, 17, 10)], &[head.clone()]),
1041 [false]
1042 );
1043 head.violation.cognitive = 11;
1045 assert_eq!(classify(vec![finding("f", 1, 17, 10)], &[head]), [true]);
1046 }
1047
1048 #[test]
1049 fn measured_crap_tier_crossing_is_introduced() {
1050 let istanbul = Some(CoverageSource::Istanbul);
1051 let mut base = crap_finding(Some(40.0), istanbul);
1052 base.violation.severity = FindingSeverity::Moderate;
1053 let mut head = crap_finding(Some(120.0), istanbul);
1054 head.violation.severity = FindingSeverity::Critical;
1055 assert_eq!(classify(vec![base.clone()], &[head.clone()]), [true]);
1056 let estimated = Some(CoverageSource::Estimated);
1058 base.violation.coverage_source = estimated;
1059 head.violation.coverage_source = estimated;
1060 assert_eq!(classify(vec![base], &[head]), [false]);
1061 }
1062
1063 #[test]
1064 fn grown_exceeded_metric_is_introduced_with_values() {
1065 let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 40, 16)]);
1066 assert_eq!(
1067 classes[0].attribution(),
1068 AuditFindingAttribution::Introduced
1069 );
1070 assert_eq!(
1071 classes[0].worsened_metrics,
1072 [metric(WorsenedMetricKind::Cyclomatic, 17.0, 40.0)]
1073 );
1074 assert!(!classes[0].is_worsened());
1075 }
1076
1077 #[test]
1078 fn improved_and_moved_functions_are_inherited() {
1079 let improved = attribution(
1080 vec![with_lines(finding("f", 1, 30, 30), 90)],
1081 &[with_lines(finding("f", 1, 20, 18), 60)],
1082 );
1083 assert_eq!(
1084 improved[0].attribution(),
1085 AuditFindingAttribution::Inherited
1086 );
1087 assert!(improved[0].worsened_metrics.is_empty());
1088 let moved = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 400, 17, 16)]);
1089 assert_eq!(moved[0].attribution(), AuditFindingAttribution::Inherited);
1090 }
1091
1092 #[test]
1093 fn new_function_is_introduced_without_values() {
1094 let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("g", 1, 17, 16)]);
1095 assert_eq!(
1096 classes[0].attribution(),
1097 AuditFindingAttribution::Introduced
1098 );
1099 assert!(classes[0].worsened_metrics.is_empty());
1100 }
1101
1102 #[test]
1103 fn crap_compares_only_when_both_sides_have_a_score() {
1104 let mut head = finding("f", 1, 20, 5);
1105 head.violation.crap = Some(50.0);
1106 let classes = attribution(vec![finding("f", 1, 20, 5)], std::slice::from_ref(&head));
1107 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1108 let mut base = finding("f", 1, 20, 5);
1109 base.violation.crap = Some(40.0);
1110 let classes = attribution(vec![base], &[head]);
1111 assert_eq!(
1112 classes[0].worsened_metrics,
1113 [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1114 );
1115 }
1116
1117 #[test]
1118 fn same_named_findings_prefer_the_base_with_equal_line_count() {
1119 let base = vec![
1121 with_lines(finding("run", 1, 17, 16), 10),
1122 with_lines(finding("run", 30, 17, 16), 40),
1123 ];
1124 let head = [
1125 with_lines(finding("run", 1, 17, 16), 40),
1126 with_lines(finding("run", 50, 17, 16), 25),
1127 ];
1128 let classes = attribution(base, &head);
1129 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1132 assert_eq!(classes[1].attribution(), AuditFindingAttribution::Worsened);
1133 }
1134
1135 #[test]
1136 fn an_exact_match_of_a_later_head_is_not_taken_by_an_earlier_head() {
1137 let base = vec![
1140 with_lines(finding("run", 1, 17, 16), 40),
1141 with_lines(finding("run", 50, 17, 16), 10),
1142 ];
1143 let head = [
1144 with_lines(finding("run", 1, 17, 16), 30),
1145 with_lines(finding("run", 20, 17, 16), 40),
1146 ];
1147 let classes = attribution(base, &head);
1148 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1149 assert_eq!(
1150 classes[0].worsened_metrics,
1151 [metric(WorsenedMetricKind::LineCount, 10.0, 30.0)]
1152 );
1153 assert_eq!(classes[1].attribution(), AuditFindingAttribution::Inherited);
1154 assert!(classes[1].worsened_metrics.is_empty());
1155 }
1156
1157 #[test]
1158 fn small_line_growth_is_not_worsened() {
1159 let classes = attribution(
1161 vec![with_lines(finding("f", 1, 17, 16), 80)],
1162 &[with_lines(finding("f", 1, 17, 16), 84)],
1163 );
1164 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1165 assert!(classes[0].worsened_metrics.is_empty());
1166 }
1167
1168 #[test]
1169 fn line_growth_needs_five_lines_at_any_function_size() {
1170 let short = attribution(
1172 vec![with_lines(finding("f", 1, 17, 16), 20)],
1173 &[with_lines(finding("f", 1, 17, 16), 24)],
1174 );
1175 assert_eq!(short[0].attribution(), AuditFindingAttribution::Inherited);
1176 let grown = attribution(
1177 vec![with_lines(finding("f", 1, 17, 16), 20)],
1178 &[with_lines(finding("f", 1, 17, 16), 25)],
1179 );
1180 assert_eq!(grown[0].attribution(), AuditFindingAttribution::Worsened);
1181 let long = attribution(
1183 vec![with_lines(finding("f", 1, 17, 16), 300)],
1184 &[with_lines(finding("f", 1, 17, 16), 309)],
1185 );
1186 assert_eq!(long[0].attribution(), AuditFindingAttribution::Worsened);
1187 }
1188
1189 #[test]
1190 fn a_base_with_the_same_values_keeps_the_finding_inherited() {
1191 let primary = baseline(vec![with_lines(finding("f", 1, 17, 16), 20)]);
1192 let merged = baseline(vec![with_lines(finding("f", 1, 17, 16), 60)]);
1193 let head = [with_lines(finding("f", 1, 17, 16), 60)];
1194 let classes =
1195 classify_complexity_attribution_against_all(&head, &root(), [&primary, &merged]);
1196 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1197 let classes = classify_complexity_attribution_against_all(&head, &root(), [&primary]);
1198 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1199 }
1200
1201 #[test]
1202 fn rename_moves_the_base_findings() {
1203 let base = baseline(vec![finding("f", 1, 17, 16)]);
1204 let renames =
1205 FxHashMap::from_iter([("src/index.js".to_string(), "src/moved.js".to_string())]);
1206 let remapped = remap_complexity_baseline_for_renames(base, &renames);
1207 assert!(remapped.contains_key("complexity:src/moved.js:f"));
1208 assert!(!remapped.contains_key("complexity:src/index.js:f"));
1209 }
1210
1211 #[test]
1212 fn ledger_keys_count_same_named_findings_separately() {
1213 let keys = complexity_ledger_keys(
1214 &[finding("run", 1, 17, 16), finding("run", 30, 17, 16)],
1215 &root(),
1216 );
1217 assert_eq!(
1218 keys,
1219 [
1220 "complexity:src/index.js:run",
1221 "complexity:src/index.js:run#2"
1222 ]
1223 );
1224 }
1225}