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::{normalize_uri, relative_path};
7
8pub(super) fn print_compact(results: &AnalysisResults, root: &Path) {
9    for line in build_compact_lines(results, root) {
10        println!("{line}");
11    }
12}
13
14/// Build compact output lines for analysis results.
15/// Each issue is represented as a single `prefix:details` line.
16pub fn build_compact_lines(results: &AnalysisResults, root: &Path) -> Vec<String> {
17    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
18
19    let compact_export = |export: &UnusedExport, kind: &str, re_kind: &str| -> String {
20        let tag = if export.is_re_export { re_kind } else { kind };
21        format!(
22            "{}:{}:{}:{}",
23            tag,
24            rel(&export.path),
25            export.line,
26            export.export_name
27        )
28    };
29
30    let compact_member = |member: &UnusedMember, kind: &str| -> String {
31        format!(
32            "{}:{}:{}:{}.{}",
33            kind,
34            rel(&member.path),
35            member.line,
36            member.parent_name,
37            member.member_name
38        )
39    };
40
41    let mut lines = Vec::new();
42
43    for file in &results.unused_files {
44        lines.push(format!("unused-file:{}", rel(&file.path)));
45    }
46    for export in &results.unused_exports {
47        lines.push(compact_export(export, "unused-export", "unused-re-export"));
48    }
49    for export in &results.unused_types {
50        lines.push(compact_export(
51            export,
52            "unused-type",
53            "unused-re-export-type",
54        ));
55    }
56    for dep in &results.unused_dependencies {
57        lines.push(format!("unused-dep:{}", dep.package_name));
58    }
59    for dep in &results.unused_dev_dependencies {
60        lines.push(format!("unused-devdep:{}", dep.package_name));
61    }
62    for dep in &results.unused_optional_dependencies {
63        lines.push(format!("unused-optionaldep:{}", dep.package_name));
64    }
65    for member in &results.unused_enum_members {
66        lines.push(compact_member(member, "unused-enum-member"));
67    }
68    for member in &results.unused_class_members {
69        lines.push(compact_member(member, "unused-class-member"));
70    }
71    for import in &results.unresolved_imports {
72        lines.push(format!(
73            "unresolved-import:{}:{}:{}",
74            rel(&import.path),
75            import.line,
76            import.specifier
77        ));
78    }
79    for dep in &results.unlisted_dependencies {
80        lines.push(format!("unlisted-dep:{}", dep.package_name));
81    }
82    for dup in &results.duplicate_exports {
83        lines.push(format!("duplicate-export:{}", dup.export_name));
84    }
85    for dep in &results.type_only_dependencies {
86        lines.push(format!("type-only-dep:{}", dep.package_name));
87    }
88    for cycle in &results.circular_dependencies {
89        let chain: Vec<String> = cycle.files.iter().map(|p| rel(p)).collect();
90        let mut display_chain = chain.clone();
91        if let Some(first) = chain.first() {
92            display_chain.push(first.clone());
93        }
94        let first_file = chain.first().map_or_else(String::new, Clone::clone);
95        lines.push(format!(
96            "circular-dependency:{}:{}:{}",
97            first_file,
98            cycle.line,
99            display_chain.join(" \u{2192} ")
100        ));
101    }
102
103    lines
104}
105
106pub(super) fn print_health_compact(report: &crate::health_types::HealthReport, root: &Path) {
107    for finding in &report.findings {
108        let relative = normalize_uri(&relative_path(&finding.path, root).display().to_string());
109        println!(
110            "high-complexity:{}:{}:{}:cyclomatic={},cognitive={}",
111            relative, finding.line, finding.name, finding.cyclomatic, finding.cognitive,
112        );
113    }
114    for score in &report.file_scores {
115        let relative = normalize_uri(&relative_path(&score.path, root).display().to_string());
116        println!(
117            "file-score:{}:mi={:.1},fan_in={},fan_out={},dead={:.2},density={:.2}",
118            relative,
119            score.maintainability_index,
120            score.fan_in,
121            score.fan_out,
122            score.dead_code_ratio,
123            score.complexity_density,
124        );
125    }
126    for entry in &report.hotspots {
127        let relative = normalize_uri(&relative_path(&entry.path, root).display().to_string());
128        println!(
129            "hotspot:{}:score={:.1},commits={},churn={},density={:.2},fan_in={},trend={}",
130            relative,
131            entry.score,
132            entry.commits,
133            entry.lines_added + entry.lines_deleted,
134            entry.complexity_density,
135            entry.fan_in,
136            entry.trend,
137        );
138    }
139    for target in &report.targets {
140        let relative = normalize_uri(&relative_path(&target.path, root).display().to_string());
141        let category = target.category.label();
142        let effort = target.effort.label();
143        println!(
144            "refactoring-target:{}:priority={:.1},category={},effort={}:{}",
145            relative, target.priority, category, effort, target.recommendation,
146        );
147    }
148}
149
150pub(super) fn print_duplication_compact(report: &DuplicationReport, root: &Path) {
151    for (i, group) in report.clone_groups.iter().enumerate() {
152        for instance in &group.instances {
153            let relative =
154                normalize_uri(&relative_path(&instance.file, root).display().to_string());
155            println!(
156                "clone-group-{}:{}:{}-{}:{}tokens",
157                i + 1,
158                relative,
159                instance.start_line,
160                instance.end_line,
161                group.token_count
162            );
163        }
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use fallow_core::extract::MemberKind;
171    use fallow_core::results::*;
172    use std::path::PathBuf;
173
174    /// Helper: build an `AnalysisResults` populated with one issue of every type.
175    fn sample_results(root: &Path) -> AnalysisResults {
176        let mut r = AnalysisResults::default();
177
178        r.unused_files.push(UnusedFile {
179            path: root.join("src/dead.ts"),
180        });
181        r.unused_exports.push(UnusedExport {
182            path: root.join("src/utils.ts"),
183            export_name: "helperFn".to_string(),
184            is_type_only: false,
185            line: 10,
186            col: 4,
187            span_start: 120,
188            is_re_export: false,
189        });
190        r.unused_types.push(UnusedExport {
191            path: root.join("src/types.ts"),
192            export_name: "OldType".to_string(),
193            is_type_only: true,
194            line: 5,
195            col: 0,
196            span_start: 60,
197            is_re_export: false,
198        });
199        r.unused_dependencies.push(UnusedDependency {
200            package_name: "lodash".to_string(),
201            location: DependencyLocation::Dependencies,
202            path: root.join("package.json"),
203            line: 5,
204        });
205        r.unused_dev_dependencies.push(UnusedDependency {
206            package_name: "jest".to_string(),
207            location: DependencyLocation::DevDependencies,
208            path: root.join("package.json"),
209            line: 5,
210        });
211        r.unused_enum_members.push(UnusedMember {
212            path: root.join("src/enums.ts"),
213            parent_name: "Status".to_string(),
214            member_name: "Deprecated".to_string(),
215            kind: MemberKind::EnumMember,
216            line: 8,
217            col: 2,
218        });
219        r.unused_class_members.push(UnusedMember {
220            path: root.join("src/service.ts"),
221            parent_name: "UserService".to_string(),
222            member_name: "legacyMethod".to_string(),
223            kind: MemberKind::ClassMethod,
224            line: 42,
225            col: 4,
226        });
227        r.unresolved_imports.push(UnresolvedImport {
228            path: root.join("src/app.ts"),
229            specifier: "./missing-module".to_string(),
230            line: 3,
231            col: 0,
232            specifier_col: 0,
233        });
234        r.unlisted_dependencies.push(UnlistedDependency {
235            package_name: "chalk".to_string(),
236            imported_from: vec![ImportSite {
237                path: root.join("src/cli.ts"),
238                line: 2,
239                col: 0,
240            }],
241        });
242        r.duplicate_exports.push(DuplicateExport {
243            export_name: "Config".to_string(),
244            locations: vec![
245                DuplicateLocation {
246                    path: root.join("src/config.ts"),
247                    line: 15,
248                    col: 0,
249                },
250                DuplicateLocation {
251                    path: root.join("src/types.ts"),
252                    line: 30,
253                    col: 0,
254                },
255            ],
256        });
257        r.type_only_dependencies.push(TypeOnlyDependency {
258            package_name: "zod".to_string(),
259            path: root.join("package.json"),
260            line: 8,
261        });
262
263        r
264    }
265
266    #[test]
267    fn compact_empty_results_no_lines() {
268        let root = PathBuf::from("/project");
269        let results = AnalysisResults::default();
270        let lines = build_compact_lines(&results, &root);
271        assert!(lines.is_empty());
272    }
273
274    #[test]
275    fn compact_unused_file_format() {
276        let root = PathBuf::from("/project");
277        let mut results = AnalysisResults::default();
278        results.unused_files.push(UnusedFile {
279            path: root.join("src/dead.ts"),
280        });
281
282        let lines = build_compact_lines(&results, &root);
283        assert_eq!(lines.len(), 1);
284        assert_eq!(lines[0], "unused-file:src/dead.ts");
285    }
286
287    #[test]
288    fn compact_unused_export_format() {
289        let root = PathBuf::from("/project");
290        let mut results = AnalysisResults::default();
291        results.unused_exports.push(UnusedExport {
292            path: root.join("src/utils.ts"),
293            export_name: "helperFn".to_string(),
294            is_type_only: false,
295            line: 10,
296            col: 4,
297            span_start: 120,
298            is_re_export: false,
299        });
300
301        let lines = build_compact_lines(&results, &root);
302        assert_eq!(lines[0], "unused-export:src/utils.ts:10:helperFn");
303    }
304
305    #[test]
306    fn compact_unused_type_format() {
307        let root = PathBuf::from("/project");
308        let mut results = AnalysisResults::default();
309        results.unused_types.push(UnusedExport {
310            path: root.join("src/types.ts"),
311            export_name: "OldType".to_string(),
312            is_type_only: true,
313            line: 5,
314            col: 0,
315            span_start: 60,
316            is_re_export: false,
317        });
318
319        let lines = build_compact_lines(&results, &root);
320        assert_eq!(lines[0], "unused-type:src/types.ts:5:OldType");
321    }
322
323    #[test]
324    fn compact_unused_dep_format() {
325        let root = PathBuf::from("/project");
326        let mut results = AnalysisResults::default();
327        results.unused_dependencies.push(UnusedDependency {
328            package_name: "lodash".to_string(),
329            location: DependencyLocation::Dependencies,
330            path: root.join("package.json"),
331            line: 5,
332        });
333
334        let lines = build_compact_lines(&results, &root);
335        assert_eq!(lines[0], "unused-dep:lodash");
336    }
337
338    #[test]
339    fn compact_unused_devdep_format() {
340        let root = PathBuf::from("/project");
341        let mut results = AnalysisResults::default();
342        results.unused_dev_dependencies.push(UnusedDependency {
343            package_name: "jest".to_string(),
344            location: DependencyLocation::DevDependencies,
345            path: root.join("package.json"),
346            line: 5,
347        });
348
349        let lines = build_compact_lines(&results, &root);
350        assert_eq!(lines[0], "unused-devdep:jest");
351    }
352
353    #[test]
354    fn compact_unused_enum_member_format() {
355        let root = PathBuf::from("/project");
356        let mut results = AnalysisResults::default();
357        results.unused_enum_members.push(UnusedMember {
358            path: root.join("src/enums.ts"),
359            parent_name: "Status".to_string(),
360            member_name: "Deprecated".to_string(),
361            kind: MemberKind::EnumMember,
362            line: 8,
363            col: 2,
364        });
365
366        let lines = build_compact_lines(&results, &root);
367        assert_eq!(
368            lines[0],
369            "unused-enum-member:src/enums.ts:8:Status.Deprecated"
370        );
371    }
372
373    #[test]
374    fn compact_unused_class_member_format() {
375        let root = PathBuf::from("/project");
376        let mut results = AnalysisResults::default();
377        results.unused_class_members.push(UnusedMember {
378            path: root.join("src/service.ts"),
379            parent_name: "UserService".to_string(),
380            member_name: "legacyMethod".to_string(),
381            kind: MemberKind::ClassMethod,
382            line: 42,
383            col: 4,
384        });
385
386        let lines = build_compact_lines(&results, &root);
387        assert_eq!(
388            lines[0],
389            "unused-class-member:src/service.ts:42:UserService.legacyMethod"
390        );
391    }
392
393    #[test]
394    fn compact_unresolved_import_format() {
395        let root = PathBuf::from("/project");
396        let mut results = AnalysisResults::default();
397        results.unresolved_imports.push(UnresolvedImport {
398            path: root.join("src/app.ts"),
399            specifier: "./missing-module".to_string(),
400            line: 3,
401            col: 0,
402            specifier_col: 0,
403        });
404
405        let lines = build_compact_lines(&results, &root);
406        assert_eq!(lines[0], "unresolved-import:src/app.ts:3:./missing-module");
407    }
408
409    #[test]
410    fn compact_unlisted_dep_format() {
411        let root = PathBuf::from("/project");
412        let mut results = AnalysisResults::default();
413        results.unlisted_dependencies.push(UnlistedDependency {
414            package_name: "chalk".to_string(),
415            imported_from: vec![],
416        });
417
418        let lines = build_compact_lines(&results, &root);
419        assert_eq!(lines[0], "unlisted-dep:chalk");
420    }
421
422    #[test]
423    fn compact_duplicate_export_format() {
424        let root = PathBuf::from("/project");
425        let mut results = AnalysisResults::default();
426        results.duplicate_exports.push(DuplicateExport {
427            export_name: "Config".to_string(),
428            locations: vec![
429                DuplicateLocation {
430                    path: root.join("src/a.ts"),
431                    line: 15,
432                    col: 0,
433                },
434                DuplicateLocation {
435                    path: root.join("src/b.ts"),
436                    line: 30,
437                    col: 0,
438                },
439            ],
440        });
441
442        let lines = build_compact_lines(&results, &root);
443        assert_eq!(lines[0], "duplicate-export:Config");
444    }
445
446    #[test]
447    fn compact_all_issue_types_produce_lines() {
448        let root = PathBuf::from("/project");
449        let results = sample_results(&root);
450        let lines = build_compact_lines(&results, &root);
451
452        // 11 issue types, one of each
453        assert_eq!(lines.len(), 11);
454
455        // Verify ordering matches output order
456        assert!(lines[0].starts_with("unused-file:"));
457        assert!(lines[1].starts_with("unused-export:"));
458        assert!(lines[2].starts_with("unused-type:"));
459        assert!(lines[3].starts_with("unused-dep:"));
460        assert!(lines[4].starts_with("unused-devdep:"));
461        assert!(lines[5].starts_with("unused-enum-member:"));
462        assert!(lines[6].starts_with("unused-class-member:"));
463        assert!(lines[7].starts_with("unresolved-import:"));
464        assert!(lines[8].starts_with("unlisted-dep:"));
465        assert!(lines[9].starts_with("duplicate-export:"));
466        assert!(lines[10].starts_with("type-only-dep:"));
467    }
468
469    #[test]
470    fn compact_strips_root_prefix_from_paths() {
471        let root = PathBuf::from("/project");
472        let mut results = AnalysisResults::default();
473        results.unused_files.push(UnusedFile {
474            path: PathBuf::from("/project/src/deep/nested/file.ts"),
475        });
476
477        let lines = build_compact_lines(&results, &root);
478        assert_eq!(lines[0], "unused-file:src/deep/nested/file.ts");
479    }
480}