Skip to main content

fallow_cli/report/
mod.rs

1mod compact;
2mod human;
3mod json;
4mod markdown;
5mod sarif;
6
7use std::path::Path;
8use std::process::ExitCode;
9use std::time::Duration;
10
11use fallow_config::{OutputFormat, ResolvedConfig, Severity};
12use fallow_core::duplicates::DuplicationReport;
13use fallow_core::results::AnalysisResults;
14use fallow_core::trace::{CloneTrace, DependencyTrace, ExportTrace, FileTrace, PipelineTimings};
15
16/// Strip the project root prefix from a path for display, falling back to the full path.
17fn relative_path<'a>(path: &'a Path, root: &Path) -> &'a Path {
18    path.strip_prefix(root).unwrap_or(path)
19}
20
21/// Split a path string into (directory, filename) for display.
22/// Directory includes the trailing `/`. If no directory, returns `("", filename)`.
23fn split_dir_filename(path: &str) -> (&str, &str) {
24    match path.rfind('/') {
25        Some(pos) => (&path[..=pos], &path[pos + 1..]),
26        None => ("", path),
27    }
28}
29
30/// Elide the common directory prefix between a base path and a target path.
31/// Only strips complete directory segments (never partial filenames).
32/// Returns the remaining suffix of `target`.
33///
34/// Example: `elide_common_prefix("a/b/c/foo.ts", "a/b/d/bar.ts")` → `"d/bar.ts"`
35fn elide_common_prefix<'a>(base: &str, target: &'a str) -> &'a str {
36    let mut last_sep = 0;
37    for (i, (a, b)) in base.bytes().zip(target.bytes()).enumerate() {
38        if a != b {
39            break;
40        }
41        if a == b'/' {
42            last_sep = i + 1;
43        }
44    }
45    if last_sep > 0 && last_sep <= target.len() {
46        &target[last_sep..]
47    } else {
48        target
49    }
50}
51
52/// Compute a SARIF-compatible relative URI from an absolute path and project root.
53fn relative_uri(path: &Path, root: &Path) -> String {
54    normalize_uri(&relative_path(path, root).display().to_string())
55}
56
57/// Normalize a path string to a valid URI: forward slashes and percent-encoded brackets.
58///
59/// Brackets (`[`, `]`) are not valid in URI path segments per RFC 3986 and cause
60/// SARIF validation warnings (e.g., Next.js dynamic routes like `[slug]`).
61pub fn normalize_uri(path_str: &str) -> String {
62    path_str
63        .replace('\\', "/")
64        .replace('[', "%5B")
65        .replace(']', "%5D")
66}
67
68/// Severity level for human-readable output.
69#[derive(Clone, Copy, Debug)]
70enum Level {
71    Warn,
72    Info,
73    Error,
74}
75
76const fn severity_to_level(s: Severity) -> Level {
77    match s {
78        Severity::Error => Level::Error,
79        Severity::Warn => Level::Warn,
80        // Off issues are filtered before reporting; fall back to Info.
81        Severity::Off => Level::Info,
82    }
83}
84
85/// Print analysis results in the configured format.
86/// Returns exit code 2 if serialization fails, SUCCESS otherwise.
87pub fn print_results(
88    results: &AnalysisResults,
89    config: &ResolvedConfig,
90    elapsed: Duration,
91    quiet: bool,
92    explain: bool,
93) -> ExitCode {
94    match config.output {
95        OutputFormat::Human => {
96            human::print_human(results, &config.root, &config.rules, elapsed, quiet);
97            ExitCode::SUCCESS
98        }
99        OutputFormat::Json => json::print_json(results, &config.root, elapsed, explain),
100        OutputFormat::Compact => {
101            compact::print_compact(results, &config.root);
102            ExitCode::SUCCESS
103        }
104        OutputFormat::Sarif => sarif::print_sarif(results, &config.root, &config.rules),
105        OutputFormat::Markdown => {
106            markdown::print_markdown(results, &config.root);
107            ExitCode::SUCCESS
108        }
109    }
110}
111
112// ── Duplication report ────────────────────────────────────────────
113
114/// Print duplication analysis results in the configured format.
115pub fn print_duplication_report(
116    report: &DuplicationReport,
117    config: &ResolvedConfig,
118    elapsed: Duration,
119    quiet: bool,
120    output: &OutputFormat,
121    explain: bool,
122) -> ExitCode {
123    match output {
124        OutputFormat::Human => {
125            human::print_duplication_human(report, &config.root, elapsed, quiet);
126            ExitCode::SUCCESS
127        }
128        OutputFormat::Json => json::print_duplication_json(report, elapsed, explain),
129        OutputFormat::Compact => {
130            compact::print_duplication_compact(report, &config.root);
131            ExitCode::SUCCESS
132        }
133        OutputFormat::Sarif => sarif::print_duplication_sarif(report, &config.root),
134        OutputFormat::Markdown => {
135            markdown::print_duplication_markdown(report, &config.root);
136            ExitCode::SUCCESS
137        }
138    }
139}
140
141// ── Health / complexity report ─────────────────────────────────────
142
143/// Print health (complexity) analysis results in the configured format.
144pub fn print_health_report(
145    report: &crate::health_types::HealthReport,
146    config: &ResolvedConfig,
147    elapsed: Duration,
148    quiet: bool,
149    output: &OutputFormat,
150    explain: bool,
151) -> ExitCode {
152    match output {
153        OutputFormat::Human => {
154            human::print_health_human(report, &config.root, elapsed, quiet);
155            ExitCode::SUCCESS
156        }
157        OutputFormat::Compact => {
158            compact::print_health_compact(report, &config.root);
159            ExitCode::SUCCESS
160        }
161        OutputFormat::Markdown => {
162            markdown::print_health_markdown(report, &config.root);
163            ExitCode::SUCCESS
164        }
165        OutputFormat::Sarif => sarif::print_health_sarif(report, &config.root),
166        OutputFormat::Json => json::print_health_json(report, &config.root, elapsed, explain),
167    }
168}
169
170/// Print cross-reference findings (duplicated code that is also dead code).
171///
172/// Only emits output in human format to avoid corrupting structured JSON/SARIF output.
173pub fn print_cross_reference_findings(
174    cross_ref: &fallow_core::cross_reference::CrossReferenceResult,
175    root: &Path,
176    quiet: bool,
177    output: &OutputFormat,
178) {
179    human::print_cross_reference_findings(cross_ref, root, quiet, output);
180}
181
182// ── Trace output ──────────────────────────────────────────────────
183
184/// Print export trace results.
185pub fn print_export_trace(trace: &ExportTrace, format: &OutputFormat) {
186    match format {
187        OutputFormat::Json => json::print_trace_json(trace),
188        _ => human::print_export_trace_human(trace),
189    }
190}
191
192/// Print file trace results.
193pub fn print_file_trace(trace: &FileTrace, format: &OutputFormat) {
194    match format {
195        OutputFormat::Json => json::print_trace_json(trace),
196        _ => human::print_file_trace_human(trace),
197    }
198}
199
200/// Print dependency trace results.
201pub fn print_dependency_trace(trace: &DependencyTrace, format: &OutputFormat) {
202    match format {
203        OutputFormat::Json => json::print_trace_json(trace),
204        _ => human::print_dependency_trace_human(trace),
205    }
206}
207
208/// Print clone trace results.
209pub fn print_clone_trace(trace: &CloneTrace, root: &Path, format: &OutputFormat) {
210    match format {
211        OutputFormat::Json => json::print_trace_json(trace),
212        _ => human::print_clone_trace_human(trace, root),
213    }
214}
215
216/// Print pipeline performance timings.
217/// In JSON mode, outputs to stderr to avoid polluting the JSON analysis output on stdout.
218pub fn print_performance(timings: &PipelineTimings, format: &OutputFormat) {
219    match format {
220        OutputFormat::Json => match serde_json::to_string_pretty(timings) {
221            Ok(json) => eprintln!("{json}"),
222            Err(e) => eprintln!("Error: failed to serialize timings: {e}"),
223        },
224        _ => human::print_performance_human(timings),
225    }
226}
227
228// Re-exported for snapshot testing via the lib target
229#[allow(unused_imports)]
230pub use compact::build_compact_lines;
231#[allow(unused_imports)]
232pub use json::build_json;
233#[allow(unused_imports)]
234pub use markdown::build_duplication_markdown;
235#[allow(unused_imports)]
236pub use markdown::build_health_markdown;
237#[allow(unused_imports)]
238pub use markdown::build_markdown;
239#[allow(unused_imports)]
240pub use sarif::build_health_sarif;
241#[allow(unused_imports)]
242pub use sarif::build_sarif;
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use std::path::PathBuf;
248
249    // ── normalize_uri ────────────────────────────────────────────────
250
251    #[test]
252    fn normalize_uri_forward_slashes_unchanged() {
253        assert_eq!(normalize_uri("src/utils.ts"), "src/utils.ts");
254    }
255
256    #[test]
257    fn normalize_uri_backslashes_replaced() {
258        assert_eq!(normalize_uri("src\\utils\\index.ts"), "src/utils/index.ts");
259    }
260
261    #[test]
262    fn normalize_uri_mixed_slashes() {
263        assert_eq!(normalize_uri("src\\utils/index.ts"), "src/utils/index.ts");
264    }
265
266    #[test]
267    fn normalize_uri_path_with_spaces() {
268        assert_eq!(
269            normalize_uri("src\\my folder\\file.ts"),
270            "src/my folder/file.ts"
271        );
272    }
273
274    #[test]
275    fn normalize_uri_empty_string() {
276        assert_eq!(normalize_uri(""), "");
277    }
278
279    // ── relative_path ────────────────────────────────────────────────
280
281    #[test]
282    fn relative_path_strips_root_prefix() {
283        let root = Path::new("/project");
284        let path = Path::new("/project/src/utils.ts");
285        assert_eq!(relative_path(path, root), Path::new("src/utils.ts"));
286    }
287
288    #[test]
289    fn relative_path_returns_full_path_when_no_prefix() {
290        let root = Path::new("/other");
291        let path = Path::new("/project/src/utils.ts");
292        assert_eq!(relative_path(path, root), path);
293    }
294
295    #[test]
296    fn relative_path_at_root_returns_empty_or_file() {
297        let root = Path::new("/project");
298        let path = Path::new("/project/file.ts");
299        assert_eq!(relative_path(path, root), Path::new("file.ts"));
300    }
301
302    #[test]
303    fn relative_path_deeply_nested() {
304        let root = Path::new("/project");
305        let path = Path::new("/project/packages/ui/src/components/Button.tsx");
306        assert_eq!(
307            relative_path(path, root),
308            Path::new("packages/ui/src/components/Button.tsx")
309        );
310    }
311
312    // ── relative_uri ─────────────────────────────────────────────────
313
314    #[test]
315    fn relative_uri_produces_forward_slash_path() {
316        let root = PathBuf::from("/project");
317        let path = root.join("src").join("utils.ts");
318        let uri = relative_uri(&path, &root);
319        assert_eq!(uri, "src/utils.ts");
320    }
321
322    #[test]
323    fn relative_uri_encodes_brackets() {
324        let root = PathBuf::from("/project");
325        let path = root.join("src/app/[...slug]/page.tsx");
326        let uri = relative_uri(&path, &root);
327        assert_eq!(uri, "src/app/%5B...slug%5D/page.tsx");
328    }
329
330    #[test]
331    fn relative_uri_encodes_nested_dynamic_routes() {
332        let root = PathBuf::from("/project");
333        let path = root.join("src/app/[slug]/[id]/page.tsx");
334        let uri = relative_uri(&path, &root);
335        assert_eq!(uri, "src/app/%5Bslug%5D/%5Bid%5D/page.tsx");
336    }
337
338    #[test]
339    fn relative_uri_no_common_prefix_returns_full() {
340        let root = PathBuf::from("/other");
341        let path = PathBuf::from("/project/src/utils.ts");
342        let uri = relative_uri(&path, &root);
343        assert!(uri.contains("project"));
344        assert!(uri.contains("utils.ts"));
345    }
346
347    // ── severity_to_level ────────────────────────────────────────────
348
349    #[test]
350    fn severity_error_maps_to_level_error() {
351        assert!(matches!(severity_to_level(Severity::Error), Level::Error));
352    }
353
354    #[test]
355    fn severity_warn_maps_to_level_warn() {
356        assert!(matches!(severity_to_level(Severity::Warn), Level::Warn));
357    }
358
359    #[test]
360    fn severity_off_maps_to_level_info() {
361        assert!(matches!(severity_to_level(Severity::Off), Level::Info));
362    }
363
364    // ── normalize_uri bracket encoding ──────────────────────────────
365
366    #[test]
367    fn normalize_uri_single_bracket_pair() {
368        assert_eq!(normalize_uri("app/[id]/page.tsx"), "app/%5Bid%5D/page.tsx");
369    }
370
371    #[test]
372    fn normalize_uri_catch_all_route() {
373        assert_eq!(
374            normalize_uri("app/[...slug]/page.tsx"),
375            "app/%5B...slug%5D/page.tsx"
376        );
377    }
378
379    #[test]
380    fn normalize_uri_optional_catch_all_route() {
381        assert_eq!(
382            normalize_uri("app/[[...slug]]/page.tsx"),
383            "app/%5B%5B...slug%5D%5D/page.tsx"
384        );
385    }
386
387    #[test]
388    fn normalize_uri_multiple_dynamic_segments() {
389        assert_eq!(
390            normalize_uri("app/[lang]/posts/[id]"),
391            "app/%5Blang%5D/posts/%5Bid%5D"
392        );
393    }
394
395    #[test]
396    fn normalize_uri_no_special_chars() {
397        let plain = "src/components/Button.tsx";
398        assert_eq!(normalize_uri(plain), plain);
399    }
400
401    #[test]
402    fn normalize_uri_only_backslashes() {
403        assert_eq!(normalize_uri("a\\b\\c"), "a/b/c");
404    }
405
406    // ── relative_path edge cases ────────────────────────────────────
407
408    #[test]
409    fn relative_path_identical_paths_returns_empty() {
410        let root = Path::new("/project");
411        assert_eq!(relative_path(root, root), Path::new(""));
412    }
413
414    #[test]
415    fn relative_path_partial_name_match_not_stripped() {
416        // "/project-two/src/a.ts" should NOT strip "/project" because
417        // "/project" is not a proper prefix of "/project-two".
418        let root = Path::new("/project");
419        let path = Path::new("/project-two/src/a.ts");
420        assert_eq!(relative_path(path, root), path);
421    }
422
423    // ── relative_uri edge cases ─────────────────────────────────────
424
425    #[test]
426    fn relative_uri_combines_stripping_and_encoding() {
427        let root = PathBuf::from("/project");
428        let path = root.join("src/app/[slug]/page.tsx");
429        let uri = relative_uri(&path, &root);
430        // Should both strip the prefix AND encode brackets.
431        assert_eq!(uri, "src/app/%5Bslug%5D/page.tsx");
432        assert!(!uri.starts_with('/'));
433    }
434
435    #[test]
436    fn relative_uri_at_root_file() {
437        let root = PathBuf::from("/project");
438        let path = root.join("index.ts");
439        assert_eq!(relative_uri(&path, &root), "index.ts");
440    }
441
442    // ── severity_to_level exhaustiveness ────────────────────────────
443
444    #[test]
445    fn severity_to_level_is_const_evaluable() {
446        // Verify the function can be used in const context.
447        const LEVEL_FROM_ERROR: Level = severity_to_level(Severity::Error);
448        const LEVEL_FROM_WARN: Level = severity_to_level(Severity::Warn);
449        const LEVEL_FROM_OFF: Level = severity_to_level(Severity::Off);
450        assert!(matches!(LEVEL_FROM_ERROR, Level::Error));
451        assert!(matches!(LEVEL_FROM_WARN, Level::Warn));
452        assert!(matches!(LEVEL_FROM_OFF, Level::Info));
453    }
454
455    // ── Level is Copy ───────────────────────────────────────────────
456
457    #[test]
458    fn level_is_copy() {
459        let level = severity_to_level(Severity::Error);
460        let copy = level;
461        // Both should still be usable (Copy semantics).
462        assert!(matches!(level, Level::Error));
463        assert!(matches!(copy, Level::Error));
464    }
465
466    // ── elide_common_prefix ─────────────────────────────────────────
467
468    #[test]
469    fn elide_common_prefix_shared_dir() {
470        assert_eq!(
471            elide_common_prefix("src/components/A.tsx", "src/components/B.tsx"),
472            "B.tsx"
473        );
474    }
475
476    #[test]
477    fn elide_common_prefix_partial_shared() {
478        assert_eq!(
479            elide_common_prefix("src/components/A.tsx", "src/utils/B.tsx"),
480            "utils/B.tsx"
481        );
482    }
483
484    #[test]
485    fn elide_common_prefix_no_shared() {
486        assert_eq!(
487            elide_common_prefix("pkg-a/src/A.tsx", "pkg-b/src/B.tsx"),
488            "pkg-b/src/B.tsx"
489        );
490    }
491
492    #[test]
493    fn elide_common_prefix_identical_files() {
494        // Same dir, different file
495        assert_eq!(elide_common_prefix("a/b/x.ts", "a/b/y.ts"), "y.ts");
496    }
497
498    #[test]
499    fn elide_common_prefix_no_dirs() {
500        assert_eq!(elide_common_prefix("foo.ts", "bar.ts"), "bar.ts");
501    }
502
503    #[test]
504    fn elide_common_prefix_deep_monorepo() {
505        assert_eq!(
506            elide_common_prefix(
507                "packages/rap/src/rap/components/SearchSelect/SearchSelect.tsx",
508                "packages/rap/src/rap/components/SearchSelect/SearchSelectItem.tsx"
509            ),
510            "SearchSelectItem.tsx"
511        );
512    }
513}