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}
140
141pub(super) fn print_duplication_compact(report: &DuplicationReport, root: &Path) {
142    for (i, group) in report.clone_groups.iter().enumerate() {
143        for instance in &group.instances {
144            let relative =
145                normalize_uri(&relative_path(&instance.file, root).display().to_string());
146            println!(
147                "clone-group-{}:{}:{}-{}:{}tokens",
148                i + 1,
149                relative,
150                instance.start_line,
151                instance.end_line,
152                group.token_count
153            );
154        }
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use fallow_core::extract::MemberKind;
162    use fallow_core::results::*;
163    use std::path::PathBuf;
164
165    /// Helper: build an `AnalysisResults` populated with one issue of every type.
166    fn sample_results(root: &Path) -> AnalysisResults {
167        let mut r = AnalysisResults::default();
168
169        r.unused_files.push(UnusedFile {
170            path: root.join("src/dead.ts"),
171        });
172        r.unused_exports.push(UnusedExport {
173            path: root.join("src/utils.ts"),
174            export_name: "helperFn".to_string(),
175            is_type_only: false,
176            line: 10,
177            col: 4,
178            span_start: 120,
179            is_re_export: false,
180        });
181        r.unused_types.push(UnusedExport {
182            path: root.join("src/types.ts"),
183            export_name: "OldType".to_string(),
184            is_type_only: true,
185            line: 5,
186            col: 0,
187            span_start: 60,
188            is_re_export: false,
189        });
190        r.unused_dependencies.push(UnusedDependency {
191            package_name: "lodash".to_string(),
192            location: DependencyLocation::Dependencies,
193            path: root.join("package.json"),
194            line: 5,
195        });
196        r.unused_dev_dependencies.push(UnusedDependency {
197            package_name: "jest".to_string(),
198            location: DependencyLocation::DevDependencies,
199            path: root.join("package.json"),
200            line: 5,
201        });
202        r.unused_enum_members.push(UnusedMember {
203            path: root.join("src/enums.ts"),
204            parent_name: "Status".to_string(),
205            member_name: "Deprecated".to_string(),
206            kind: MemberKind::EnumMember,
207            line: 8,
208            col: 2,
209        });
210        r.unused_class_members.push(UnusedMember {
211            path: root.join("src/service.ts"),
212            parent_name: "UserService".to_string(),
213            member_name: "legacyMethod".to_string(),
214            kind: MemberKind::ClassMethod,
215            line: 42,
216            col: 4,
217        });
218        r.unresolved_imports.push(UnresolvedImport {
219            path: root.join("src/app.ts"),
220            specifier: "./missing-module".to_string(),
221            line: 3,
222            col: 0,
223        });
224        r.unlisted_dependencies.push(UnlistedDependency {
225            package_name: "chalk".to_string(),
226            imported_from: vec![ImportSite {
227                path: root.join("src/cli.ts"),
228                line: 2,
229                col: 0,
230            }],
231        });
232        r.duplicate_exports.push(DuplicateExport {
233            export_name: "Config".to_string(),
234            locations: vec![
235                DuplicateLocation {
236                    path: root.join("src/config.ts"),
237                    line: 15,
238                    col: 0,
239                },
240                DuplicateLocation {
241                    path: root.join("src/types.ts"),
242                    line: 30,
243                    col: 0,
244                },
245            ],
246        });
247        r.type_only_dependencies.push(TypeOnlyDependency {
248            package_name: "zod".to_string(),
249            path: root.join("package.json"),
250            line: 8,
251        });
252
253        r
254    }
255
256    #[test]
257    fn compact_empty_results_no_lines() {
258        let root = PathBuf::from("/project");
259        let results = AnalysisResults::default();
260        let lines = build_compact_lines(&results, &root);
261        assert!(lines.is_empty());
262    }
263
264    #[test]
265    fn compact_unused_file_format() {
266        let root = PathBuf::from("/project");
267        let mut results = AnalysisResults::default();
268        results.unused_files.push(UnusedFile {
269            path: root.join("src/dead.ts"),
270        });
271
272        let lines = build_compact_lines(&results, &root);
273        assert_eq!(lines.len(), 1);
274        assert_eq!(lines[0], "unused-file:src/dead.ts");
275    }
276
277    #[test]
278    fn compact_unused_export_format() {
279        let root = PathBuf::from("/project");
280        let mut results = AnalysisResults::default();
281        results.unused_exports.push(UnusedExport {
282            path: root.join("src/utils.ts"),
283            export_name: "helperFn".to_string(),
284            is_type_only: false,
285            line: 10,
286            col: 4,
287            span_start: 120,
288            is_re_export: false,
289        });
290
291        let lines = build_compact_lines(&results, &root);
292        assert_eq!(lines[0], "unused-export:src/utils.ts:10:helperFn");
293    }
294
295    #[test]
296    fn compact_unused_type_format() {
297        let root = PathBuf::from("/project");
298        let mut results = AnalysisResults::default();
299        results.unused_types.push(UnusedExport {
300            path: root.join("src/types.ts"),
301            export_name: "OldType".to_string(),
302            is_type_only: true,
303            line: 5,
304            col: 0,
305            span_start: 60,
306            is_re_export: false,
307        });
308
309        let lines = build_compact_lines(&results, &root);
310        assert_eq!(lines[0], "unused-type:src/types.ts:5:OldType");
311    }
312
313    #[test]
314    fn compact_unused_dep_format() {
315        let root = PathBuf::from("/project");
316        let mut results = AnalysisResults::default();
317        results.unused_dependencies.push(UnusedDependency {
318            package_name: "lodash".to_string(),
319            location: DependencyLocation::Dependencies,
320            path: root.join("package.json"),
321            line: 5,
322        });
323
324        let lines = build_compact_lines(&results, &root);
325        assert_eq!(lines[0], "unused-dep:lodash");
326    }
327
328    #[test]
329    fn compact_unused_devdep_format() {
330        let root = PathBuf::from("/project");
331        let mut results = AnalysisResults::default();
332        results.unused_dev_dependencies.push(UnusedDependency {
333            package_name: "jest".to_string(),
334            location: DependencyLocation::DevDependencies,
335            path: root.join("package.json"),
336            line: 5,
337        });
338
339        let lines = build_compact_lines(&results, &root);
340        assert_eq!(lines[0], "unused-devdep:jest");
341    }
342
343    #[test]
344    fn compact_unused_enum_member_format() {
345        let root = PathBuf::from("/project");
346        let mut results = AnalysisResults::default();
347        results.unused_enum_members.push(UnusedMember {
348            path: root.join("src/enums.ts"),
349            parent_name: "Status".to_string(),
350            member_name: "Deprecated".to_string(),
351            kind: MemberKind::EnumMember,
352            line: 8,
353            col: 2,
354        });
355
356        let lines = build_compact_lines(&results, &root);
357        assert_eq!(
358            lines[0],
359            "unused-enum-member:src/enums.ts:8:Status.Deprecated"
360        );
361    }
362
363    #[test]
364    fn compact_unused_class_member_format() {
365        let root = PathBuf::from("/project");
366        let mut results = AnalysisResults::default();
367        results.unused_class_members.push(UnusedMember {
368            path: root.join("src/service.ts"),
369            parent_name: "UserService".to_string(),
370            member_name: "legacyMethod".to_string(),
371            kind: MemberKind::ClassMethod,
372            line: 42,
373            col: 4,
374        });
375
376        let lines = build_compact_lines(&results, &root);
377        assert_eq!(
378            lines[0],
379            "unused-class-member:src/service.ts:42:UserService.legacyMethod"
380        );
381    }
382
383    #[test]
384    fn compact_unresolved_import_format() {
385        let root = PathBuf::from("/project");
386        let mut results = AnalysisResults::default();
387        results.unresolved_imports.push(UnresolvedImport {
388            path: root.join("src/app.ts"),
389            specifier: "./missing-module".to_string(),
390            line: 3,
391            col: 0,
392        });
393
394        let lines = build_compact_lines(&results, &root);
395        assert_eq!(lines[0], "unresolved-import:src/app.ts:3:./missing-module");
396    }
397
398    #[test]
399    fn compact_unlisted_dep_format() {
400        let root = PathBuf::from("/project");
401        let mut results = AnalysisResults::default();
402        results.unlisted_dependencies.push(UnlistedDependency {
403            package_name: "chalk".to_string(),
404            imported_from: vec![],
405        });
406
407        let lines = build_compact_lines(&results, &root);
408        assert_eq!(lines[0], "unlisted-dep:chalk");
409    }
410
411    #[test]
412    fn compact_duplicate_export_format() {
413        let root = PathBuf::from("/project");
414        let mut results = AnalysisResults::default();
415        results.duplicate_exports.push(DuplicateExport {
416            export_name: "Config".to_string(),
417            locations: vec![
418                DuplicateLocation {
419                    path: root.join("src/a.ts"),
420                    line: 15,
421                    col: 0,
422                },
423                DuplicateLocation {
424                    path: root.join("src/b.ts"),
425                    line: 30,
426                    col: 0,
427                },
428            ],
429        });
430
431        let lines = build_compact_lines(&results, &root);
432        assert_eq!(lines[0], "duplicate-export:Config");
433    }
434
435    #[test]
436    fn compact_all_issue_types_produce_lines() {
437        let root = PathBuf::from("/project");
438        let results = sample_results(&root);
439        let lines = build_compact_lines(&results, &root);
440
441        // 11 issue types, one of each
442        assert_eq!(lines.len(), 11);
443
444        // Verify ordering matches output order
445        assert!(lines[0].starts_with("unused-file:"));
446        assert!(lines[1].starts_with("unused-export:"));
447        assert!(lines[2].starts_with("unused-type:"));
448        assert!(lines[3].starts_with("unused-dep:"));
449        assert!(lines[4].starts_with("unused-devdep:"));
450        assert!(lines[5].starts_with("unused-enum-member:"));
451        assert!(lines[6].starts_with("unused-class-member:"));
452        assert!(lines[7].starts_with("unresolved-import:"));
453        assert!(lines[8].starts_with("unlisted-dep:"));
454        assert!(lines[9].starts_with("duplicate-export:"));
455        assert!(lines[10].starts_with("type-only-dep:"));
456    }
457
458    #[test]
459    fn compact_strips_root_prefix_from_paths() {
460        let root = PathBuf::from("/project");
461        let mut results = AnalysisResults::default();
462        results.unused_files.push(UnusedFile {
463            path: PathBuf::from("/project/src/deep/nested/file.ts"),
464        });
465
466        let lines = build_compact_lines(&results, &root);
467        assert_eq!(lines[0], "unused-file:src/deep/nested/file.ts");
468    }
469}