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, RuntimeCoverageDataSource, RuntimeCoverageEvidence,
394        RuntimeCoverageFinding, RuntimeCoverageHotPath, RuntimeCoverageReport,
395        RuntimeCoverageReportVerdict, 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                    data_source: RuntimeCoverageDataSource::Local,
449                    last_received_at: None,
450                    functions_tracked: 4,
451                    functions_hit: 2,
452                    functions_unhit: 1,
453                    functions_untracked: 1,
454                    coverage_percent: 50.0,
455                    trace_count: 512,
456                    period_days: 7,
457                    deployments_seen: 2,
458                    capture_quality: None,
459                },
460                findings: vec![RuntimeCoverageFinding {
461                    id: "fallow:prod:deadbeef".to_owned(),
462                    path: root.join("src/cold.ts"),
463                    function: "coldPath".to_owned(),
464                    line: 14,
465                    verdict: RuntimeCoverageVerdict::ReviewRequired,
466                    invocations: Some(0),
467                    confidence: RuntimeCoverageConfidence::Medium,
468                    evidence: RuntimeCoverageEvidence {
469                        static_status: "used".to_owned(),
470                        test_coverage: "not_covered".to_owned(),
471                        v8_tracking: "tracked".to_owned(),
472                        untracked_reason: None,
473                        observation_days: 7,
474                        deployments_observed: 2,
475                    },
476                    actions: vec![],
477                }],
478                hot_paths: vec![RuntimeCoverageHotPath {
479                    id: "fallow:hot:cafebabe".to_owned(),
480                    path: root.join("src/hot.ts"),
481                    function: "hotPath".to_owned(),
482                    line: 3,
483                    invocations: 250,
484                    percentile: 99,
485                    actions: vec![],
486                }],
487                watermark: None,
488                warnings: vec![],
489            }),
490            ..Default::default()
491        };
492
493        let lines = build_runtime_coverage_compact_lines(
494            report
495                .runtime_coverage
496                .as_ref()
497                .expect("runtime coverage should be set"),
498            &root,
499        );
500        assert_eq!(
501            lines[0],
502            "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"
503        );
504        assert_eq!(
505            lines[1],
506            "runtime-coverage:src/cold.ts:14:coldPath:id=fallow:prod:deadbeef,verdict=review_required,invocations=0,confidence=medium"
507        );
508        assert_eq!(
509            lines[2],
510            "production-hot-path:src/hot.ts:3:hotPath:id=fallow:hot:cafebabe,invocations=250,percentile=99"
511        );
512    }
513
514    #[test]
515    fn compact_unused_type_format() {
516        let root = PathBuf::from("/project");
517        let mut results = AnalysisResults::default();
518        results.unused_types.push(UnusedExport {
519            path: root.join("src/types.ts"),
520            export_name: "OldType".to_string(),
521            is_type_only: true,
522            line: 5,
523            col: 0,
524            span_start: 60,
525            is_re_export: false,
526        });
527
528        let lines = build_compact_lines(&results, &root);
529        assert_eq!(lines[0], "unused-type:src/types.ts:5:OldType");
530    }
531
532    #[test]
533    fn compact_unused_dep_format() {
534        let root = PathBuf::from("/project");
535        let mut results = AnalysisResults::default();
536        results.unused_dependencies.push(UnusedDependency {
537            package_name: "lodash".to_string(),
538            location: DependencyLocation::Dependencies,
539            path: root.join("package.json"),
540            line: 5,
541            used_in_workspaces: Vec::new(),
542        });
543
544        let lines = build_compact_lines(&results, &root);
545        assert_eq!(lines[0], "unused-dep:lodash");
546    }
547
548    #[test]
549    fn compact_unused_devdep_format() {
550        let root = PathBuf::from("/project");
551        let mut results = AnalysisResults::default();
552        results.unused_dev_dependencies.push(UnusedDependency {
553            package_name: "jest".to_string(),
554            location: DependencyLocation::DevDependencies,
555            path: root.join("package.json"),
556            line: 5,
557            used_in_workspaces: Vec::new(),
558        });
559
560        let lines = build_compact_lines(&results, &root);
561        assert_eq!(lines[0], "unused-devdep:jest");
562    }
563
564    #[test]
565    fn compact_unused_enum_member_format() {
566        let root = PathBuf::from("/project");
567        let mut results = AnalysisResults::default();
568        results.unused_enum_members.push(UnusedMember {
569            path: root.join("src/enums.ts"),
570            parent_name: "Status".to_string(),
571            member_name: "Deprecated".to_string(),
572            kind: MemberKind::EnumMember,
573            line: 8,
574            col: 2,
575        });
576
577        let lines = build_compact_lines(&results, &root);
578        assert_eq!(
579            lines[0],
580            "unused-enum-member:src/enums.ts:8:Status.Deprecated"
581        );
582    }
583
584    #[test]
585    fn compact_unused_class_member_format() {
586        let root = PathBuf::from("/project");
587        let mut results = AnalysisResults::default();
588        results.unused_class_members.push(UnusedMember {
589            path: root.join("src/service.ts"),
590            parent_name: "UserService".to_string(),
591            member_name: "legacyMethod".to_string(),
592            kind: MemberKind::ClassMethod,
593            line: 42,
594            col: 4,
595        });
596
597        let lines = build_compact_lines(&results, &root);
598        assert_eq!(
599            lines[0],
600            "unused-class-member:src/service.ts:42:UserService.legacyMethod"
601        );
602    }
603
604    #[test]
605    fn compact_unresolved_import_format() {
606        let root = PathBuf::from("/project");
607        let mut results = AnalysisResults::default();
608        results.unresolved_imports.push(UnresolvedImport {
609            path: root.join("src/app.ts"),
610            specifier: "./missing-module".to_string(),
611            line: 3,
612            col: 0,
613            specifier_col: 0,
614        });
615
616        let lines = build_compact_lines(&results, &root);
617        assert_eq!(lines[0], "unresolved-import:src/app.ts:3:./missing-module");
618    }
619
620    #[test]
621    fn compact_unlisted_dep_format() {
622        let root = PathBuf::from("/project");
623        let mut results = AnalysisResults::default();
624        results.unlisted_dependencies.push(UnlistedDependency {
625            package_name: "chalk".to_string(),
626            imported_from: vec![],
627        });
628
629        let lines = build_compact_lines(&results, &root);
630        assert_eq!(lines[0], "unlisted-dep:chalk");
631    }
632
633    #[test]
634    fn compact_duplicate_export_format() {
635        let root = PathBuf::from("/project");
636        let mut results = AnalysisResults::default();
637        results.duplicate_exports.push(DuplicateExport {
638            export_name: "Config".to_string(),
639            locations: vec![
640                DuplicateLocation {
641                    path: root.join("src/a.ts"),
642                    line: 15,
643                    col: 0,
644                },
645                DuplicateLocation {
646                    path: root.join("src/b.ts"),
647                    line: 30,
648                    col: 0,
649                },
650            ],
651        });
652
653        let lines = build_compact_lines(&results, &root);
654        assert_eq!(lines[0], "duplicate-export:Config");
655    }
656
657    #[test]
658    fn compact_all_issue_types_produce_lines() {
659        let root = PathBuf::from("/project");
660        let results = sample_results(&root);
661        let lines = build_compact_lines(&results, &root);
662
663        // 16 issue types, one of each
664        assert_eq!(lines.len(), 16);
665
666        // Verify ordering matches output order
667        assert!(lines[0].starts_with("unused-file:"));
668        assert!(lines[1].starts_with("unused-export:"));
669        assert!(lines[2].starts_with("unused-type:"));
670        assert!(lines[3].starts_with("unused-dep:"));
671        assert!(lines[4].starts_with("unused-devdep:"));
672        assert!(lines[5].starts_with("unused-optionaldep:"));
673        assert!(lines[6].starts_with("unused-enum-member:"));
674        assert!(lines[7].starts_with("unused-class-member:"));
675        assert!(lines[8].starts_with("unresolved-import:"));
676        assert!(lines[9].starts_with("unlisted-dep:"));
677        assert!(lines[10].starts_with("duplicate-export:"));
678        assert!(lines[11].starts_with("type-only-dep:"));
679        assert!(lines[12].starts_with("test-only-dep:"));
680        assert!(lines[13].starts_with("circular-dependency:"));
681        assert!(lines[14].starts_with("boundary-violation:"));
682    }
683
684    #[test]
685    fn compact_strips_root_prefix_from_paths() {
686        let root = PathBuf::from("/project");
687        let mut results = AnalysisResults::default();
688        results.unused_files.push(UnusedFile {
689            path: PathBuf::from("/project/src/deep/nested/file.ts"),
690        });
691
692        let lines = build_compact_lines(&results, &root);
693        assert_eq!(lines[0], "unused-file:src/deep/nested/file.ts");
694    }
695
696    // ── Re-export variants ──
697
698    #[test]
699    fn compact_re_export_tagged_correctly() {
700        let root = PathBuf::from("/project");
701        let mut results = AnalysisResults::default();
702        results.unused_exports.push(UnusedExport {
703            path: root.join("src/index.ts"),
704            export_name: "reExported".to_string(),
705            is_type_only: false,
706            line: 1,
707            col: 0,
708            span_start: 0,
709            is_re_export: true,
710        });
711
712        let lines = build_compact_lines(&results, &root);
713        assert_eq!(lines[0], "unused-re-export:src/index.ts:1:reExported");
714    }
715
716    #[test]
717    fn compact_type_re_export_tagged_correctly() {
718        let root = PathBuf::from("/project");
719        let mut results = AnalysisResults::default();
720        results.unused_types.push(UnusedExport {
721            path: root.join("src/index.ts"),
722            export_name: "ReExportedType".to_string(),
723            is_type_only: true,
724            line: 3,
725            col: 0,
726            span_start: 0,
727            is_re_export: true,
728        });
729
730        let lines = build_compact_lines(&results, &root);
731        assert_eq!(
732            lines[0],
733            "unused-re-export-type:src/index.ts:3:ReExportedType"
734        );
735    }
736
737    // ── Unused optional dependency ──
738
739    #[test]
740    fn compact_unused_optional_dep_format() {
741        let root = PathBuf::from("/project");
742        let mut results = AnalysisResults::default();
743        results.unused_optional_dependencies.push(UnusedDependency {
744            package_name: "fsevents".to_string(),
745            location: DependencyLocation::OptionalDependencies,
746            path: root.join("package.json"),
747            line: 12,
748            used_in_workspaces: Vec::new(),
749        });
750
751        let lines = build_compact_lines(&results, &root);
752        assert_eq!(lines[0], "unused-optionaldep:fsevents");
753    }
754
755    // ── Circular dependency ──
756
757    #[test]
758    fn compact_circular_dependency_format() {
759        let root = PathBuf::from("/project");
760        let mut results = AnalysisResults::default();
761        results.circular_dependencies.push(CircularDependency {
762            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
763            length: 2,
764            line: 3,
765            col: 0,
766            is_cross_package: false,
767        });
768
769        let lines = build_compact_lines(&results, &root);
770        assert_eq!(lines.len(), 1);
771        assert!(lines[0].starts_with("circular-dependency:src/a.ts:3:"));
772        assert!(lines[0].contains("src/a.ts"));
773        assert!(lines[0].contains("src/b.ts"));
774        // Chain should close the cycle: a -> b -> a
775        assert!(lines[0].contains("\u{2192}"));
776    }
777
778    #[test]
779    fn compact_circular_dependency_closes_cycle() {
780        let root = PathBuf::from("/project");
781        let mut results = AnalysisResults::default();
782        results.circular_dependencies.push(CircularDependency {
783            files: vec![
784                root.join("src/a.ts"),
785                root.join("src/b.ts"),
786                root.join("src/c.ts"),
787            ],
788            length: 3,
789            line: 1,
790            col: 0,
791            is_cross_package: false,
792        });
793
794        let lines = build_compact_lines(&results, &root);
795        // Chain: a -> b -> c -> a
796        let chain_part = lines[0].split(':').next_back().unwrap();
797        let parts: Vec<&str> = chain_part.split(" \u{2192} ").collect();
798        assert_eq!(parts.len(), 4);
799        assert_eq!(parts[0], parts[3]); // first == last (cycle closes)
800    }
801
802    // ── Type-only dependency ──
803
804    #[test]
805    fn compact_type_only_dep_format() {
806        let root = PathBuf::from("/project");
807        let mut results = AnalysisResults::default();
808        results.type_only_dependencies.push(TypeOnlyDependency {
809            package_name: "zod".to_string(),
810            path: root.join("package.json"),
811            line: 8,
812        });
813
814        let lines = build_compact_lines(&results, &root);
815        assert_eq!(lines[0], "type-only-dep:zod");
816    }
817
818    // ── Multiple items of same type ──
819
820    #[test]
821    fn compact_multiple_unused_files() {
822        let root = PathBuf::from("/project");
823        let mut results = AnalysisResults::default();
824        results.unused_files.push(UnusedFile {
825            path: root.join("src/a.ts"),
826        });
827        results.unused_files.push(UnusedFile {
828            path: root.join("src/b.ts"),
829        });
830
831        let lines = build_compact_lines(&results, &root);
832        assert_eq!(lines.len(), 2);
833        assert_eq!(lines[0], "unused-file:src/a.ts");
834        assert_eq!(lines[1], "unused-file:src/b.ts");
835    }
836
837    // ── Output ordering matches issue types ──
838
839    #[test]
840    fn compact_ordering_optional_dep_between_devdep_and_enum() {
841        let root = PathBuf::from("/project");
842        let mut results = AnalysisResults::default();
843        results.unused_dev_dependencies.push(UnusedDependency {
844            package_name: "jest".to_string(),
845            location: DependencyLocation::DevDependencies,
846            path: root.join("package.json"),
847            line: 5,
848            used_in_workspaces: Vec::new(),
849        });
850        results.unused_optional_dependencies.push(UnusedDependency {
851            package_name: "fsevents".to_string(),
852            location: DependencyLocation::OptionalDependencies,
853            path: root.join("package.json"),
854            line: 12,
855            used_in_workspaces: Vec::new(),
856        });
857        results.unused_enum_members.push(UnusedMember {
858            path: root.join("src/enums.ts"),
859            parent_name: "Status".to_string(),
860            member_name: "Deprecated".to_string(),
861            kind: MemberKind::EnumMember,
862            line: 8,
863            col: 2,
864        });
865
866        let lines = build_compact_lines(&results, &root);
867        assert_eq!(lines.len(), 3);
868        assert!(lines[0].starts_with("unused-devdep:"));
869        assert!(lines[1].starts_with("unused-optionaldep:"));
870        assert!(lines[2].starts_with("unused-enum-member:"));
871    }
872
873    // ── Path outside root ──
874
875    #[test]
876    fn compact_path_outside_root_preserved() {
877        let root = PathBuf::from("/project");
878        let mut results = AnalysisResults::default();
879        results.unused_files.push(UnusedFile {
880            path: PathBuf::from("/other/place/file.ts"),
881        });
882
883        let lines = build_compact_lines(&results, &root);
884        assert!(lines[0].contains("/other/place/file.ts"));
885    }
886}