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