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