Skip to main content

fallow_cli/report/
compact.rs

1use std::path::Path;
2
3use fallow_core::duplicates::DuplicationReport;
4use fallow_core::results::{AnalysisResults, UnusedExport, UnusedMember};
5
6use super::grouping::ResultGroup;
7use super::{normalize_uri, relative_path};
8
9pub(super) fn print_compact(results: &AnalysisResults, root: &Path) {
10    for line in build_compact_lines(results, root) {
11        println!("{line}");
12    }
13}
14
15/// Build compact output lines for analysis results.
16/// Each issue is represented as a single `prefix:details` line.
17#[expect(
18    clippy::too_many_lines,
19    reason = "One uniform loop per issue type; the line count grows linearly with new issue types and the structure is clearer than extracting per-loop helpers."
20)]
21pub fn build_compact_lines(results: &AnalysisResults, root: &Path) -> Vec<String> {
22    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
23
24    let compact_export = |export: &UnusedExport, kind: &str, re_kind: &str| -> String {
25        let tag = if export.is_re_export { re_kind } else { kind };
26        format!(
27            "{}:{}:{}:{}",
28            tag,
29            rel(&export.path),
30            export.line,
31            export.export_name
32        )
33    };
34
35    let compact_member = |member: &UnusedMember, kind: &str| -> String {
36        format!(
37            "{}:{}:{}:{}.{}",
38            kind,
39            rel(&member.path),
40            member.line,
41            member.parent_name,
42            member.member_name
43        )
44    };
45
46    let mut lines = Vec::new();
47
48    for file in &results.unused_files {
49        lines.push(format!("unused-file:{}", rel(&file.file.path)));
50    }
51    for export in &results.unused_exports {
52        lines.push(compact_export(
53            &export.export,
54            "unused-export",
55            "unused-re-export",
56        ));
57    }
58    for export in &results.unused_types {
59        lines.push(compact_export(
60            &export.export,
61            "unused-type",
62            "unused-re-export-type",
63        ));
64    }
65    for leak in &results.private_type_leaks {
66        lines.push(format!(
67            "private-type-leak:{}:{}:{}->{}",
68            rel(&leak.leak.path),
69            leak.leak.line,
70            leak.leak.export_name,
71            leak.leak.type_name
72        ));
73    }
74    for dep in &results.unused_dependencies {
75        lines.push(format!("unused-dep:{}", dep.dep.package_name));
76    }
77    for dep in &results.unused_dev_dependencies {
78        lines.push(format!("unused-devdep:{}", dep.dep.package_name));
79    }
80    for dep in &results.unused_optional_dependencies {
81        lines.push(format!("unused-optionaldep:{}", dep.dep.package_name));
82    }
83    for member in &results.unused_enum_members {
84        lines.push(compact_member(&member.member, "unused-enum-member"));
85    }
86    for member in &results.unused_class_members {
87        lines.push(compact_member(&member.member, "unused-class-member"));
88    }
89    for import in &results.unresolved_imports {
90        lines.push(format!(
91            "unresolved-import:{}:{}:{}",
92            rel(&import.import.path),
93            import.import.line,
94            import.import.specifier
95        ));
96    }
97    for dep in &results.unlisted_dependencies {
98        lines.push(format!("unlisted-dep:{}", dep.dep.package_name));
99    }
100    for dup in &results.duplicate_exports {
101        lines.push(format!("duplicate-export:{}", dup.export.export_name));
102    }
103    for dep in &results.type_only_dependencies {
104        lines.push(format!("type-only-dep:{}", dep.dep.package_name));
105    }
106    for dep in &results.test_only_dependencies {
107        lines.push(format!("test-only-dep:{}", dep.dep.package_name));
108    }
109    for cycle in &results.circular_dependencies {
110        let chain: Vec<String> = cycle.cycle.files.iter().map(|p| rel(p)).collect();
111        let mut display_chain = chain.clone();
112        if let Some(first) = chain.first() {
113            display_chain.push(first.clone());
114        }
115        let first_file = chain.first().map_or_else(String::new, Clone::clone);
116        let cross_pkg_tag = if cycle.cycle.is_cross_package {
117            " (cross-package)"
118        } else {
119            ""
120        };
121        lines.push(format!(
122            "circular-dependency:{}:{}:{}{}",
123            first_file,
124            cycle.cycle.line,
125            display_chain.join(" \u{2192} "),
126            cross_pkg_tag
127        ));
128    }
129    for v in &results.boundary_violations {
130        lines.push(format!(
131            "boundary-violation:{}:{}:{} -> {} ({} -> {})",
132            rel(&v.violation.from_path),
133            v.violation.line,
134            rel(&v.violation.from_path),
135            rel(&v.violation.to_path),
136            v.violation.from_zone,
137            v.violation.to_zone,
138        ));
139    }
140    for s in &results.stale_suppressions {
141        lines.push(format!(
142            "stale-suppression:{}:{}:{}",
143            rel(&s.path),
144            s.line,
145            s.description(),
146        ));
147    }
148    for entry in &results.unused_catalog_entries {
149        lines.push(format!(
150            "unused-catalog-entry:{}:{}:{}:{}",
151            rel(&entry.entry.path),
152            entry.entry.line,
153            entry.entry.catalog_name,
154            entry.entry.entry_name,
155        ));
156    }
157    for group in &results.empty_catalog_groups {
158        lines.push(format!(
159            "empty-catalog-group:{}:{}:{}",
160            rel(&group.group.path),
161            group.group.line,
162            group.group.catalog_name,
163        ));
164    }
165    for finding in &results.unresolved_catalog_references {
166        lines.push(format!(
167            "unresolved-catalog-reference:{}:{}:{}:{}",
168            rel(&finding.reference.path),
169            finding.reference.line,
170            finding.reference.catalog_name,
171            finding.reference.entry_name,
172        ));
173    }
174    for finding in &results.unused_dependency_overrides {
175        lines.push(format!(
176            "unused-dependency-override:{}:{}:{}:{}",
177            rel(&finding.entry.path),
178            finding.entry.line,
179            finding.entry.source.as_label(),
180            finding.entry.raw_key,
181        ));
182    }
183    for finding in &results.misconfigured_dependency_overrides {
184        lines.push(format!(
185            "misconfigured-dependency-override:{}:{}:{}:{}",
186            rel(&finding.entry.path),
187            finding.entry.line,
188            finding.entry.source.as_label(),
189            finding.entry.raw_key,
190        ));
191    }
192
193    lines
194}
195
196/// Print grouped compact output: each line is prefixed with the group key.
197///
198/// Format: `group-key\tissue-tag:details`
199pub(super) fn print_grouped_compact(groups: &[ResultGroup], root: &Path) {
200    for group in groups {
201        for line in build_compact_lines(&group.results, root) {
202            println!("{}\t{line}", group.key);
203        }
204    }
205}
206
207#[expect(
208    clippy::too_many_lines,
209    reason = "health compact formatter stitches many optional sections into one stream"
210)]
211pub(super) fn print_health_compact(report: &crate::health_types::HealthReport, root: &Path) {
212    if let Some(ref hs) = report.health_score {
213        println!("health-score:{:.1}:{}", hs.score, hs.grade);
214    }
215    if let Some(ref vs) = report.vital_signs {
216        let mut parts = Vec::new();
217        if vs.total_loc > 0 {
218            parts.push(format!("total_loc={}", vs.total_loc));
219        }
220        parts.push(format!("avg_cyclomatic={:.1}", vs.avg_cyclomatic));
221        parts.push(format!("p90_cyclomatic={}", vs.p90_cyclomatic));
222        if let Some(v) = vs.dead_file_pct {
223            parts.push(format!("dead_file_pct={v:.1}"));
224        }
225        if let Some(v) = vs.dead_export_pct {
226            parts.push(format!("dead_export_pct={v:.1}"));
227        }
228        if let Some(v) = vs.maintainability_avg {
229            parts.push(format!("maintainability_avg={v:.1}"));
230        }
231        if let Some(v) = vs.hotspot_count {
232            parts.push(format!("hotspot_count={v}"));
233        }
234        if let Some(v) = vs.circular_dep_count {
235            parts.push(format!("circular_dep_count={v}"));
236        }
237        if let Some(v) = vs.unused_dep_count {
238            parts.push(format!("unused_dep_count={v}"));
239        }
240        println!("vital-signs:{}", parts.join(","));
241    }
242    for finding in &report.findings {
243        let relative = normalize_uri(&relative_path(&finding.path, root).display().to_string());
244        let severity = match finding.severity {
245            crate::health_types::FindingSeverity::Critical => "critical",
246            crate::health_types::FindingSeverity::High => "high",
247            crate::health_types::FindingSeverity::Moderate => "moderate",
248        };
249        let crap_suffix = match finding.crap {
250            Some(crap) => {
251                let coverage = finding
252                    .coverage_pct
253                    .map(|pct| format!(",coverage_pct={pct:.1}"))
254                    .unwrap_or_default();
255                format!(",crap={crap:.1}{coverage}")
256            }
257            None => String::new(),
258        };
259        println!(
260            "high-complexity:{}:{}:{}:cyclomatic={},cognitive={},severity={}{}",
261            relative,
262            finding.line,
263            finding.name,
264            finding.cyclomatic,
265            finding.cognitive,
266            severity,
267            crap_suffix,
268        );
269    }
270    for score in &report.file_scores {
271        let relative = normalize_uri(&relative_path(&score.path, root).display().to_string());
272        println!(
273            "file-score:{}:mi={:.1},fan_in={},fan_out={},dead={:.2},density={:.2},crap_max={:.1},crap_above={}",
274            relative,
275            score.maintainability_index,
276            score.fan_in,
277            score.fan_out,
278            score.dead_code_ratio,
279            score.complexity_density,
280            score.crap_max,
281            score.crap_above_threshold,
282        );
283    }
284    if let Some(ref gaps) = report.coverage_gaps {
285        println!(
286            "coverage-gap-summary:runtime_files={},covered_files={},file_coverage_pct={:.1},untested_files={},untested_exports={}",
287            gaps.summary.runtime_files,
288            gaps.summary.covered_files,
289            gaps.summary.file_coverage_pct,
290            gaps.summary.untested_files,
291            gaps.summary.untested_exports,
292        );
293        for item in &gaps.files {
294            let relative =
295                normalize_uri(&relative_path(&item.file.path, root).display().to_string());
296            println!(
297                "untested-file:{}:value_exports={}",
298                relative, item.file.value_export_count,
299            );
300        }
301        for item in &gaps.exports {
302            let relative =
303                normalize_uri(&relative_path(&item.export.path, root).display().to_string());
304            println!(
305                "untested-export:{}:{}:{}",
306                relative, item.export.line, item.export.export_name,
307            );
308        }
309    }
310    if let Some(ref production) = report.runtime_coverage {
311        for line in build_runtime_coverage_compact_lines(production, root) {
312            println!("{line}");
313        }
314    }
315    for entry in &report.hotspots {
316        let relative = normalize_uri(&relative_path(&entry.path, root).display().to_string());
317        let ownership_suffix = entry
318            .ownership
319            .as_ref()
320            .map(|o| {
321                let mut parts = vec![
322                    format!("bus={}", o.bus_factor),
323                    format!("contributors={}", o.contributor_count),
324                    format!("top={}", o.top_contributor.identifier),
325                    format!("top_share={:.3}", o.top_contributor.share),
326                ];
327                if let Some(owner) = &o.declared_owner {
328                    parts.push(format!("owner={owner}"));
329                }
330                if let Some(unowned) = o.unowned {
331                    parts.push(format!("unowned={unowned}"));
332                }
333                if o.drift {
334                    parts.push("drift=true".to_string());
335                }
336                format!(",{}", parts.join(","))
337            })
338            .unwrap_or_default();
339        println!(
340            "hotspot:{}:score={:.1},commits={},churn={},density={:.2},fan_in={},trend={}{}",
341            relative,
342            entry.score,
343            entry.commits,
344            entry.lines_added + entry.lines_deleted,
345            entry.complexity_density,
346            entry.fan_in,
347            entry.trend,
348            ownership_suffix,
349        );
350    }
351    if let Some(ref trend) = report.health_trend {
352        println!(
353            "trend:overall:direction={}",
354            trend.overall_direction.label()
355        );
356        for m in &trend.metrics {
357            println!(
358                "trend:{}:previous={:.1},current={:.1},delta={:+.1},direction={}",
359                m.name,
360                m.previous,
361                m.current,
362                m.delta,
363                m.direction.label(),
364            );
365        }
366    }
367    for target in &report.targets {
368        let relative = normalize_uri(&relative_path(&target.path, root).display().to_string());
369        let category = target.category.compact_label();
370        let effort = target.effort.label();
371        let confidence = target.confidence.label();
372        println!(
373            "refactoring-target:{}:priority={:.1},efficiency={:.1},category={},effort={},confidence={}:{}",
374            relative,
375            target.priority,
376            target.efficiency,
377            category,
378            effort,
379            confidence,
380            target.recommendation,
381        );
382    }
383}
384
385fn build_runtime_coverage_compact_lines(
386    production: &crate::health_types::RuntimeCoverageReport,
387    root: &Path,
388) -> Vec<String> {
389    let mut lines = vec![format!(
390        "runtime-coverage-summary:functions_tracked={},functions_hit={},functions_unhit={},functions_untracked={},coverage_percent={:.1},trace_count={},period_days={},deployments_seen={}",
391        production.summary.functions_tracked,
392        production.summary.functions_hit,
393        production.summary.functions_unhit,
394        production.summary.functions_untracked,
395        production.summary.coverage_percent,
396        production.summary.trace_count,
397        production.summary.period_days,
398        production.summary.deployments_seen,
399    )];
400    for finding in &production.findings {
401        let relative = normalize_uri(&relative_path(&finding.path, root).display().to_string());
402        let invocations = finding
403            .invocations
404            .map_or_else(|| "null".to_owned(), |hits| hits.to_string());
405        lines.push(format!(
406            "runtime-coverage:{}:{}:{}:id={},verdict={},invocations={},confidence={}",
407            relative,
408            finding.line,
409            finding.function,
410            finding.id,
411            finding.verdict,
412            invocations,
413            finding.confidence,
414        ));
415    }
416    for entry in &production.hot_paths {
417        let relative = normalize_uri(&relative_path(&entry.path, root).display().to_string());
418        lines.push(format!(
419            "production-hot-path:{}:{}:{}:id={},invocations={},percentile={}",
420            relative, entry.line, entry.function, entry.id, entry.invocations, entry.percentile,
421        ));
422    }
423    lines
424}
425
426pub(super) fn print_duplication_compact(report: &DuplicationReport, root: &Path) {
427    for (i, group) in report.clone_groups.iter().enumerate() {
428        for instance in &group.instances {
429            let relative =
430                normalize_uri(&relative_path(&instance.file, root).display().to_string());
431            println!(
432                "clone-group-{}:{}:{}-{}:{}tokens",
433                i + 1,
434                relative,
435                instance.start_line,
436                instance.end_line,
437                group.token_count
438            );
439        }
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::health_types::{
447        RuntimeCoverageConfidence, RuntimeCoverageDataSource, RuntimeCoverageEvidence,
448        RuntimeCoverageFinding, RuntimeCoverageHotPath, RuntimeCoverageReport,
449        RuntimeCoverageReportVerdict, RuntimeCoverageSchemaVersion, RuntimeCoverageSummary,
450        RuntimeCoverageVerdict,
451    };
452    use crate::report::test_helpers::sample_results;
453    use fallow_core::extract::MemberKind;
454    use fallow_core::results::*;
455    use std::path::PathBuf;
456
457    #[test]
458    fn compact_empty_results_no_lines() {
459        let root = PathBuf::from("/project");
460        let results = AnalysisResults::default();
461        let lines = build_compact_lines(&results, &root);
462        assert!(lines.is_empty());
463    }
464
465    #[test]
466    fn compact_unused_file_format() {
467        let root = PathBuf::from("/project");
468        let mut results = AnalysisResults::default();
469        results
470            .unused_files
471            .push(UnusedFileFinding::with_actions(UnusedFile {
472                path: root.join("src/dead.ts"),
473            }));
474
475        let lines = build_compact_lines(&results, &root);
476        assert_eq!(lines.len(), 1);
477        assert_eq!(lines[0], "unused-file:src/dead.ts");
478    }
479
480    #[test]
481    fn compact_unused_export_format() {
482        let root = PathBuf::from("/project");
483        let mut results = AnalysisResults::default();
484        results
485            .unused_exports
486            .push(UnusedExportFinding::with_actions(UnusedExport {
487                path: root.join("src/utils.ts"),
488                export_name: "helperFn".to_string(),
489                is_type_only: false,
490                line: 10,
491                col: 4,
492                span_start: 120,
493                is_re_export: false,
494            }));
495
496        let lines = build_compact_lines(&results, &root);
497        assert_eq!(lines[0], "unused-export:src/utils.ts:10:helperFn");
498    }
499
500    #[test]
501    fn compact_health_includes_runtime_coverage_lines() {
502        let root = PathBuf::from("/project");
503        let report = crate::health_types::HealthReport {
504            runtime_coverage: Some(RuntimeCoverageReport {
505                schema_version: RuntimeCoverageSchemaVersion::V1,
506                verdict: RuntimeCoverageReportVerdict::ColdCodeDetected,
507                signals: Vec::new(),
508                summary: RuntimeCoverageSummary {
509                    data_source: RuntimeCoverageDataSource::Local,
510                    last_received_at: None,
511                    functions_tracked: 4,
512                    functions_hit: 2,
513                    functions_unhit: 1,
514                    functions_untracked: 1,
515                    coverage_percent: 50.0,
516                    trace_count: 512,
517                    period_days: 7,
518                    deployments_seen: 2,
519                    capture_quality: None,
520                },
521                findings: vec![RuntimeCoverageFinding {
522                    id: "fallow:prod:deadbeef".to_owned(),
523                    path: root.join("src/cold.ts"),
524                    function: "coldPath".to_owned(),
525                    line: 14,
526                    verdict: RuntimeCoverageVerdict::ReviewRequired,
527                    invocations: Some(0),
528                    confidence: RuntimeCoverageConfidence::Medium,
529                    evidence: RuntimeCoverageEvidence {
530                        static_status: "used".to_owned(),
531                        test_coverage: "not_covered".to_owned(),
532                        v8_tracking: "tracked".to_owned(),
533                        untracked_reason: None,
534                        observation_days: 7,
535                        deployments_observed: 2,
536                    },
537                    actions: vec![],
538                }],
539                hot_paths: vec![RuntimeCoverageHotPath {
540                    id: "fallow:hot:cafebabe".to_owned(),
541                    path: root.join("src/hot.ts"),
542                    function: "hotPath".to_owned(),
543                    line: 3,
544                    end_line: 9,
545                    invocations: 250,
546                    percentile: 99,
547                    actions: vec![],
548                }],
549                blast_radius: vec![],
550                importance: vec![],
551                watermark: None,
552                warnings: vec![],
553            }),
554            ..Default::default()
555        };
556
557        let lines = build_runtime_coverage_compact_lines(
558            report
559                .runtime_coverage
560                .as_ref()
561                .expect("runtime coverage should be set"),
562            &root,
563        );
564        assert_eq!(
565            lines[0],
566            "runtime-coverage-summary:functions_tracked=4,functions_hit=2,functions_unhit=1,functions_untracked=1,coverage_percent=50.0,trace_count=512,period_days=7,deployments_seen=2"
567        );
568        assert_eq!(
569            lines[1],
570            "runtime-coverage:src/cold.ts:14:coldPath:id=fallow:prod:deadbeef,verdict=review_required,invocations=0,confidence=medium"
571        );
572        assert_eq!(
573            lines[2],
574            "production-hot-path:src/hot.ts:3:hotPath:id=fallow:hot:cafebabe,invocations=250,percentile=99"
575        );
576    }
577
578    #[test]
579    fn compact_unused_type_format() {
580        let root = PathBuf::from("/project");
581        let mut results = AnalysisResults::default();
582        results
583            .unused_types
584            .push(UnusedTypeFinding::with_actions(UnusedExport {
585                path: root.join("src/types.ts"),
586                export_name: "OldType".to_string(),
587                is_type_only: true,
588                line: 5,
589                col: 0,
590                span_start: 60,
591                is_re_export: false,
592            }));
593
594        let lines = build_compact_lines(&results, &root);
595        assert_eq!(lines[0], "unused-type:src/types.ts:5:OldType");
596    }
597
598    #[test]
599    fn compact_unused_dep_format() {
600        let root = PathBuf::from("/project");
601        let mut results = AnalysisResults::default();
602        results
603            .unused_dependencies
604            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
605                package_name: "lodash".to_string(),
606                location: DependencyLocation::Dependencies,
607                path: root.join("package.json"),
608                line: 5,
609                used_in_workspaces: Vec::new(),
610            }));
611
612        let lines = build_compact_lines(&results, &root);
613        assert_eq!(lines[0], "unused-dep:lodash");
614    }
615
616    #[test]
617    fn compact_unused_devdep_format() {
618        let root = PathBuf::from("/project");
619        let mut results = AnalysisResults::default();
620        results
621            .unused_dev_dependencies
622            .push(UnusedDevDependencyFinding::with_actions(UnusedDependency {
623                package_name: "jest".to_string(),
624                location: DependencyLocation::DevDependencies,
625                path: root.join("package.json"),
626                line: 5,
627                used_in_workspaces: Vec::new(),
628            }));
629
630        let lines = build_compact_lines(&results, &root);
631        assert_eq!(lines[0], "unused-devdep:jest");
632    }
633
634    #[test]
635    fn compact_unused_enum_member_format() {
636        let root = PathBuf::from("/project");
637        let mut results = AnalysisResults::default();
638        results
639            .unused_enum_members
640            .push(UnusedEnumMemberFinding::with_actions(UnusedMember {
641                path: root.join("src/enums.ts"),
642                parent_name: "Status".to_string(),
643                member_name: "Deprecated".to_string(),
644                kind: MemberKind::EnumMember,
645                line: 8,
646                col: 2,
647            }));
648
649        let lines = build_compact_lines(&results, &root);
650        assert_eq!(
651            lines[0],
652            "unused-enum-member:src/enums.ts:8:Status.Deprecated"
653        );
654    }
655
656    #[test]
657    fn compact_unused_class_member_format() {
658        let root = PathBuf::from("/project");
659        let mut results = AnalysisResults::default();
660        results
661            .unused_class_members
662            .push(UnusedClassMemberFinding::with_actions(UnusedMember {
663                path: root.join("src/service.ts"),
664                parent_name: "UserService".to_string(),
665                member_name: "legacyMethod".to_string(),
666                kind: MemberKind::ClassMethod,
667                line: 42,
668                col: 4,
669            }));
670
671        let lines = build_compact_lines(&results, &root);
672        assert_eq!(
673            lines[0],
674            "unused-class-member:src/service.ts:42:UserService.legacyMethod"
675        );
676    }
677
678    #[test]
679    fn compact_unresolved_import_format() {
680        let root = PathBuf::from("/project");
681        let mut results = AnalysisResults::default();
682        results
683            .unresolved_imports
684            .push(UnresolvedImportFinding::with_actions(UnresolvedImport {
685                path: root.join("src/app.ts"),
686                specifier: "./missing-module".to_string(),
687                line: 3,
688                col: 0,
689                specifier_col: 0,
690            }));
691
692        let lines = build_compact_lines(&results, &root);
693        assert_eq!(lines[0], "unresolved-import:src/app.ts:3:./missing-module");
694    }
695
696    #[test]
697    fn compact_unlisted_dep_format() {
698        let root = PathBuf::from("/project");
699        let mut results = AnalysisResults::default();
700        results
701            .unlisted_dependencies
702            .push(UnlistedDependencyFinding::with_actions(
703                UnlistedDependency {
704                    package_name: "chalk".to_string(),
705                    imported_from: vec![],
706                },
707            ));
708
709        let lines = build_compact_lines(&results, &root);
710        assert_eq!(lines[0], "unlisted-dep:chalk");
711    }
712
713    #[test]
714    fn compact_duplicate_export_format() {
715        let root = PathBuf::from("/project");
716        let mut results = AnalysisResults::default();
717        results
718            .duplicate_exports
719            .push(DuplicateExportFinding::with_actions(DuplicateExport {
720                export_name: "Config".to_string(),
721                locations: vec![
722                    DuplicateLocation {
723                        path: root.join("src/a.ts"),
724                        line: 15,
725                        col: 0,
726                    },
727                    DuplicateLocation {
728                        path: root.join("src/b.ts"),
729                        line: 30,
730                        col: 0,
731                    },
732                ],
733            }));
734
735        let lines = build_compact_lines(&results, &root);
736        assert_eq!(lines[0], "duplicate-export:Config");
737    }
738
739    #[test]
740    fn compact_all_issue_types_produce_lines() {
741        let root = PathBuf::from("/project");
742        let results = sample_results(&root);
743        let lines = build_compact_lines(&results, &root);
744
745        // 16 issue types, one of each
746        assert_eq!(lines.len(), 16);
747
748        // Verify ordering matches output order
749        assert!(lines[0].starts_with("unused-file:"));
750        assert!(lines[1].starts_with("unused-export:"));
751        assert!(lines[2].starts_with("unused-type:"));
752        assert!(lines[3].starts_with("unused-dep:"));
753        assert!(lines[4].starts_with("unused-devdep:"));
754        assert!(lines[5].starts_with("unused-optionaldep:"));
755        assert!(lines[6].starts_with("unused-enum-member:"));
756        assert!(lines[7].starts_with("unused-class-member:"));
757        assert!(lines[8].starts_with("unresolved-import:"));
758        assert!(lines[9].starts_with("unlisted-dep:"));
759        assert!(lines[10].starts_with("duplicate-export:"));
760        assert!(lines[11].starts_with("type-only-dep:"));
761        assert!(lines[12].starts_with("test-only-dep:"));
762        assert!(lines[13].starts_with("circular-dependency:"));
763        assert!(lines[14].starts_with("boundary-violation:"));
764    }
765
766    #[test]
767    fn compact_strips_root_prefix_from_paths() {
768        let root = PathBuf::from("/project");
769        let mut results = AnalysisResults::default();
770        results
771            .unused_files
772            .push(UnusedFileFinding::with_actions(UnusedFile {
773                path: PathBuf::from("/project/src/deep/nested/file.ts"),
774            }));
775
776        let lines = build_compact_lines(&results, &root);
777        assert_eq!(lines[0], "unused-file:src/deep/nested/file.ts");
778    }
779
780    // ── Re-export variants ──
781
782    #[test]
783    fn compact_re_export_tagged_correctly() {
784        let root = PathBuf::from("/project");
785        let mut results = AnalysisResults::default();
786        results
787            .unused_exports
788            .push(UnusedExportFinding::with_actions(UnusedExport {
789                path: root.join("src/index.ts"),
790                export_name: "reExported".to_string(),
791                is_type_only: false,
792                line: 1,
793                col: 0,
794                span_start: 0,
795                is_re_export: true,
796            }));
797
798        let lines = build_compact_lines(&results, &root);
799        assert_eq!(lines[0], "unused-re-export:src/index.ts:1:reExported");
800    }
801
802    #[test]
803    fn compact_type_re_export_tagged_correctly() {
804        let root = PathBuf::from("/project");
805        let mut results = AnalysisResults::default();
806        results
807            .unused_types
808            .push(UnusedTypeFinding::with_actions(UnusedExport {
809                path: root.join("src/index.ts"),
810                export_name: "ReExportedType".to_string(),
811                is_type_only: true,
812                line: 3,
813                col: 0,
814                span_start: 0,
815                is_re_export: true,
816            }));
817
818        let lines = build_compact_lines(&results, &root);
819        assert_eq!(
820            lines[0],
821            "unused-re-export-type:src/index.ts:3:ReExportedType"
822        );
823    }
824
825    // ── Unused optional dependency ──
826
827    #[test]
828    fn compact_unused_optional_dep_format() {
829        let root = PathBuf::from("/project");
830        let mut results = AnalysisResults::default();
831        results
832            .unused_optional_dependencies
833            .push(UnusedOptionalDependencyFinding::with_actions(
834                UnusedDependency {
835                    package_name: "fsevents".to_string(),
836                    location: DependencyLocation::OptionalDependencies,
837                    path: root.join("package.json"),
838                    line: 12,
839                    used_in_workspaces: Vec::new(),
840                },
841            ));
842
843        let lines = build_compact_lines(&results, &root);
844        assert_eq!(lines[0], "unused-optionaldep:fsevents");
845    }
846
847    // ── Circular dependency ──
848
849    #[test]
850    fn compact_circular_dependency_format() {
851        let root = PathBuf::from("/project");
852        let mut results = AnalysisResults::default();
853        results
854            .circular_dependencies
855            .push(CircularDependencyFinding::with_actions(
856                CircularDependency {
857                    files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
858                    length: 2,
859                    line: 3,
860                    col: 0,
861                    is_cross_package: false,
862                },
863            ));
864
865        let lines = build_compact_lines(&results, &root);
866        assert_eq!(lines.len(), 1);
867        assert!(lines[0].starts_with("circular-dependency:src/a.ts:3:"));
868        assert!(lines[0].contains("src/a.ts"));
869        assert!(lines[0].contains("src/b.ts"));
870        // Chain should close the cycle: a -> b -> a
871        assert!(lines[0].contains("\u{2192}"));
872    }
873
874    #[test]
875    fn compact_circular_dependency_closes_cycle() {
876        let root = PathBuf::from("/project");
877        let mut results = AnalysisResults::default();
878        results
879            .circular_dependencies
880            .push(CircularDependencyFinding::with_actions(
881                CircularDependency {
882                    files: vec![
883                        root.join("src/a.ts"),
884                        root.join("src/b.ts"),
885                        root.join("src/c.ts"),
886                    ],
887                    length: 3,
888                    line: 1,
889                    col: 0,
890                    is_cross_package: false,
891                },
892            ));
893
894        let lines = build_compact_lines(&results, &root);
895        // Chain: a -> b -> c -> a
896        let chain_part = lines[0].split(':').next_back().unwrap();
897        let parts: Vec<&str> = chain_part.split(" \u{2192} ").collect();
898        assert_eq!(parts.len(), 4);
899        assert_eq!(parts[0], parts[3]); // first == last (cycle closes)
900    }
901
902    // ── Type-only dependency ──
903
904    #[test]
905    fn compact_type_only_dep_format() {
906        let root = PathBuf::from("/project");
907        let mut results = AnalysisResults::default();
908        results
909            .type_only_dependencies
910            .push(TypeOnlyDependencyFinding::with_actions(
911                TypeOnlyDependency {
912                    package_name: "zod".to_string(),
913                    path: root.join("package.json"),
914                    line: 8,
915                },
916            ));
917
918        let lines = build_compact_lines(&results, &root);
919        assert_eq!(lines[0], "type-only-dep:zod");
920    }
921
922    // ── Multiple items of same type ──
923
924    #[test]
925    fn compact_multiple_unused_files() {
926        let root = PathBuf::from("/project");
927        let mut results = AnalysisResults::default();
928        results
929            .unused_files
930            .push(UnusedFileFinding::with_actions(UnusedFile {
931                path: root.join("src/a.ts"),
932            }));
933        results
934            .unused_files
935            .push(UnusedFileFinding::with_actions(UnusedFile {
936                path: root.join("src/b.ts"),
937            }));
938
939        let lines = build_compact_lines(&results, &root);
940        assert_eq!(lines.len(), 2);
941        assert_eq!(lines[0], "unused-file:src/a.ts");
942        assert_eq!(lines[1], "unused-file:src/b.ts");
943    }
944
945    // ── Output ordering matches issue types ──
946
947    #[test]
948    fn compact_ordering_optional_dep_between_devdep_and_enum() {
949        let root = PathBuf::from("/project");
950        let mut results = AnalysisResults::default();
951        results
952            .unused_dev_dependencies
953            .push(UnusedDevDependencyFinding::with_actions(UnusedDependency {
954                package_name: "jest".to_string(),
955                location: DependencyLocation::DevDependencies,
956                path: root.join("package.json"),
957                line: 5,
958                used_in_workspaces: Vec::new(),
959            }));
960        results
961            .unused_optional_dependencies
962            .push(UnusedOptionalDependencyFinding::with_actions(
963                UnusedDependency {
964                    package_name: "fsevents".to_string(),
965                    location: DependencyLocation::OptionalDependencies,
966                    path: root.join("package.json"),
967                    line: 12,
968                    used_in_workspaces: Vec::new(),
969                },
970            ));
971        results
972            .unused_enum_members
973            .push(UnusedEnumMemberFinding::with_actions(UnusedMember {
974                path: root.join("src/enums.ts"),
975                parent_name: "Status".to_string(),
976                member_name: "Deprecated".to_string(),
977                kind: MemberKind::EnumMember,
978                line: 8,
979                col: 2,
980            }));
981
982        let lines = build_compact_lines(&results, &root);
983        assert_eq!(lines.len(), 3);
984        assert!(lines[0].starts_with("unused-devdep:"));
985        assert!(lines[1].starts_with("unused-optionaldep:"));
986        assert!(lines[2].starts_with("unused-enum-member:"));
987    }
988
989    // ── Path outside root ──
990
991    #[test]
992    fn compact_path_outside_root_preserved() {
993        let root = PathBuf::from("/project");
994        let mut results = AnalysisResults::default();
995        results
996            .unused_files
997            .push(UnusedFileFinding::with_actions(UnusedFile {
998                path: PathBuf::from("/other/place/file.ts"),
999            }));
1000
1001        let lines = build_compact_lines(&results, &root);
1002        assert!(lines[0].contains("/other/place/file.ts"));
1003    }
1004}