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