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