1use std::path::Path;
2use std::process::ExitCode;
3
4use fallow_config::{RulesConfig, Severity};
5use fallow_core::duplicates::DuplicationReport;
6use fallow_core::results::AnalysisResults;
7
8use super::ci::{fingerprint, severity};
9use super::grouping::{self, OwnershipResolver};
10use super::{emit_json, normalize_uri, relative_path};
11use crate::health_types::{
12 ComplexityViolation, CoverageIntelligenceFinding, ExceededThreshold, HealthReport,
13 RuntimeCoverageFinding, UntestedExportFinding, UntestedFileFinding,
14};
15use crate::output_envelope::{
16 CodeClimateIssue, CodeClimateIssueKind, CodeClimateLines, CodeClimateLocation,
17 CodeClimateSeverity,
18};
19
20fn severity_to_codeclimate(s: Severity) -> CodeClimateSeverity {
22 severity::codeclimate_severity(s)
23}
24
25fn cc_path(path: &Path, root: &Path) -> String {
30 normalize_uri(&relative_path(path, root).display().to_string())
31}
32
33fn fingerprint_hash(parts: &[&str]) -> String {
38 fingerprint::fingerprint_hash(parts)
39}
40
41fn cc_issue(
45 check_name: &str,
46 description: &str,
47 severity: CodeClimateSeverity,
48 category: &str,
49 path: &str,
50 begin_line: Option<u32>,
51 fingerprint: &str,
52) -> CodeClimateIssue {
53 CodeClimateIssue {
54 kind: CodeClimateIssueKind::Issue,
55 check_name: check_name.to_string(),
56 description: description.to_string(),
57 categories: vec![category.to_string()],
58 severity,
59 fingerprint: fingerprint.to_string(),
60 location: CodeClimateLocation {
61 path: path.to_string(),
62 lines: CodeClimateLines {
63 begin: begin_line.unwrap_or(1),
64 },
65 },
66 }
67}
68
69fn coverage_intelligence_check_name(
70 recommendation: crate::health_types::CoverageIntelligenceRecommendation,
71) -> &'static str {
72 match recommendation {
73 crate::health_types::CoverageIntelligenceRecommendation::AddTestOrSplitBeforeMerge => {
74 "fallow/coverage-intelligence-risky-change"
75 }
76 crate::health_types::CoverageIntelligenceRecommendation::DeleteAfterConfirmingOwner => {
77 "fallow/coverage-intelligence-delete"
78 }
79 crate::health_types::CoverageIntelligenceRecommendation::ReviewBeforeChanging => {
80 "fallow/coverage-intelligence-review"
81 }
82 crate::health_types::CoverageIntelligenceRecommendation::RefactorCarefullyKeepBehavior => {
83 "fallow/coverage-intelligence-refactor"
84 }
85 }
86}
87
88struct HealthCodeClimateContext<'a> {
89 root: &'a Path,
90 cyc_t: u16,
91 cog_t: u16,
92 crap_t: f64,
93}
94
95impl HealthCodeClimateContext<'_> {
96 fn complexity_issue(&self, finding: &ComplexityViolation) -> CodeClimateIssue {
97 let path = cc_path(&finding.path, self.root);
98 let check_name = complexity_check_name(finding);
99 let line_str = finding.line.to_string();
100 let fp = fingerprint_hash(&[check_name, &path, &line_str, &finding.name]);
101 cc_issue(
102 check_name,
103 &self.complexity_description(finding),
104 health_finding_severity(finding.severity),
105 "Complexity",
106 &path,
107 Some(finding.line),
108 &fp,
109 )
110 }
111
112 fn complexity_description(&self, finding: &ComplexityViolation) -> String {
113 match finding.exceeded {
114 ExceededThreshold::Both => format!(
115 "'{}' has cyclomatic complexity {} (threshold: {}) and cognitive complexity {} (threshold: {})",
116 finding.name, finding.cyclomatic, self.cyc_t, finding.cognitive, self.cog_t
117 ),
118 ExceededThreshold::Cyclomatic => format!(
119 "'{}' has cyclomatic complexity {} (threshold: {})",
120 finding.name, finding.cyclomatic, self.cyc_t
121 ),
122 ExceededThreshold::Cognitive => format!(
123 "'{}' has cognitive complexity {} (threshold: {})",
124 finding.name, finding.cognitive, self.cog_t
125 ),
126 ExceededThreshold::Crap
127 | ExceededThreshold::CyclomaticCrap
128 | ExceededThreshold::CognitiveCrap
129 | ExceededThreshold::All => {
130 let crap = finding.crap.unwrap_or(0.0);
131 let coverage = finding
132 .coverage_pct
133 .map(|pct| format!(", coverage {pct:.0}%"))
134 .unwrap_or_default();
135 format!(
136 "'{}' has CRAP score {crap:.1} (threshold: {:.1}, cyclomatic {}{coverage})",
137 finding.name, self.crap_t, finding.cyclomatic,
138 )
139 }
140 }
141 }
142
143 fn runtime_coverage_issue(&self, finding: &RuntimeCoverageFinding) -> CodeClimateIssue {
144 let path = cc_path(&finding.path, self.root);
145 let check_name = runtime_coverage_check_name(finding.verdict);
146 let invocations_hint = finding.invocations.map_or_else(
147 || "untracked".to_owned(),
148 |hits| format!("{hits} invocations"),
149 );
150 let description = format!(
151 "'{}' runtime coverage verdict: {} ({})",
152 finding.function,
153 finding.verdict.human_label(),
154 invocations_hint,
155 );
156 let fp = fingerprint_hash(&[
157 check_name,
158 &path,
159 &finding.line.to_string(),
160 &finding.function,
161 ]);
162 cc_issue(
163 check_name,
164 &description,
165 runtime_coverage_severity(finding.verdict),
166 "Bug Risk",
167 &path,
168 Some(finding.line),
169 &fp,
170 )
171 }
172
173 fn coverage_intelligence_issue(
174 &self,
175 finding: &CoverageIntelligenceFinding,
176 ) -> Option<CodeClimateIssue> {
177 let severity = coverage_intelligence_severity(finding.verdict)?;
178 let path = cc_path(&finding.path, self.root);
179 let check_name = coverage_intelligence_check_name(finding.recommendation);
180 let identity = finding.identity.as_deref().unwrap_or("code");
181 let description = format!(
182 "'{}' coverage intelligence verdict: {} ({})",
183 identity, finding.verdict, finding.recommendation,
184 );
185 let fp = fingerprint_hash(&[
186 check_name,
187 &path,
188 &finding.line.to_string(),
189 identity,
190 &finding.id,
191 ]);
192 Some(cc_issue(
193 check_name,
194 &description,
195 severity,
196 "Bug Risk",
197 &path,
198 Some(finding.line),
199 &fp,
200 ))
201 }
202
203 fn untested_file_issue(&self, item: &UntestedFileFinding) -> CodeClimateIssue {
204 let path = cc_path(&item.file.path, self.root);
205 let description = format!(
206 "File is runtime-reachable but has no test dependency path ({} value export{})",
207 item.file.value_export_count,
208 if item.file.value_export_count == 1 {
209 ""
210 } else {
211 "s"
212 },
213 );
214 let fp = fingerprint_hash(&["fallow/untested-file", &path]);
215 cc_issue(
216 "fallow/untested-file",
217 &description,
218 CodeClimateSeverity::Minor,
219 "Coverage",
220 &path,
221 None,
222 &fp,
223 )
224 }
225
226 fn untested_export_issue(&self, item: &UntestedExportFinding) -> CodeClimateIssue {
227 let path = cc_path(&item.export.path, self.root);
228 let description = format!(
229 "Export '{}' is runtime-reachable but never referenced by test-reachable modules",
230 item.export.export_name
231 );
232 let line_str = item.export.line.to_string();
233 let fp = fingerprint_hash(&[
234 "fallow/untested-export",
235 &path,
236 &line_str,
237 &item.export.export_name,
238 ]);
239 cc_issue(
240 "fallow/untested-export",
241 &description,
242 CodeClimateSeverity::Minor,
243 "Coverage",
244 &path,
245 Some(item.export.line),
246 &fp,
247 )
248 }
249}
250
251const fn complexity_check_name(finding: &ComplexityViolation) -> &'static str {
252 match finding.exceeded {
253 ExceededThreshold::Both => "fallow/high-complexity",
254 ExceededThreshold::Cyclomatic => "fallow/high-cyclomatic-complexity",
255 ExceededThreshold::Cognitive => "fallow/high-cognitive-complexity",
256 ExceededThreshold::Crap
257 | ExceededThreshold::CyclomaticCrap
258 | ExceededThreshold::CognitiveCrap
259 | ExceededThreshold::All => "fallow/high-crap-score",
260 }
261}
262
263const fn health_finding_severity(
264 severity: crate::health_types::FindingSeverity,
265) -> CodeClimateSeverity {
266 match severity {
267 crate::health_types::FindingSeverity::Critical => CodeClimateSeverity::Critical,
268 crate::health_types::FindingSeverity::High => CodeClimateSeverity::Major,
269 crate::health_types::FindingSeverity::Moderate => CodeClimateSeverity::Minor,
270 }
271}
272
273const fn runtime_coverage_check_name(
274 verdict: crate::health_types::RuntimeCoverageVerdict,
275) -> &'static str {
276 match verdict {
277 crate::health_types::RuntimeCoverageVerdict::SafeToDelete => {
278 "fallow/runtime-safe-to-delete"
279 }
280 crate::health_types::RuntimeCoverageVerdict::ReviewRequired => {
281 "fallow/runtime-review-required"
282 }
283 crate::health_types::RuntimeCoverageVerdict::LowTraffic => "fallow/runtime-low-traffic",
284 crate::health_types::RuntimeCoverageVerdict::CoverageUnavailable => {
285 "fallow/runtime-coverage-unavailable"
286 }
287 crate::health_types::RuntimeCoverageVerdict::Active
288 | crate::health_types::RuntimeCoverageVerdict::Unknown => "fallow/runtime-coverage",
289 }
290}
291
292const fn runtime_coverage_severity(
293 verdict: crate::health_types::RuntimeCoverageVerdict,
294) -> CodeClimateSeverity {
295 match verdict {
296 crate::health_types::RuntimeCoverageVerdict::SafeToDelete => CodeClimateSeverity::Critical,
297 crate::health_types::RuntimeCoverageVerdict::ReviewRequired => CodeClimateSeverity::Major,
298 _ => CodeClimateSeverity::Minor,
299 }
300}
301
302const fn coverage_intelligence_severity(
303 verdict: crate::health_types::CoverageIntelligenceVerdict,
304) -> Option<CodeClimateSeverity> {
305 match verdict {
306 crate::health_types::CoverageIntelligenceVerdict::RiskyChangeDetected
307 | crate::health_types::CoverageIntelligenceVerdict::HighConfidenceDelete => {
308 Some(CodeClimateSeverity::Major)
309 }
310 crate::health_types::CoverageIntelligenceVerdict::ReviewRequired
311 | crate::health_types::CoverageIntelligenceVerdict::RefactorCarefully => {
312 Some(CodeClimateSeverity::Minor)
313 }
314 crate::health_types::CoverageIntelligenceVerdict::Clean
315 | crate::health_types::CoverageIntelligenceVerdict::Unknown => None,
316 }
317}
318
319fn push_dep_cc_issues<'a, I>(
321 issues: &mut Vec<CodeClimateIssue>,
322 deps: I,
323 root: &Path,
324 rule_id: &str,
325 location_label: &str,
326 severity: Severity,
327) where
328 I: IntoIterator<Item = &'a fallow_core::results::UnusedDependency>,
329{
330 for dep in deps {
331 let level = severity_to_codeclimate(severity);
332 let path = cc_path(&dep.path, root);
333 let line = if dep.line > 0 { Some(dep.line) } else { None };
334 let fp = fingerprint_hash(&[rule_id, &dep.package_name]);
335 let workspace_context = if dep.used_in_workspaces.is_empty() {
336 String::new()
337 } else {
338 let workspaces = dep
339 .used_in_workspaces
340 .iter()
341 .map(|path| cc_path(path, root))
342 .collect::<Vec<_>>()
343 .join(", ");
344 format!("; imported in other workspaces: {workspaces}")
345 };
346 issues.push(cc_issue(
347 rule_id,
348 &format!(
349 "Package '{}' is in {location_label} but never imported{workspace_context}",
350 dep.package_name
351 ),
352 level,
353 "Bug Risk",
354 &path,
355 line,
356 &fp,
357 ));
358 }
359}
360
361fn push_unused_file_issues(
362 issues: &mut Vec<CodeClimateIssue>,
363 files: &[fallow_types::output_dead_code::UnusedFileFinding],
364 root: &Path,
365 severity: Severity,
366) {
367 if files.is_empty() {
368 return;
369 }
370 let level = severity_to_codeclimate(severity);
371 for entry in files {
372 let path = cc_path(&entry.file.path, root);
373 let fp = fingerprint_hash(&["fallow/unused-file", &path]);
374 issues.push(cc_issue(
375 "fallow/unused-file",
376 "File is not reachable from any entry point",
377 level,
378 "Bug Risk",
379 &path,
380 None,
381 &fp,
382 ));
383 }
384}
385
386fn push_unused_export_issues<'a, I>(
392 issues: &mut Vec<CodeClimateIssue>,
393 exports: I,
394 root: &Path,
395 rule_id: &str,
396 direct_label: &str,
397 re_export_label: &str,
398 severity: Severity,
399) where
400 I: IntoIterator<Item = &'a fallow_core::results::UnusedExport>,
401{
402 for export in exports {
403 let level = severity_to_codeclimate(severity);
404 let path = cc_path(&export.path, root);
405 let kind = if export.is_re_export {
406 re_export_label
407 } else {
408 direct_label
409 };
410 let line_str = export.line.to_string();
411 let fp = fingerprint_hash(&[rule_id, &path, &line_str, &export.export_name]);
412 issues.push(cc_issue(
413 rule_id,
414 &format!(
415 "{kind} '{}' is never imported by other modules",
416 export.export_name
417 ),
418 level,
419 "Bug Risk",
420 &path,
421 Some(export.line),
422 &fp,
423 ));
424 }
425}
426
427fn push_private_type_leak_issues(
428 issues: &mut Vec<CodeClimateIssue>,
429 leaks: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
430 root: &Path,
431 severity: Severity,
432) {
433 if leaks.is_empty() {
434 return;
435 }
436 let level = severity_to_codeclimate(severity);
437 for entry in leaks {
438 let leak = &entry.leak;
439 let path = cc_path(&leak.path, root);
440 let line_str = leak.line.to_string();
441 let fp = fingerprint_hash(&[
442 "fallow/private-type-leak",
443 &path,
444 &line_str,
445 &leak.export_name,
446 &leak.type_name,
447 ]);
448 issues.push(cc_issue(
449 "fallow/private-type-leak",
450 &format!(
451 "Export '{}' references private type '{}'",
452 leak.export_name, leak.type_name
453 ),
454 level,
455 "Bug Risk",
456 &path,
457 Some(leak.line),
458 &fp,
459 ));
460 }
461}
462
463fn push_type_only_dep_issues(
464 issues: &mut Vec<CodeClimateIssue>,
465 deps: &[fallow_core::results::TypeOnlyDependencyFinding],
466 root: &Path,
467 severity: Severity,
468) {
469 if deps.is_empty() {
470 return;
471 }
472 let level = severity_to_codeclimate(severity);
473 for entry in deps {
474 let dep = &entry.dep;
475 let path = cc_path(&dep.path, root);
476 let line = if dep.line > 0 { Some(dep.line) } else { None };
477 let fp = fingerprint_hash(&["fallow/type-only-dependency", &dep.package_name]);
478 issues.push(cc_issue(
479 "fallow/type-only-dependency",
480 &format!(
481 "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
482 dep.package_name
483 ),
484 level,
485 "Bug Risk",
486 &path,
487 line,
488 &fp,
489 ));
490 }
491}
492
493fn push_test_only_dep_issues(
494 issues: &mut Vec<CodeClimateIssue>,
495 deps: &[fallow_core::results::TestOnlyDependencyFinding],
496 root: &Path,
497 severity: Severity,
498) {
499 if deps.is_empty() {
500 return;
501 }
502 let level = severity_to_codeclimate(severity);
503 for entry in deps {
504 let dep = &entry.dep;
505 let path = cc_path(&dep.path, root);
506 let line = if dep.line > 0 { Some(dep.line) } else { None };
507 let fp = fingerprint_hash(&["fallow/test-only-dependency", &dep.package_name]);
508 issues.push(cc_issue(
509 "fallow/test-only-dependency",
510 &format!(
511 "Package '{}' is only imported by test files (consider moving to devDependencies)",
512 dep.package_name
513 ),
514 level,
515 "Bug Risk",
516 &path,
517 line,
518 &fp,
519 ));
520 }
521}
522
523fn push_unused_member_issues<'a, I>(
528 issues: &mut Vec<CodeClimateIssue>,
529 members: I,
530 root: &Path,
531 rule_id: &str,
532 entity_label: &str,
533 severity: Severity,
534) where
535 I: IntoIterator<Item = &'a fallow_core::results::UnusedMember>,
536{
537 for member in members {
538 let level = severity_to_codeclimate(severity);
539 let path = cc_path(&member.path, root);
540 let line_str = member.line.to_string();
541 let fp = fingerprint_hash(&[
542 rule_id,
543 &path,
544 &line_str,
545 &member.parent_name,
546 &member.member_name,
547 ]);
548 issues.push(cc_issue(
549 rule_id,
550 &format!(
551 "{entity_label} member '{}.{}' is never referenced",
552 member.parent_name, member.member_name
553 ),
554 level,
555 "Bug Risk",
556 &path,
557 Some(member.line),
558 &fp,
559 ));
560 }
561}
562
563fn push_unresolved_import_issues(
564 issues: &mut Vec<CodeClimateIssue>,
565 imports: &[fallow_types::output_dead_code::UnresolvedImportFinding],
566 root: &Path,
567 severity: Severity,
568) {
569 if imports.is_empty() {
570 return;
571 }
572 let level = severity_to_codeclimate(severity);
573 for entry in imports {
574 let import = &entry.import;
575 let path = cc_path(&import.path, root);
576 let line_str = import.line.to_string();
577 let fp = fingerprint_hash(&[
578 "fallow/unresolved-import",
579 &path,
580 &line_str,
581 &import.specifier,
582 ]);
583 issues.push(cc_issue(
584 "fallow/unresolved-import",
585 &format!("Import '{}' could not be resolved", import.specifier),
586 level,
587 "Bug Risk",
588 &path,
589 Some(import.line),
590 &fp,
591 ));
592 }
593}
594
595fn push_unlisted_dep_issues(
596 issues: &mut Vec<CodeClimateIssue>,
597 deps: &[fallow_core::results::UnlistedDependencyFinding],
598 root: &Path,
599 severity: Severity,
600) {
601 if deps.is_empty() {
602 return;
603 }
604 let level = severity_to_codeclimate(severity);
605 for entry in deps {
606 let dep = &entry.dep;
607 for site in &dep.imported_from {
608 let path = cc_path(&site.path, root);
609 let line_str = site.line.to_string();
610 let fp = fingerprint_hash(&[
611 "fallow/unlisted-dependency",
612 &path,
613 &line_str,
614 &dep.package_name,
615 ]);
616 issues.push(cc_issue(
617 "fallow/unlisted-dependency",
618 &format!(
619 "Package '{}' is imported but not listed in package.json",
620 dep.package_name
621 ),
622 level,
623 "Bug Risk",
624 &path,
625 Some(site.line),
626 &fp,
627 ));
628 }
629 }
630}
631
632fn push_duplicate_export_issues(
633 issues: &mut Vec<CodeClimateIssue>,
634 dups: &[fallow_core::results::DuplicateExportFinding],
635 root: &Path,
636 severity: Severity,
637) {
638 if dups.is_empty() {
639 return;
640 }
641 let level = severity_to_codeclimate(severity);
642 for dup in dups {
643 let dup = &dup.export;
644 for loc in &dup.locations {
645 let path = cc_path(&loc.path, root);
646 let line_str = loc.line.to_string();
647 let fp = fingerprint_hash(&[
648 "fallow/duplicate-export",
649 &path,
650 &line_str,
651 &dup.export_name,
652 ]);
653 issues.push(cc_issue(
654 "fallow/duplicate-export",
655 &format!("Export '{}' appears in multiple modules", dup.export_name),
656 level,
657 "Bug Risk",
658 &path,
659 Some(loc.line),
660 &fp,
661 ));
662 }
663 }
664}
665
666fn push_circular_dep_issues(
667 issues: &mut Vec<CodeClimateIssue>,
668 cycles: &[fallow_types::output_dead_code::CircularDependencyFinding],
669 root: &Path,
670 severity: Severity,
671) {
672 if cycles.is_empty() {
673 return;
674 }
675 let level = severity_to_codeclimate(severity);
676 for entry in cycles {
677 let cycle = &entry.cycle;
678 let Some(first) = cycle.files.first() else {
679 continue;
680 };
681 let path = cc_path(first, root);
682 let chain: Vec<String> = cycle.files.iter().map(|f| cc_path(f, root)).collect();
683 let chain_str = chain.join(":");
684 let fp = fingerprint_hash(&["fallow/circular-dependency", &chain_str]);
685 let line = if cycle.line > 0 {
686 Some(cycle.line)
687 } else {
688 None
689 };
690 issues.push(cc_issue(
691 "fallow/circular-dependency",
692 &format!(
693 "Circular dependency{}: {}",
694 if cycle.is_cross_package {
695 " (cross-package)"
696 } else {
697 ""
698 },
699 chain.join(" \u{2192} ")
700 ),
701 level,
702 "Bug Risk",
703 &path,
704 line,
705 &fp,
706 ));
707 }
708}
709
710fn push_re_export_cycle_issues(
711 issues: &mut Vec<CodeClimateIssue>,
712 cycles: &[fallow_types::output_dead_code::ReExportCycleFinding],
713 root: &Path,
714 severity: Severity,
715) {
716 if cycles.is_empty() {
717 return;
718 }
719 let level = severity_to_codeclimate(severity);
720 for entry in cycles {
721 let cycle = &entry.cycle;
722 let Some(first) = cycle.files.first() else {
723 continue;
724 };
725 let path = cc_path(first, root);
726 let chain: Vec<String> = cycle.files.iter().map(|f| cc_path(f, root)).collect();
727 let chain_str = chain.join(":");
728 let kind_token = match cycle.kind {
729 fallow_core::results::ReExportCycleKind::SelfLoop => "self-loop",
730 fallow_core::results::ReExportCycleKind::MultiNode => "multi-node",
731 };
732 let kind_tag = match cycle.kind {
733 fallow_core::results::ReExportCycleKind::SelfLoop => " (self-loop)",
734 fallow_core::results::ReExportCycleKind::MultiNode => "",
735 };
736 let fp = fingerprint_hash(&["fallow/re-export-cycle", kind_token, &chain_str]);
737 issues.push(cc_issue(
738 "fallow/re-export-cycle",
739 &format!("Re-export cycle{}: {}", kind_tag, chain.join(" <-> ")),
740 level,
741 "Bug Risk",
742 &path,
743 None,
744 &fp,
745 ));
746 }
747}
748
749fn push_boundary_violation_issues(
750 issues: &mut Vec<CodeClimateIssue>,
751 violations: &[fallow_types::output_dead_code::BoundaryViolationFinding],
752 root: &Path,
753 severity: Severity,
754) {
755 if violations.is_empty() {
756 return;
757 }
758 let level = severity_to_codeclimate(severity);
759 for entry in violations {
760 let v = &entry.violation;
761 let path = cc_path(&v.from_path, root);
762 let to = cc_path(&v.to_path, root);
763 let fp = fingerprint_hash(&["fallow/boundary-violation", &path, &to]);
764 let line = if v.line > 0 { Some(v.line) } else { None };
765 issues.push(cc_issue(
766 "fallow/boundary-violation",
767 &format!(
768 "Boundary violation: {} -> {} ({} -> {})",
769 path, to, v.from_zone, v.to_zone
770 ),
771 level,
772 "Bug Risk",
773 &path,
774 line,
775 &fp,
776 ));
777 }
778}
779
780fn push_boundary_coverage_issues(
781 issues: &mut Vec<CodeClimateIssue>,
782 violations: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
783 root: &Path,
784 severity: Severity,
785) {
786 if violations.is_empty() {
787 return;
788 }
789 let level = severity_to_codeclimate(severity);
790 for entry in violations {
791 let v = &entry.violation;
792 let path = cc_path(&v.path, root);
793 let fp = fingerprint_hash(&["fallow/boundary-coverage", &path]);
794 let line = if v.line > 0 { Some(v.line) } else { None };
795 issues.push(cc_issue(
796 "fallow/boundary-coverage",
797 &format!("Boundary coverage: {path} matches no configured zone"),
798 level,
799 "Bug Risk",
800 &path,
801 line,
802 &fp,
803 ));
804 }
805}
806
807fn push_boundary_call_issues(
808 issues: &mut Vec<CodeClimateIssue>,
809 violations: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
810 root: &Path,
811 severity: Severity,
812) {
813 if violations.is_empty() {
814 return;
815 }
816 let level = severity_to_codeclimate(severity);
817 for entry in violations {
818 let v = &entry.violation;
819 let path = cc_path(&v.path, root);
820 let fp = fingerprint_hash(&["fallow/boundary-call-violation", &path, &v.callee]);
821 let line = if v.line > 0 { Some(v.line) } else { None };
822 issues.push(cc_issue(
823 "fallow/boundary-call-violation",
824 &format!(
825 "Boundary call: `{}` matches forbidden pattern `{}` in zone '{}'",
826 v.callee, v.pattern, v.zone
827 ),
828 level,
829 "Bug Risk",
830 &path,
831 line,
832 &fp,
833 ));
834 }
835}
836
837fn push_policy_violation_issues(
838 issues: &mut Vec<CodeClimateIssue>,
839 violations: &[fallow_types::output_dead_code::PolicyViolationFinding],
840 root: &Path,
841) {
842 use fallow_core::results::PolicyViolationSeverity;
843
844 for entry in violations {
845 let v = &entry.violation;
846 let path = cc_path(&v.path, root);
847 let rule = format!("{}/{}", v.pack, v.rule_id);
848 let fp = fingerprint_hash(&["fallow/policy-violation", &path, &rule, &v.matched]);
849 let line = if v.line > 0 { Some(v.line) } else { None };
850 let level = severity_to_codeclimate(match v.severity {
854 PolicyViolationSeverity::Error => Severity::Error,
855 PolicyViolationSeverity::Warn => Severity::Warn,
856 });
857 let message = match &v.message {
858 Some(message) => format!(
859 "Policy violation: `{}` is banned by `{rule}`. {message}",
860 v.matched
861 ),
862 None => format!("Policy violation: `{}` is banned by `{rule}`", v.matched),
863 };
864 issues.push(cc_issue(
865 "fallow/policy-violation",
866 &message,
867 level,
868 "Bug Risk",
869 &path,
870 line,
871 &fp,
872 ));
873 }
874}
875
876fn push_invalid_client_export_issues(
877 issues: &mut Vec<CodeClimateIssue>,
878 findings: &[fallow_types::output_dead_code::InvalidClientExportFinding],
879 root: &Path,
880 severity: Severity,
881) {
882 if findings.is_empty() {
883 return;
884 }
885 let level = severity_to_codeclimate(severity);
886 for entry in findings {
887 let e = &entry.export;
888 let path = cc_path(&e.path, root);
889 let fp = fingerprint_hash(&["fallow/invalid-client-export", &path, &e.export_name]);
890 let line = if e.line > 0 { Some(e.line) } else { None };
891 let message = format!(
892 "Export `{}` is not allowed in a \"{}\" file (Next.js server-only / route-config name)",
893 e.export_name, e.directive
894 );
895 issues.push(cc_issue(
896 "fallow/invalid-client-export",
897 &message,
898 level,
899 "Bug Risk",
900 &path,
901 line,
902 &fp,
903 ));
904 }
905}
906
907fn push_mixed_client_server_barrel_issues(
908 issues: &mut Vec<CodeClimateIssue>,
909 findings: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
910 root: &Path,
911 severity: Severity,
912) {
913 if findings.is_empty() {
914 return;
915 }
916 let level = severity_to_codeclimate(severity);
917 for entry in findings {
918 let b = &entry.barrel;
919 let path = cc_path(&b.path, root);
920 let fp = fingerprint_hash(&[
921 "fallow/mixed-client-server-barrel",
922 &path,
923 &b.client_origin,
924 &b.server_origin,
925 ]);
926 let line = if b.line > 0 { Some(b.line) } else { None };
927 let message = format!(
928 "Barrel re-exports both a \"use client\" module (`{}`) and a server-only module (`{}`); one import drags the other's directive across the boundary",
929 b.client_origin, b.server_origin
930 );
931 issues.push(cc_issue(
932 "fallow/mixed-client-server-barrel",
933 &message,
934 level,
935 "Bug Risk",
936 &path,
937 line,
938 &fp,
939 ));
940 }
941}
942
943fn push_misplaced_directive_issues(
944 issues: &mut Vec<CodeClimateIssue>,
945 findings: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
946 root: &Path,
947 severity: Severity,
948) {
949 if findings.is_empty() {
950 return;
951 }
952 let level = severity_to_codeclimate(severity);
953 for entry in findings {
954 let d = &entry.directive_site;
955 let path = cc_path(&d.path, root);
956 let fp = fingerprint_hash(&[
957 "fallow/misplaced-directive",
958 &path,
959 &d.line.to_string(),
960 &d.directive,
961 ]);
962 let line = if d.line > 0 { Some(d.line) } else { None };
963 let message = format!(
964 "Directive `\"{}\"` is not in the leading position, so the RSC bundler ignores it; move it to the top of the file",
965 d.directive
966 );
967 issues.push(cc_issue(
968 "fallow/misplaced-directive",
969 &message,
970 level,
971 "Bug Risk",
972 &path,
973 line,
974 &fp,
975 ));
976 }
977}
978
979fn push_unprovided_inject_issues(
980 issues: &mut Vec<CodeClimateIssue>,
981 findings: &[fallow_types::output_dead_code::UnprovidedInjectFinding],
982 root: &Path,
983 severity: Severity,
984) {
985 if findings.is_empty() {
986 return;
987 }
988 let level = severity_to_codeclimate(severity);
989 for entry in findings {
990 let i = &entry.inject;
991 let path = cc_path(&i.path, root);
992 let fp = fingerprint_hash(&[
993 "fallow/unprovided-inject",
994 &path,
995 &i.line.to_string(),
996 &i.key_name,
997 ]);
998 let line = if i.line > 0 { Some(i.line) } else { None };
999 let message = format!(
1000 "inject(`{}`) has no matching provide(`{}`) in this project; at runtime it returns undefined (provide the key or remove this inject)",
1001 i.key_name, i.key_name
1002 );
1003 issues.push(cc_issue(
1004 "fallow/unprovided-inject",
1005 &message,
1006 level,
1007 "Bug Risk",
1008 &path,
1009 line,
1010 &fp,
1011 ));
1012 }
1013}
1014
1015fn push_unrendered_component_issues(
1016 issues: &mut Vec<CodeClimateIssue>,
1017 findings: &[fallow_types::output_dead_code::UnrenderedComponentFinding],
1018 root: &Path,
1019 severity: Severity,
1020) {
1021 if findings.is_empty() {
1022 return;
1023 }
1024 let level = severity_to_codeclimate(severity);
1025 for entry in findings {
1026 let c = &entry.component;
1027 let path = cc_path(&c.path, root);
1028 let fp = fingerprint_hash(&[
1029 "fallow/unrendered-component",
1030 &path,
1031 &c.line.to_string(),
1032 &c.component_name,
1033 ]);
1034 let line = if c.line > 0 { Some(c.line) } else { None };
1035 let message = format!(
1036 "component `{}` is reachable but rendered nowhere in this project (render it somewhere or remove it)",
1037 c.component_name
1038 );
1039 issues.push(cc_issue(
1040 "fallow/unrendered-component",
1041 &message,
1042 level,
1043 "Bug Risk",
1044 &path,
1045 line,
1046 &fp,
1047 ));
1048 }
1049}
1050
1051fn push_unused_component_prop_issues(
1052 issues: &mut Vec<CodeClimateIssue>,
1053 findings: &[fallow_types::output_dead_code::UnusedComponentPropFinding],
1054 root: &Path,
1055 severity: Severity,
1056) {
1057 if findings.is_empty() {
1058 return;
1059 }
1060 let level = severity_to_codeclimate(severity);
1061 for entry in findings {
1062 let p = &entry.prop;
1063 let path = cc_path(&p.path, root);
1064 let fp = fingerprint_hash(&[
1065 "fallow/unused-component-prop",
1066 &path,
1067 &p.line.to_string(),
1068 &p.prop_name,
1069 ]);
1070 let line = if p.line > 0 { Some(p.line) } else { None };
1071 let message = format!(
1072 "prop `{}` is declared but referenced nowhere in component `{}` (remove it or use it)",
1073 p.prop_name, p.component_name
1074 );
1075 issues.push(cc_issue(
1076 "fallow/unused-component-prop",
1077 &message,
1078 level,
1079 "Bug Risk",
1080 &path,
1081 line,
1082 &fp,
1083 ));
1084 }
1085}
1086
1087fn push_unused_component_emit_issues(
1088 issues: &mut Vec<CodeClimateIssue>,
1089 findings: &[fallow_types::output_dead_code::UnusedComponentEmitFinding],
1090 root: &Path,
1091 severity: Severity,
1092) {
1093 if findings.is_empty() {
1094 return;
1095 }
1096 let level = severity_to_codeclimate(severity);
1097 for entry in findings {
1098 let e = &entry.emit;
1099 let path = cc_path(&e.path, root);
1100 let fp = fingerprint_hash(&[
1101 "fallow/unused-component-emit",
1102 &path,
1103 &e.line.to_string(),
1104 &e.emit_name,
1105 ]);
1106 let line = if e.line > 0 { Some(e.line) } else { None };
1107 let message = format!(
1108 "emit `{}` is declared but emitted nowhere in component `{}` (remove it or emit it)",
1109 e.emit_name, e.component_name
1110 );
1111 issues.push(cc_issue(
1112 "fallow/unused-component-emit",
1113 &message,
1114 level,
1115 "Bug Risk",
1116 &path,
1117 line,
1118 &fp,
1119 ));
1120 }
1121}
1122
1123fn push_unused_server_action_issues(
1124 issues: &mut Vec<CodeClimateIssue>,
1125 findings: &[fallow_types::output_dead_code::UnusedServerActionFinding],
1126 root: &Path,
1127 severity: Severity,
1128) {
1129 if findings.is_empty() {
1130 return;
1131 }
1132 let level = severity_to_codeclimate(severity);
1133 for entry in findings {
1134 let a = &entry.action;
1135 let path = cc_path(&a.path, root);
1136 let fp = fingerprint_hash(&[
1137 "fallow/unused-server-action",
1138 &path,
1139 &a.line.to_string(),
1140 &a.action_name,
1141 ]);
1142 let line = if a.line > 0 { Some(a.line) } else { None };
1143 let message = format!(
1144 "server action `{}` is exported from a \"use server\" file but no code in this project references it (wire it to a consumer or remove it)",
1145 a.action_name
1146 );
1147 issues.push(cc_issue(
1148 "fallow/unused-server-action",
1149 &message,
1150 level,
1151 "Bug Risk",
1152 &path,
1153 line,
1154 &fp,
1155 ));
1156 }
1157}
1158
1159fn push_unused_load_data_key_issues(
1160 issues: &mut Vec<CodeClimateIssue>,
1161 findings: &[fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
1162 root: &Path,
1163 severity: Severity,
1164) {
1165 if findings.is_empty() {
1166 return;
1167 }
1168 let level = severity_to_codeclimate(severity);
1169 for entry in findings {
1170 let k = &entry.key;
1171 let path = cc_path(&k.path, root);
1172 let fp = fingerprint_hash(&[
1173 "fallow/unused-load-data-key",
1174 &path,
1175 &k.line.to_string(),
1176 &k.key_name,
1177 ]);
1178 let line = if k.line > 0 { Some(k.line) } else { None };
1179 let message = format!(
1180 "load() return key `{}` is read by no consumer (sibling +page.svelte data.<key> or project-wide page.data.<key>); delete the key or wire a consumer",
1181 k.key_name
1182 );
1183 issues.push(cc_issue(
1184 "fallow/unused-load-data-key",
1185 &message,
1186 level,
1187 "Bug Risk",
1188 &path,
1189 line,
1190 &fp,
1191 ));
1192 }
1193}
1194
1195fn push_route_collision_issues(
1196 issues: &mut Vec<CodeClimateIssue>,
1197 findings: &[fallow_types::output_dead_code::RouteCollisionFinding],
1198 root: &Path,
1199 severity: Severity,
1200) {
1201 if findings.is_empty() {
1202 return;
1203 }
1204 let level = severity_to_codeclimate(severity);
1205 for entry in findings {
1206 let c = &entry.collision;
1207 let path = cc_path(&c.path, root);
1208 let fp = fingerprint_hash(&["fallow/route-collision", &path, &c.url]);
1209 let line = if c.line > 0 { Some(c.line) } else { None };
1210 let message = format!(
1211 "Route file resolves to `{}`, also owned by {} other file(s); Next.js fails the build because a URL can have only one owner",
1212 c.url,
1213 c.conflicting_paths.len()
1214 );
1215 issues.push(cc_issue(
1216 "fallow/route-collision",
1217 &message,
1218 level,
1219 "Bug Risk",
1220 &path,
1221 line,
1222 &fp,
1223 ));
1224 }
1225}
1226
1227fn push_dynamic_segment_name_conflict_issues(
1228 issues: &mut Vec<CodeClimateIssue>,
1229 findings: &[fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
1230 root: &Path,
1231 severity: Severity,
1232) {
1233 if findings.is_empty() {
1234 return;
1235 }
1236 let level = severity_to_codeclimate(severity);
1237 for entry in findings {
1238 let c = &entry.conflict;
1239 let path = cc_path(&c.path, root);
1240 let fp = fingerprint_hash(&["fallow/dynamic-segment-name-conflict", &path, &c.position]);
1241 let line = if c.line > 0 { Some(c.line) } else { None };
1242 let message = format!(
1243 "Dynamic segments at `{}` use different slug names ({}); Next.js requires one consistent name per dynamic path",
1244 c.position,
1245 c.conflicting_segments.join(", ")
1246 );
1247 issues.push(cc_issue(
1248 "fallow/dynamic-segment-name-conflict",
1249 &message,
1250 level,
1251 "Bug Risk",
1252 &path,
1253 line,
1254 &fp,
1255 ));
1256 }
1257}
1258
1259fn push_stale_suppression_issues(
1260 issues: &mut Vec<CodeClimateIssue>,
1261 suppressions: &[fallow_core::results::StaleSuppression],
1262 root: &Path,
1263 severity: Severity,
1264) {
1265 if suppressions.is_empty() {
1266 return;
1267 }
1268 let level = severity_to_codeclimate(severity);
1269 for s in suppressions {
1270 let path = cc_path(&s.path, root);
1271 let line_str = s.line.to_string();
1272 let fp = fingerprint_hash(&["fallow/stale-suppression", &path, &line_str]);
1273 issues.push(cc_issue(
1274 "fallow/stale-suppression",
1275 &s.display_message(),
1276 level,
1277 "Bug Risk",
1278 &path,
1279 Some(s.line),
1280 &fp,
1281 ));
1282 }
1283}
1284
1285fn push_unused_catalog_entry_issues(
1286 issues: &mut Vec<CodeClimateIssue>,
1287 entries: &[fallow_core::results::UnusedCatalogEntryFinding],
1288 root: &Path,
1289 severity: Severity,
1290) {
1291 if entries.is_empty() {
1292 return;
1293 }
1294 let level = severity_to_codeclimate(severity);
1295 for entry in entries {
1296 let entry = &entry.entry;
1297 let path = cc_path(&entry.path, root);
1298 let line_str = entry.line.to_string();
1299 let fp = fingerprint_hash(&[
1300 "fallow/unused-catalog-entry",
1301 &path,
1302 &line_str,
1303 &entry.catalog_name,
1304 &entry.entry_name,
1305 ]);
1306 let description = if entry.catalog_name == "default" {
1307 format!(
1308 "Catalog entry '{}' is not referenced by any workspace package",
1309 entry.entry_name
1310 )
1311 } else {
1312 format!(
1313 "Catalog entry '{}' (catalog '{}') is not referenced by any workspace package",
1314 entry.entry_name, entry.catalog_name
1315 )
1316 };
1317 issues.push(cc_issue(
1318 "fallow/unused-catalog-entry",
1319 &description,
1320 level,
1321 "Bug Risk",
1322 &path,
1323 Some(entry.line),
1324 &fp,
1325 ));
1326 }
1327}
1328
1329fn push_unresolved_catalog_reference_issues(
1330 issues: &mut Vec<CodeClimateIssue>,
1331 findings: &[fallow_core::results::UnresolvedCatalogReferenceFinding],
1332 root: &Path,
1333 severity: Severity,
1334) {
1335 if findings.is_empty() {
1336 return;
1337 }
1338 let level = severity_to_codeclimate(severity);
1339 for finding in findings {
1340 let finding = &finding.reference;
1341 let path = cc_path(&finding.path, root);
1342 let line_str = finding.line.to_string();
1343 let fp = fingerprint_hash(&[
1344 "fallow/unresolved-catalog-reference",
1345 &path,
1346 &line_str,
1347 &finding.catalog_name,
1348 &finding.entry_name,
1349 ]);
1350 let catalog_phrase = if finding.catalog_name == "default" {
1351 "the default catalog".to_string()
1352 } else {
1353 format!("catalog '{}'", finding.catalog_name)
1354 };
1355 let mut description = format!(
1356 "Package '{}' is referenced via `catalog:{}` but {} does not declare it; `pnpm install` will fail",
1357 finding.entry_name,
1358 if finding.catalog_name == "default" {
1359 ""
1360 } else {
1361 finding.catalog_name.as_str()
1362 },
1363 catalog_phrase,
1364 );
1365 if !finding.available_in_catalogs.is_empty() {
1366 use std::fmt::Write as _;
1367 let _ = write!(
1368 description,
1369 " (available in: {})",
1370 finding.available_in_catalogs.join(", ")
1371 );
1372 }
1373 issues.push(cc_issue(
1374 "fallow/unresolved-catalog-reference",
1375 &description,
1376 level,
1377 "Bug Risk",
1378 &path,
1379 Some(finding.line),
1380 &fp,
1381 ));
1382 }
1383}
1384
1385fn push_empty_catalog_group_issues(
1386 issues: &mut Vec<CodeClimateIssue>,
1387 groups: &[fallow_core::results::EmptyCatalogGroupFinding],
1388 root: &Path,
1389 severity: Severity,
1390) {
1391 if groups.is_empty() {
1392 return;
1393 }
1394 let level = severity_to_codeclimate(severity);
1395 for group in groups {
1396 let group = &group.group;
1397 let path = cc_path(&group.path, root);
1398 let line_str = group.line.to_string();
1399 let fp = fingerprint_hash(&[
1400 "fallow/empty-catalog-group",
1401 &path,
1402 &line_str,
1403 &group.catalog_name,
1404 ]);
1405 issues.push(cc_issue(
1406 "fallow/empty-catalog-group",
1407 &format!("Catalog group '{}' has no entries", group.catalog_name),
1408 level,
1409 "Bug Risk",
1410 &path,
1411 Some(group.line),
1412 &fp,
1413 ));
1414 }
1415}
1416
1417fn push_unused_dependency_override_issues(
1418 issues: &mut Vec<CodeClimateIssue>,
1419 findings: &[fallow_core::results::UnusedDependencyOverrideFinding],
1420 root: &Path,
1421 severity: Severity,
1422) {
1423 if findings.is_empty() {
1424 return;
1425 }
1426 let level = severity_to_codeclimate(severity);
1427 for finding in findings {
1428 let finding = &finding.entry;
1429 let path = cc_path(&finding.path, root);
1430 let line_str = finding.line.to_string();
1431 let fp = fingerprint_hash(&[
1432 "fallow/unused-dependency-override",
1433 &path,
1434 &line_str,
1435 finding.source.as_label(),
1436 &finding.raw_key,
1437 ]);
1438 let mut description = format!(
1439 "Override `{}` forces version `{}` but `{}` is not declared by any workspace package or resolved in pnpm-lock.yaml",
1440 finding.raw_key, finding.version_range, finding.target_package,
1441 );
1442 if let Some(hint) = &finding.hint {
1443 use std::fmt::Write as _;
1444 let _ = write!(description, " ({hint})");
1445 }
1446 issues.push(cc_issue(
1447 "fallow/unused-dependency-override",
1448 &description,
1449 level,
1450 "Bug Risk",
1451 &path,
1452 Some(finding.line),
1453 &fp,
1454 ));
1455 }
1456}
1457
1458fn push_misconfigured_dependency_override_issues(
1459 issues: &mut Vec<CodeClimateIssue>,
1460 findings: &[fallow_core::results::MisconfiguredDependencyOverrideFinding],
1461 root: &Path,
1462 severity: Severity,
1463) {
1464 if findings.is_empty() {
1465 return;
1466 }
1467 let level = severity_to_codeclimate(severity);
1468 for finding in findings {
1469 let finding = &finding.entry;
1470 let path = cc_path(&finding.path, root);
1471 let line_str = finding.line.to_string();
1472 let fp = fingerprint_hash(&[
1473 "fallow/misconfigured-dependency-override",
1474 &path,
1475 &line_str,
1476 finding.source.as_label(),
1477 &finding.raw_key,
1478 ]);
1479 let description = format!(
1480 "Override `{}` -> `{}` is malformed: {}",
1481 finding.raw_key,
1482 finding.raw_value,
1483 finding.reason.describe(),
1484 );
1485 issues.push(cc_issue(
1486 "fallow/misconfigured-dependency-override",
1487 &description,
1488 level,
1489 "Bug Risk",
1490 &path,
1491 Some(finding.line),
1492 &fp,
1493 ));
1494 }
1495}
1496
1497#[must_use]
1506#[expect(
1507 clippy::expect_used,
1508 reason = "CodeClimateIssue contains only infallibly serializable fields"
1509)]
1510pub fn issues_to_value(issues: &[CodeClimateIssue]) -> serde_json::Value {
1511 serde_json::to_value(issues).expect("CodeClimateIssue serializes infallibly")
1512}
1513
1514#[must_use]
1521pub fn build_codeclimate(
1522 results: &AnalysisResults,
1523 root: &Path,
1524 rules: &RulesConfig,
1525) -> Vec<CodeClimateIssue> {
1526 CodeClimateBuilder {
1527 issues: Vec::new(),
1528 results,
1529 root,
1530 rules,
1531 }
1532 .build()
1533}
1534
1535struct CodeClimateBuilder<'a> {
1536 issues: Vec<CodeClimateIssue>,
1537 results: &'a AnalysisResults,
1538 root: &'a Path,
1539 rules: &'a RulesConfig,
1540}
1541
1542impl CodeClimateBuilder<'_> {
1543 fn build(mut self) -> Vec<CodeClimateIssue> {
1544 self.push_file_and_export_issues();
1545 self.push_private_type_leak_issues();
1546 self.push_package_dependency_issues();
1547 self.push_type_test_dependency_issues();
1548 self.push_member_issues();
1549 self.push_import_and_duplicate_issues();
1550 self.push_graph_issues();
1551 self.push_boundary_issues();
1552 self.push_suppression_and_catalog_issues();
1553 self.push_override_issues();
1554 self.issues
1555 }
1556
1557 fn push_file_and_export_issues(&mut self) {
1558 push_unused_file_issues(
1559 &mut self.issues,
1560 &self.results.unused_files,
1561 self.root,
1562 self.rules.unused_files,
1563 );
1564 push_unused_export_issues(
1565 &mut self.issues,
1566 self.results.unused_exports.iter().map(|e| &e.export),
1567 self.root,
1568 "fallow/unused-export",
1569 "Export",
1570 "Re-export",
1571 self.rules.unused_exports,
1572 );
1573 push_unused_export_issues(
1574 &mut self.issues,
1575 self.results.unused_types.iter().map(|e| &e.export),
1576 self.root,
1577 "fallow/unused-type",
1578 "Type export",
1579 "Type re-export",
1580 self.rules.unused_types,
1581 );
1582 }
1583
1584 fn push_private_type_leak_issues(&mut self) {
1585 push_private_type_leak_issues(
1586 &mut self.issues,
1587 &self.results.private_type_leaks,
1588 self.root,
1589 self.rules.private_type_leaks,
1590 );
1591 }
1592
1593 fn push_package_dependency_issues(&mut self) {
1594 push_dep_cc_issues(
1595 &mut self.issues,
1596 self.results.unused_dependencies.iter().map(|f| &f.dep),
1597 self.root,
1598 "fallow/unused-dependency",
1599 "dependencies",
1600 self.rules.unused_dependencies,
1601 );
1602 push_dep_cc_issues(
1603 &mut self.issues,
1604 self.results.unused_dev_dependencies.iter().map(|f| &f.dep),
1605 self.root,
1606 "fallow/unused-dev-dependency",
1607 "devDependencies",
1608 self.rules.unused_dev_dependencies,
1609 );
1610 push_dep_cc_issues(
1611 &mut self.issues,
1612 self.results
1613 .unused_optional_dependencies
1614 .iter()
1615 .map(|f| &f.dep),
1616 self.root,
1617 "fallow/unused-optional-dependency",
1618 "optionalDependencies",
1619 self.rules.unused_optional_dependencies,
1620 );
1621 }
1622
1623 fn push_type_test_dependency_issues(&mut self) {
1624 push_type_only_dep_issues(
1625 &mut self.issues,
1626 &self.results.type_only_dependencies,
1627 self.root,
1628 self.rules.type_only_dependencies,
1629 );
1630 push_test_only_dep_issues(
1631 &mut self.issues,
1632 &self.results.test_only_dependencies,
1633 self.root,
1634 self.rules.test_only_dependencies,
1635 );
1636 }
1637
1638 fn push_member_issues(&mut self) {
1639 push_unused_member_issues(
1640 &mut self.issues,
1641 self.results.unused_enum_members.iter().map(|m| &m.member),
1642 self.root,
1643 "fallow/unused-enum-member",
1644 "Enum",
1645 self.rules.unused_enum_members,
1646 );
1647 push_unused_member_issues(
1648 &mut self.issues,
1649 self.results.unused_class_members.iter().map(|m| &m.member),
1650 self.root,
1651 "fallow/unused-class-member",
1652 "Class",
1653 self.rules.unused_class_members,
1654 );
1655 push_unused_member_issues(
1656 &mut self.issues,
1657 self.results.unused_store_members.iter().map(|m| &m.member),
1658 self.root,
1659 "fallow/unused-store-member",
1660 "Store",
1661 self.rules.unused_store_members,
1662 );
1663 }
1664
1665 fn push_import_and_duplicate_issues(&mut self) {
1666 push_unresolved_import_issues(
1667 &mut self.issues,
1668 &self.results.unresolved_imports,
1669 self.root,
1670 self.rules.unresolved_imports,
1671 );
1672 push_unlisted_dep_issues(
1673 &mut self.issues,
1674 &self.results.unlisted_dependencies,
1675 self.root,
1676 self.rules.unlisted_dependencies,
1677 );
1678 push_duplicate_export_issues(
1679 &mut self.issues,
1680 &self.results.duplicate_exports,
1681 self.root,
1682 self.rules.duplicate_exports,
1683 );
1684 }
1685
1686 fn push_graph_issues(&mut self) {
1687 push_circular_dep_issues(
1688 &mut self.issues,
1689 &self.results.circular_dependencies,
1690 self.root,
1691 self.rules.circular_dependencies,
1692 );
1693 push_re_export_cycle_issues(
1694 &mut self.issues,
1695 &self.results.re_export_cycles,
1696 self.root,
1697 self.rules.re_export_cycle,
1698 );
1699 }
1700
1701 fn push_boundary_issues(&mut self) {
1702 self.push_architecture_boundary_issues();
1703 self.push_client_server_boundary_issues();
1704 self.push_component_boundary_issues();
1705 self.push_framework_route_issues();
1706 }
1707
1708 fn push_architecture_boundary_issues(&mut self) {
1709 push_boundary_violation_issues(
1710 &mut self.issues,
1711 &self.results.boundary_violations,
1712 self.root,
1713 self.rules.boundary_violation,
1714 );
1715 push_boundary_coverage_issues(
1716 &mut self.issues,
1717 &self.results.boundary_coverage_violations,
1718 self.root,
1719 self.rules.boundary_violation,
1720 );
1721 push_boundary_call_issues(
1722 &mut self.issues,
1723 &self.results.boundary_call_violations,
1724 self.root,
1725 self.rules.boundary_violation,
1726 );
1727 push_policy_violation_issues(&mut self.issues, &self.results.policy_violations, self.root);
1728 }
1729
1730 fn push_client_server_boundary_issues(&mut self) {
1731 push_invalid_client_export_issues(
1732 &mut self.issues,
1733 &self.results.invalid_client_exports,
1734 self.root,
1735 self.rules.invalid_client_export,
1736 );
1737 push_mixed_client_server_barrel_issues(
1738 &mut self.issues,
1739 &self.results.mixed_client_server_barrels,
1740 self.root,
1741 self.rules.mixed_client_server_barrel,
1742 );
1743 push_misplaced_directive_issues(
1744 &mut self.issues,
1745 &self.results.misplaced_directives,
1746 self.root,
1747 self.rules.misplaced_directive,
1748 );
1749 }
1750
1751 fn push_component_boundary_issues(&mut self) {
1752 push_unprovided_inject_issues(
1753 &mut self.issues,
1754 &self.results.unprovided_injects,
1755 self.root,
1756 self.rules.unprovided_injects,
1757 );
1758 push_unrendered_component_issues(
1759 &mut self.issues,
1760 &self.results.unrendered_components,
1761 self.root,
1762 self.rules.unrendered_components,
1763 );
1764 push_unused_component_prop_issues(
1765 &mut self.issues,
1766 &self.results.unused_component_props,
1767 self.root,
1768 self.rules.unused_component_props,
1769 );
1770 push_unused_component_emit_issues(
1771 &mut self.issues,
1772 &self.results.unused_component_emits,
1773 self.root,
1774 self.rules.unused_component_emits,
1775 );
1776 }
1777
1778 fn push_framework_route_issues(&mut self) {
1779 push_unused_server_action_issues(
1780 &mut self.issues,
1781 &self.results.unused_server_actions,
1782 self.root,
1783 self.rules.unused_server_actions,
1784 );
1785 push_unused_load_data_key_issues(
1786 &mut self.issues,
1787 &self.results.unused_load_data_keys,
1788 self.root,
1789 self.rules.unused_load_data_keys,
1790 );
1791 push_route_collision_issues(
1792 &mut self.issues,
1793 &self.results.route_collisions,
1794 self.root,
1795 self.rules.route_collision,
1796 );
1797 push_dynamic_segment_name_conflict_issues(
1798 &mut self.issues,
1799 &self.results.dynamic_segment_name_conflicts,
1800 self.root,
1801 self.rules.dynamic_segment_name_conflict,
1802 );
1803 }
1804
1805 fn push_suppression_and_catalog_issues(&mut self) {
1806 push_stale_suppression_issues(
1807 &mut self.issues,
1808 &self.results.stale_suppressions,
1809 self.root,
1810 self.rules.stale_suppressions,
1811 );
1812 push_unused_catalog_entry_issues(
1813 &mut self.issues,
1814 &self.results.unused_catalog_entries,
1815 self.root,
1816 self.rules.unused_catalog_entries,
1817 );
1818 push_empty_catalog_group_issues(
1819 &mut self.issues,
1820 &self.results.empty_catalog_groups,
1821 self.root,
1822 self.rules.empty_catalog_groups,
1823 );
1824 push_unresolved_catalog_reference_issues(
1825 &mut self.issues,
1826 &self.results.unresolved_catalog_references,
1827 self.root,
1828 self.rules.unresolved_catalog_references,
1829 );
1830 }
1831
1832 fn push_override_issues(&mut self) {
1833 push_unused_dependency_override_issues(
1834 &mut self.issues,
1835 &self.results.unused_dependency_overrides,
1836 self.root,
1837 self.rules.unused_dependency_overrides,
1838 );
1839 push_misconfigured_dependency_override_issues(
1840 &mut self.issues,
1841 &self.results.misconfigured_dependency_overrides,
1842 self.root,
1843 self.rules.misconfigured_dependency_overrides,
1844 );
1845 }
1846}
1847
1848pub(super) fn print_codeclimate(
1850 results: &AnalysisResults,
1851 root: &Path,
1852 rules: &RulesConfig,
1853) -> ExitCode {
1854 let issues = build_codeclimate(results, root, rules);
1855 let value = issues_to_value(&issues);
1856 emit_json(&value, "CodeClimate")
1857}
1858
1859#[expect(
1865 clippy::expect_used,
1866 reason = "grouped CodeClimate entries are JSON objects created by issues_to_value"
1867)]
1868pub(super) fn print_grouped_codeclimate(
1869 results: &AnalysisResults,
1870 root: &Path,
1871 rules: &RulesConfig,
1872 resolver: &OwnershipResolver,
1873) -> ExitCode {
1874 let issues = build_codeclimate(results, root, rules);
1875 let mut value = issues_to_value(&issues);
1876
1877 if let Some(items) = value.as_array_mut() {
1878 for issue in items {
1879 let path = issue
1880 .pointer("/location/path")
1881 .and_then(|v| v.as_str())
1882 .unwrap_or("");
1883 let owner = grouping::resolve_owner(Path::new(path), Path::new(""), resolver);
1884 issue
1885 .as_object_mut()
1886 .expect("CodeClimate issue should be an object")
1887 .insert("owner".to_string(), serde_json::Value::String(owner));
1888 }
1889 }
1890
1891 emit_json(&value, "CodeClimate")
1892}
1893
1894#[must_use]
1896pub fn build_health_codeclimate(report: &HealthReport, root: &Path) -> Vec<CodeClimateIssue> {
1897 let mut issues = Vec::new();
1898 let ctx = HealthCodeClimateContext {
1899 root,
1900 cyc_t: report.summary.max_cyclomatic_threshold,
1901 cog_t: report.summary.max_cognitive_threshold,
1902 crap_t: report.summary.max_crap_threshold,
1903 };
1904
1905 for finding in &report.findings {
1906 issues.push(ctx.complexity_issue(finding));
1907 }
1908
1909 if let Some(ref production) = report.runtime_coverage {
1910 for finding in &production.findings {
1911 issues.push(ctx.runtime_coverage_issue(finding));
1912 }
1913 }
1914
1915 if let Some(ref intelligence) = report.coverage_intelligence {
1916 for finding in &intelligence.findings {
1917 if let Some(issue) = ctx.coverage_intelligence_issue(finding) {
1918 issues.push(issue);
1919 }
1920 }
1921 }
1922
1923 if let Some(ref gaps) = report.coverage_gaps {
1924 for item in &gaps.files {
1925 issues.push(ctx.untested_file_issue(item));
1926 }
1927
1928 for item in &gaps.exports {
1929 issues.push(ctx.untested_export_issue(item));
1930 }
1931 }
1932
1933 issues
1934}
1935
1936pub(super) fn print_health_codeclimate(report: &HealthReport, root: &Path) -> ExitCode {
1938 let issues = build_health_codeclimate(report, root);
1939 let value = issues_to_value(&issues);
1940 emit_json(&value, "CodeClimate")
1941}
1942
1943#[expect(
1952 clippy::expect_used,
1953 reason = "grouped health CodeClimate entries are JSON objects created by issues_to_value"
1954)]
1955pub(super) fn print_grouped_health_codeclimate(
1956 report: &HealthReport,
1957 root: &Path,
1958 resolver: &OwnershipResolver,
1959) -> ExitCode {
1960 let issues = build_health_codeclimate(report, root);
1961 let mut value = issues_to_value(&issues);
1962
1963 if let Some(items) = value.as_array_mut() {
1964 for issue in items {
1965 let path = issue
1966 .pointer("/location/path")
1967 .and_then(|v| v.as_str())
1968 .unwrap_or("");
1969 let group = grouping::resolve_owner(Path::new(path), Path::new(""), resolver);
1970 issue
1971 .as_object_mut()
1972 .expect("CodeClimate issue should be an object")
1973 .insert("group".to_string(), serde_json::Value::String(group));
1974 }
1975 }
1976
1977 emit_json(&value, "CodeClimate")
1978}
1979
1980#[must_use]
1982#[expect(
1983 clippy::cast_possible_truncation,
1984 reason = "line numbers are bounded by source size"
1985)]
1986pub fn build_duplication_codeclimate(
1987 report: &DuplicationReport,
1988 root: &Path,
1989) -> Vec<CodeClimateIssue> {
1990 let mut issues = Vec::new();
1991
1992 for (i, group) in report.clone_groups.iter().enumerate() {
1993 let token_str = group.token_count.to_string();
1994 let line_count_str = group.line_count.to_string();
1995 let fragment_prefix: String = group
1996 .instances
1997 .first()
1998 .map(|inst| inst.fragment.chars().take(64).collect())
1999 .unwrap_or_default();
2000
2001 for instance in &group.instances {
2002 let path = cc_path(&instance.file, root);
2003 let start_str = instance.start_line.to_string();
2004 let fp = fingerprint_hash(&[
2005 "fallow/code-duplication",
2006 &path,
2007 &start_str,
2008 &token_str,
2009 &line_count_str,
2010 &fragment_prefix,
2011 ]);
2012 issues.push(cc_issue(
2013 "fallow/code-duplication",
2014 &format!(
2015 "Code clone group {} ({} lines, {} instances)",
2016 i + 1,
2017 group.line_count,
2018 group.instances.len()
2019 ),
2020 CodeClimateSeverity::Minor,
2021 "Duplication",
2022 &path,
2023 Some(instance.start_line as u32),
2024 &fp,
2025 ));
2026 }
2027 }
2028
2029 issues
2030}
2031
2032pub(super) fn print_duplication_codeclimate(report: &DuplicationReport, root: &Path) -> ExitCode {
2034 let issues = build_duplication_codeclimate(report, root);
2035 let value = issues_to_value(&issues);
2036 emit_json(&value, "CodeClimate")
2037}
2038
2039#[expect(
2048 clippy::expect_used,
2049 reason = "grouped duplication CodeClimate entries are JSON objects created by issues_to_value"
2050)]
2051pub(super) fn print_grouped_duplication_codeclimate(
2052 report: &DuplicationReport,
2053 root: &Path,
2054 resolver: &OwnershipResolver,
2055) -> ExitCode {
2056 let issues = build_duplication_codeclimate(report, root);
2057 let mut value = issues_to_value(&issues);
2058
2059 use rustc_hash::FxHashMap;
2060 let mut path_to_owner: FxHashMap<String, String> = FxHashMap::default();
2061 for group in &report.clone_groups {
2062 let owner = super::dupes_grouping::largest_owner(group, root, resolver);
2063 for instance in &group.instances {
2064 let path = cc_path(&instance.file, root);
2065 path_to_owner.insert(path, owner.clone());
2066 }
2067 }
2068
2069 if let Some(items) = value.as_array_mut() {
2070 for issue in items {
2071 let path = issue
2072 .pointer("/location/path")
2073 .and_then(|v| v.as_str())
2074 .unwrap_or("")
2075 .to_string();
2076 let group = path_to_owner
2077 .get(&path)
2078 .cloned()
2079 .unwrap_or_else(|| crate::codeowners::UNOWNED_LABEL.to_string());
2080 issue
2081 .as_object_mut()
2082 .expect("CodeClimate issue should be an object")
2083 .insert("group".to_string(), serde_json::Value::String(group));
2084 }
2085 }
2086
2087 emit_json(&value, "CodeClimate")
2088}
2089
2090#[cfg(test)]
2091mod tests {
2092 use super::*;
2093 use crate::report::test_helpers::sample_results;
2094 use fallow_config::RulesConfig;
2095 use fallow_core::results::*;
2096 use std::path::PathBuf;
2097
2098 fn health_severity(value: u16, threshold: u16) -> &'static str {
2101 if threshold == 0 {
2102 return "minor";
2103 }
2104 let ratio = f64::from(value) / f64::from(threshold);
2105 if ratio > 2.5 {
2106 "critical"
2107 } else if ratio > 1.5 {
2108 "major"
2109 } else {
2110 "minor"
2111 }
2112 }
2113
2114 #[test]
2115 fn codeclimate_empty_results_produces_empty_array() {
2116 let root = PathBuf::from("/project");
2117 let results = AnalysisResults::default();
2118 let rules = RulesConfig::default();
2119 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2120 let arr = output.as_array().unwrap();
2121 assert!(arr.is_empty());
2122 }
2123
2124 #[test]
2125 fn codeclimate_produces_array_of_issues() {
2126 let root = PathBuf::from("/project");
2127 let results = sample_results(&root);
2128 let rules = RulesConfig::default();
2129 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2130 assert!(output.is_array());
2131 let arr = output.as_array().unwrap();
2132 assert!(!arr.is_empty());
2133 }
2134
2135 #[test]
2136 fn codeclimate_issue_has_required_fields() {
2137 let root = PathBuf::from("/project");
2138 let mut results = AnalysisResults::default();
2139 results
2140 .unused_files
2141 .push(UnusedFileFinding::with_actions(UnusedFile {
2142 path: root.join("src/dead.ts"),
2143 }));
2144 let rules = RulesConfig::default();
2145 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2146 let issue = &output.as_array().unwrap()[0];
2147
2148 assert_eq!(issue["type"], "issue");
2149 assert_eq!(issue["check_name"], "fallow/unused-file");
2150 assert!(issue["description"].is_string());
2151 assert!(issue["categories"].is_array());
2152 assert!(issue["severity"].is_string());
2153 assert!(issue["fingerprint"].is_string());
2154 assert!(issue["location"].is_object());
2155 assert!(issue["location"]["path"].is_string());
2156 assert!(issue["location"]["lines"].is_object());
2157 }
2158
2159 #[test]
2160 fn codeclimate_unused_file_severity_follows_rules() {
2161 let root = PathBuf::from("/project");
2162 let mut results = AnalysisResults::default();
2163 results
2164 .unused_files
2165 .push(UnusedFileFinding::with_actions(UnusedFile {
2166 path: root.join("src/dead.ts"),
2167 }));
2168
2169 let rules = RulesConfig::default();
2170 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2171 assert_eq!(output[0]["severity"], "major");
2172
2173 let rules = RulesConfig {
2174 unused_files: Severity::Warn,
2175 ..RulesConfig::default()
2176 };
2177 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2178 assert_eq!(output[0]["severity"], "minor");
2179 }
2180
2181 #[test]
2182 fn codeclimate_unused_export_has_line_number() {
2183 let root = PathBuf::from("/project");
2184 let mut results = AnalysisResults::default();
2185 results
2186 .unused_exports
2187 .push(UnusedExportFinding::with_actions(UnusedExport {
2188 path: root.join("src/utils.ts"),
2189 export_name: "helperFn".to_string(),
2190 is_type_only: false,
2191 line: 10,
2192 col: 4,
2193 span_start: 120,
2194 is_re_export: false,
2195 }));
2196 let rules = RulesConfig::default();
2197 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2198 let issue = &output[0];
2199 assert_eq!(issue["location"]["lines"]["begin"], 10);
2200 }
2201
2202 #[test]
2203 fn codeclimate_unused_file_line_defaults_to_1() {
2204 let root = PathBuf::from("/project");
2205 let mut results = AnalysisResults::default();
2206 results
2207 .unused_files
2208 .push(UnusedFileFinding::with_actions(UnusedFile {
2209 path: root.join("src/dead.ts"),
2210 }));
2211 let rules = RulesConfig::default();
2212 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2213 let issue = &output[0];
2214 assert_eq!(issue["location"]["lines"]["begin"], 1);
2215 }
2216
2217 #[test]
2218 fn codeclimate_paths_are_relative() {
2219 let root = PathBuf::from("/project");
2220 let mut results = AnalysisResults::default();
2221 results
2222 .unused_files
2223 .push(UnusedFileFinding::with_actions(UnusedFile {
2224 path: root.join("src/deep/nested/file.ts"),
2225 }));
2226 let rules = RulesConfig::default();
2227 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2228 let path = output[0]["location"]["path"].as_str().unwrap();
2229 assert_eq!(path, "src/deep/nested/file.ts");
2230 assert!(!path.starts_with("/project"));
2231 }
2232
2233 #[test]
2234 fn codeclimate_re_export_label_in_description() {
2235 let root = PathBuf::from("/project");
2236 let mut results = AnalysisResults::default();
2237 results
2238 .unused_exports
2239 .push(UnusedExportFinding::with_actions(UnusedExport {
2240 path: root.join("src/index.ts"),
2241 export_name: "reExported".to_string(),
2242 is_type_only: false,
2243 line: 1,
2244 col: 0,
2245 span_start: 0,
2246 is_re_export: true,
2247 }));
2248 let rules = RulesConfig::default();
2249 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2250 let desc = output[0]["description"].as_str().unwrap();
2251 assert!(desc.contains("Re-export"));
2252 }
2253
2254 #[test]
2255 fn codeclimate_unlisted_dep_one_issue_per_import_site() {
2256 let root = PathBuf::from("/project");
2257 let mut results = AnalysisResults::default();
2258 results
2259 .unlisted_dependencies
2260 .push(UnlistedDependencyFinding::with_actions(
2261 UnlistedDependency {
2262 package_name: "chalk".to_string(),
2263 imported_from: vec![
2264 ImportSite {
2265 path: root.join("src/a.ts"),
2266 line: 1,
2267 col: 0,
2268 },
2269 ImportSite {
2270 path: root.join("src/b.ts"),
2271 line: 5,
2272 col: 0,
2273 },
2274 ],
2275 },
2276 ));
2277 let rules = RulesConfig::default();
2278 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2279 let arr = output.as_array().unwrap();
2280 assert_eq!(arr.len(), 2);
2281 assert_eq!(arr[0]["check_name"], "fallow/unlisted-dependency");
2282 assert_eq!(arr[1]["check_name"], "fallow/unlisted-dependency");
2283 }
2284
2285 #[test]
2286 fn codeclimate_duplicate_export_one_issue_per_location() {
2287 let root = PathBuf::from("/project");
2288 let mut results = AnalysisResults::default();
2289 results
2290 .duplicate_exports
2291 .push(DuplicateExportFinding::with_actions(DuplicateExport {
2292 export_name: "Config".to_string(),
2293 locations: vec![
2294 DuplicateLocation {
2295 path: root.join("src/a.ts"),
2296 line: 10,
2297 col: 0,
2298 },
2299 DuplicateLocation {
2300 path: root.join("src/b.ts"),
2301 line: 20,
2302 col: 0,
2303 },
2304 DuplicateLocation {
2305 path: root.join("src/c.ts"),
2306 line: 30,
2307 col: 0,
2308 },
2309 ],
2310 }));
2311 let rules = RulesConfig::default();
2312 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2313 let arr = output.as_array().unwrap();
2314 assert_eq!(arr.len(), 3);
2315 }
2316
2317 #[test]
2318 fn codeclimate_circular_dep_emits_chain_in_description() {
2319 let root = PathBuf::from("/project");
2320 let mut results = AnalysisResults::default();
2321 results
2322 .circular_dependencies
2323 .push(CircularDependencyFinding::with_actions(
2324 CircularDependency {
2325 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
2326 length: 2,
2327 line: 3,
2328 col: 0,
2329 edges: Vec::new(),
2330 is_cross_package: false,
2331 },
2332 ));
2333 let rules = RulesConfig::default();
2334 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2335 let desc = output[0]["description"].as_str().unwrap();
2336 assert!(desc.contains("Circular dependency"));
2337 assert!(desc.contains("src/a.ts"));
2338 assert!(desc.contains("src/b.ts"));
2339 }
2340
2341 #[test]
2342 fn codeclimate_fingerprints_are_deterministic() {
2343 let root = PathBuf::from("/project");
2344 let results = sample_results(&root);
2345 let rules = RulesConfig::default();
2346 let output1 = issues_to_value(&build_codeclimate(&results, &root, &rules));
2347 let output2 = issues_to_value(&build_codeclimate(&results, &root, &rules));
2348
2349 let fps1: Vec<&str> = output1
2350 .as_array()
2351 .unwrap()
2352 .iter()
2353 .map(|i| i["fingerprint"].as_str().unwrap())
2354 .collect();
2355 let fps2: Vec<&str> = output2
2356 .as_array()
2357 .unwrap()
2358 .iter()
2359 .map(|i| i["fingerprint"].as_str().unwrap())
2360 .collect();
2361 assert_eq!(fps1, fps2);
2362 }
2363
2364 #[test]
2365 fn codeclimate_fingerprints_are_unique() {
2366 let root = PathBuf::from("/project");
2367 let results = sample_results(&root);
2368 let rules = RulesConfig::default();
2369 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2370
2371 let mut fps: Vec<&str> = output
2372 .as_array()
2373 .unwrap()
2374 .iter()
2375 .map(|i| i["fingerprint"].as_str().unwrap())
2376 .collect();
2377 let original_len = fps.len();
2378 fps.sort_unstable();
2379 fps.dedup();
2380 assert_eq!(fps.len(), original_len, "fingerprints should be unique");
2381 }
2382
2383 #[test]
2384 fn codeclimate_type_only_dep_has_correct_check_name() {
2385 let root = PathBuf::from("/project");
2386 let mut results = AnalysisResults::default();
2387 results
2388 .type_only_dependencies
2389 .push(TypeOnlyDependencyFinding::with_actions(
2390 TypeOnlyDependency {
2391 package_name: "zod".to_string(),
2392 path: root.join("package.json"),
2393 line: 8,
2394 },
2395 ));
2396 let rules = RulesConfig::default();
2397 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2398 assert_eq!(output[0]["check_name"], "fallow/type-only-dependency");
2399 let desc = output[0]["description"].as_str().unwrap();
2400 assert!(desc.contains("zod"));
2401 assert!(desc.contains("type-only"));
2402 }
2403
2404 #[test]
2405 fn codeclimate_dep_with_zero_line_omits_line_number() {
2406 let root = PathBuf::from("/project");
2407 let mut results = AnalysisResults::default();
2408 results
2409 .unused_dependencies
2410 .push(UnusedDependencyFinding::with_actions(UnusedDependency {
2411 package_name: "lodash".to_string(),
2412 location: DependencyLocation::Dependencies,
2413 path: root.join("package.json"),
2414 line: 0,
2415 used_in_workspaces: Vec::new(),
2416 }));
2417 let rules = RulesConfig::default();
2418 let output = issues_to_value(&build_codeclimate(&results, &root, &rules));
2419 assert_eq!(output[0]["location"]["lines"]["begin"], 1);
2420 }
2421
2422 #[test]
2423 fn fingerprint_hash_different_inputs_differ() {
2424 let h1 = fingerprint_hash(&["a", "b"]);
2425 let h2 = fingerprint_hash(&["a", "c"]);
2426 assert_ne!(h1, h2);
2427 }
2428
2429 #[test]
2430 fn fingerprint_hash_order_matters() {
2431 let h1 = fingerprint_hash(&["a", "b"]);
2432 let h2 = fingerprint_hash(&["b", "a"]);
2433 assert_ne!(h1, h2);
2434 }
2435
2436 #[test]
2437 fn fingerprint_hash_separator_prevents_collision() {
2438 let h1 = fingerprint_hash(&["ab", "c"]);
2439 let h2 = fingerprint_hash(&["a", "bc"]);
2440 assert_ne!(h1, h2);
2441 }
2442
2443 #[test]
2444 fn fingerprint_hash_is_16_hex_chars() {
2445 let h = fingerprint_hash(&["test"]);
2446 assert_eq!(h.len(), 16);
2447 assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
2448 }
2449
2450 #[test]
2451 fn severity_error_maps_to_major() {
2452 assert_eq!(
2453 severity_to_codeclimate(Severity::Error),
2454 CodeClimateSeverity::Major
2455 );
2456 }
2457
2458 #[test]
2459 fn severity_warn_maps_to_minor() {
2460 assert_eq!(
2461 severity_to_codeclimate(Severity::Warn),
2462 CodeClimateSeverity::Minor
2463 );
2464 }
2465
2466 #[test]
2467 #[should_panic(expected = "internal error: entered unreachable code")]
2468 fn severity_off_is_unreachable() {
2469 let _ = severity_to_codeclimate(Severity::Off);
2470 }
2471
2472 #[test]
2484 fn build_codeclimate_with_off_severity_and_empty_findings_does_not_panic() {
2485 let root = PathBuf::from("/project");
2486 let results = AnalysisResults::default();
2487 let rules = RulesConfig {
2488 unused_dependencies: Severity::Off,
2489 unused_dev_dependencies: Severity::Off,
2490 unused_optional_dependencies: Severity::Off,
2491 unused_exports: Severity::Off,
2492 unused_types: Severity::Off,
2493 unused_enum_members: Severity::Off,
2494 unused_class_members: Severity::Off,
2495 ..RulesConfig::default()
2496 };
2497 let issues = build_codeclimate(&results, &root, &rules);
2498 assert!(issues.is_empty());
2499 }
2500
2501 #[test]
2502 fn health_severity_zero_threshold_returns_minor() {
2503 assert_eq!(health_severity(100, 0), "minor");
2504 }
2505
2506 #[test]
2507 fn health_severity_at_threshold_returns_minor() {
2508 assert_eq!(health_severity(10, 10), "minor");
2509 }
2510
2511 #[test]
2512 fn health_severity_1_5x_threshold_returns_minor() {
2513 assert_eq!(health_severity(15, 10), "minor");
2514 }
2515
2516 #[test]
2517 fn health_severity_above_1_5x_returns_major() {
2518 assert_eq!(health_severity(16, 10), "major");
2519 }
2520
2521 #[test]
2522 fn health_severity_at_2_5x_returns_major() {
2523 assert_eq!(health_severity(25, 10), "major");
2524 }
2525
2526 #[test]
2527 fn health_severity_above_2_5x_returns_critical() {
2528 assert_eq!(health_severity(26, 10), "critical");
2529 }
2530
2531 #[test]
2532 fn health_codeclimate_includes_coverage_gaps() {
2533 use crate::health_types::*;
2534
2535 let root = PathBuf::from("/project");
2536 let report = HealthReport {
2537 summary: HealthSummary {
2538 files_analyzed: 10,
2539 functions_analyzed: 50,
2540 ..Default::default()
2541 },
2542 coverage_gaps: Some(CoverageGaps {
2543 summary: CoverageGapSummary {
2544 runtime_files: 2,
2545 covered_files: 0,
2546 file_coverage_pct: 0.0,
2547 untested_files: 1,
2548 untested_exports: 1,
2549 },
2550 files: vec![UntestedFileFinding::with_actions(
2551 UntestedFile {
2552 path: root.join("src/app.ts"),
2553 value_export_count: 2,
2554 },
2555 &root,
2556 )],
2557 exports: vec![UntestedExportFinding::with_actions(
2558 UntestedExport {
2559 path: root.join("src/app.ts"),
2560 export_name: "loader".into(),
2561 line: 12,
2562 col: 4,
2563 },
2564 &root,
2565 )],
2566 }),
2567 ..Default::default()
2568 };
2569
2570 let output = issues_to_value(&build_health_codeclimate(&report, &root));
2571 let issues = output.as_array().unwrap();
2572 assert_eq!(issues.len(), 2);
2573 assert_eq!(issues[0]["check_name"], "fallow/untested-file");
2574 assert_eq!(issues[0]["categories"][0], "Coverage");
2575 assert_eq!(issues[0]["location"]["path"], "src/app.ts");
2576 assert_eq!(issues[1]["check_name"], "fallow/untested-export");
2577 assert_eq!(issues[1]["location"]["lines"]["begin"], 12);
2578 assert!(
2579 issues[1]["description"]
2580 .as_str()
2581 .unwrap()
2582 .contains("loader")
2583 );
2584 }
2585
2586 #[test]
2587 fn health_codeclimate_includes_coverage_intelligence_issue() {
2588 use crate::health_types::{
2589 CoverageIntelligenceAction, CoverageIntelligenceConfidence,
2590 CoverageIntelligenceEvidence, CoverageIntelligenceFinding,
2591 CoverageIntelligenceMatchConfidence, CoverageIntelligenceRecommendation,
2592 CoverageIntelligenceReport, CoverageIntelligenceSchemaVersion,
2593 CoverageIntelligenceSignal, CoverageIntelligenceSummary, CoverageIntelligenceVerdict,
2594 HealthReport, HealthSummary,
2595 };
2596
2597 let root = PathBuf::from("/project");
2598 let report = HealthReport {
2599 summary: HealthSummary {
2600 files_analyzed: 10,
2601 functions_analyzed: 50,
2602 ..Default::default()
2603 },
2604 coverage_intelligence: Some(CoverageIntelligenceReport {
2605 schema_version: CoverageIntelligenceSchemaVersion::V1,
2606 verdict: CoverageIntelligenceVerdict::HighConfidenceDelete,
2607 summary: CoverageIntelligenceSummary {
2608 findings: 1,
2609 high_confidence_deletes: 1,
2610 ..Default::default()
2611 },
2612 findings: vec![CoverageIntelligenceFinding {
2613 id: "fallow:coverage-intel:abc123".to_owned(),
2614 path: root.join("src/dead.ts"),
2615 identity: Some("deadPath".to_owned()),
2616 line: 9,
2617 verdict: CoverageIntelligenceVerdict::HighConfidenceDelete,
2618 signals: vec![CoverageIntelligenceSignal::RuntimeCold],
2619 recommendation: CoverageIntelligenceRecommendation::DeleteAfterConfirmingOwner,
2620 confidence: CoverageIntelligenceConfidence::High,
2621 related_ids: vec!["fallow:prod:deadbeef".to_owned()],
2622 evidence: CoverageIntelligenceEvidence {
2623 match_confidence: CoverageIntelligenceMatchConfidence::Direct,
2624 ..Default::default()
2625 },
2626 actions: vec![CoverageIntelligenceAction {
2627 kind: "delete-after-confirming-owner".to_owned(),
2628 description: "Confirm ownership".to_owned(),
2629 auto_fixable: false,
2630 }],
2631 }],
2632 }),
2633 ..Default::default()
2634 };
2635
2636 let output = issues_to_value(&build_health_codeclimate(&report, &root));
2637 let issues = output.as_array().unwrap();
2638 assert_eq!(issues.len(), 1);
2639 assert_eq!(
2640 issues[0]["check_name"],
2641 "fallow/coverage-intelligence-delete"
2642 );
2643 assert!(!issues[0]["fingerprint"].as_str().unwrap().is_empty());
2644 assert_eq!(issues[0]["location"]["path"], "src/dead.ts");
2645 assert!(
2646 issues[0]["description"]
2647 .as_str()
2648 .unwrap()
2649 .contains("deadPath")
2650 );
2651 }
2652
2653 #[test]
2654 fn health_codeclimate_skips_summary_only_coverage_intelligence() {
2655 use crate::health_types::{
2656 CoverageIntelligenceReport, CoverageIntelligenceSchemaVersion,
2657 CoverageIntelligenceSummary, CoverageIntelligenceVerdict, HealthReport,
2658 };
2659
2660 let root = PathBuf::from("/project");
2661 let report = HealthReport {
2662 coverage_intelligence: Some(CoverageIntelligenceReport {
2663 schema_version: CoverageIntelligenceSchemaVersion::V1,
2664 verdict: CoverageIntelligenceVerdict::Clean,
2665 summary: CoverageIntelligenceSummary {
2666 skipped_ambiguous_matches: 2,
2667 ..Default::default()
2668 },
2669 findings: vec![],
2670 }),
2671 ..Default::default()
2672 };
2673
2674 let issues = build_health_codeclimate(&report, &root);
2675 assert!(issues.is_empty());
2676 }
2677
2678 #[test]
2679 fn health_codeclimate_crap_only_uses_crap_check_name() {
2680 use crate::health_types::{
2681 ComplexityViolation, FindingSeverity, HealthReport, HealthSummary,
2682 };
2683 let root = PathBuf::from("/project");
2684 let report = HealthReport {
2685 findings: vec![
2686 ComplexityViolation {
2687 path: root.join("src/untested.ts"),
2688 name: "risky".to_string(),
2689 line: 7,
2690 col: 0,
2691 cyclomatic: 10,
2692 cognitive: 10,
2693 line_count: 20,
2694 param_count: 1,
2695 react_hook_count: 0,
2696 react_jsx_max_depth: 0,
2697 react_prop_count: 0,
2698 react_hook_profile: None,
2699 exceeded: crate::health_types::ExceededThreshold::Crap,
2700 severity: FindingSeverity::High,
2701 crap: Some(60.0),
2702 coverage_pct: Some(25.0),
2703 coverage_tier: None,
2704 coverage_source: None,
2705 inherited_from: None,
2706 component_rollup: None,
2707 contributions: Vec::new(),
2708 effective_thresholds: None,
2709 threshold_source: None,
2710 }
2711 .into(),
2712 ],
2713 summary: HealthSummary {
2714 functions_analyzed: 10,
2715 functions_above_threshold: 1,
2716 ..Default::default()
2717 },
2718 ..Default::default()
2719 };
2720 let json = issues_to_value(&build_health_codeclimate(&report, &root));
2721 let issues = json.as_array().unwrap();
2722 assert_eq!(issues[0]["check_name"], "fallow/high-crap-score");
2723 assert_eq!(issues[0]["severity"], "major");
2724 let description = issues[0]["description"].as_str().unwrap();
2725 assert!(description.contains("CRAP score"), "desc: {description}");
2726 assert!(description.contains("coverage 25%"), "desc: {description}");
2727 }
2728}