1mod badge;
2mod codeclimate;
3mod compact;
4mod human;
5mod json;
6mod markdown;
7mod sarif;
8#[cfg(test)]
9mod test_helpers;
10
11use std::path::Path;
12use std::process::ExitCode;
13use std::time::Duration;
14
15use fallow_config::{OutputFormat, RulesConfig, Severity};
16use fallow_core::duplicates::DuplicationReport;
17use fallow_core::results::AnalysisResults;
18use fallow_core::trace::{CloneTrace, DependencyTrace, ExportTrace, FileTrace, PipelineTimings};
19
20pub struct ReportContext<'a> {
25 pub root: &'a Path,
26 pub rules: &'a RulesConfig,
27 pub elapsed: Duration,
28 pub quiet: bool,
29 pub explain: bool,
30}
31
32#[must_use]
34pub fn relative_path<'a>(path: &'a Path, root: &Path) -> &'a Path {
35 path.strip_prefix(root).unwrap_or(path)
36}
37
38#[must_use]
41pub fn split_dir_filename(path: &str) -> (&str, &str) {
42 path.rfind('/')
43 .map_or(("", path), |pos| (&path[..=pos], &path[pos + 1..]))
44}
45
46#[must_use]
48pub const fn plural(n: usize) -> &'static str {
49 if n == 1 { "" } else { "s" }
50}
51
52#[must_use]
57pub fn emit_json(value: &serde_json::Value, kind: &str) -> ExitCode {
58 match serde_json::to_string_pretty(value) {
59 Ok(json) => {
60 println!("{json}");
61 ExitCode::SUCCESS
62 }
63 Err(e) => {
64 eprintln!("Error: failed to serialize {kind} output: {e}");
65 ExitCode::from(2)
66 }
67 }
68}
69
70#[must_use]
76pub fn elide_common_prefix<'a>(base: &str, target: &'a str) -> &'a str {
77 let mut last_sep = 0;
78 for (i, (a, b)) in base.bytes().zip(target.bytes()).enumerate() {
79 if a != b {
80 break;
81 }
82 if a == b'/' {
83 last_sep = i + 1;
84 }
85 }
86 if last_sep > 0 && last_sep <= target.len() {
87 &target[last_sep..]
88 } else {
89 target
90 }
91}
92
93fn relative_uri(path: &Path, root: &Path) -> String {
95 normalize_uri(&relative_path(path, root).display().to_string())
96}
97
98#[must_use]
103pub fn normalize_uri(path_str: &str) -> String {
104 path_str
105 .replace('\\', "/")
106 .replace('[', "%5B")
107 .replace(']', "%5D")
108}
109
110#[derive(Clone, Copy, Debug)]
112pub enum Level {
113 Warn,
114 Info,
115 Error,
116}
117
118#[must_use]
119pub const fn severity_to_level(s: Severity) -> Level {
120 match s {
121 Severity::Error => Level::Error,
122 Severity::Warn => Level::Warn,
123 Severity::Off => Level::Info,
125 }
126}
127
128#[must_use]
133pub fn print_results(
134 results: &AnalysisResults,
135 ctx: &ReportContext<'_>,
136 output: OutputFormat,
137 regression: Option<&crate::regression::RegressionOutcome>,
138) -> ExitCode {
139 match output {
140 OutputFormat::Human => {
141 human::print_human(results, ctx.root, ctx.rules, ctx.elapsed, ctx.quiet);
142 ExitCode::SUCCESS
143 }
144 OutputFormat::Json => {
145 json::print_json(results, ctx.root, ctx.elapsed, ctx.explain, regression)
146 }
147 OutputFormat::Compact => {
148 compact::print_compact(results, ctx.root);
149 ExitCode::SUCCESS
150 }
151 OutputFormat::Sarif => sarif::print_sarif(results, ctx.root, ctx.rules),
152 OutputFormat::Markdown => {
153 markdown::print_markdown(results, ctx.root);
154 ExitCode::SUCCESS
155 }
156 OutputFormat::CodeClimate => codeclimate::print_codeclimate(results, ctx.root, ctx.rules),
157 OutputFormat::Badge => {
158 eprintln!("Error: badge format is only supported for the health command");
159 ExitCode::from(2)
160 }
161 }
162}
163
164#[must_use]
168pub fn print_duplication_report(
169 report: &DuplicationReport,
170 ctx: &ReportContext<'_>,
171 output: OutputFormat,
172) -> ExitCode {
173 match output {
174 OutputFormat::Human => {
175 human::print_duplication_human(report, ctx.root, ctx.elapsed, ctx.quiet);
176 ExitCode::SUCCESS
177 }
178 OutputFormat::Json => json::print_duplication_json(report, ctx.elapsed, ctx.explain),
179 OutputFormat::Compact => {
180 compact::print_duplication_compact(report, ctx.root);
181 ExitCode::SUCCESS
182 }
183 OutputFormat::Sarif => sarif::print_duplication_sarif(report, ctx.root),
184 OutputFormat::Markdown => {
185 markdown::print_duplication_markdown(report, ctx.root);
186 ExitCode::SUCCESS
187 }
188 OutputFormat::CodeClimate => codeclimate::print_duplication_codeclimate(report, ctx.root),
189 OutputFormat::Badge => {
190 eprintln!("Error: badge format is only supported for the health command");
191 ExitCode::from(2)
192 }
193 }
194}
195
196#[must_use]
200pub fn print_health_report(
201 report: &crate::health_types::HealthReport,
202 ctx: &ReportContext<'_>,
203 output: OutputFormat,
204) -> ExitCode {
205 match output {
206 OutputFormat::Human => {
207 human::print_health_human(report, ctx.root, ctx.elapsed, ctx.quiet);
208 ExitCode::SUCCESS
209 }
210 OutputFormat::Compact => {
211 compact::print_health_compact(report, ctx.root);
212 ExitCode::SUCCESS
213 }
214 OutputFormat::Markdown => {
215 markdown::print_health_markdown(report, ctx.root);
216 ExitCode::SUCCESS
217 }
218 OutputFormat::Sarif => sarif::print_health_sarif(report, ctx.root),
219 OutputFormat::Json => json::print_health_json(report, ctx.root, ctx.elapsed, ctx.explain),
220 OutputFormat::CodeClimate => codeclimate::print_health_codeclimate(report, ctx.root),
221 OutputFormat::Badge => badge::print_health_badge(report),
222 }
223}
224
225pub fn print_cross_reference_findings(
229 cross_ref: &fallow_core::cross_reference::CrossReferenceResult,
230 root: &Path,
231 quiet: bool,
232 output: OutputFormat,
233) {
234 human::print_cross_reference_findings(cross_ref, root, quiet, output);
235}
236
237pub fn print_export_trace(trace: &ExportTrace, format: OutputFormat) {
241 match format {
242 OutputFormat::Json => json::print_trace_json(trace),
243 _ => human::print_export_trace_human(trace),
244 }
245}
246
247pub fn print_file_trace(trace: &FileTrace, format: OutputFormat) {
249 match format {
250 OutputFormat::Json => json::print_trace_json(trace),
251 _ => human::print_file_trace_human(trace),
252 }
253}
254
255pub fn print_dependency_trace(trace: &DependencyTrace, format: OutputFormat) {
257 match format {
258 OutputFormat::Json => json::print_trace_json(trace),
259 _ => human::print_dependency_trace_human(trace),
260 }
261}
262
263pub fn print_clone_trace(trace: &CloneTrace, root: &Path, format: OutputFormat) {
265 match format {
266 OutputFormat::Json => json::print_trace_json(trace),
267 _ => human::print_clone_trace_human(trace, root),
268 }
269}
270
271pub fn print_performance(timings: &PipelineTimings, format: OutputFormat) {
274 match format {
275 OutputFormat::Json => match serde_json::to_string_pretty(timings) {
276 Ok(json) => eprintln!("{json}"),
277 Err(e) => eprintln!("Error: failed to serialize timings: {e}"),
278 },
279 _ => human::print_performance_human(timings),
280 }
281}
282
283#[allow(
286 unused_imports,
287 reason = "target-dependent: used in lib, unused in bin"
288)]
289pub use codeclimate::build_codeclimate;
290#[allow(
291 unused_imports,
292 reason = "target-dependent: used in lib, unused in bin"
293)]
294pub use codeclimate::build_duplication_codeclimate;
295#[allow(
296 unused_imports,
297 reason = "target-dependent: used in lib, unused in bin"
298)]
299pub use codeclimate::build_health_codeclimate;
300#[allow(
301 unused_imports,
302 reason = "target-dependent: used in lib, unused in bin"
303)]
304pub use compact::build_compact_lines;
305#[allow(
306 unused_imports,
307 reason = "target-dependent: used in lib, unused in bin"
308)]
309pub use json::build_json;
310#[allow(
311 unused_imports,
312 reason = "target-dependent: used in lib, unused in bin"
313)]
314pub use markdown::build_duplication_markdown;
315#[allow(
316 unused_imports,
317 reason = "target-dependent: used in lib, unused in bin"
318)]
319pub use markdown::build_health_markdown;
320#[allow(
321 unused_imports,
322 reason = "target-dependent: used in lib, unused in bin"
323)]
324pub use markdown::build_markdown;
325#[allow(
326 unused_imports,
327 reason = "target-dependent: used in lib, unused in bin"
328)]
329pub use sarif::build_health_sarif;
330#[allow(
331 unused_imports,
332 reason = "target-dependent: used in lib, unused in bin"
333)]
334pub use sarif::build_sarif;
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use std::path::PathBuf;
340
341 #[test]
344 fn normalize_uri_forward_slashes_unchanged() {
345 assert_eq!(normalize_uri("src/utils.ts"), "src/utils.ts");
346 }
347
348 #[test]
349 fn normalize_uri_backslashes_replaced() {
350 assert_eq!(normalize_uri("src\\utils\\index.ts"), "src/utils/index.ts");
351 }
352
353 #[test]
354 fn normalize_uri_mixed_slashes() {
355 assert_eq!(normalize_uri("src\\utils/index.ts"), "src/utils/index.ts");
356 }
357
358 #[test]
359 fn normalize_uri_path_with_spaces() {
360 assert_eq!(
361 normalize_uri("src\\my folder\\file.ts"),
362 "src/my folder/file.ts"
363 );
364 }
365
366 #[test]
367 fn normalize_uri_empty_string() {
368 assert_eq!(normalize_uri(""), "");
369 }
370
371 #[test]
374 fn relative_path_strips_root_prefix() {
375 let root = Path::new("/project");
376 let path = Path::new("/project/src/utils.ts");
377 assert_eq!(relative_path(path, root), Path::new("src/utils.ts"));
378 }
379
380 #[test]
381 fn relative_path_returns_full_path_when_no_prefix() {
382 let root = Path::new("/other");
383 let path = Path::new("/project/src/utils.ts");
384 assert_eq!(relative_path(path, root), path);
385 }
386
387 #[test]
388 fn relative_path_at_root_returns_empty_or_file() {
389 let root = Path::new("/project");
390 let path = Path::new("/project/file.ts");
391 assert_eq!(relative_path(path, root), Path::new("file.ts"));
392 }
393
394 #[test]
395 fn relative_path_deeply_nested() {
396 let root = Path::new("/project");
397 let path = Path::new("/project/packages/ui/src/components/Button.tsx");
398 assert_eq!(
399 relative_path(path, root),
400 Path::new("packages/ui/src/components/Button.tsx")
401 );
402 }
403
404 #[test]
407 fn relative_uri_produces_forward_slash_path() {
408 let root = PathBuf::from("/project");
409 let path = root.join("src").join("utils.ts");
410 let uri = relative_uri(&path, &root);
411 assert_eq!(uri, "src/utils.ts");
412 }
413
414 #[test]
415 fn relative_uri_encodes_brackets() {
416 let root = PathBuf::from("/project");
417 let path = root.join("src/app/[...slug]/page.tsx");
418 let uri = relative_uri(&path, &root);
419 assert_eq!(uri, "src/app/%5B...slug%5D/page.tsx");
420 }
421
422 #[test]
423 fn relative_uri_encodes_nested_dynamic_routes() {
424 let root = PathBuf::from("/project");
425 let path = root.join("src/app/[slug]/[id]/page.tsx");
426 let uri = relative_uri(&path, &root);
427 assert_eq!(uri, "src/app/%5Bslug%5D/%5Bid%5D/page.tsx");
428 }
429
430 #[test]
431 fn relative_uri_no_common_prefix_returns_full() {
432 let root = PathBuf::from("/other");
433 let path = PathBuf::from("/project/src/utils.ts");
434 let uri = relative_uri(&path, &root);
435 assert!(uri.contains("project"));
436 assert!(uri.contains("utils.ts"));
437 }
438
439 #[test]
442 fn severity_error_maps_to_level_error() {
443 assert!(matches!(severity_to_level(Severity::Error), Level::Error));
444 }
445
446 #[test]
447 fn severity_warn_maps_to_level_warn() {
448 assert!(matches!(severity_to_level(Severity::Warn), Level::Warn));
449 }
450
451 #[test]
452 fn severity_off_maps_to_level_info() {
453 assert!(matches!(severity_to_level(Severity::Off), Level::Info));
454 }
455
456 #[test]
459 fn normalize_uri_single_bracket_pair() {
460 assert_eq!(normalize_uri("app/[id]/page.tsx"), "app/%5Bid%5D/page.tsx");
461 }
462
463 #[test]
464 fn normalize_uri_catch_all_route() {
465 assert_eq!(
466 normalize_uri("app/[...slug]/page.tsx"),
467 "app/%5B...slug%5D/page.tsx"
468 );
469 }
470
471 #[test]
472 fn normalize_uri_optional_catch_all_route() {
473 assert_eq!(
474 normalize_uri("app/[[...slug]]/page.tsx"),
475 "app/%5B%5B...slug%5D%5D/page.tsx"
476 );
477 }
478
479 #[test]
480 fn normalize_uri_multiple_dynamic_segments() {
481 assert_eq!(
482 normalize_uri("app/[lang]/posts/[id]"),
483 "app/%5Blang%5D/posts/%5Bid%5D"
484 );
485 }
486
487 #[test]
488 fn normalize_uri_no_special_chars() {
489 let plain = "src/components/Button.tsx";
490 assert_eq!(normalize_uri(plain), plain);
491 }
492
493 #[test]
494 fn normalize_uri_only_backslashes() {
495 assert_eq!(normalize_uri("a\\b\\c"), "a/b/c");
496 }
497
498 #[test]
501 fn relative_path_identical_paths_returns_empty() {
502 let root = Path::new("/project");
503 assert_eq!(relative_path(root, root), Path::new(""));
504 }
505
506 #[test]
507 fn relative_path_partial_name_match_not_stripped() {
508 let root = Path::new("/project");
511 let path = Path::new("/project-two/src/a.ts");
512 assert_eq!(relative_path(path, root), path);
513 }
514
515 #[test]
518 fn relative_uri_combines_stripping_and_encoding() {
519 let root = PathBuf::from("/project");
520 let path = root.join("src/app/[slug]/page.tsx");
521 let uri = relative_uri(&path, &root);
522 assert_eq!(uri, "src/app/%5Bslug%5D/page.tsx");
524 assert!(!uri.starts_with('/'));
525 }
526
527 #[test]
528 fn relative_uri_at_root_file() {
529 let root = PathBuf::from("/project");
530 let path = root.join("index.ts");
531 assert_eq!(relative_uri(&path, &root), "index.ts");
532 }
533
534 #[test]
537 fn severity_to_level_is_const_evaluable() {
538 const LEVEL_FROM_ERROR: Level = severity_to_level(Severity::Error);
540 const LEVEL_FROM_WARN: Level = severity_to_level(Severity::Warn);
541 const LEVEL_FROM_OFF: Level = severity_to_level(Severity::Off);
542 assert!(matches!(LEVEL_FROM_ERROR, Level::Error));
543 assert!(matches!(LEVEL_FROM_WARN, Level::Warn));
544 assert!(matches!(LEVEL_FROM_OFF, Level::Info));
545 }
546
547 #[test]
550 fn level_is_copy() {
551 let level = severity_to_level(Severity::Error);
552 let copy = level;
553 assert!(matches!(level, Level::Error));
555 assert!(matches!(copy, Level::Error));
556 }
557
558 #[test]
561 fn elide_common_prefix_shared_dir() {
562 assert_eq!(
563 elide_common_prefix("src/components/A.tsx", "src/components/B.tsx"),
564 "B.tsx"
565 );
566 }
567
568 #[test]
569 fn elide_common_prefix_partial_shared() {
570 assert_eq!(
571 elide_common_prefix("src/components/A.tsx", "src/utils/B.tsx"),
572 "utils/B.tsx"
573 );
574 }
575
576 #[test]
577 fn elide_common_prefix_no_shared() {
578 assert_eq!(
579 elide_common_prefix("pkg-a/src/A.tsx", "pkg-b/src/B.tsx"),
580 "pkg-b/src/B.tsx"
581 );
582 }
583
584 #[test]
585 fn elide_common_prefix_identical_files() {
586 assert_eq!(elide_common_prefix("a/b/x.ts", "a/b/y.ts"), "y.ts");
588 }
589
590 #[test]
591 fn elide_common_prefix_no_dirs() {
592 assert_eq!(elide_common_prefix("foo.ts", "bar.ts"), "bar.ts");
593 }
594
595 #[test]
596 fn elide_common_prefix_deep_monorepo() {
597 assert_eq!(
598 elide_common_prefix(
599 "packages/rap/src/rap/components/SearchSelect/SearchSelect.tsx",
600 "packages/rap/src/rap/components/SearchSelect/SearchSelectItem.tsx"
601 ),
602 "SearchSelectItem.tsx"
603 );
604 }
605
606 #[test]
609 fn split_dir_filename_with_dir() {
610 let (dir, file) = split_dir_filename("src/utils/index.ts");
611 assert_eq!(dir, "src/utils/");
612 assert_eq!(file, "index.ts");
613 }
614
615 #[test]
616 fn split_dir_filename_no_dir() {
617 let (dir, file) = split_dir_filename("file.ts");
618 assert_eq!(dir, "");
619 assert_eq!(file, "file.ts");
620 }
621
622 #[test]
623 fn split_dir_filename_deeply_nested() {
624 let (dir, file) = split_dir_filename("a/b/c/d/e.ts");
625 assert_eq!(dir, "a/b/c/d/");
626 assert_eq!(file, "e.ts");
627 }
628
629 #[test]
630 fn split_dir_filename_trailing_slash() {
631 let (dir, file) = split_dir_filename("src/");
632 assert_eq!(dir, "src/");
633 assert_eq!(file, "");
634 }
635
636 #[test]
637 fn split_dir_filename_empty() {
638 let (dir, file) = split_dir_filename("");
639 assert_eq!(dir, "");
640 assert_eq!(file, "");
641 }
642
643 #[test]
646 fn plural_zero_is_plural() {
647 assert_eq!(plural(0), "s");
648 }
649
650 #[test]
651 fn plural_one_is_singular() {
652 assert_eq!(plural(1), "");
653 }
654
655 #[test]
656 fn plural_two_is_plural() {
657 assert_eq!(plural(2), "s");
658 }
659
660 #[test]
661 fn plural_large_number() {
662 assert_eq!(plural(999), "s");
663 }
664
665 #[test]
668 fn elide_common_prefix_empty_base() {
669 assert_eq!(elide_common_prefix("", "src/foo.ts"), "src/foo.ts");
670 }
671
672 #[test]
673 fn elide_common_prefix_empty_target() {
674 assert_eq!(elide_common_prefix("src/foo.ts", ""), "");
675 }
676
677 #[test]
678 fn elide_common_prefix_both_empty() {
679 assert_eq!(elide_common_prefix("", ""), "");
680 }
681
682 #[test]
683 fn elide_common_prefix_same_file_different_extension() {
684 assert_eq!(
686 elide_common_prefix("src/utils.ts", "src/utils.js"),
687 "utils.js"
688 );
689 }
690
691 #[test]
692 fn elide_common_prefix_partial_filename_match_not_stripped() {
693 assert_eq!(
695 elide_common_prefix("src/App.tsx", "src/AppUtils.tsx"),
696 "AppUtils.tsx"
697 );
698 }
699
700 #[test]
701 fn elide_common_prefix_identical_paths() {
702 assert_eq!(elide_common_prefix("src/foo.ts", "src/foo.ts"), "foo.ts");
703 }
704
705 #[test]
706 fn split_dir_filename_single_slash() {
707 let (dir, file) = split_dir_filename("/file.ts");
708 assert_eq!(dir, "/");
709 assert_eq!(file, "file.ts");
710 }
711
712 #[test]
713 fn emit_json_returns_success_for_valid_value() {
714 let value = serde_json::json!({"key": "value"});
715 let code = emit_json(&value, "test");
716 assert_eq!(code, ExitCode::SUCCESS);
717 }
718
719 mod proptests {
720 use super::*;
721 use proptest::prelude::*;
722
723 proptest! {
724 #[test]
726 fn split_dir_filename_reconstructs_path(path in "[a-zA-Z0-9_./\\-]{0,100}") {
727 let (dir, file) = split_dir_filename(&path);
728 let reconstructed = format!("{dir}{file}");
729 prop_assert_eq!(
730 reconstructed, path,
731 "dir+file should reconstruct the original path"
732 );
733 }
734
735 #[test]
737 fn plural_returns_empty_or_s(n: usize) {
738 let result = plural(n);
739 prop_assert!(
740 result.is_empty() || result == "s",
741 "plural should return \"\" or \"s\", got {:?}",
742 result
743 );
744 }
745
746 #[test]
748 fn plural_singular_only_for_one(n: usize) {
749 let result = plural(n);
750 if n == 1 {
751 prop_assert_eq!(result, "", "plural(1) should be empty");
752 } else {
753 prop_assert_eq!(result, "s", "plural({}) should be \"s\"", n);
754 }
755 }
756
757 #[test]
759 fn normalize_uri_no_backslashes(path in "[a-zA-Z0-9_.\\\\/ \\[\\]%-]{0,100}") {
760 let result = normalize_uri(&path);
761 prop_assert!(
762 !result.contains('\\'),
763 "Result should not contain backslashes: {result}"
764 );
765 }
766
767 #[test]
769 fn normalize_uri_encodes_all_brackets(path in "[a-zA-Z0-9_./\\[\\]%-]{0,80}") {
770 let result = normalize_uri(&path);
771 prop_assert!(
772 !result.contains('[') && !result.contains(']'),
773 "Result should not contain raw brackets: {result}"
774 );
775 }
776
777 #[test]
779 fn elide_common_prefix_returns_suffix_of_target(
780 base in "[a-zA-Z0-9_./]{0,50}",
781 target in "[a-zA-Z0-9_./]{0,50}",
782 ) {
783 let result = elide_common_prefix(&base, &target);
784 prop_assert!(
785 target.ends_with(result),
786 "Result {:?} should be a suffix of target {:?}",
787 result, target
788 );
789 }
790
791 #[test]
793 fn relative_path_never_panics(
794 root in "/[a-zA-Z0-9_/]{0,30}",
795 suffix in "[a-zA-Z0-9_./]{0,30}",
796 ) {
797 let root_path = Path::new(&root);
798 let full = PathBuf::from(format!("{root}/{suffix}"));
799 let _ = relative_path(&full, root_path);
800 }
801 }
802 }
803}