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