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