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            used_in_workspaces: Vec::new(),
531        });
532
533        let lines = build_compact_lines(&results, &root);
534        assert_eq!(lines[0], "unused-dep:lodash");
535    }
536
537    #[test]
538    fn compact_unused_devdep_format() {
539        let root = PathBuf::from("/project");
540        let mut results = AnalysisResults::default();
541        results.unused_dev_dependencies.push(UnusedDependency {
542            package_name: "jest".to_string(),
543            location: DependencyLocation::DevDependencies,
544            path: root.join("package.json"),
545            line: 5,
546            used_in_workspaces: Vec::new(),
547        });
548
549        let lines = build_compact_lines(&results, &root);
550        assert_eq!(lines[0], "unused-devdep:jest");
551    }
552
553    #[test]
554    fn compact_unused_enum_member_format() {
555        let root = PathBuf::from("/project");
556        let mut results = AnalysisResults::default();
557        results.unused_enum_members.push(UnusedMember {
558            path: root.join("src/enums.ts"),
559            parent_name: "Status".to_string(),
560            member_name: "Deprecated".to_string(),
561            kind: MemberKind::EnumMember,
562            line: 8,
563            col: 2,
564        });
565
566        let lines = build_compact_lines(&results, &root);
567        assert_eq!(
568            lines[0],
569            "unused-enum-member:src/enums.ts:8:Status.Deprecated"
570        );
571    }
572
573    #[test]
574    fn compact_unused_class_member_format() {
575        let root = PathBuf::from("/project");
576        let mut results = AnalysisResults::default();
577        results.unused_class_members.push(UnusedMember {
578            path: root.join("src/service.ts"),
579            parent_name: "UserService".to_string(),
580            member_name: "legacyMethod".to_string(),
581            kind: MemberKind::ClassMethod,
582            line: 42,
583            col: 4,
584        });
585
586        let lines = build_compact_lines(&results, &root);
587        assert_eq!(
588            lines[0],
589            "unused-class-member:src/service.ts:42:UserService.legacyMethod"
590        );
591    }
592
593    #[test]
594    fn compact_unresolved_import_format() {
595        let root = PathBuf::from("/project");
596        let mut results = AnalysisResults::default();
597        results.unresolved_imports.push(UnresolvedImport {
598            path: root.join("src/app.ts"),
599            specifier: "./missing-module".to_string(),
600            line: 3,
601            col: 0,
602            specifier_col: 0,
603        });
604
605        let lines = build_compact_lines(&results, &root);
606        assert_eq!(lines[0], "unresolved-import:src/app.ts:3:./missing-module");
607    }
608
609    #[test]
610    fn compact_unlisted_dep_format() {
611        let root = PathBuf::from("/project");
612        let mut results = AnalysisResults::default();
613        results.unlisted_dependencies.push(UnlistedDependency {
614            package_name: "chalk".to_string(),
615            imported_from: vec![],
616        });
617
618        let lines = build_compact_lines(&results, &root);
619        assert_eq!(lines[0], "unlisted-dep:chalk");
620    }
621
622    #[test]
623    fn compact_duplicate_export_format() {
624        let root = PathBuf::from("/project");
625        let mut results = AnalysisResults::default();
626        results.duplicate_exports.push(DuplicateExport {
627            export_name: "Config".to_string(),
628            locations: vec![
629                DuplicateLocation {
630                    path: root.join("src/a.ts"),
631                    line: 15,
632                    col: 0,
633                },
634                DuplicateLocation {
635                    path: root.join("src/b.ts"),
636                    line: 30,
637                    col: 0,
638                },
639            ],
640        });
641
642        let lines = build_compact_lines(&results, &root);
643        assert_eq!(lines[0], "duplicate-export:Config");
644    }
645
646    #[test]
647    fn compact_all_issue_types_produce_lines() {
648        let root = PathBuf::from("/project");
649        let results = sample_results(&root);
650        let lines = build_compact_lines(&results, &root);
651
652        // 16 issue types, one of each
653        assert_eq!(lines.len(), 16);
654
655        // Verify ordering matches output order
656        assert!(lines[0].starts_with("unused-file:"));
657        assert!(lines[1].starts_with("unused-export:"));
658        assert!(lines[2].starts_with("unused-type:"));
659        assert!(lines[3].starts_with("unused-dep:"));
660        assert!(lines[4].starts_with("unused-devdep:"));
661        assert!(lines[5].starts_with("unused-optionaldep:"));
662        assert!(lines[6].starts_with("unused-enum-member:"));
663        assert!(lines[7].starts_with("unused-class-member:"));
664        assert!(lines[8].starts_with("unresolved-import:"));
665        assert!(lines[9].starts_with("unlisted-dep:"));
666        assert!(lines[10].starts_with("duplicate-export:"));
667        assert!(lines[11].starts_with("type-only-dep:"));
668        assert!(lines[12].starts_with("test-only-dep:"));
669        assert!(lines[13].starts_with("circular-dependency:"));
670        assert!(lines[14].starts_with("boundary-violation:"));
671    }
672
673    #[test]
674    fn compact_strips_root_prefix_from_paths() {
675        let root = PathBuf::from("/project");
676        let mut results = AnalysisResults::default();
677        results.unused_files.push(UnusedFile {
678            path: PathBuf::from("/project/src/deep/nested/file.ts"),
679        });
680
681        let lines = build_compact_lines(&results, &root);
682        assert_eq!(lines[0], "unused-file:src/deep/nested/file.ts");
683    }
684
685    // ── Re-export variants ──
686
687    #[test]
688    fn compact_re_export_tagged_correctly() {
689        let root = PathBuf::from("/project");
690        let mut results = AnalysisResults::default();
691        results.unused_exports.push(UnusedExport {
692            path: root.join("src/index.ts"),
693            export_name: "reExported".to_string(),
694            is_type_only: false,
695            line: 1,
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!(lines[0], "unused-re-export:src/index.ts:1:reExported");
703    }
704
705    #[test]
706    fn compact_type_re_export_tagged_correctly() {
707        let root = PathBuf::from("/project");
708        let mut results = AnalysisResults::default();
709        results.unused_types.push(UnusedExport {
710            path: root.join("src/index.ts"),
711            export_name: "ReExportedType".to_string(),
712            is_type_only: true,
713            line: 3,
714            col: 0,
715            span_start: 0,
716            is_re_export: true,
717        });
718
719        let lines = build_compact_lines(&results, &root);
720        assert_eq!(
721            lines[0],
722            "unused-re-export-type:src/index.ts:3:ReExportedType"
723        );
724    }
725
726    // ── Unused optional dependency ──
727
728    #[test]
729    fn compact_unused_optional_dep_format() {
730        let root = PathBuf::from("/project");
731        let mut results = AnalysisResults::default();
732        results.unused_optional_dependencies.push(UnusedDependency {
733            package_name: "fsevents".to_string(),
734            location: DependencyLocation::OptionalDependencies,
735            path: root.join("package.json"),
736            line: 12,
737            used_in_workspaces: Vec::new(),
738        });
739
740        let lines = build_compact_lines(&results, &root);
741        assert_eq!(lines[0], "unused-optionaldep:fsevents");
742    }
743
744    // ── Circular dependency ──
745
746    #[test]
747    fn compact_circular_dependency_format() {
748        let root = PathBuf::from("/project");
749        let mut results = AnalysisResults::default();
750        results.circular_dependencies.push(CircularDependency {
751            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
752            length: 2,
753            line: 3,
754            col: 0,
755            is_cross_package: false,
756        });
757
758        let lines = build_compact_lines(&results, &root);
759        assert_eq!(lines.len(), 1);
760        assert!(lines[0].starts_with("circular-dependency:src/a.ts:3:"));
761        assert!(lines[0].contains("src/a.ts"));
762        assert!(lines[0].contains("src/b.ts"));
763        // Chain should close the cycle: a -> b -> a
764        assert!(lines[0].contains("\u{2192}"));
765    }
766
767    #[test]
768    fn compact_circular_dependency_closes_cycle() {
769        let root = PathBuf::from("/project");
770        let mut results = AnalysisResults::default();
771        results.circular_dependencies.push(CircularDependency {
772            files: vec![
773                root.join("src/a.ts"),
774                root.join("src/b.ts"),
775                root.join("src/c.ts"),
776            ],
777            length: 3,
778            line: 1,
779            col: 0,
780            is_cross_package: false,
781        });
782
783        let lines = build_compact_lines(&results, &root);
784        // Chain: a -> b -> c -> a
785        let chain_part = lines[0].split(':').next_back().unwrap();
786        let parts: Vec<&str> = chain_part.split(" \u{2192} ").collect();
787        assert_eq!(parts.len(), 4);
788        assert_eq!(parts[0], parts[3]); // first == last (cycle closes)
789    }
790
791    // ── Type-only dependency ──
792
793    #[test]
794    fn compact_type_only_dep_format() {
795        let root = PathBuf::from("/project");
796        let mut results = AnalysisResults::default();
797        results.type_only_dependencies.push(TypeOnlyDependency {
798            package_name: "zod".to_string(),
799            path: root.join("package.json"),
800            line: 8,
801        });
802
803        let lines = build_compact_lines(&results, &root);
804        assert_eq!(lines[0], "type-only-dep:zod");
805    }
806
807    // ── Multiple items of same type ──
808
809    #[test]
810    fn compact_multiple_unused_files() {
811        let root = PathBuf::from("/project");
812        let mut results = AnalysisResults::default();
813        results.unused_files.push(UnusedFile {
814            path: root.join("src/a.ts"),
815        });
816        results.unused_files.push(UnusedFile {
817            path: root.join("src/b.ts"),
818        });
819
820        let lines = build_compact_lines(&results, &root);
821        assert_eq!(lines.len(), 2);
822        assert_eq!(lines[0], "unused-file:src/a.ts");
823        assert_eq!(lines[1], "unused-file:src/b.ts");
824    }
825
826    // ── Output ordering matches issue types ──
827
828    #[test]
829    fn compact_ordering_optional_dep_between_devdep_and_enum() {
830        let root = PathBuf::from("/project");
831        let mut results = AnalysisResults::default();
832        results.unused_dev_dependencies.push(UnusedDependency {
833            package_name: "jest".to_string(),
834            location: DependencyLocation::DevDependencies,
835            path: root.join("package.json"),
836            line: 5,
837            used_in_workspaces: Vec::new(),
838        });
839        results.unused_optional_dependencies.push(UnusedDependency {
840            package_name: "fsevents".to_string(),
841            location: DependencyLocation::OptionalDependencies,
842            path: root.join("package.json"),
843            line: 12,
844            used_in_workspaces: Vec::new(),
845        });
846        results.unused_enum_members.push(UnusedMember {
847            path: root.join("src/enums.ts"),
848            parent_name: "Status".to_string(),
849            member_name: "Deprecated".to_string(),
850            kind: MemberKind::EnumMember,
851            line: 8,
852            col: 2,
853        });
854
855        let lines = build_compact_lines(&results, &root);
856        assert_eq!(lines.len(), 3);
857        assert!(lines[0].starts_with("unused-devdep:"));
858        assert!(lines[1].starts_with("unused-optionaldep:"));
859        assert!(lines[2].starts_with("unused-enum-member:"));
860    }
861
862    // ── Path outside root ──
863
864    #[test]
865    fn compact_path_outside_root_preserved() {
866        let root = PathBuf::from("/project");
867        let mut results = AnalysisResults::default();
868        results.unused_files.push(UnusedFile {
869            path: PathBuf::from("/other/place/file.ts"),
870        });
871
872        let lines = build_compact_lines(&results, &root);
873        assert!(lines[0].contains("/other/place/file.ts"));
874    }
875}