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
124    lines
125}
126
127/// Print grouped compact output: each line is prefixed with the group key.
128///
129/// Format: `group-key\tissue-tag:details`
130pub(super) fn print_grouped_compact(groups: &[ResultGroup], root: &Path) {
131    for group in groups {
132        for line in build_compact_lines(&group.results, root) {
133            println!("{}\t{line}", group.key);
134        }
135    }
136}
137
138pub(super) fn print_health_compact(report: &crate::health_types::HealthReport, root: &Path) {
139    if let Some(ref hs) = report.health_score {
140        println!("health-score:{:.1}:{}", hs.score, hs.grade);
141    }
142    if let Some(ref vs) = report.vital_signs {
143        let mut parts = Vec::new();
144        parts.push(format!("avg_cyclomatic={:.1}", vs.avg_cyclomatic));
145        parts.push(format!("p90_cyclomatic={}", vs.p90_cyclomatic));
146        if let Some(v) = vs.dead_file_pct {
147            parts.push(format!("dead_file_pct={v:.1}"));
148        }
149        if let Some(v) = vs.dead_export_pct {
150            parts.push(format!("dead_export_pct={v:.1}"));
151        }
152        if let Some(v) = vs.maintainability_avg {
153            parts.push(format!("maintainability_avg={v:.1}"));
154        }
155        if let Some(v) = vs.hotspot_count {
156            parts.push(format!("hotspot_count={v}"));
157        }
158        if let Some(v) = vs.circular_dep_count {
159            parts.push(format!("circular_dep_count={v}"));
160        }
161        if let Some(v) = vs.unused_dep_count {
162            parts.push(format!("unused_dep_count={v}"));
163        }
164        println!("vital-signs:{}", parts.join(","));
165    }
166    for finding in &report.findings {
167        let relative = normalize_uri(&relative_path(&finding.path, root).display().to_string());
168        println!(
169            "high-complexity:{}:{}:{}:cyclomatic={},cognitive={}",
170            relative, finding.line, finding.name, finding.cyclomatic, finding.cognitive,
171        );
172    }
173    for score in &report.file_scores {
174        let relative = normalize_uri(&relative_path(&score.path, root).display().to_string());
175        println!(
176            "file-score:{}:mi={:.1},fan_in={},fan_out={},dead={:.2},density={:.2},crap_max={:.1},crap_above={}",
177            relative,
178            score.maintainability_index,
179            score.fan_in,
180            score.fan_out,
181            score.dead_code_ratio,
182            score.complexity_density,
183            score.crap_max,
184            score.crap_above_threshold,
185        );
186    }
187    if let Some(ref gaps) = report.coverage_gaps {
188        println!(
189            "coverage-gap-summary:runtime_files={},covered_files={},file_coverage_pct={:.1},untested_files={},untested_exports={}",
190            gaps.summary.runtime_files,
191            gaps.summary.covered_files,
192            gaps.summary.file_coverage_pct,
193            gaps.summary.untested_files,
194            gaps.summary.untested_exports,
195        );
196        for item in &gaps.files {
197            let relative = normalize_uri(&relative_path(&item.path, root).display().to_string());
198            println!(
199                "untested-file:{}:value_exports={}",
200                relative, item.value_export_count,
201            );
202        }
203        for item in &gaps.exports {
204            let relative = normalize_uri(&relative_path(&item.path, root).display().to_string());
205            println!(
206                "untested-export:{}:{}:{}",
207                relative, item.line, item.export_name,
208            );
209        }
210    }
211    for entry in &report.hotspots {
212        let relative = normalize_uri(&relative_path(&entry.path, root).display().to_string());
213        println!(
214            "hotspot:{}:score={:.1},commits={},churn={},density={:.2},fan_in={},trend={}",
215            relative,
216            entry.score,
217            entry.commits,
218            entry.lines_added + entry.lines_deleted,
219            entry.complexity_density,
220            entry.fan_in,
221            entry.trend,
222        );
223    }
224    if let Some(ref trend) = report.health_trend {
225        println!(
226            "trend:overall:direction={}",
227            trend.overall_direction.label()
228        );
229        for m in &trend.metrics {
230            println!(
231                "trend:{}:previous={:.1},current={:.1},delta={:+.1},direction={}",
232                m.name,
233                m.previous,
234                m.current,
235                m.delta,
236                m.direction.label(),
237            );
238        }
239    }
240    for target in &report.targets {
241        let relative = normalize_uri(&relative_path(&target.path, root).display().to_string());
242        let category = target.category.compact_label();
243        let effort = target.effort.label();
244        let confidence = target.confidence.label();
245        println!(
246            "refactoring-target:{}:priority={:.1},efficiency={:.1},category={},effort={},confidence={}:{}",
247            relative,
248            target.priority,
249            target.efficiency,
250            category,
251            effort,
252            confidence,
253            target.recommendation,
254        );
255    }
256}
257
258pub(super) fn print_duplication_compact(report: &DuplicationReport, root: &Path) {
259    for (i, group) in report.clone_groups.iter().enumerate() {
260        for instance in &group.instances {
261            let relative =
262                normalize_uri(&relative_path(&instance.file, root).display().to_string());
263            println!(
264                "clone-group-{}:{}:{}-{}:{}tokens",
265                i + 1,
266                relative,
267                instance.start_line,
268                instance.end_line,
269                group.token_count
270            );
271        }
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use crate::report::test_helpers::sample_results;
279    use fallow_core::extract::MemberKind;
280    use fallow_core::results::*;
281    use std::path::PathBuf;
282
283    #[test]
284    fn compact_empty_results_no_lines() {
285        let root = PathBuf::from("/project");
286        let results = AnalysisResults::default();
287        let lines = build_compact_lines(&results, &root);
288        assert!(lines.is_empty());
289    }
290
291    #[test]
292    fn compact_unused_file_format() {
293        let root = PathBuf::from("/project");
294        let mut results = AnalysisResults::default();
295        results.unused_files.push(UnusedFile {
296            path: root.join("src/dead.ts"),
297        });
298
299        let lines = build_compact_lines(&results, &root);
300        assert_eq!(lines.len(), 1);
301        assert_eq!(lines[0], "unused-file:src/dead.ts");
302    }
303
304    #[test]
305    fn compact_unused_export_format() {
306        let root = PathBuf::from("/project");
307        let mut results = AnalysisResults::default();
308        results.unused_exports.push(UnusedExport {
309            path: root.join("src/utils.ts"),
310            export_name: "helperFn".to_string(),
311            is_type_only: false,
312            line: 10,
313            col: 4,
314            span_start: 120,
315            is_re_export: false,
316        });
317
318        let lines = build_compact_lines(&results, &root);
319        assert_eq!(lines[0], "unused-export:src/utils.ts:10:helperFn");
320    }
321
322    #[test]
323    fn compact_unused_type_format() {
324        let root = PathBuf::from("/project");
325        let mut results = AnalysisResults::default();
326        results.unused_types.push(UnusedExport {
327            path: root.join("src/types.ts"),
328            export_name: "OldType".to_string(),
329            is_type_only: true,
330            line: 5,
331            col: 0,
332            span_start: 60,
333            is_re_export: false,
334        });
335
336        let lines = build_compact_lines(&results, &root);
337        assert_eq!(lines[0], "unused-type:src/types.ts:5:OldType");
338    }
339
340    #[test]
341    fn compact_unused_dep_format() {
342        let root = PathBuf::from("/project");
343        let mut results = AnalysisResults::default();
344        results.unused_dependencies.push(UnusedDependency {
345            package_name: "lodash".to_string(),
346            location: DependencyLocation::Dependencies,
347            path: root.join("package.json"),
348            line: 5,
349        });
350
351        let lines = build_compact_lines(&results, &root);
352        assert_eq!(lines[0], "unused-dep:lodash");
353    }
354
355    #[test]
356    fn compact_unused_devdep_format() {
357        let root = PathBuf::from("/project");
358        let mut results = AnalysisResults::default();
359        results.unused_dev_dependencies.push(UnusedDependency {
360            package_name: "jest".to_string(),
361            location: DependencyLocation::DevDependencies,
362            path: root.join("package.json"),
363            line: 5,
364        });
365
366        let lines = build_compact_lines(&results, &root);
367        assert_eq!(lines[0], "unused-devdep:jest");
368    }
369
370    #[test]
371    fn compact_unused_enum_member_format() {
372        let root = PathBuf::from("/project");
373        let mut results = AnalysisResults::default();
374        results.unused_enum_members.push(UnusedMember {
375            path: root.join("src/enums.ts"),
376            parent_name: "Status".to_string(),
377            member_name: "Deprecated".to_string(),
378            kind: MemberKind::EnumMember,
379            line: 8,
380            col: 2,
381        });
382
383        let lines = build_compact_lines(&results, &root);
384        assert_eq!(
385            lines[0],
386            "unused-enum-member:src/enums.ts:8:Status.Deprecated"
387        );
388    }
389
390    #[test]
391    fn compact_unused_class_member_format() {
392        let root = PathBuf::from("/project");
393        let mut results = AnalysisResults::default();
394        results.unused_class_members.push(UnusedMember {
395            path: root.join("src/service.ts"),
396            parent_name: "UserService".to_string(),
397            member_name: "legacyMethod".to_string(),
398            kind: MemberKind::ClassMethod,
399            line: 42,
400            col: 4,
401        });
402
403        let lines = build_compact_lines(&results, &root);
404        assert_eq!(
405            lines[0],
406            "unused-class-member:src/service.ts:42:UserService.legacyMethod"
407        );
408    }
409
410    #[test]
411    fn compact_unresolved_import_format() {
412        let root = PathBuf::from("/project");
413        let mut results = AnalysisResults::default();
414        results.unresolved_imports.push(UnresolvedImport {
415            path: root.join("src/app.ts"),
416            specifier: "./missing-module".to_string(),
417            line: 3,
418            col: 0,
419            specifier_col: 0,
420        });
421
422        let lines = build_compact_lines(&results, &root);
423        assert_eq!(lines[0], "unresolved-import:src/app.ts:3:./missing-module");
424    }
425
426    #[test]
427    fn compact_unlisted_dep_format() {
428        let root = PathBuf::from("/project");
429        let mut results = AnalysisResults::default();
430        results.unlisted_dependencies.push(UnlistedDependency {
431            package_name: "chalk".to_string(),
432            imported_from: vec![],
433        });
434
435        let lines = build_compact_lines(&results, &root);
436        assert_eq!(lines[0], "unlisted-dep:chalk");
437    }
438
439    #[test]
440    fn compact_duplicate_export_format() {
441        let root = PathBuf::from("/project");
442        let mut results = AnalysisResults::default();
443        results.duplicate_exports.push(DuplicateExport {
444            export_name: "Config".to_string(),
445            locations: vec![
446                DuplicateLocation {
447                    path: root.join("src/a.ts"),
448                    line: 15,
449                    col: 0,
450                },
451                DuplicateLocation {
452                    path: root.join("src/b.ts"),
453                    line: 30,
454                    col: 0,
455                },
456            ],
457        });
458
459        let lines = build_compact_lines(&results, &root);
460        assert_eq!(lines[0], "duplicate-export:Config");
461    }
462
463    #[test]
464    fn compact_all_issue_types_produce_lines() {
465        let root = PathBuf::from("/project");
466        let results = sample_results(&root);
467        let lines = build_compact_lines(&results, &root);
468
469        // 15 issue types, one of each
470        assert_eq!(lines.len(), 15);
471
472        // Verify ordering matches output order
473        assert!(lines[0].starts_with("unused-file:"));
474        assert!(lines[1].starts_with("unused-export:"));
475        assert!(lines[2].starts_with("unused-type:"));
476        assert!(lines[3].starts_with("unused-dep:"));
477        assert!(lines[4].starts_with("unused-devdep:"));
478        assert!(lines[5].starts_with("unused-optionaldep:"));
479        assert!(lines[6].starts_with("unused-enum-member:"));
480        assert!(lines[7].starts_with("unused-class-member:"));
481        assert!(lines[8].starts_with("unresolved-import:"));
482        assert!(lines[9].starts_with("unlisted-dep:"));
483        assert!(lines[10].starts_with("duplicate-export:"));
484        assert!(lines[11].starts_with("type-only-dep:"));
485        assert!(lines[12].starts_with("test-only-dep:"));
486        assert!(lines[13].starts_with("circular-dependency:"));
487        assert!(lines[14].starts_with("boundary-violation:"));
488    }
489
490    #[test]
491    fn compact_strips_root_prefix_from_paths() {
492        let root = PathBuf::from("/project");
493        let mut results = AnalysisResults::default();
494        results.unused_files.push(UnusedFile {
495            path: PathBuf::from("/project/src/deep/nested/file.ts"),
496        });
497
498        let lines = build_compact_lines(&results, &root);
499        assert_eq!(lines[0], "unused-file:src/deep/nested/file.ts");
500    }
501
502    // ── Re-export variants ──
503
504    #[test]
505    fn compact_re_export_tagged_correctly() {
506        let root = PathBuf::from("/project");
507        let mut results = AnalysisResults::default();
508        results.unused_exports.push(UnusedExport {
509            path: root.join("src/index.ts"),
510            export_name: "reExported".to_string(),
511            is_type_only: false,
512            line: 1,
513            col: 0,
514            span_start: 0,
515            is_re_export: true,
516        });
517
518        let lines = build_compact_lines(&results, &root);
519        assert_eq!(lines[0], "unused-re-export:src/index.ts:1:reExported");
520    }
521
522    #[test]
523    fn compact_type_re_export_tagged_correctly() {
524        let root = PathBuf::from("/project");
525        let mut results = AnalysisResults::default();
526        results.unused_types.push(UnusedExport {
527            path: root.join("src/index.ts"),
528            export_name: "ReExportedType".to_string(),
529            is_type_only: true,
530            line: 3,
531            col: 0,
532            span_start: 0,
533            is_re_export: true,
534        });
535
536        let lines = build_compact_lines(&results, &root);
537        assert_eq!(
538            lines[0],
539            "unused-re-export-type:src/index.ts:3:ReExportedType"
540        );
541    }
542
543    // ── Unused optional dependency ──
544
545    #[test]
546    fn compact_unused_optional_dep_format() {
547        let root = PathBuf::from("/project");
548        let mut results = AnalysisResults::default();
549        results.unused_optional_dependencies.push(UnusedDependency {
550            package_name: "fsevents".to_string(),
551            location: DependencyLocation::OptionalDependencies,
552            path: root.join("package.json"),
553            line: 12,
554        });
555
556        let lines = build_compact_lines(&results, &root);
557        assert_eq!(lines[0], "unused-optionaldep:fsevents");
558    }
559
560    // ── Circular dependency ──
561
562    #[test]
563    fn compact_circular_dependency_format() {
564        let root = PathBuf::from("/project");
565        let mut results = AnalysisResults::default();
566        results.circular_dependencies.push(CircularDependency {
567            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
568            length: 2,
569            line: 3,
570            col: 0,
571            is_cross_package: false,
572        });
573
574        let lines = build_compact_lines(&results, &root);
575        assert_eq!(lines.len(), 1);
576        assert!(lines[0].starts_with("circular-dependency:src/a.ts:3:"));
577        assert!(lines[0].contains("src/a.ts"));
578        assert!(lines[0].contains("src/b.ts"));
579        // Chain should close the cycle: a -> b -> a
580        assert!(lines[0].contains("\u{2192}"));
581    }
582
583    #[test]
584    fn compact_circular_dependency_closes_cycle() {
585        let root = PathBuf::from("/project");
586        let mut results = AnalysisResults::default();
587        results.circular_dependencies.push(CircularDependency {
588            files: vec![
589                root.join("src/a.ts"),
590                root.join("src/b.ts"),
591                root.join("src/c.ts"),
592            ],
593            length: 3,
594            line: 1,
595            col: 0,
596            is_cross_package: false,
597        });
598
599        let lines = build_compact_lines(&results, &root);
600        // Chain: a -> b -> c -> a
601        let chain_part = lines[0].split(':').next_back().unwrap();
602        let parts: Vec<&str> = chain_part.split(" \u{2192} ").collect();
603        assert_eq!(parts.len(), 4);
604        assert_eq!(parts[0], parts[3]); // first == last (cycle closes)
605    }
606
607    // ── Type-only dependency ──
608
609    #[test]
610    fn compact_type_only_dep_format() {
611        let root = PathBuf::from("/project");
612        let mut results = AnalysisResults::default();
613        results.type_only_dependencies.push(TypeOnlyDependency {
614            package_name: "zod".to_string(),
615            path: root.join("package.json"),
616            line: 8,
617        });
618
619        let lines = build_compact_lines(&results, &root);
620        assert_eq!(lines[0], "type-only-dep:zod");
621    }
622
623    // ── Multiple items of same type ──
624
625    #[test]
626    fn compact_multiple_unused_files() {
627        let root = PathBuf::from("/project");
628        let mut results = AnalysisResults::default();
629        results.unused_files.push(UnusedFile {
630            path: root.join("src/a.ts"),
631        });
632        results.unused_files.push(UnusedFile {
633            path: root.join("src/b.ts"),
634        });
635
636        let lines = build_compact_lines(&results, &root);
637        assert_eq!(lines.len(), 2);
638        assert_eq!(lines[0], "unused-file:src/a.ts");
639        assert_eq!(lines[1], "unused-file:src/b.ts");
640    }
641
642    // ── Output ordering matches issue types ──
643
644    #[test]
645    fn compact_ordering_optional_dep_between_devdep_and_enum() {
646        let root = PathBuf::from("/project");
647        let mut results = AnalysisResults::default();
648        results.unused_dev_dependencies.push(UnusedDependency {
649            package_name: "jest".to_string(),
650            location: DependencyLocation::DevDependencies,
651            path: root.join("package.json"),
652            line: 5,
653        });
654        results.unused_optional_dependencies.push(UnusedDependency {
655            package_name: "fsevents".to_string(),
656            location: DependencyLocation::OptionalDependencies,
657            path: root.join("package.json"),
658            line: 12,
659        });
660        results.unused_enum_members.push(UnusedMember {
661            path: root.join("src/enums.ts"),
662            parent_name: "Status".to_string(),
663            member_name: "Deprecated".to_string(),
664            kind: MemberKind::EnumMember,
665            line: 8,
666            col: 2,
667        });
668
669        let lines = build_compact_lines(&results, &root);
670        assert_eq!(lines.len(), 3);
671        assert!(lines[0].starts_with("unused-devdep:"));
672        assert!(lines[1].starts_with("unused-optionaldep:"));
673        assert!(lines[2].starts_with("unused-enum-member:"));
674    }
675
676    // ── Path outside root ──
677
678    #[test]
679    fn compact_path_outside_root_preserved() {
680        let root = PathBuf::from("/project");
681        let mut results = AnalysisResults::default();
682        results.unused_files.push(UnusedFile {
683            path: PathBuf::from("/other/place/file.ts"),
684        });
685
686        let lines = build_compact_lines(&results, &root);
687        assert!(lines[0].contains("/other/place/file.ts"));
688    }
689}