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