Skip to main content

fallow_api/
dead_code_codeclimate.rs

1//! Shared dead-code CodeClimate issue construction.
2
3#[path = "dead_code_codeclimate_component_health.rs"]
4mod component_health;
5
6use std::path::Path;
7
8use fallow_config::{RulesConfig, Severity};
9use fallow_output::{
10    CodeClimateIssue, CodeClimateIssueInput, CodeClimateSeverity, build_codeclimate_issue,
11    codeclimate_fingerprint_hash, normalize_uri,
12};
13use fallow_types::envelope::AuditIntroduced;
14use fallow_types::identity::dead_code_finding_id;
15use fallow_types::output_dead_code::{
16    EffectiveSeverity, GatedFinding, ReachabilityCaveat, caveat_suffix,
17};
18use fallow_types::results::AnalysisResults;
19
20#[path = "dead_code_codeclimate_caller_review.rs"]
21mod caller_review;
22#[path = "dead_code_codeclimate_catalog.rs"]
23mod catalog_issues;
24#[path = "dead_code_codeclimate_component_io.rs"]
25mod component_io;
26use caller_review::{push_absent_component_prop_issues, push_constant_parameter_issues};
27use catalog_issues::{
28    push_empty_catalog_group_issues, push_misconfigured_dependency_override_issues,
29    push_unresolved_catalog_reference_issues, push_unused_catalog_entry_issues,
30    push_unused_dependency_override_issues,
31};
32use component_io::{
33    push_unused_component_input_issues, push_unused_component_output_issues,
34    push_unused_svelte_event_issues,
35};
36
37fn severity_to_codeclimate(s: Severity) -> CodeClimateSeverity {
38    match s {
39        Severity::Error => CodeClimateSeverity::Major,
40        Severity::Warn => CodeClimateSeverity::Minor,
41        Severity::Off => unreachable!(),
42    }
43}
44
45/// The CodeClimate severity for one finding: its gate severity when the
46/// finding carries one, otherwise the configured rule severity (a saved report
47/// from an older version has no gate severity).
48///
49/// A saved finding exists, so its rule was on when it was reported. When the
50/// config at render time sets the rule `off`, the severity is `minor`.
51fn gate_codeclimate(effective: Option<EffectiveSeverity>, rule: Severity) -> CodeClimateSeverity {
52    match effective {
53        Some(EffectiveSeverity::Error) => CodeClimateSeverity::Major,
54        Some(EffectiveSeverity::Warn) => CodeClimateSeverity::Minor,
55        None => match rule {
56            Severity::Off => CodeClimateSeverity::Minor,
57            Severity::Error | Severity::Warn => severity_to_codeclimate(rule),
58        },
59    }
60}
61
62fn finding_codeclimate(finding: &impl GatedFinding, rule: Severity) -> CodeClimateSeverity {
63    gate_codeclimate(finding.effective_severity(), rule)
64}
65
66fn cc_path(path: &Path, root: &Path) -> String {
67    normalize_uri(
68        &path
69            .strip_prefix(root)
70            .unwrap_or(path)
71            .display()
72            .to_string(),
73    )
74}
75
76/// The caveat parenthetical a CodeClimate `description` ends with, or an empty
77/// string when the verdict rests on a fully analyzed run.
78///
79/// `description` is the one field GitLab renders inline on the MR diff, and it
80/// is also what `CiIssue` carries into the PR-comment and review-comment
81/// bodies. Those bodies offer a mutation, so the sentence that offers it has to
82/// say when the evidence behind it is incomplete. The suffix is the same
83/// parenthetical the human report and the SARIF message already use, so one
84/// finding reads identically across every surface.
85///
86/// Deliberately NOT part of the fingerprint: `codeclimate_fingerprint_hash` is
87/// fed rule id plus location by every call site in this file, never the
88/// description, so a finding that gains or loses a caveat keeps its identity
89/// and no previously resolved review thread reopens.
90fn cc_caveat_suffix(caveats: &[ReachabilityCaveat]) -> String {
91    caveat_suffix(caveats).unwrap_or_default()
92}
93
94/// Build one dead-code issue with its stable fingerprint.
95///
96/// `input.fingerprint` is the legacy fingerprint: the value that Fallow gave
97/// this issue before findings had a `finding_id`. For most kinds it holds the
98/// line, so a line shift above the finding changed it.
99///
100/// When the finding has a `finding_id`, the fingerprint is the FNV-1a 64 hash
101/// of that id plus `discriminator`, as 16 lowercase hex digits. The id holds
102/// no line and no column, so a line shift keeps the fingerprint. The hash
103/// covers the full id, not only the hex part of the id, so the `~k` tiebreak
104/// suffix keeps two findings with the same base id apart. The 16-hex form is
105/// the form that GitLab Code Quality and the review marker regex accept.
106/// `discriminator` separates the issues of one finding that emits one issue
107/// per location (duplicate exports, unlisted-dependency import sites). See
108/// [`location_discriminators`].
109///
110/// A finding without an id (a saved report from an older version) keeps the
111/// legacy fingerprint, so its review threads stay matched.
112///
113/// `introduced` is the audit flag of the finding. An audit sets it when it
114/// compares the run with a base snapshot. The issue then carries the
115/// attribution for the inline review comment.
116fn dead_code_issue(
117    finding_id: Option<&str>,
118    introduced: Option<AuditIntroduced>,
119    discriminator: &[&str],
120    input: CodeClimateIssueInput<'_>,
121) -> CodeClimateIssue {
122    let mut issue = build_codeclimate_issue(input);
123    issue.audit = introduced.map(|AuditIntroduced(introduced)| audit_review_context(introduced));
124    if let Some(id) = finding_id {
125        let mut parts = Vec::with_capacity(discriminator.len() + 1);
126        parts.push(id);
127        parts.extend_from_slice(discriminator);
128        let stable = codeclimate_fingerprint_hash(&parts);
129        if stable != issue.fingerprint {
130            issue.legacy_fingerprint = Some(std::mem::replace(&mut issue.fingerprint, stable));
131        }
132    }
133    issue
134}
135
136/// The audit facts of an inline review comment for a finding that an audit
137/// compared with the base snapshot. `introduced` is the audit flag.
138pub(crate) const fn audit_review_context(introduced: bool) -> fallow_output::AuditReviewContext {
139    fallow_output::AuditReviewContext {
140        attribution: if introduced {
141            fallow_output::AuditFindingAttribution::Introduced
142        } else {
143            fallow_output::AuditFindingAttribution::Inherited
144        },
145        gate_exemption: None,
146        gate: None,
147    }
148}
149
150/// The discriminator of each location of one finding, in input order.
151///
152/// A location is named by what it is, not by where it is. The only content a
153/// location carries next to the finding id is its path: the engine reports
154/// one unlisted-dependency import site per file, and every location of a
155/// duplicate export has the same export name, which the id already holds. So
156/// the discriminator is the path. Only locations with the same path (the same
157/// content) also get a position: the first by line keeps the bare path, the
158/// next one gets `~1`, and so on. A location added to or removed from another
159/// file, or after this one in the same file, never changes it.
160fn location_discriminators(locations: &[(String, u32, u32)]) -> Vec<Vec<String>> {
161    locations
162        .iter()
163        .enumerate()
164        .map(|(index, (path, line, col))| {
165            let earlier = locations
166                .iter()
167                .enumerate()
168                .filter(|(other, (other_path, other_line, other_col))| {
169                    other_path == path && (other_line, other_col, *other) < (line, col, index)
170                })
171                .count();
172            if earlier == 0 {
173                vec![path.clone()]
174            } else {
175                vec![path.clone(), format!("~{earlier}")]
176            }
177        })
178        .collect()
179}
180
181/// Push CodeClimate issues for unused dependencies with a shared structure.
182fn push_dep_cc_issues<'a, I>(
183    issues: &mut Vec<CodeClimateIssue>,
184    deps: I,
185    root: &Path,
186    rule_id: &str,
187    location_label: &str,
188    severity: Severity,
189) where
190    I: IntoIterator<
191        Item = (
192            &'a fallow_types::results::UnusedDependency,
193            &'a [ReachabilityCaveat],
194            Option<EffectiveSeverity>,
195            Option<&'a str>,
196            Option<AuditIntroduced>,
197        ),
198    >,
199{
200    for (dep, caveats, effective, finding_id, introduced) in deps {
201        let level = gate_codeclimate(effective, severity);
202        let path = cc_path(&dep.path, root);
203        let line = if dep.line > 0 { Some(dep.line) } else { None };
204        let fp = codeclimate_fingerprint_hash(&[rule_id, &dep.package_name]);
205        let workspace_context = if dep.used_in_workspaces.is_empty() {
206            String::new()
207        } else {
208            let workspaces = dep
209                .used_in_workspaces
210                .iter()
211                .map(|path| cc_path(path, root))
212                .collect::<Vec<_>>()
213                .join(", ");
214            format!("; imported in other workspaces: {workspaces}")
215        };
216        issues.push(dead_code_issue(
217            finding_id,
218            introduced,
219            &[],
220            CodeClimateIssueInput {
221                check_name: rule_id,
222                description: &format!(
223                    "Package '{}' is in {location_label} but never imported{workspace_context}{}",
224                    dep.package_name,
225                    cc_caveat_suffix(caveats)
226                ),
227                severity: level,
228                category: "Bug Risk",
229                path: &path,
230                begin_line: line,
231                fingerprint: &fp,
232            },
233        ));
234    }
235}
236
237fn push_unused_file_issues(
238    issues: &mut Vec<CodeClimateIssue>,
239    files: &[fallow_types::output_dead_code::UnusedFileFinding],
240    root: &Path,
241    severity: Severity,
242) {
243    if files.is_empty() {
244        return;
245    }
246    for entry in files {
247        let level = finding_codeclimate(entry, severity);
248        let path = cc_path(&entry.file.path, root);
249        let fp = codeclimate_fingerprint_hash(&["fallow/unused-file", &path]);
250        issues.push(dead_code_issue(
251            entry.finding_id.as_deref(),
252            entry.introduced,
253            &[],
254            CodeClimateIssueInput {
255                check_name: "fallow/unused-file",
256                description: &format!(
257                    "File is not reachable from any entry point{}",
258                    cc_caveat_suffix(&entry.reachability_caveats)
259                ),
260                severity: level,
261                category: "Bug Risk",
262                path: &path,
263                begin_line: None,
264                fingerprint: &fp,
265            },
266        ));
267    }
268}
269
270/// Push CodeClimate issues for unused exports or unused types.
271///
272/// `direct_label` / `re_export_label` let the same helper produce the right
273/// prose for both `unused-export` (Export / Re-export) and `unused-type`
274/// (Type export / Type re-export) rule ids.
275struct UnusedExportIssuesInput<'a, I> {
276    issues: &'a mut Vec<CodeClimateIssue>,
277    exports: I,
278    root: &'a Path,
279    rule_id: &'a str,
280    direct_label: &'a str,
281    re_export_label: &'a str,
282    severity: Severity,
283}
284
285fn push_unused_export_issues<'a, I>(input: UnusedExportIssuesInput<'a, I>)
286where
287    I: IntoIterator<
288        Item = (
289            &'a fallow_types::results::UnusedExport,
290            &'a [ReachabilityCaveat],
291            Option<EffectiveSeverity>,
292            Option<&'a str>,
293            Option<AuditIntroduced>,
294        ),
295    >,
296{
297    for (export, caveats, effective, finding_id, introduced) in input.exports {
298        let level = gate_codeclimate(effective, input.severity);
299        let path = cc_path(&export.path, input.root);
300        let kind = if export.is_re_export {
301            input.re_export_label
302        } else {
303            input.direct_label
304        };
305        let line_str = export.line.to_string();
306        let fp =
307            codeclimate_fingerprint_hash(&[input.rule_id, &path, &line_str, &export.export_name]);
308        input.issues.push(dead_code_issue(
309            finding_id,
310            introduced,
311            &[],
312            CodeClimateIssueInput {
313                check_name: input.rule_id,
314                description: &format!(
315                    "{kind} '{}' is never imported by other modules{}",
316                    export.export_name,
317                    cc_caveat_suffix(caveats)
318                ),
319                severity: level,
320                category: "Bug Risk",
321                path: &path,
322                begin_line: Some(export.line),
323                fingerprint: &fp,
324            },
325        ));
326    }
327}
328
329fn push_private_type_leak_issues(
330    issues: &mut Vec<CodeClimateIssue>,
331    leaks: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
332    root: &Path,
333    severity: Severity,
334) {
335    if leaks.is_empty() {
336        return;
337    }
338    for entry in leaks {
339        let level = finding_codeclimate(entry, severity);
340        let leak = &entry.leak;
341        let path = cc_path(&leak.path, root);
342        let line_str = leak.line.to_string();
343        let fp = codeclimate_fingerprint_hash(&[
344            "fallow/private-type-leak",
345            &path,
346            &line_str,
347            &leak.export_name,
348            &leak.type_name,
349        ]);
350        issues.push(dead_code_issue(
351            entry.finding_id.as_deref(),
352            entry.introduced,
353            &[],
354            CodeClimateIssueInput {
355                check_name: "fallow/private-type-leak",
356                description: &format!(
357                    "Export '{}' references private type '{}'",
358                    leak.export_name, leak.type_name
359                ),
360                severity: level,
361                category: "Bug Risk",
362                path: &path,
363                begin_line: Some(leak.line),
364                fingerprint: &fp,
365            },
366        ));
367    }
368}
369
370fn push_deprecated_export_issues(
371    issues: &mut Vec<CodeClimateIssue>,
372    findings: &[fallow_types::output_dead_code::DeprecatedExportInUseFinding],
373    root: &Path,
374    severity: Severity,
375) {
376    for entry in findings {
377        let level = finding_codeclimate(entry, severity);
378        let export = &entry.export;
379        let path = cc_path(&export.path, root);
380        let line_str = export.line.to_string();
381        let fp = codeclimate_fingerprint_hash(&[
382            "fallow/deprecated-export-in-use",
383            &path,
384            &line_str,
385            &export.export_name,
386        ]);
387        issues.push(dead_code_issue(
388            entry.finding_id.as_deref(),
389            entry.introduced,
390            &[],
391            CodeClimateIssueInput {
392                check_name: "fallow/deprecated-export-in-use",
393                description: &export.description(),
394                severity: level,
395                category: "Compatibility",
396                path: &path,
397                begin_line: Some(export.line),
398                fingerprint: &fp,
399            },
400        ));
401    }
402}
403
404fn push_type_only_dep_issues(
405    issues: &mut Vec<CodeClimateIssue>,
406    deps: &[fallow_types::output_dead_code::TypeOnlyDependencyFinding],
407    root: &Path,
408    severity: Severity,
409) {
410    if deps.is_empty() {
411        return;
412    }
413    for entry in deps {
414        let level = finding_codeclimate(entry, severity);
415        let dep = &entry.dep;
416        let path = cc_path(&dep.path, root);
417        let line = if dep.line > 0 { Some(dep.line) } else { None };
418        let fp = codeclimate_fingerprint_hash(&["fallow/type-only-dependency", &dep.package_name]);
419        issues.push(dead_code_issue(
420            entry.finding_id.as_deref(),
421            entry.introduced,
422            &[],
423            CodeClimateIssueInput {
424                check_name: "fallow/type-only-dependency",
425                description: &format!(
426                    "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
427                    dep.package_name
428                ),
429                severity: level,
430                category: "Bug Risk",
431                path: &path,
432                begin_line: line,
433                fingerprint: &fp,
434            },
435        ));
436    }
437}
438
439fn push_test_only_dep_issues(
440    issues: &mut Vec<CodeClimateIssue>,
441    deps: &[fallow_types::output_dead_code::TestOnlyDependencyFinding],
442    root: &Path,
443    severity: Severity,
444) {
445    if deps.is_empty() {
446        return;
447    }
448    for entry in deps {
449        let level = finding_codeclimate(entry, severity);
450        let dep = &entry.dep;
451        let path = cc_path(&dep.path, root);
452        let line = if dep.line > 0 { Some(dep.line) } else { None };
453        let fp = codeclimate_fingerprint_hash(&["fallow/test-only-dependency", &dep.package_name]);
454        issues.push(dead_code_issue(
455            entry.finding_id.as_deref(),
456            entry.introduced,
457            &[],
458            CodeClimateIssueInput {
459                check_name: "fallow/test-only-dependency",
460                description: &format!(
461                    "Package '{}' is only imported by test files (consider moving to devDependencies)",
462                    dep.package_name
463                ),
464                severity: level,
465                category: "Bug Risk",
466                path: &path,
467                begin_line: line,
468                fingerprint: &fp,
469            },
470        ));
471    }
472}
473
474fn push_dev_dep_in_prod_issues(
475    issues: &mut Vec<CodeClimateIssue>,
476    deps: &[fallow_types::output_dead_code::DevDependencyInProductionFinding],
477    root: &Path,
478    severity: Severity,
479) {
480    if deps.is_empty() {
481        return;
482    }
483    for entry in deps {
484        let level = finding_codeclimate(entry, severity);
485        let dep = &entry.dep;
486        let path = cc_path(&dep.path, root);
487        let line = if dep.line > 0 { Some(dep.line) } else { None };
488        let fp = codeclimate_fingerprint_hash(&[
489            "fallow/dev-dependency-in-production",
490            &dep.package_name,
491        ]);
492        issues.push(dead_code_issue(
493            entry.finding_id.as_deref(),
494            entry.introduced,
495            &[],
496            CodeClimateIssueInput {
497                check_name: "fallow/dev-dependency-in-production",
498                description: &format!(
499                    "devDependency '{}' is imported by production code at runtime (consider moving to dependencies)",
500                    dep.package_name
501                ),
502                severity: level,
503                category: "Bug Risk",
504                path: &path,
505                begin_line: line,
506                fingerprint: &fp,
507            },
508        ));
509    }
510}
511
512/// Push CodeClimate issues for unused enum or class members.
513///
514/// `entity_label` is `"Enum"` or `"Class"` so the rendered description reads
515/// "Enum member ..." or "Class member ..." accordingly.
516fn push_unused_member_issues<'a, I>(
517    issues: &mut Vec<CodeClimateIssue>,
518    members: I,
519    root: &Path,
520    rule_id: &str,
521    entity_label: &str,
522    severity: Severity,
523) where
524    I: IntoIterator<
525        Item = (
526            &'a fallow_types::results::UnusedMember,
527            &'a [ReachabilityCaveat],
528            Option<EffectiveSeverity>,
529            Option<&'a str>,
530            Option<AuditIntroduced>,
531        ),
532    >,
533{
534    for (member, caveats, effective, finding_id, introduced) in members {
535        let level = gate_codeclimate(effective, severity);
536        let path = cc_path(&member.path, root);
537        let line_str = member.line.to_string();
538        let fp = codeclimate_fingerprint_hash(&[
539            rule_id,
540            &path,
541            &line_str,
542            &member.parent_name,
543            &member.member_name,
544        ]);
545        issues.push(dead_code_issue(
546            finding_id,
547            introduced,
548            &[],
549            CodeClimateIssueInput {
550                check_name: rule_id,
551                description: &format!(
552                    "{entity_label} member '{}.{}' is never referenced{}",
553                    member.parent_name,
554                    member.member_name,
555                    cc_caveat_suffix(caveats)
556                ),
557                severity: level,
558                category: "Bug Risk",
559                path: &path,
560                begin_line: Some(member.line),
561                fingerprint: &fp,
562            },
563        ));
564    }
565}
566
567fn push_unresolved_import_issues(
568    issues: &mut Vec<CodeClimateIssue>,
569    imports: &[fallow_types::output_dead_code::UnresolvedImportFinding],
570    root: &Path,
571    severity: Severity,
572) {
573    if imports.is_empty() {
574        return;
575    }
576    for entry in imports {
577        let level = finding_codeclimate(entry, severity);
578        let import = &entry.import;
579        let path = cc_path(&import.path, root);
580        let line_str = import.line.to_string();
581        let fp = codeclimate_fingerprint_hash(&[
582            "fallow/unresolved-import",
583            &path,
584            &line_str,
585            &import.specifier,
586        ]);
587        issues.push(dead_code_issue(
588            entry.finding_id.as_deref(),
589            entry.introduced,
590            &[],
591            CodeClimateIssueInput {
592                check_name: "fallow/unresolved-import",
593                description: &format!("Import '{}' could not be resolved", import.specifier),
594                severity: level,
595                category: "Bug Risk",
596                path: &path,
597                begin_line: Some(import.line),
598                fingerprint: &fp,
599            },
600        ));
601    }
602}
603
604fn push_unlisted_dep_issues(
605    issues: &mut Vec<CodeClimateIssue>,
606    deps: &[fallow_types::output_dead_code::UnlistedDependencyFinding],
607    root: &Path,
608    severity: Severity,
609) {
610    if deps.is_empty() {
611        return;
612    }
613    for entry in deps {
614        let level = finding_codeclimate(entry, severity);
615        let dep = &entry.dep;
616        let sites: Vec<(String, u32, u32)> = dep
617            .imported_from
618            .iter()
619            .map(|site| (cc_path(&site.path, root), site.line, site.col))
620            .collect();
621        let discriminators = location_discriminators(&sites);
622        for ((path, line, _), discriminator) in sites.iter().zip(&discriminators) {
623            let line_str = line.to_string();
624            let discriminator: Vec<&str> = discriminator.iter().map(String::as_str).collect();
625            let fp = codeclimate_fingerprint_hash(&[
626                "fallow/unlisted-dependency",
627                path,
628                &line_str,
629                &dep.package_name,
630            ]);
631            issues.push(dead_code_issue(
632                entry.finding_id.as_deref(),
633                entry.introduced,
634                &discriminator,
635                CodeClimateIssueInput {
636                    check_name: "fallow/unlisted-dependency",
637                    description: &format!(
638                        "Package '{}' is imported but not listed in package.json",
639                        dep.package_name
640                    ),
641                    severity: level,
642                    category: "Bug Risk",
643                    path,
644                    begin_line: Some(*line),
645                    fingerprint: &fp,
646                },
647            ));
648        }
649    }
650}
651
652fn push_unlisted_binary_issues(
653    issues: &mut Vec<CodeClimateIssue>,
654    binaries: &[fallow_types::output_dead_code::UnlistedBinaryFinding],
655    root: &Path,
656    severity: Severity,
657) {
658    for entry in binaries {
659        let level = finding_codeclimate(entry, severity);
660        let binary = &entry.binary;
661        let sites: Vec<(String, u32, u32)> = binary
662            .used_in
663            .iter()
664            .map(|site| (cc_path(&site.path, root), site.line, site.col))
665            .collect();
666        let discriminators = location_discriminators(&sites);
667        for ((path, line, _), discriminator) in sites.iter().zip(&discriminators) {
668            let line_str = line.to_string();
669            let discriminator: Vec<&str> = discriminator.iter().map(String::as_str).collect();
670            let fp = codeclimate_fingerprint_hash(&[
671                "fallow/unlisted-binary",
672                path,
673                &line_str,
674                &binary.binary_name,
675            ]);
676            issues.push(dead_code_issue(
677                entry.finding_id.as_deref(),
678                entry.introduced,
679                &discriminator,
680                CodeClimateIssueInput {
681                    check_name: "fallow/unlisted-binary",
682                    description: &format!(
683                        "Binary '{}' is used but no installed or listed package provides it",
684                        binary.binary_name
685                    ),
686                    severity: level,
687                    category: "Bug Risk",
688                    path,
689                    begin_line: Some(*line),
690                    fingerprint: &fp,
691                },
692            ));
693        }
694    }
695}
696
697fn push_duplicate_export_issues(
698    issues: &mut Vec<CodeClimateIssue>,
699    dups: &[fallow_types::output_dead_code::DuplicateExportFinding],
700    root: &Path,
701    severity: Severity,
702) {
703    if dups.is_empty() {
704        return;
705    }
706    for dup in dups {
707        let level = finding_codeclimate(dup, severity);
708        // The finding id of a duplicate export holds the set of its paths, so
709        // one more or one less location gives the finding a new id. Each
710        // issue is one location, so its fingerprint uses the part of the id
711        // that stays: the rule and the export name. The location discriminator
712        // adds the path. A saved finding without an id keeps the legacy
713        // fingerprint.
714        let location_identity = dup
715            .finding_id
716            .is_some()
717            .then(|| dead_code_finding_id("duplicate-export", &[&dup.export.export_name]));
718        let finding_id = location_identity.as_deref();
719        let introduced = dup.introduced;
720        let dup = &dup.export;
721        let locations: Vec<(String, u32, u32)> = dup
722            .locations
723            .iter()
724            .map(|loc| (cc_path(&loc.path, root), loc.line, loc.col))
725            .collect();
726        let discriminators = location_discriminators(&locations);
727        for ((path, line, _), discriminator) in locations.iter().zip(&discriminators) {
728            let line_str = line.to_string();
729            let discriminator: Vec<&str> = discriminator.iter().map(String::as_str).collect();
730            let fp = codeclimate_fingerprint_hash(&[
731                "fallow/duplicate-export",
732                path,
733                &line_str,
734                &dup.export_name,
735            ]);
736            issues.push(dead_code_issue(
737                finding_id,
738                introduced,
739                &discriminator,
740                CodeClimateIssueInput {
741                    check_name: "fallow/duplicate-export",
742                    description: &format!(
743                        "Export '{}' appears in multiple modules",
744                        dup.export_name
745                    ),
746                    severity: level,
747                    category: "Bug Risk",
748                    path,
749                    begin_line: Some(*line),
750                    fingerprint: &fp,
751                },
752            ));
753        }
754    }
755}
756
757fn push_circular_dep_issues(
758    issues: &mut Vec<CodeClimateIssue>,
759    cycles: &[fallow_types::output_dead_code::CircularDependencyFinding],
760    root: &Path,
761    severity: Severity,
762) {
763    if cycles.is_empty() {
764        return;
765    }
766    for entry in cycles {
767        let level = finding_codeclimate(entry, severity);
768        let cycle = &entry.cycle;
769        let Some(first) = cycle.files.first() else {
770            continue;
771        };
772        let path = cc_path(first, root);
773        let chain: Vec<String> = cycle.files.iter().map(|f| cc_path(f, root)).collect();
774        let chain_str = chain.join(":");
775        let fp = codeclimate_fingerprint_hash(&["fallow/circular-dependency", &chain_str]);
776        let line = if cycle.line > 0 {
777            Some(cycle.line)
778        } else {
779            None
780        };
781        issues.push(dead_code_issue(
782            entry.finding_id.as_deref(),
783            entry.introduced,
784            &[],
785            CodeClimateIssueInput {
786                check_name: "fallow/circular-dependency",
787                description: &format!(
788                    "Circular dependency{}: {}",
789                    if cycle.is_cross_package {
790                        " (cross-package)"
791                    } else {
792                        ""
793                    },
794                    chain.join(" \u{2192} ")
795                ),
796                severity: level,
797                category: "Bug Risk",
798                path: &path,
799                begin_line: line,
800                fingerprint: &fp,
801            },
802        ));
803    }
804}
805
806fn push_re_export_cycle_issues(
807    issues: &mut Vec<CodeClimateIssue>,
808    cycles: &[fallow_types::output_dead_code::ReExportCycleFinding],
809    root: &Path,
810    severity: Severity,
811) {
812    if cycles.is_empty() {
813        return;
814    }
815    for entry in cycles {
816        let level = finding_codeclimate(entry, severity);
817        let cycle = &entry.cycle;
818        let Some(first) = cycle.files.first() else {
819            continue;
820        };
821        let path = cc_path(first, root);
822        let chain: Vec<String> = cycle.files.iter().map(|f| cc_path(f, root)).collect();
823        let chain_str = chain.join(":");
824        let kind_token = match cycle.kind {
825            fallow_types::results::ReExportCycleKind::SelfLoop => "self-loop",
826            fallow_types::results::ReExportCycleKind::MultiNode => "multi-node",
827        };
828        let kind_tag = match cycle.kind {
829            fallow_types::results::ReExportCycleKind::SelfLoop => " (self-loop)",
830            fallow_types::results::ReExportCycleKind::MultiNode => "",
831        };
832        let fp = codeclimate_fingerprint_hash(&["fallow/re-export-cycle", kind_token, &chain_str]);
833        issues.push(dead_code_issue(
834            entry.finding_id.as_deref(),
835            entry.introduced,
836            &[],
837            CodeClimateIssueInput {
838                check_name: "fallow/re-export-cycle",
839                description: &format!("Re-export cycle{}: {}", kind_tag, chain.join(" <-> ")),
840                severity: level,
841                category: "Bug Risk",
842                path: &path,
843                begin_line: None,
844                fingerprint: &fp,
845            },
846        ));
847    }
848}
849
850fn push_package_cycle_issues(
851    issues: &mut Vec<CodeClimateIssue>,
852    cycles: &[fallow_types::output_dead_code::PackageCycleFinding],
853    root: &Path,
854    severity: Severity,
855) {
856    for entry in cycles {
857        let level = finding_codeclimate(entry, severity);
858        let cycle = &entry.cycle;
859        let Some(anchor) = cycle.edges.first() else {
860            continue;
861        };
862        let path = cc_path(&anchor.path, root);
863        let packages = cycle.packages.join(":");
864        let fp = codeclimate_fingerprint_hash(&["fallow/package-cycle", &packages]);
865        let note = if cycle.group_truncated {
866            format!(
867                " ({})",
868                fallow_types::results::PackageCycle::GROUP_TRUNCATED_NOTE
869            )
870        } else {
871            String::new()
872        };
873        let mut issue = build_codeclimate_issue(CodeClimateIssueInput {
874            check_name: "fallow/package-cycle",
875            description: &format!("Package cycle: {}{note}", cycle.chain(" \u{2192} ")),
876            severity: level,
877            category: "Bug Risk",
878            path: &path,
879            begin_line: (anchor.line > 0).then_some(anchor.line),
880            fingerprint: &fp,
881        });
882        issue.audit = entry
883            .introduced
884            .map(|AuditIntroduced(introduced)| audit_review_context(introduced));
885        issues.push(issue);
886    }
887}
888
889fn push_boundary_violation_issues(
890    issues: &mut Vec<CodeClimateIssue>,
891    violations: &[fallow_types::output_dead_code::BoundaryViolationFinding],
892    root: &Path,
893    severity: Severity,
894) {
895    if violations.is_empty() {
896        return;
897    }
898    for entry in violations {
899        let level = finding_codeclimate(entry, severity);
900        let v = &entry.violation;
901        let path = cc_path(&v.from_path, root);
902        let to = cc_path(&v.to_path, root);
903        let fp = codeclimate_fingerprint_hash(&["fallow/boundary-violation", &path, &to]);
904        let line = if v.line > 0 { Some(v.line) } else { None };
905        let via = v
906            .via_path
907            .as_ref()
908            .map_or_else(String::new, |via| format!(", via {}", cc_path(via, root)));
909        issues.push(dead_code_issue(
910            entry.finding_id.as_deref(),
911            entry.introduced,
912            &[],
913            CodeClimateIssueInput {
914                check_name: "fallow/boundary-violation",
915                description: &format!(
916                    "Boundary violation: {} -> {} ({} -> {}{})",
917                    path, to, v.from_zone, v.to_zone, via
918                ),
919                severity: level,
920                category: "Bug Risk",
921                path: &path,
922                begin_line: line,
923                fingerprint: &fp,
924            },
925        ));
926    }
927}
928
929fn push_boundary_coverage_issues(
930    issues: &mut Vec<CodeClimateIssue>,
931    violations: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
932    root: &Path,
933    severity: Severity,
934) {
935    if violations.is_empty() {
936        return;
937    }
938    for entry in violations {
939        let level = finding_codeclimate(entry, severity);
940        let v = &entry.violation;
941        let path = cc_path(&v.path, root);
942        let fp = codeclimate_fingerprint_hash(&["fallow/boundary-coverage", &path]);
943        let line = if v.line > 0 { Some(v.line) } else { None };
944        issues.push(dead_code_issue(
945            entry.finding_id.as_deref(),
946            entry.introduced,
947            &[],
948            CodeClimateIssueInput {
949                check_name: "fallow/boundary-coverage",
950                description: &format!("Boundary coverage: {path} matches no configured zone"),
951                severity: level,
952                category: "Bug Risk",
953                path: &path,
954                begin_line: line,
955                fingerprint: &fp,
956            },
957        ));
958    }
959}
960
961fn push_boundary_call_issues(
962    issues: &mut Vec<CodeClimateIssue>,
963    violations: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
964    root: &Path,
965    severity: Severity,
966) {
967    if violations.is_empty() {
968        return;
969    }
970    for entry in violations {
971        let level = finding_codeclimate(entry, severity);
972        let v = &entry.violation;
973        let path = cc_path(&v.path, root);
974        let fp =
975            codeclimate_fingerprint_hash(&["fallow/boundary-call-violation", &path, &v.callee]);
976        let line = if v.line > 0 { Some(v.line) } else { None };
977        issues.push(dead_code_issue(
978            entry.finding_id.as_deref(),
979            entry.introduced,
980            &[],
981            CodeClimateIssueInput {
982                check_name: "fallow/boundary-call-violation",
983                description: &format!(
984                    "Boundary call: `{}` matches forbidden pattern `{}` in zone '{}'",
985                    v.callee, v.pattern, v.zone
986                ),
987                severity: level,
988                category: "Bug Risk",
989                path: &path,
990                begin_line: line,
991                fingerprint: &fp,
992            },
993        ));
994    }
995}
996
997fn push_policy_violation_issues(
998    issues: &mut Vec<CodeClimateIssue>,
999    violations: &[fallow_types::output_dead_code::PolicyViolationFinding],
1000    root: &Path,
1001) {
1002    use fallow_types::results::PolicyViolationSeverity;
1003
1004    for entry in violations {
1005        let v = &entry.violation;
1006        let path = cc_path(&v.path, root);
1007        let rule = format!("{}/{}", v.pack, v.rule_id);
1008        let fp =
1009            codeclimate_fingerprint_hash(&["fallow/policy-violation", &path, &rule, &v.matched]);
1010        let line = if v.line > 0 { Some(v.line) } else { None };
1011        // Severity comes from the EFFECTIVE per-finding value, not the
1012        // policy-violation master, so a severity: "error" rule under a warn
1013        // master maps to blocker-level just like the exit-code gate.
1014        let level = severity_to_codeclimate(match v.severity {
1015            PolicyViolationSeverity::Error => Severity::Error,
1016            PolicyViolationSeverity::Warn => Severity::Warn,
1017        });
1018        let message = match &v.message {
1019            Some(message) => format!(
1020                "Policy violation: `{}` is banned by `{rule}`. {message}",
1021                v.matched
1022            ),
1023            None => format!("Policy violation: `{}` is banned by `{rule}`", v.matched),
1024        };
1025        issues.push(dead_code_issue(
1026            entry.finding_id.as_deref(),
1027            entry.introduced,
1028            &[],
1029            CodeClimateIssueInput {
1030                check_name: "fallow/policy-violation",
1031                description: &message,
1032                severity: level,
1033                category: "Bug Risk",
1034                path: &path,
1035                begin_line: line,
1036                fingerprint: &fp,
1037            },
1038        ));
1039    }
1040}
1041
1042fn push_invalid_client_export_issues(
1043    issues: &mut Vec<CodeClimateIssue>,
1044    findings: &[fallow_types::output_dead_code::InvalidClientExportFinding],
1045    root: &Path,
1046    severity: Severity,
1047) {
1048    if findings.is_empty() {
1049        return;
1050    }
1051    for entry in findings {
1052        let level = finding_codeclimate(entry, severity);
1053        let e = &entry.export;
1054        let path = cc_path(&e.path, root);
1055        let fp =
1056            codeclimate_fingerprint_hash(&["fallow/invalid-client-export", &path, &e.export_name]);
1057        let line = if e.line > 0 { Some(e.line) } else { None };
1058        let message = format!(
1059            "Export `{}` is not allowed in a \"{}\" file (Next.js server-only / route-config name)",
1060            e.export_name, e.directive
1061        );
1062        issues.push(dead_code_issue(
1063            entry.finding_id.as_deref(),
1064            entry.introduced,
1065            &[],
1066            CodeClimateIssueInput {
1067                check_name: "fallow/invalid-client-export",
1068                description: &message,
1069                severity: level,
1070                category: "Bug Risk",
1071                path: &path,
1072                begin_line: line,
1073                fingerprint: &fp,
1074            },
1075        ));
1076    }
1077}
1078
1079fn push_mixed_client_server_barrel_issues(
1080    issues: &mut Vec<CodeClimateIssue>,
1081    findings: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
1082    root: &Path,
1083    severity: Severity,
1084) {
1085    if findings.is_empty() {
1086        return;
1087    }
1088    for entry in findings {
1089        let level = finding_codeclimate(entry, severity);
1090        let b = &entry.barrel;
1091        let path = cc_path(&b.path, root);
1092        let fp = codeclimate_fingerprint_hash(&[
1093            "fallow/mixed-client-server-barrel",
1094            &path,
1095            &b.client_origin,
1096            &b.server_origin,
1097        ]);
1098        let line = if b.line > 0 { Some(b.line) } else { None };
1099        let message = format!(
1100            "Barrel re-exports both a \"use client\" module (`{}`) and a server-only module (`{}`); one import drags the other's directive across the boundary",
1101            b.client_origin, b.server_origin
1102        );
1103        issues.push(dead_code_issue(
1104            entry.finding_id.as_deref(),
1105            entry.introduced,
1106            &[],
1107            CodeClimateIssueInput {
1108                check_name: "fallow/mixed-client-server-barrel",
1109                description: &message,
1110                severity: level,
1111                category: "Bug Risk",
1112                path: &path,
1113                begin_line: line,
1114                fingerprint: &fp,
1115            },
1116        ));
1117    }
1118}
1119
1120fn push_misplaced_directive_issues(
1121    issues: &mut Vec<CodeClimateIssue>,
1122    findings: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
1123    root: &Path,
1124    severity: Severity,
1125) {
1126    if findings.is_empty() {
1127        return;
1128    }
1129    for entry in findings {
1130        let level = finding_codeclimate(entry, severity);
1131        let d = &entry.directive_site;
1132        let path = cc_path(&d.path, root);
1133        let fp = codeclimate_fingerprint_hash(&[
1134            "fallow/misplaced-directive",
1135            &path,
1136            &d.line.to_string(),
1137            &d.directive,
1138        ]);
1139        let line = if d.line > 0 { Some(d.line) } else { None };
1140        let message = format!(
1141            "Directive `\"{}\"` is not in the leading position, so the RSC bundler ignores it; move it to the top of the file",
1142            d.directive
1143        );
1144        issues.push(dead_code_issue(
1145            entry.finding_id.as_deref(),
1146            entry.introduced,
1147            &[],
1148            CodeClimateIssueInput {
1149                check_name: "fallow/misplaced-directive",
1150                description: &message,
1151                severity: level,
1152                category: "Bug Risk",
1153                path: &path,
1154                begin_line: line,
1155                fingerprint: &fp,
1156            },
1157        ));
1158    }
1159}
1160
1161fn push_unprovided_inject_issues(
1162    issues: &mut Vec<CodeClimateIssue>,
1163    findings: &[fallow_types::output_dead_code::UnprovidedInjectFinding],
1164    root: &Path,
1165    severity: Severity,
1166) {
1167    if findings.is_empty() {
1168        return;
1169    }
1170    for entry in findings {
1171        let level = finding_codeclimate(entry, severity);
1172        let i = &entry.inject;
1173        let path = cc_path(&i.path, root);
1174        let fp = codeclimate_fingerprint_hash(&[
1175            "fallow/unprovided-inject",
1176            &path,
1177            &i.line.to_string(),
1178            &i.key_name,
1179        ]);
1180        let line = if i.line > 0 { Some(i.line) } else { None };
1181        let message = format!(
1182            "inject(`{}`) has no matching provide(`{}`) in this project; at runtime it returns undefined (provide the key or remove this inject)",
1183            i.key_name, i.key_name
1184        );
1185        issues.push(dead_code_issue(
1186            entry.finding_id.as_deref(),
1187            entry.introduced,
1188            &[],
1189            CodeClimateIssueInput {
1190                check_name: "fallow/unprovided-inject",
1191                description: &message,
1192                severity: level,
1193                category: "Bug Risk",
1194                path: &path,
1195                begin_line: line,
1196                fingerprint: &fp,
1197            },
1198        ));
1199    }
1200}
1201
1202fn push_unrendered_component_issues(
1203    issues: &mut Vec<CodeClimateIssue>,
1204    findings: &[fallow_types::output_dead_code::UnrenderedComponentFinding],
1205    root: &Path,
1206    severity: Severity,
1207) {
1208    if findings.is_empty() {
1209        return;
1210    }
1211    for entry in findings {
1212        let level = finding_codeclimate(entry, severity);
1213        let c = &entry.component;
1214        let path = cc_path(&c.path, root);
1215        let fp = codeclimate_fingerprint_hash(&[
1216            "fallow/unrendered-component",
1217            &path,
1218            &c.line.to_string(),
1219            &c.component_name,
1220        ]);
1221        let line = if c.line > 0 { Some(c.line) } else { None };
1222        let message = format!(
1223            "component `{}` is reachable but rendered nowhere in this project (render it somewhere or remove it)",
1224            c.component_name
1225        );
1226        issues.push(dead_code_issue(
1227            entry.finding_id.as_deref(),
1228            entry.introduced,
1229            &[],
1230            CodeClimateIssueInput {
1231                check_name: "fallow/unrendered-component",
1232                description: &message,
1233                severity: level,
1234                category: "Bug Risk",
1235                path: &path,
1236                begin_line: line,
1237                fingerprint: &fp,
1238            },
1239        ));
1240    }
1241}
1242
1243fn push_unused_component_prop_issues(
1244    issues: &mut Vec<CodeClimateIssue>,
1245    findings: &[fallow_types::output_dead_code::UnusedComponentPropFinding],
1246    root: &Path,
1247    severity: Severity,
1248) {
1249    if findings.is_empty() {
1250        return;
1251    }
1252    for entry in findings {
1253        let level = finding_codeclimate(entry, severity);
1254        let p = &entry.prop;
1255        let path = cc_path(&p.path, root);
1256        let fp = codeclimate_fingerprint_hash(&[
1257            "fallow/unused-component-prop",
1258            &path,
1259            &p.line.to_string(),
1260            &p.prop_name,
1261        ]);
1262        let line = if p.line > 0 { Some(p.line) } else { None };
1263        let message = format!(
1264            "prop `{}` is declared but referenced nowhere in component `{}` (remove it or use it)",
1265            p.prop_name, p.component_name
1266        );
1267        issues.push(dead_code_issue(
1268            entry.finding_id.as_deref(),
1269            entry.introduced,
1270            &[],
1271            CodeClimateIssueInput {
1272                check_name: "fallow/unused-component-prop",
1273                description: &message,
1274                severity: level,
1275                category: "Bug Risk",
1276                path: &path,
1277                begin_line: line,
1278                fingerprint: &fp,
1279            },
1280        ));
1281    }
1282}
1283
1284fn push_unused_component_emit_issues(
1285    issues: &mut Vec<CodeClimateIssue>,
1286    findings: &[fallow_types::output_dead_code::UnusedComponentEmitFinding],
1287    root: &Path,
1288    severity: Severity,
1289) {
1290    if findings.is_empty() {
1291        return;
1292    }
1293    for entry in findings {
1294        let level = finding_codeclimate(entry, severity);
1295        let e = &entry.emit;
1296        let path = cc_path(&e.path, root);
1297        let fp = codeclimate_fingerprint_hash(&[
1298            "fallow/unused-component-emit",
1299            &path,
1300            &e.line.to_string(),
1301            &e.emit_name,
1302        ]);
1303        let line = if e.line > 0 { Some(e.line) } else { None };
1304        let message = format!(
1305            "emit `{}` is declared but emitted nowhere in component `{}` (remove it or emit it)",
1306            e.emit_name, e.component_name
1307        );
1308        issues.push(dead_code_issue(
1309            entry.finding_id.as_deref(),
1310            entry.introduced,
1311            &[],
1312            CodeClimateIssueInput {
1313                check_name: "fallow/unused-component-emit",
1314                description: &message,
1315                severity: level,
1316                category: "Bug Risk",
1317                path: &path,
1318                begin_line: line,
1319                fingerprint: &fp,
1320            },
1321        ));
1322    }
1323}
1324
1325fn push_unused_effect_layer_issues(
1326    issues: &mut Vec<CodeClimateIssue>,
1327    findings: &[fallow_types::output_dead_code::UnusedEffectLayerFinding],
1328    root: &Path,
1329    severity: Severity,
1330) {
1331    for entry in findings {
1332        let level = finding_codeclimate(entry, severity);
1333        let f = &entry.layer;
1334        let path = cc_path(&f.path, root);
1335        let fp = codeclimate_fingerprint_hash(&[
1336            "fallow/unused-effect-layer",
1337            &path,
1338            &f.line.to_string(),
1339            &f.name,
1340        ]);
1341        let line = if f.line > 0 { Some(f.line) } else { None };
1342        let message = format!(
1343            "layer `{}` is composed only into layers that nothing uses ({}); compose it into a live layer or remove it",
1344            f.name,
1345            f.dead_consumers.join(", ")
1346        );
1347        issues.push(dead_code_issue(
1348            entry.finding_id.as_deref(),
1349            entry.introduced,
1350            &[],
1351            CodeClimateIssueInput {
1352                check_name: "fallow/unused-effect-layer",
1353                description: &message,
1354                severity: level,
1355                category: "Bug Risk",
1356                path: &path,
1357                begin_line: line,
1358                fingerprint: &fp,
1359            },
1360        ));
1361    }
1362}
1363
1364fn push_duplicate_export_alias_issues(
1365    issues: &mut Vec<CodeClimateIssue>,
1366    findings: &[fallow_types::output_dead_code::DuplicateExportAliasFinding],
1367    root: &Path,
1368    severity: Severity,
1369) {
1370    for entry in findings {
1371        let level = finding_codeclimate(entry, severity);
1372        let f = &entry.alias;
1373        let path = cc_path(&f.path, root);
1374        let names = f.export_names.join(",");
1375        let fp = codeclimate_fingerprint_hash(&[
1376            "fallow/duplicate-export-alias",
1377            &path,
1378            &f.local_name,
1379            &names,
1380        ]);
1381        let line = if f.line > 0 { Some(f.line) } else { None };
1382        let message = format!(
1383            "`{}` is exported under {} names ({}); keep one name or add the names to ignoreExports",
1384            f.local_name,
1385            f.export_names.len(),
1386            f.export_names.join(", ")
1387        );
1388        issues.push(dead_code_issue(
1389            entry.finding_id.as_deref(),
1390            entry.introduced,
1391            &[],
1392            CodeClimateIssueInput {
1393                check_name: "fallow/duplicate-export-alias",
1394                description: &message,
1395                severity: level,
1396                category: "Duplication",
1397                path: &path,
1398                begin_line: line,
1399                fingerprint: &fp,
1400            },
1401        ));
1402    }
1403}
1404
1405fn push_unused_tagged_error_issues(
1406    issues: &mut Vec<CodeClimateIssue>,
1407    findings: &[fallow_types::output_dead_code::UnusedTaggedErrorFinding],
1408    root: &Path,
1409    severity: Severity,
1410) {
1411    for entry in findings {
1412        let level = finding_codeclimate(entry, severity);
1413        let f = &entry.error;
1414        let path = cc_path(&f.path, root);
1415        let fp = codeclimate_fingerprint_hash(&[
1416            "fallow/unused-tagged-error",
1417            &path,
1418            &f.line.to_string(),
1419            &f.name,
1420        ]);
1421        let line = if f.line > 0 { Some(f.line) } else { None };
1422        let message = format!(
1423            "tagged error `{}` (tag `{}`) is never constructed or failed with; fail with it or remove it",
1424            f.name, f.tag
1425        );
1426        issues.push(dead_code_issue(
1427            entry.finding_id.as_deref(),
1428            entry.introduced,
1429            &[],
1430            CodeClimateIssueInput {
1431                check_name: "fallow/unused-tagged-error",
1432                description: &message,
1433                severity: level,
1434                category: "Bug Risk",
1435                path: &path,
1436                begin_line: line,
1437                fingerprint: &fp,
1438            },
1439        ));
1440    }
1441}
1442
1443fn push_unproduced_catch_tag_issues(
1444    issues: &mut Vec<CodeClimateIssue>,
1445    findings: &[fallow_types::output_dead_code::UnproducedCatchTagFinding],
1446    root: &Path,
1447    severity: Severity,
1448) {
1449    for entry in findings {
1450        let level = finding_codeclimate(entry, severity);
1451        let f = &entry.catch_tag;
1452        let path = cc_path(&f.path, root);
1453        let fp = codeclimate_fingerprint_hash(&[
1454            "fallow/unproduced-catch-tag",
1455            &path,
1456            &f.line.to_string(),
1457            &f.tag,
1458        ]);
1459        let line = if f.line > 0 { Some(f.line) } else { None };
1460        let message = format!(
1461            "catchTag handler for `{}` never runs: no code produces {}",
1462            f.tag,
1463            f.candidate_classes.join(", ")
1464        );
1465        issues.push(dead_code_issue(
1466            entry.finding_id.as_deref(),
1467            entry.introduced,
1468            &[],
1469            CodeClimateIssueInput {
1470                check_name: "fallow/unproduced-catch-tag",
1471                description: &message,
1472                severity: level,
1473                category: "Bug Risk",
1474                path: &path,
1475                begin_line: line,
1476                fingerprint: &fp,
1477            },
1478        ));
1479    }
1480}
1481
1482fn push_unused_server_action_issues(
1483    issues: &mut Vec<CodeClimateIssue>,
1484    findings: &[fallow_types::output_dead_code::UnusedServerActionFinding],
1485    root: &Path,
1486    severity: Severity,
1487) {
1488    if findings.is_empty() {
1489        return;
1490    }
1491    for entry in findings {
1492        let level = finding_codeclimate(entry, severity);
1493        let a = &entry.action;
1494        let path = cc_path(&a.path, root);
1495        let fp = codeclimate_fingerprint_hash(&[
1496            "fallow/unused-server-action",
1497            &path,
1498            &a.line.to_string(),
1499            &a.action_name,
1500        ]);
1501        let line = if a.line > 0 { Some(a.line) } else { None };
1502        let message = format!(
1503            "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)",
1504            a.action_name
1505        );
1506        issues.push(dead_code_issue(
1507            entry.finding_id.as_deref(),
1508            entry.introduced,
1509            &[],
1510            CodeClimateIssueInput {
1511                check_name: "fallow/unused-server-action",
1512                description: &message,
1513                severity: level,
1514                category: "Bug Risk",
1515                path: &path,
1516                begin_line: line,
1517                fingerprint: &fp,
1518            },
1519        ));
1520    }
1521}
1522
1523fn push_unused_load_data_key_issues(
1524    issues: &mut Vec<CodeClimateIssue>,
1525    findings: &[fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
1526    root: &Path,
1527    severity: Severity,
1528) {
1529    if findings.is_empty() {
1530        return;
1531    }
1532    for entry in findings {
1533        let level = finding_codeclimate(entry, severity);
1534        let k = &entry.key;
1535        let path = cc_path(&k.path, root);
1536        let fp = codeclimate_fingerprint_hash(&[
1537            "fallow/unused-load-data-key",
1538            &path,
1539            &k.line.to_string(),
1540            &k.key_name,
1541        ]);
1542        let line = if k.line > 0 { Some(k.line) } else { None };
1543        let message = format!(
1544            "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",
1545            k.key_name
1546        );
1547        issues.push(dead_code_issue(
1548            entry.finding_id.as_deref(),
1549            entry.introduced,
1550            &[],
1551            CodeClimateIssueInput {
1552                check_name: "fallow/unused-load-data-key",
1553                description: &message,
1554                severity: level,
1555                category: "Bug Risk",
1556                path: &path,
1557                begin_line: line,
1558                fingerprint: &fp,
1559            },
1560        ));
1561    }
1562}
1563
1564fn push_route_collision_issues(
1565    issues: &mut Vec<CodeClimateIssue>,
1566    findings: &[fallow_types::output_dead_code::RouteCollisionFinding],
1567    root: &Path,
1568    severity: Severity,
1569) {
1570    if findings.is_empty() {
1571        return;
1572    }
1573    for entry in findings {
1574        let level = finding_codeclimate(entry, severity);
1575        let c = &entry.collision;
1576        let path = cc_path(&c.path, root);
1577        let fp = codeclimate_fingerprint_hash(&["fallow/route-collision", &path, &c.url]);
1578        let line = if c.line > 0 { Some(c.line) } else { None };
1579        let message = format!(
1580            "Route file resolves to `{}`, also owned by {} other file(s); Next.js fails the build because a URL can have only one owner",
1581            c.url,
1582            c.conflicting_paths.len()
1583        );
1584        issues.push(dead_code_issue(
1585            entry.finding_id.as_deref(),
1586            entry.introduced,
1587            &[],
1588            CodeClimateIssueInput {
1589                check_name: "fallow/route-collision",
1590                description: &message,
1591                severity: level,
1592                category: "Bug Risk",
1593                path: &path,
1594                begin_line: line,
1595                fingerprint: &fp,
1596            },
1597        ));
1598    }
1599}
1600
1601fn push_dynamic_segment_name_conflict_issues(
1602    issues: &mut Vec<CodeClimateIssue>,
1603    findings: &[fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
1604    root: &Path,
1605    severity: Severity,
1606) {
1607    if findings.is_empty() {
1608        return;
1609    }
1610    for entry in findings {
1611        let level = finding_codeclimate(entry, severity);
1612        let c = &entry.conflict;
1613        let path = cc_path(&c.path, root);
1614        let fp = codeclimate_fingerprint_hash(&[
1615            "fallow/dynamic-segment-name-conflict",
1616            &path,
1617            &c.position,
1618        ]);
1619        let line = if c.line > 0 { Some(c.line) } else { None };
1620        let message = format!(
1621            "Dynamic segments at `{}` use different slug names ({}); Next.js requires one consistent name per dynamic path",
1622            c.position,
1623            c.conflicting_segments.join(", ")
1624        );
1625        issues.push(dead_code_issue(
1626            entry.finding_id.as_deref(),
1627            entry.introduced,
1628            &[],
1629            CodeClimateIssueInput {
1630                check_name: "fallow/dynamic-segment-name-conflict",
1631                description: &message,
1632                severity: level,
1633                category: "Bug Risk",
1634                path: &path,
1635                begin_line: line,
1636                fingerprint: &fp,
1637            },
1638        ));
1639    }
1640}
1641
1642fn push_stale_suppression_issues(
1643    issues: &mut Vec<CodeClimateIssue>,
1644    suppressions: &[fallow_types::results::StaleSuppression],
1645    root: &Path,
1646    rules: &RulesConfig,
1647) {
1648    if suppressions.is_empty() {
1649        return;
1650    }
1651    for s in suppressions {
1652        let severity = if s.missing_reason {
1653            rules.require_suppression_reason
1654        } else {
1655            rules.stale_suppressions
1656        };
1657        let level = finding_codeclimate(s, severity);
1658        let path = cc_path(&s.path, root);
1659        let line_str = s.line.to_string();
1660        let check_name = if s.missing_reason {
1661            "fallow/missing-suppression-reason"
1662        } else {
1663            "fallow/stale-suppression"
1664        };
1665        let fp = codeclimate_fingerprint_hash(&[check_name, &path, &line_str]);
1666        issues.push(dead_code_issue(
1667            s.finding_id.as_deref(),
1668            // The audit sets this flag with `set_stale_suppression_audit_attribution`.
1669            None,
1670            &[],
1671            CodeClimateIssueInput {
1672                check_name,
1673                description: &s.display_message(),
1674                severity: level,
1675                category: "Bug Risk",
1676                path: &path,
1677                begin_line: Some(s.line),
1678                fingerprint: &fp,
1679            },
1680        ));
1681    }
1682}
1683
1684/// Build CodeClimate issues from dead-code analysis results.
1685///
1686/// Returns the typed [`CodeClimateIssue`] vec; callers that emit the wire
1687/// shape convert via [`fallow_output::codeclimate_issues_to_value`]. The schema
1688/// drift gate locks the per-issue shape against
1689/// [`fallow_output::CodeClimateOutput`].
1690#[must_use]
1691pub fn build_codeclimate(
1692    results: &AnalysisResults,
1693    root: &Path,
1694    rules: &RulesConfig,
1695) -> Vec<CodeClimateIssue> {
1696    CodeClimateBuilder {
1697        issues: Vec::new(),
1698        results,
1699        root,
1700        rules,
1701    }
1702    .build()
1703}
1704
1705struct CodeClimateBuilder<'a> {
1706    issues: Vec<CodeClimateIssue>,
1707    results: &'a AnalysisResults,
1708    root: &'a Path,
1709    rules: &'a RulesConfig,
1710}
1711
1712impl CodeClimateBuilder<'_> {
1713    fn build(mut self) -> Vec<CodeClimateIssue> {
1714        self.push_file_and_export_issues();
1715        self.push_private_type_leak_issues();
1716        push_deprecated_export_issues(
1717            &mut self.issues,
1718            &self.results.deprecated_exports_in_use,
1719            self.root,
1720            self.rules.deprecated_exports_in_use,
1721        );
1722        self.push_package_dependency_issues();
1723        self.push_type_test_dependency_issues();
1724        self.push_member_issues();
1725        self.push_import_and_duplicate_issues();
1726        self.push_graph_issues();
1727        self.push_boundary_issues();
1728        self.push_suppression_and_catalog_issues();
1729        self.push_override_issues();
1730        self.push_prop_drilling_issues();
1731        self.push_component_shape_issues();
1732        self.issues
1733    }
1734
1735    fn push_file_and_export_issues(&mut self) {
1736        push_unused_file_issues(
1737            &mut self.issues,
1738            &self.results.unused_files,
1739            self.root,
1740            self.rules.unused_files,
1741        );
1742        push_unused_export_issues(UnusedExportIssuesInput {
1743            issues: &mut self.issues,
1744            exports: self.results.unused_exports.iter().map(|e| {
1745                (
1746                    &e.export,
1747                    e.reachability_caveats.as_slice(),
1748                    e.effective_severity,
1749                    e.finding_id.as_deref(),
1750                    e.introduced,
1751                )
1752            }),
1753            root: self.root,
1754            rule_id: "fallow/unused-export",
1755            direct_label: "Export",
1756            re_export_label: "Re-export",
1757            severity: self.rules.unused_exports,
1758        });
1759        push_unused_export_issues(UnusedExportIssuesInput {
1760            issues: &mut self.issues,
1761            exports: self.results.unused_types.iter().map(|e| {
1762                (
1763                    &e.export,
1764                    e.reachability_caveats.as_slice(),
1765                    e.effective_severity,
1766                    e.finding_id.as_deref(),
1767                    e.introduced,
1768                )
1769            }),
1770            root: self.root,
1771            rule_id: "fallow/unused-type",
1772            direct_label: "Type export",
1773            re_export_label: "Type re-export",
1774            severity: self.rules.unused_types,
1775        });
1776    }
1777
1778    fn push_private_type_leak_issues(&mut self) {
1779        push_private_type_leak_issues(
1780            &mut self.issues,
1781            &self.results.private_type_leaks,
1782            self.root,
1783            self.rules.private_type_leaks,
1784        );
1785    }
1786
1787    fn push_package_dependency_issues(&mut self) {
1788        push_dep_cc_issues(
1789            &mut self.issues,
1790            self.results.unused_dependencies.iter().map(|f| {
1791                (
1792                    &f.dep,
1793                    f.reachability_caveats.as_slice(),
1794                    f.effective_severity,
1795                    f.finding_id.as_deref(),
1796                    f.introduced,
1797                )
1798            }),
1799            self.root,
1800            "fallow/unused-dependency",
1801            "dependencies",
1802            self.rules.unused_dependencies,
1803        );
1804        push_dep_cc_issues(
1805            &mut self.issues,
1806            self.results.unused_dev_dependencies.iter().map(|f| {
1807                (
1808                    &f.dep,
1809                    f.reachability_caveats.as_slice(),
1810                    f.effective_severity,
1811                    f.finding_id.as_deref(),
1812                    f.introduced,
1813                )
1814            }),
1815            self.root,
1816            "fallow/unused-dev-dependency",
1817            "devDependencies",
1818            self.rules.unused_dev_dependencies,
1819        );
1820        push_dep_cc_issues(
1821            &mut self.issues,
1822            self.results.unused_optional_dependencies.iter().map(|f| {
1823                (
1824                    &f.dep,
1825                    f.reachability_caveats.as_slice(),
1826                    f.effective_severity,
1827                    f.finding_id.as_deref(),
1828                    f.introduced,
1829                )
1830            }),
1831            self.root,
1832            "fallow/unused-optional-dependency",
1833            "optionalDependencies",
1834            self.rules.unused_optional_dependencies,
1835        );
1836    }
1837
1838    fn push_type_test_dependency_issues(&mut self) {
1839        push_type_only_dep_issues(
1840            &mut self.issues,
1841            &self.results.type_only_dependencies,
1842            self.root,
1843            self.rules.type_only_dependencies,
1844        );
1845        push_test_only_dep_issues(
1846            &mut self.issues,
1847            &self.results.test_only_dependencies,
1848            self.root,
1849            self.rules.test_only_dependencies,
1850        );
1851        push_dev_dep_in_prod_issues(
1852            &mut self.issues,
1853            &self.results.dev_dependencies_in_production,
1854            self.root,
1855            self.rules.dev_dependencies_in_production,
1856        );
1857    }
1858
1859    fn push_member_issues(&mut self) {
1860        push_unused_member_issues(
1861            &mut self.issues,
1862            self.results.unused_enum_members.iter().map(|m| {
1863                (
1864                    &m.member,
1865                    m.reachability_caveats.as_slice(),
1866                    m.effective_severity,
1867                    m.finding_id.as_deref(),
1868                    m.introduced,
1869                )
1870            }),
1871            self.root,
1872            "fallow/unused-enum-member",
1873            "Enum",
1874            self.rules.unused_enum_members,
1875        );
1876        push_unused_member_issues(
1877            &mut self.issues,
1878            self.results.unused_class_members.iter().map(|m| {
1879                (
1880                    &m.member,
1881                    m.reachability_caveats.as_slice(),
1882                    m.effective_severity,
1883                    m.finding_id.as_deref(),
1884                    m.introduced,
1885                )
1886            }),
1887            self.root,
1888            "fallow/unused-class-member",
1889            "Class",
1890            self.rules.unused_class_members,
1891        );
1892        push_unused_member_issues(
1893            &mut self.issues,
1894            self.results.unused_store_members.iter().map(|m| {
1895                (
1896                    &m.member,
1897                    m.reachability_caveats.as_slice(),
1898                    m.effective_severity,
1899                    m.finding_id.as_deref(),
1900                    m.introduced,
1901                )
1902            }),
1903            self.root,
1904            "fallow/unused-store-member",
1905            "Store",
1906            self.rules.unused_store_members,
1907        );
1908        push_unused_member_issues(
1909            &mut self.issues,
1910            self.results.unused_namespace_members.iter().map(|m| {
1911                (
1912                    &m.member,
1913                    m.reachability_caveats.as_slice(),
1914                    m.effective_severity,
1915                    m.finding_id.as_deref(),
1916                    m.introduced,
1917                )
1918            }),
1919            self.root,
1920            "fallow/unused-namespace-member",
1921            "Namespace",
1922            self.rules.unused_namespace_members,
1923        );
1924    }
1925
1926    fn push_import_and_duplicate_issues(&mut self) {
1927        push_unresolved_import_issues(
1928            &mut self.issues,
1929            &self.results.unresolved_imports,
1930            self.root,
1931            self.rules.unresolved_imports,
1932        );
1933        push_unlisted_dep_issues(
1934            &mut self.issues,
1935            &self.results.unlisted_dependencies,
1936            self.root,
1937            self.rules.unlisted_dependencies,
1938        );
1939        push_unlisted_binary_issues(
1940            &mut self.issues,
1941            &self.results.unlisted_binaries,
1942            self.root,
1943            self.rules.unlisted_binaries,
1944        );
1945        push_duplicate_export_issues(
1946            &mut self.issues,
1947            &self.results.duplicate_exports,
1948            self.root,
1949            self.rules.duplicate_exports,
1950        );
1951    }
1952
1953    fn push_graph_issues(&mut self) {
1954        push_circular_dep_issues(
1955            &mut self.issues,
1956            &self.results.circular_dependencies,
1957            self.root,
1958            self.rules.circular_dependencies,
1959        );
1960        push_re_export_cycle_issues(
1961            &mut self.issues,
1962            &self.results.re_export_cycles,
1963            self.root,
1964            self.rules.re_export_cycle,
1965        );
1966        push_package_cycle_issues(
1967            &mut self.issues,
1968            &self.results.package_cycles,
1969            self.root,
1970            self.rules.package_cycle,
1971        );
1972    }
1973
1974    fn push_boundary_issues(&mut self) {
1975        self.push_architecture_boundary_issues();
1976        self.push_client_server_boundary_issues();
1977        self.push_component_boundary_issues();
1978        self.push_framework_route_issues();
1979    }
1980
1981    fn push_architecture_boundary_issues(&mut self) {
1982        push_boundary_violation_issues(
1983            &mut self.issues,
1984            &self.results.boundary_violations,
1985            self.root,
1986            self.rules.boundary_violation,
1987        );
1988        push_boundary_coverage_issues(
1989            &mut self.issues,
1990            &self.results.boundary_coverage_violations,
1991            self.root,
1992            self.rules.boundary_violation,
1993        );
1994        push_boundary_call_issues(
1995            &mut self.issues,
1996            &self.results.boundary_call_violations,
1997            self.root,
1998            self.rules.boundary_violation,
1999        );
2000        push_policy_violation_issues(&mut self.issues, &self.results.policy_violations, self.root);
2001    }
2002
2003    fn push_client_server_boundary_issues(&mut self) {
2004        push_invalid_client_export_issues(
2005            &mut self.issues,
2006            &self.results.invalid_client_exports,
2007            self.root,
2008            self.rules.invalid_client_export,
2009        );
2010        push_mixed_client_server_barrel_issues(
2011            &mut self.issues,
2012            &self.results.mixed_client_server_barrels,
2013            self.root,
2014            self.rules.mixed_client_server_barrel,
2015        );
2016        push_misplaced_directive_issues(
2017            &mut self.issues,
2018            &self.results.misplaced_directives,
2019            self.root,
2020            self.rules.misplaced_directive,
2021        );
2022    }
2023
2024    fn push_component_boundary_issues(&mut self) {
2025        push_unprovided_inject_issues(
2026            &mut self.issues,
2027            &self.results.unprovided_injects,
2028            self.root,
2029            self.rules.unprovided_injects,
2030        );
2031        push_unrendered_component_issues(
2032            &mut self.issues,
2033            &self.results.unrendered_components,
2034            self.root,
2035            self.rules.unrendered_components,
2036        );
2037        push_absent_component_prop_issues(
2038            &mut self.issues,
2039            &self.results.absent_component_props,
2040            self.root,
2041            self.rules.absent_component_props,
2042        );
2043        push_constant_parameter_issues(
2044            &mut self.issues,
2045            &self.results.constant_parameters,
2046            self.root,
2047            self.rules.constant_parameters,
2048        );
2049        push_unused_component_prop_issues(
2050            &mut self.issues,
2051            &self.results.unused_component_props,
2052            self.root,
2053            self.rules.unused_component_props,
2054        );
2055        push_unused_component_emit_issues(
2056            &mut self.issues,
2057            &self.results.unused_component_emits,
2058            self.root,
2059            self.rules.unused_component_emits,
2060        );
2061        push_unused_component_input_issues(
2062            &mut self.issues,
2063            &self.results.unused_component_inputs,
2064            self.root,
2065            self.rules.unused_component_inputs,
2066        );
2067        push_unused_component_output_issues(
2068            &mut self.issues,
2069            &self.results.unused_component_outputs,
2070            self.root,
2071            self.rules.unused_component_outputs,
2072        );
2073        push_unused_svelte_event_issues(
2074            &mut self.issues,
2075            &self.results.unused_svelte_events,
2076            self.root,
2077            self.rules.unused_svelte_events,
2078        );
2079        push_unused_effect_layer_issues(
2080            &mut self.issues,
2081            &self.results.unused_effect_layers,
2082            self.root,
2083            self.rules.unused_effect_layers,
2084        );
2085        push_duplicate_export_alias_issues(
2086            &mut self.issues,
2087            &self.results.duplicate_export_aliases,
2088            self.root,
2089            self.rules.duplicate_export_aliases,
2090        );
2091        push_unused_tagged_error_issues(
2092            &mut self.issues,
2093            &self.results.unused_tagged_errors,
2094            self.root,
2095            self.rules.unused_tagged_errors,
2096        );
2097        push_unproduced_catch_tag_issues(
2098            &mut self.issues,
2099            &self.results.unproduced_catch_tags,
2100            self.root,
2101            self.rules.unproduced_catch_tags,
2102        );
2103    }
2104
2105    fn push_framework_route_issues(&mut self) {
2106        push_unused_server_action_issues(
2107            &mut self.issues,
2108            &self.results.unused_server_actions,
2109            self.root,
2110            self.rules.unused_server_actions,
2111        );
2112        push_unused_load_data_key_issues(
2113            &mut self.issues,
2114            &self.results.unused_load_data_keys,
2115            self.root,
2116            self.rules.unused_load_data_keys,
2117        );
2118        push_route_collision_issues(
2119            &mut self.issues,
2120            &self.results.route_collisions,
2121            self.root,
2122            self.rules.route_collision,
2123        );
2124        push_dynamic_segment_name_conflict_issues(
2125            &mut self.issues,
2126            &self.results.dynamic_segment_name_conflicts,
2127            self.root,
2128            self.rules.dynamic_segment_name_conflict,
2129        );
2130    }
2131
2132    fn push_suppression_and_catalog_issues(&mut self) {
2133        push_stale_suppression_issues(
2134            &mut self.issues,
2135            &self.results.stale_suppressions,
2136            self.root,
2137            self.rules,
2138        );
2139        push_unused_catalog_entry_issues(
2140            &mut self.issues,
2141            &self.results.unused_catalog_entries,
2142            self.root,
2143            self.rules.unused_catalog_entries,
2144        );
2145        push_empty_catalog_group_issues(
2146            &mut self.issues,
2147            &self.results.empty_catalog_groups,
2148            self.root,
2149            self.rules.empty_catalog_groups,
2150        );
2151        push_unresolved_catalog_reference_issues(
2152            &mut self.issues,
2153            &self.results.unresolved_catalog_references,
2154            self.root,
2155            self.rules.unresolved_catalog_references,
2156        );
2157    }
2158
2159    fn push_override_issues(&mut self) {
2160        push_unused_dependency_override_issues(
2161            &mut self.issues,
2162            &self.results.unused_dependency_overrides,
2163            self.root,
2164            self.rules.unused_dependency_overrides,
2165        );
2166        push_misconfigured_dependency_override_issues(
2167            &mut self.issues,
2168            &self.results.misconfigured_dependency_overrides,
2169            self.root,
2170            self.rules.misconfigured_dependency_overrides,
2171        );
2172    }
2173}
2174
2175#[cfg(test)]
2176#[path = "dead_code_codeclimate_tests.rs"]
2177mod tests;