Skip to main content

fallow_cli/report/
codeclimate.rs

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::grouping::{self, OwnershipResolver};
9use super::{emit_json, normalize_uri, relative_path};
10use crate::health_types::{ExceededThreshold, HealthReport};
11
12/// Map fallow severity to CodeClimate severity.
13const fn severity_to_codeclimate(s: Severity) -> &'static str {
14    match s {
15        Severity::Error => "major",
16        Severity::Warn | Severity::Off => "minor",
17    }
18}
19
20/// Compute a relative path string with forward-slash normalization.
21///
22/// Uses `normalize_uri` to ensure forward slashes on all platforms
23/// and percent-encode brackets for Next.js dynamic routes.
24fn cc_path(path: &Path, root: &Path) -> String {
25    normalize_uri(&relative_path(path, root).display().to_string())
26}
27
28/// Compute a deterministic fingerprint hash from key fields.
29///
30/// Uses FNV-1a (64-bit) for guaranteed cross-version stability.
31/// `DefaultHasher` is explicitly not specified across Rust versions.
32fn fingerprint_hash(parts: &[&str]) -> String {
33    let mut hash: u64 = 0xcbf2_9ce4_8422_2325; // FNV offset basis
34    for part in parts {
35        for byte in part.bytes() {
36            hash ^= u64::from(byte);
37            hash = hash.wrapping_mul(0x0100_0000_01b3); // FNV prime
38        }
39        // Separator between parts to avoid "ab"+"c" == "a"+"bc"
40        hash ^= 0xff;
41        hash = hash.wrapping_mul(0x0100_0000_01b3);
42    }
43    format!("{hash:016x}")
44}
45
46/// Build a single CodeClimate issue object.
47fn cc_issue(
48    check_name: &str,
49    description: &str,
50    severity: &str,
51    category: &str,
52    path: &str,
53    begin_line: Option<u32>,
54    fingerprint: &str,
55) -> serde_json::Value {
56    let lines = begin_line.map_or_else(
57        || serde_json::json!({ "begin": 1 }),
58        |line| serde_json::json!({ "begin": line }),
59    );
60
61    serde_json::json!({
62        "type": "issue",
63        "check_name": check_name,
64        "description": description,
65        "categories": [category],
66        "severity": severity,
67        "fingerprint": fingerprint,
68        "location": {
69            "path": path,
70            "lines": lines
71        }
72    })
73}
74
75/// Push CodeClimate issues for unused dependencies with a shared structure.
76fn push_dep_cc_issues(
77    issues: &mut Vec<serde_json::Value>,
78    deps: &[fallow_core::results::UnusedDependency],
79    root: &Path,
80    rule_id: &str,
81    location_label: &str,
82    severity: Severity,
83) {
84    let level = severity_to_codeclimate(severity);
85    for dep in deps {
86        let path = cc_path(&dep.path, root);
87        let line = if dep.line > 0 { Some(dep.line) } else { None };
88        let fp = fingerprint_hash(&[rule_id, &dep.package_name]);
89        issues.push(cc_issue(
90            rule_id,
91            &format!(
92                "Package '{}' is in {location_label} but never imported",
93                dep.package_name
94            ),
95            level,
96            "Bug Risk",
97            &path,
98            line,
99            &fp,
100        ));
101    }
102}
103
104/// Build CodeClimate JSON array from dead-code analysis results.
105#[must_use]
106pub fn build_codeclimate(
107    results: &AnalysisResults,
108    root: &Path,
109    rules: &RulesConfig,
110) -> serde_json::Value {
111    let mut issues = Vec::new();
112
113    // Unused files
114    let level = severity_to_codeclimate(rules.unused_files);
115    for file in &results.unused_files {
116        let path = cc_path(&file.path, root);
117        let fp = fingerprint_hash(&["fallow/unused-file", &path]);
118        issues.push(cc_issue(
119            "fallow/unused-file",
120            "File is not reachable from any entry point",
121            level,
122            "Bug Risk",
123            &path,
124            None,
125            &fp,
126        ));
127    }
128
129    // Unused exports
130    let level = severity_to_codeclimate(rules.unused_exports);
131    for export in &results.unused_exports {
132        let path = cc_path(&export.path, root);
133        let kind = if export.is_re_export {
134            "Re-export"
135        } else {
136            "Export"
137        };
138        let line_str = export.line.to_string();
139        let fp = fingerprint_hash(&[
140            "fallow/unused-export",
141            &path,
142            &line_str,
143            &export.export_name,
144        ]);
145        issues.push(cc_issue(
146            "fallow/unused-export",
147            &format!(
148                "{kind} '{}' is never imported by other modules",
149                export.export_name
150            ),
151            level,
152            "Bug Risk",
153            &path,
154            Some(export.line),
155            &fp,
156        ));
157    }
158
159    // Unused types
160    let level = severity_to_codeclimate(rules.unused_types);
161    for export in &results.unused_types {
162        let path = cc_path(&export.path, root);
163        let kind = if export.is_re_export {
164            "Type re-export"
165        } else {
166            "Type export"
167        };
168        let line_str = export.line.to_string();
169        let fp = fingerprint_hash(&["fallow/unused-type", &path, &line_str, &export.export_name]);
170        issues.push(cc_issue(
171            "fallow/unused-type",
172            &format!(
173                "{kind} '{}' is never imported by other modules",
174                export.export_name
175            ),
176            level,
177            "Bug Risk",
178            &path,
179            Some(export.line),
180            &fp,
181        ));
182    }
183
184    // Unused dependencies
185    push_dep_cc_issues(
186        &mut issues,
187        &results.unused_dependencies,
188        root,
189        "fallow/unused-dependency",
190        "dependencies",
191        rules.unused_dependencies,
192    );
193    push_dep_cc_issues(
194        &mut issues,
195        &results.unused_dev_dependencies,
196        root,
197        "fallow/unused-dev-dependency",
198        "devDependencies",
199        rules.unused_dev_dependencies,
200    );
201    push_dep_cc_issues(
202        &mut issues,
203        &results.unused_optional_dependencies,
204        root,
205        "fallow/unused-optional-dependency",
206        "optionalDependencies",
207        rules.unused_optional_dependencies,
208    );
209
210    // Type-only dependencies
211    let level = severity_to_codeclimate(rules.type_only_dependencies);
212    for dep in &results.type_only_dependencies {
213        let path = cc_path(&dep.path, root);
214        let line = if dep.line > 0 { Some(dep.line) } else { None };
215        let fp = fingerprint_hash(&["fallow/type-only-dependency", &dep.package_name]);
216        issues.push(cc_issue(
217            "fallow/type-only-dependency",
218            &format!(
219                "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
220                dep.package_name
221            ),
222            level,
223            "Bug Risk",
224            &path,
225            line,
226            &fp,
227        ));
228    }
229
230    // Test-only dependencies
231    let level = severity_to_codeclimate(rules.test_only_dependencies);
232    for dep in &results.test_only_dependencies {
233        let path = cc_path(&dep.path, root);
234        let line = if dep.line > 0 { Some(dep.line) } else { None };
235        let fp = fingerprint_hash(&["fallow/test-only-dependency", &dep.package_name]);
236        issues.push(cc_issue(
237            "fallow/test-only-dependency",
238            &format!(
239                "Package '{}' is only imported by test files (consider moving to devDependencies)",
240                dep.package_name
241            ),
242            level,
243            "Bug Risk",
244            &path,
245            line,
246            &fp,
247        ));
248    }
249
250    // Unused enum members
251    let level = severity_to_codeclimate(rules.unused_enum_members);
252    for member in &results.unused_enum_members {
253        let path = cc_path(&member.path, root);
254        let line_str = member.line.to_string();
255        let fp = fingerprint_hash(&[
256            "fallow/unused-enum-member",
257            &path,
258            &line_str,
259            &member.parent_name,
260            &member.member_name,
261        ]);
262        issues.push(cc_issue(
263            "fallow/unused-enum-member",
264            &format!(
265                "Enum member '{}.{}' is never referenced",
266                member.parent_name, member.member_name
267            ),
268            level,
269            "Bug Risk",
270            &path,
271            Some(member.line),
272            &fp,
273        ));
274    }
275
276    // Unused class members
277    let level = severity_to_codeclimate(rules.unused_class_members);
278    for member in &results.unused_class_members {
279        let path = cc_path(&member.path, root);
280        let line_str = member.line.to_string();
281        let fp = fingerprint_hash(&[
282            "fallow/unused-class-member",
283            &path,
284            &line_str,
285            &member.parent_name,
286            &member.member_name,
287        ]);
288        issues.push(cc_issue(
289            "fallow/unused-class-member",
290            &format!(
291                "Class member '{}.{}' is never referenced",
292                member.parent_name, member.member_name
293            ),
294            level,
295            "Bug Risk",
296            &path,
297            Some(member.line),
298            &fp,
299        ));
300    }
301
302    // Unresolved imports
303    let level = severity_to_codeclimate(rules.unresolved_imports);
304    for import in &results.unresolved_imports {
305        let path = cc_path(&import.path, root);
306        let line_str = import.line.to_string();
307        let fp = fingerprint_hash(&[
308            "fallow/unresolved-import",
309            &path,
310            &line_str,
311            &import.specifier,
312        ]);
313        issues.push(cc_issue(
314            "fallow/unresolved-import",
315            &format!("Import '{}' could not be resolved", import.specifier),
316            level,
317            "Bug Risk",
318            &path,
319            Some(import.line),
320            &fp,
321        ));
322    }
323
324    // Unlisted dependencies — one issue per import site
325    let level = severity_to_codeclimate(rules.unlisted_dependencies);
326    for dep in &results.unlisted_dependencies {
327        for site in &dep.imported_from {
328            let path = cc_path(&site.path, root);
329            let line_str = site.line.to_string();
330            let fp = fingerprint_hash(&[
331                "fallow/unlisted-dependency",
332                &path,
333                &line_str,
334                &dep.package_name,
335            ]);
336            issues.push(cc_issue(
337                "fallow/unlisted-dependency",
338                &format!(
339                    "Package '{}' is imported but not listed in package.json",
340                    dep.package_name
341                ),
342                level,
343                "Bug Risk",
344                &path,
345                Some(site.line),
346                &fp,
347            ));
348        }
349    }
350
351    // Duplicate exports — one issue per location
352    let level = severity_to_codeclimate(rules.duplicate_exports);
353    for dup in &results.duplicate_exports {
354        for loc in &dup.locations {
355            let path = cc_path(&loc.path, root);
356            let line_str = loc.line.to_string();
357            let fp = fingerprint_hash(&[
358                "fallow/duplicate-export",
359                &path,
360                &line_str,
361                &dup.export_name,
362            ]);
363            issues.push(cc_issue(
364                "fallow/duplicate-export",
365                &format!("Export '{}' appears in multiple modules", dup.export_name),
366                level,
367                "Bug Risk",
368                &path,
369                Some(loc.line),
370                &fp,
371            ));
372        }
373    }
374
375    // Circular dependencies
376    let level = severity_to_codeclimate(rules.circular_dependencies);
377    for cycle in &results.circular_dependencies {
378        let Some(first) = cycle.files.first() else {
379            continue;
380        };
381        let path = cc_path(first, root);
382        let chain: Vec<String> = cycle.files.iter().map(|f| cc_path(f, root)).collect();
383        let chain_str = chain.join(":");
384        let fp = fingerprint_hash(&["fallow/circular-dependency", &chain_str]);
385        let line = if cycle.line > 0 {
386            Some(cycle.line)
387        } else {
388            None
389        };
390        issues.push(cc_issue(
391            "fallow/circular-dependency",
392            &format!(
393                "Circular dependency{}: {}",
394                if cycle.is_cross_package {
395                    " (cross-package)"
396                } else {
397                    ""
398                },
399                chain.join(" \u{2192} ")
400            ),
401            level,
402            "Bug Risk",
403            &path,
404            line,
405            &fp,
406        ));
407    }
408
409    // Boundary violations
410    let level = severity_to_codeclimate(rules.boundary_violation);
411    for v in &results.boundary_violations {
412        let path = cc_path(&v.from_path, root);
413        let to = cc_path(&v.to_path, root);
414        let fp = fingerprint_hash(&["fallow/boundary-violation", &path, &to]);
415        let line = if v.line > 0 { Some(v.line) } else { None };
416        issues.push(cc_issue(
417            "fallow/boundary-violation",
418            &format!(
419                "Boundary violation: {} -> {} ({} -> {})",
420                path, to, v.from_zone, v.to_zone
421            ),
422            level,
423            "Bug Risk",
424            &path,
425            line,
426            &fp,
427        ));
428    }
429
430    serde_json::Value::Array(issues)
431}
432
433/// Print dead-code analysis results in CodeClimate format.
434pub(super) fn print_codeclimate(
435    results: &AnalysisResults,
436    root: &Path,
437    rules: &RulesConfig,
438) -> ExitCode {
439    let value = build_codeclimate(results, root, rules);
440    emit_json(&value, "CodeClimate")
441}
442
443/// Print CodeClimate output with owner properties added to each issue.
444///
445/// Calls `build_codeclimate` to produce the standard CodeClimate JSON array,
446/// then post-processes each entry to add `"owner": "@team"` by resolving the
447/// issue's location path through the `OwnershipResolver`.
448pub(super) fn print_grouped_codeclimate(
449    results: &AnalysisResults,
450    root: &Path,
451    rules: &RulesConfig,
452    resolver: &OwnershipResolver,
453) {
454    let mut value = build_codeclimate(results, root, rules);
455
456    if let Some(issues) = value.as_array_mut() {
457        for issue in issues {
458            let path = issue
459                .pointer("/location/path")
460                .and_then(|v| v.as_str())
461                .unwrap_or("");
462            let owner = grouping::resolve_owner(Path::new(path), Path::new(""), resolver);
463            issue
464                .as_object_mut()
465                .expect("CodeClimate issue should be an object")
466                .insert("owner".to_string(), serde_json::Value::String(owner));
467        }
468    }
469
470    let _ = emit_json(&value, "CodeClimate");
471}
472
473/// Compute graduated severity for health findings based on threshold ratio.
474///
475/// - 1.0×–1.5× threshold → minor
476/// - 1.5×–2.5× threshold → major
477/// - >2.5× threshold → critical
478fn health_severity(value: u16, threshold: u16) -> &'static str {
479    if threshold == 0 {
480        return "minor";
481    }
482    let ratio = f64::from(value) / f64::from(threshold);
483    if ratio > 2.5 {
484        "critical"
485    } else if ratio > 1.5 {
486        "major"
487    } else {
488        "minor"
489    }
490}
491
492/// Build CodeClimate JSON array from health/complexity analysis results.
493#[must_use]
494pub fn build_health_codeclimate(report: &HealthReport, root: &Path) -> serde_json::Value {
495    let mut issues = Vec::new();
496
497    let cyc_t = report.summary.max_cyclomatic_threshold;
498    let cog_t = report.summary.max_cognitive_threshold;
499
500    for finding in &report.findings {
501        let path = cc_path(&finding.path, root);
502        let description = match finding.exceeded {
503            ExceededThreshold::Both => format!(
504                "'{}' has cyclomatic complexity {} (threshold: {}) and cognitive complexity {} (threshold: {})",
505                finding.name, finding.cyclomatic, cyc_t, finding.cognitive, cog_t
506            ),
507            ExceededThreshold::Cyclomatic => format!(
508                "'{}' has cyclomatic complexity {} (threshold: {})",
509                finding.name, finding.cyclomatic, cyc_t
510            ),
511            ExceededThreshold::Cognitive => format!(
512                "'{}' has cognitive complexity {} (threshold: {})",
513                finding.name, finding.cognitive, cog_t
514            ),
515        };
516        let check_name = match finding.exceeded {
517            ExceededThreshold::Both => "fallow/high-complexity",
518            ExceededThreshold::Cyclomatic => "fallow/high-cyclomatic-complexity",
519            ExceededThreshold::Cognitive => "fallow/high-cognitive-complexity",
520        };
521        // Graduate severity: use the worst exceeded metric
522        let severity = match finding.exceeded {
523            ExceededThreshold::Both => {
524                let cyc_sev = health_severity(finding.cyclomatic, cyc_t);
525                let cog_sev = health_severity(finding.cognitive, cog_t);
526                // Pick the more severe of the two
527                match (cyc_sev, cog_sev) {
528                    ("critical", _) | (_, "critical") => "critical",
529                    ("major", _) | (_, "major") => "major",
530                    _ => "minor",
531                }
532            }
533            ExceededThreshold::Cyclomatic => health_severity(finding.cyclomatic, cyc_t),
534            ExceededThreshold::Cognitive => health_severity(finding.cognitive, cog_t),
535        };
536        let line_str = finding.line.to_string();
537        let fp = fingerprint_hash(&[check_name, &path, &line_str, &finding.name]);
538        issues.push(cc_issue(
539            check_name,
540            &description,
541            severity,
542            "Complexity",
543            &path,
544            Some(finding.line),
545            &fp,
546        ));
547    }
548
549    serde_json::Value::Array(issues)
550}
551
552/// Print health analysis results in CodeClimate format.
553pub(super) fn print_health_codeclimate(report: &HealthReport, root: &Path) -> ExitCode {
554    let value = build_health_codeclimate(report, root);
555    emit_json(&value, "CodeClimate")
556}
557
558/// Build CodeClimate JSON array from duplication analysis results.
559#[must_use]
560#[expect(
561    clippy::cast_possible_truncation,
562    reason = "line numbers are bounded by source size"
563)]
564pub fn build_duplication_codeclimate(report: &DuplicationReport, root: &Path) -> serde_json::Value {
565    let mut issues = Vec::new();
566
567    for (i, group) in report.clone_groups.iter().enumerate() {
568        // Content-based fingerprint: hash token_count + line_count + first 64 chars of fragment
569        // This is stable across runs regardless of group ordering.
570        let token_str = group.token_count.to_string();
571        let line_count_str = group.line_count.to_string();
572        let fragment_prefix: String = group
573            .instances
574            .first()
575            .map(|inst| inst.fragment.chars().take(64).collect())
576            .unwrap_or_default();
577
578        for instance in &group.instances {
579            let path = cc_path(&instance.file, root);
580            let start_str = instance.start_line.to_string();
581            let fp = fingerprint_hash(&[
582                "fallow/code-duplication",
583                &path,
584                &start_str,
585                &token_str,
586                &line_count_str,
587                &fragment_prefix,
588            ]);
589            issues.push(cc_issue(
590                "fallow/code-duplication",
591                &format!(
592                    "Code clone group {} ({} lines, {} instances)",
593                    i + 1,
594                    group.line_count,
595                    group.instances.len()
596                ),
597                "minor",
598                "Duplication",
599                &path,
600                Some(instance.start_line as u32),
601                &fp,
602            ));
603        }
604    }
605
606    serde_json::Value::Array(issues)
607}
608
609/// Print duplication analysis results in CodeClimate format.
610pub(super) fn print_duplication_codeclimate(report: &DuplicationReport, root: &Path) -> ExitCode {
611    let value = build_duplication_codeclimate(report, root);
612    emit_json(&value, "CodeClimate")
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618    use crate::report::test_helpers::sample_results;
619    use fallow_config::RulesConfig;
620    use fallow_core::results::*;
621    use std::path::PathBuf;
622
623    #[test]
624    fn codeclimate_empty_results_produces_empty_array() {
625        let root = PathBuf::from("/project");
626        let results = AnalysisResults::default();
627        let rules = RulesConfig::default();
628        let output = build_codeclimate(&results, &root, &rules);
629        let arr = output.as_array().unwrap();
630        assert!(arr.is_empty());
631    }
632
633    #[test]
634    fn codeclimate_produces_array_of_issues() {
635        let root = PathBuf::from("/project");
636        let results = sample_results(&root);
637        let rules = RulesConfig::default();
638        let output = build_codeclimate(&results, &root, &rules);
639        assert!(output.is_array());
640        let arr = output.as_array().unwrap();
641        // Should have at least one issue per type
642        assert!(!arr.is_empty());
643    }
644
645    #[test]
646    fn codeclimate_issue_has_required_fields() {
647        let root = PathBuf::from("/project");
648        let mut results = AnalysisResults::default();
649        results.unused_files.push(UnusedFile {
650            path: root.join("src/dead.ts"),
651        });
652        let rules = RulesConfig::default();
653        let output = build_codeclimate(&results, &root, &rules);
654        let issue = &output.as_array().unwrap()[0];
655
656        assert_eq!(issue["type"], "issue");
657        assert_eq!(issue["check_name"], "fallow/unused-file");
658        assert!(issue["description"].is_string());
659        assert!(issue["categories"].is_array());
660        assert!(issue["severity"].is_string());
661        assert!(issue["fingerprint"].is_string());
662        assert!(issue["location"].is_object());
663        assert!(issue["location"]["path"].is_string());
664        assert!(issue["location"]["lines"].is_object());
665    }
666
667    #[test]
668    fn codeclimate_unused_file_severity_follows_rules() {
669        let root = PathBuf::from("/project");
670        let mut results = AnalysisResults::default();
671        results.unused_files.push(UnusedFile {
672            path: root.join("src/dead.ts"),
673        });
674
675        // Error severity -> major
676        let rules = RulesConfig::default();
677        let output = build_codeclimate(&results, &root, &rules);
678        assert_eq!(output[0]["severity"], "major");
679
680        // Warn severity -> minor
681        let rules = RulesConfig {
682            unused_files: Severity::Warn,
683            ..RulesConfig::default()
684        };
685        let output = build_codeclimate(&results, &root, &rules);
686        assert_eq!(output[0]["severity"], "minor");
687    }
688
689    #[test]
690    fn codeclimate_unused_export_has_line_number() {
691        let root = PathBuf::from("/project");
692        let mut results = AnalysisResults::default();
693        results.unused_exports.push(UnusedExport {
694            path: root.join("src/utils.ts"),
695            export_name: "helperFn".to_string(),
696            is_type_only: false,
697            line: 10,
698            col: 4,
699            span_start: 120,
700            is_re_export: false,
701        });
702        let rules = RulesConfig::default();
703        let output = build_codeclimate(&results, &root, &rules);
704        let issue = &output[0];
705        assert_eq!(issue["location"]["lines"]["begin"], 10);
706    }
707
708    #[test]
709    fn codeclimate_unused_file_line_defaults_to_1() {
710        let root = PathBuf::from("/project");
711        let mut results = AnalysisResults::default();
712        results.unused_files.push(UnusedFile {
713            path: root.join("src/dead.ts"),
714        });
715        let rules = RulesConfig::default();
716        let output = build_codeclimate(&results, &root, &rules);
717        let issue = &output[0];
718        assert_eq!(issue["location"]["lines"]["begin"], 1);
719    }
720
721    #[test]
722    fn codeclimate_paths_are_relative() {
723        let root = PathBuf::from("/project");
724        let mut results = AnalysisResults::default();
725        results.unused_files.push(UnusedFile {
726            path: root.join("src/deep/nested/file.ts"),
727        });
728        let rules = RulesConfig::default();
729        let output = build_codeclimate(&results, &root, &rules);
730        let path = output[0]["location"]["path"].as_str().unwrap();
731        assert_eq!(path, "src/deep/nested/file.ts");
732        assert!(!path.starts_with("/project"));
733    }
734
735    #[test]
736    fn codeclimate_re_export_label_in_description() {
737        let root = PathBuf::from("/project");
738        let mut results = AnalysisResults::default();
739        results.unused_exports.push(UnusedExport {
740            path: root.join("src/index.ts"),
741            export_name: "reExported".to_string(),
742            is_type_only: false,
743            line: 1,
744            col: 0,
745            span_start: 0,
746            is_re_export: true,
747        });
748        let rules = RulesConfig::default();
749        let output = build_codeclimate(&results, &root, &rules);
750        let desc = output[0]["description"].as_str().unwrap();
751        assert!(desc.contains("Re-export"));
752    }
753
754    #[test]
755    fn codeclimate_unlisted_dep_one_issue_per_import_site() {
756        let root = PathBuf::from("/project");
757        let mut results = AnalysisResults::default();
758        results.unlisted_dependencies.push(UnlistedDependency {
759            package_name: "chalk".to_string(),
760            imported_from: vec![
761                ImportSite {
762                    path: root.join("src/a.ts"),
763                    line: 1,
764                    col: 0,
765                },
766                ImportSite {
767                    path: root.join("src/b.ts"),
768                    line: 5,
769                    col: 0,
770                },
771            ],
772        });
773        let rules = RulesConfig::default();
774        let output = build_codeclimate(&results, &root, &rules);
775        let arr = output.as_array().unwrap();
776        assert_eq!(arr.len(), 2);
777        assert_eq!(arr[0]["check_name"], "fallow/unlisted-dependency");
778        assert_eq!(arr[1]["check_name"], "fallow/unlisted-dependency");
779    }
780
781    #[test]
782    fn codeclimate_duplicate_export_one_issue_per_location() {
783        let root = PathBuf::from("/project");
784        let mut results = AnalysisResults::default();
785        results.duplicate_exports.push(DuplicateExport {
786            export_name: "Config".to_string(),
787            locations: vec![
788                DuplicateLocation {
789                    path: root.join("src/a.ts"),
790                    line: 10,
791                    col: 0,
792                },
793                DuplicateLocation {
794                    path: root.join("src/b.ts"),
795                    line: 20,
796                    col: 0,
797                },
798                DuplicateLocation {
799                    path: root.join("src/c.ts"),
800                    line: 30,
801                    col: 0,
802                },
803            ],
804        });
805        let rules = RulesConfig::default();
806        let output = build_codeclimate(&results, &root, &rules);
807        let arr = output.as_array().unwrap();
808        assert_eq!(arr.len(), 3);
809    }
810
811    #[test]
812    fn codeclimate_circular_dep_emits_chain_in_description() {
813        let root = PathBuf::from("/project");
814        let mut results = AnalysisResults::default();
815        results.circular_dependencies.push(CircularDependency {
816            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
817            length: 2,
818            line: 3,
819            col: 0,
820            is_cross_package: false,
821        });
822        let rules = RulesConfig::default();
823        let output = build_codeclimate(&results, &root, &rules);
824        let desc = output[0]["description"].as_str().unwrap();
825        assert!(desc.contains("Circular dependency"));
826        assert!(desc.contains("src/a.ts"));
827        assert!(desc.contains("src/b.ts"));
828    }
829
830    #[test]
831    fn codeclimate_fingerprints_are_deterministic() {
832        let root = PathBuf::from("/project");
833        let results = sample_results(&root);
834        let rules = RulesConfig::default();
835        let output1 = build_codeclimate(&results, &root, &rules);
836        let output2 = build_codeclimate(&results, &root, &rules);
837
838        let fps1: Vec<&str> = output1
839            .as_array()
840            .unwrap()
841            .iter()
842            .map(|i| i["fingerprint"].as_str().unwrap())
843            .collect();
844        let fps2: Vec<&str> = output2
845            .as_array()
846            .unwrap()
847            .iter()
848            .map(|i| i["fingerprint"].as_str().unwrap())
849            .collect();
850        assert_eq!(fps1, fps2);
851    }
852
853    #[test]
854    fn codeclimate_fingerprints_are_unique() {
855        let root = PathBuf::from("/project");
856        let results = sample_results(&root);
857        let rules = RulesConfig::default();
858        let output = build_codeclimate(&results, &root, &rules);
859
860        let mut fps: Vec<&str> = output
861            .as_array()
862            .unwrap()
863            .iter()
864            .map(|i| i["fingerprint"].as_str().unwrap())
865            .collect();
866        let original_len = fps.len();
867        fps.sort_unstable();
868        fps.dedup();
869        assert_eq!(fps.len(), original_len, "fingerprints should be unique");
870    }
871
872    #[test]
873    fn codeclimate_type_only_dep_has_correct_check_name() {
874        let root = PathBuf::from("/project");
875        let mut results = AnalysisResults::default();
876        results.type_only_dependencies.push(TypeOnlyDependency {
877            package_name: "zod".to_string(),
878            path: root.join("package.json"),
879            line: 8,
880        });
881        let rules = RulesConfig::default();
882        let output = build_codeclimate(&results, &root, &rules);
883        assert_eq!(output[0]["check_name"], "fallow/type-only-dependency");
884        let desc = output[0]["description"].as_str().unwrap();
885        assert!(desc.contains("zod"));
886        assert!(desc.contains("type-only"));
887    }
888
889    #[test]
890    fn codeclimate_dep_with_zero_line_omits_line_number() {
891        let root = PathBuf::from("/project");
892        let mut results = AnalysisResults::default();
893        results.unused_dependencies.push(UnusedDependency {
894            package_name: "lodash".to_string(),
895            location: DependencyLocation::Dependencies,
896            path: root.join("package.json"),
897            line: 0,
898        });
899        let rules = RulesConfig::default();
900        let output = build_codeclimate(&results, &root, &rules);
901        // Line 0 -> begin defaults to 1
902        assert_eq!(output[0]["location"]["lines"]["begin"], 1);
903    }
904
905    // ── fingerprint_hash tests ─────────────────────────────────────
906
907    #[test]
908    fn fingerprint_hash_different_inputs_differ() {
909        let h1 = fingerprint_hash(&["a", "b"]);
910        let h2 = fingerprint_hash(&["a", "c"]);
911        assert_ne!(h1, h2);
912    }
913
914    #[test]
915    fn fingerprint_hash_order_matters() {
916        let h1 = fingerprint_hash(&["a", "b"]);
917        let h2 = fingerprint_hash(&["b", "a"]);
918        assert_ne!(h1, h2);
919    }
920
921    #[test]
922    fn fingerprint_hash_separator_prevents_collision() {
923        // "ab" + "c" should differ from "a" + "bc"
924        let h1 = fingerprint_hash(&["ab", "c"]);
925        let h2 = fingerprint_hash(&["a", "bc"]);
926        assert_ne!(h1, h2);
927    }
928
929    #[test]
930    fn fingerprint_hash_is_16_hex_chars() {
931        let h = fingerprint_hash(&["test"]);
932        assert_eq!(h.len(), 16);
933        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
934    }
935
936    // ── severity_to_codeclimate ─────────────────────────────────────
937
938    #[test]
939    fn severity_error_maps_to_major() {
940        assert_eq!(severity_to_codeclimate(Severity::Error), "major");
941    }
942
943    #[test]
944    fn severity_warn_maps_to_minor() {
945        assert_eq!(severity_to_codeclimate(Severity::Warn), "minor");
946    }
947
948    #[test]
949    fn severity_off_maps_to_minor() {
950        assert_eq!(severity_to_codeclimate(Severity::Off), "minor");
951    }
952
953    // ── health_severity ─────────────────────────────────────────────
954
955    #[test]
956    fn health_severity_zero_threshold_returns_minor() {
957        assert_eq!(health_severity(100, 0), "minor");
958    }
959
960    #[test]
961    fn health_severity_at_threshold_returns_minor() {
962        assert_eq!(health_severity(10, 10), "minor");
963    }
964
965    #[test]
966    fn health_severity_1_5x_threshold_returns_minor() {
967        assert_eq!(health_severity(15, 10), "minor");
968    }
969
970    #[test]
971    fn health_severity_above_1_5x_returns_major() {
972        assert_eq!(health_severity(16, 10), "major");
973    }
974
975    #[test]
976    fn health_severity_at_2_5x_returns_major() {
977        assert_eq!(health_severity(25, 10), "major");
978    }
979
980    #[test]
981    fn health_severity_above_2_5x_returns_critical() {
982        assert_eq!(health_severity(26, 10), "critical");
983    }
984}