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