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(unused_imports)]
287pub use codeclimate::build_codeclimate;
288#[allow(unused_imports)]
289pub use codeclimate::build_duplication_codeclimate;
290#[allow(unused_imports)]
291pub use codeclimate::build_health_codeclimate;
292#[allow(unused_imports)]
293pub use compact::build_compact_lines;
294#[allow(unused_imports)]
295pub use json::build_json;
296#[allow(unused_imports)]
297pub use markdown::build_duplication_markdown;
298#[allow(unused_imports)]
299pub use markdown::build_health_markdown;
300#[allow(unused_imports)]
301pub use markdown::build_markdown;
302#[allow(unused_imports)]
303pub use sarif::build_health_sarif;
304#[allow(unused_imports)]
305pub use sarif::build_sarif;
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use std::path::PathBuf;
311
312 #[test]
315 fn normalize_uri_forward_slashes_unchanged() {
316 assert_eq!(normalize_uri("src/utils.ts"), "src/utils.ts");
317 }
318
319 #[test]
320 fn normalize_uri_backslashes_replaced() {
321 assert_eq!(normalize_uri("src\\utils\\index.ts"), "src/utils/index.ts");
322 }
323
324 #[test]
325 fn normalize_uri_mixed_slashes() {
326 assert_eq!(normalize_uri("src\\utils/index.ts"), "src/utils/index.ts");
327 }
328
329 #[test]
330 fn normalize_uri_path_with_spaces() {
331 assert_eq!(
332 normalize_uri("src\\my folder\\file.ts"),
333 "src/my folder/file.ts"
334 );
335 }
336
337 #[test]
338 fn normalize_uri_empty_string() {
339 assert_eq!(normalize_uri(""), "");
340 }
341
342 #[test]
345 fn relative_path_strips_root_prefix() {
346 let root = Path::new("/project");
347 let path = Path::new("/project/src/utils.ts");
348 assert_eq!(relative_path(path, root), Path::new("src/utils.ts"));
349 }
350
351 #[test]
352 fn relative_path_returns_full_path_when_no_prefix() {
353 let root = Path::new("/other");
354 let path = Path::new("/project/src/utils.ts");
355 assert_eq!(relative_path(path, root), path);
356 }
357
358 #[test]
359 fn relative_path_at_root_returns_empty_or_file() {
360 let root = Path::new("/project");
361 let path = Path::new("/project/file.ts");
362 assert_eq!(relative_path(path, root), Path::new("file.ts"));
363 }
364
365 #[test]
366 fn relative_path_deeply_nested() {
367 let root = Path::new("/project");
368 let path = Path::new("/project/packages/ui/src/components/Button.tsx");
369 assert_eq!(
370 relative_path(path, root),
371 Path::new("packages/ui/src/components/Button.tsx")
372 );
373 }
374
375 #[test]
378 fn relative_uri_produces_forward_slash_path() {
379 let root = PathBuf::from("/project");
380 let path = root.join("src").join("utils.ts");
381 let uri = relative_uri(&path, &root);
382 assert_eq!(uri, "src/utils.ts");
383 }
384
385 #[test]
386 fn relative_uri_encodes_brackets() {
387 let root = PathBuf::from("/project");
388 let path = root.join("src/app/[...slug]/page.tsx");
389 let uri = relative_uri(&path, &root);
390 assert_eq!(uri, "src/app/%5B...slug%5D/page.tsx");
391 }
392
393 #[test]
394 fn relative_uri_encodes_nested_dynamic_routes() {
395 let root = PathBuf::from("/project");
396 let path = root.join("src/app/[slug]/[id]/page.tsx");
397 let uri = relative_uri(&path, &root);
398 assert_eq!(uri, "src/app/%5Bslug%5D/%5Bid%5D/page.tsx");
399 }
400
401 #[test]
402 fn relative_uri_no_common_prefix_returns_full() {
403 let root = PathBuf::from("/other");
404 let path = PathBuf::from("/project/src/utils.ts");
405 let uri = relative_uri(&path, &root);
406 assert!(uri.contains("project"));
407 assert!(uri.contains("utils.ts"));
408 }
409
410 #[test]
413 fn severity_error_maps_to_level_error() {
414 assert!(matches!(severity_to_level(Severity::Error), Level::Error));
415 }
416
417 #[test]
418 fn severity_warn_maps_to_level_warn() {
419 assert!(matches!(severity_to_level(Severity::Warn), Level::Warn));
420 }
421
422 #[test]
423 fn severity_off_maps_to_level_info() {
424 assert!(matches!(severity_to_level(Severity::Off), Level::Info));
425 }
426
427 #[test]
430 fn normalize_uri_single_bracket_pair() {
431 assert_eq!(normalize_uri("app/[id]/page.tsx"), "app/%5Bid%5D/page.tsx");
432 }
433
434 #[test]
435 fn normalize_uri_catch_all_route() {
436 assert_eq!(
437 normalize_uri("app/[...slug]/page.tsx"),
438 "app/%5B...slug%5D/page.tsx"
439 );
440 }
441
442 #[test]
443 fn normalize_uri_optional_catch_all_route() {
444 assert_eq!(
445 normalize_uri("app/[[...slug]]/page.tsx"),
446 "app/%5B%5B...slug%5D%5D/page.tsx"
447 );
448 }
449
450 #[test]
451 fn normalize_uri_multiple_dynamic_segments() {
452 assert_eq!(
453 normalize_uri("app/[lang]/posts/[id]"),
454 "app/%5Blang%5D/posts/%5Bid%5D"
455 );
456 }
457
458 #[test]
459 fn normalize_uri_no_special_chars() {
460 let plain = "src/components/Button.tsx";
461 assert_eq!(normalize_uri(plain), plain);
462 }
463
464 #[test]
465 fn normalize_uri_only_backslashes() {
466 assert_eq!(normalize_uri("a\\b\\c"), "a/b/c");
467 }
468
469 #[test]
472 fn relative_path_identical_paths_returns_empty() {
473 let root = Path::new("/project");
474 assert_eq!(relative_path(root, root), Path::new(""));
475 }
476
477 #[test]
478 fn relative_path_partial_name_match_not_stripped() {
479 let root = Path::new("/project");
482 let path = Path::new("/project-two/src/a.ts");
483 assert_eq!(relative_path(path, root), path);
484 }
485
486 #[test]
489 fn relative_uri_combines_stripping_and_encoding() {
490 let root = PathBuf::from("/project");
491 let path = root.join("src/app/[slug]/page.tsx");
492 let uri = relative_uri(&path, &root);
493 assert_eq!(uri, "src/app/%5Bslug%5D/page.tsx");
495 assert!(!uri.starts_with('/'));
496 }
497
498 #[test]
499 fn relative_uri_at_root_file() {
500 let root = PathBuf::from("/project");
501 let path = root.join("index.ts");
502 assert_eq!(relative_uri(&path, &root), "index.ts");
503 }
504
505 #[test]
508 fn severity_to_level_is_const_evaluable() {
509 const LEVEL_FROM_ERROR: Level = severity_to_level(Severity::Error);
511 const LEVEL_FROM_WARN: Level = severity_to_level(Severity::Warn);
512 const LEVEL_FROM_OFF: Level = severity_to_level(Severity::Off);
513 assert!(matches!(LEVEL_FROM_ERROR, Level::Error));
514 assert!(matches!(LEVEL_FROM_WARN, Level::Warn));
515 assert!(matches!(LEVEL_FROM_OFF, Level::Info));
516 }
517
518 #[test]
521 fn level_is_copy() {
522 let level = severity_to_level(Severity::Error);
523 let copy = level;
524 assert!(matches!(level, Level::Error));
526 assert!(matches!(copy, Level::Error));
527 }
528
529 #[test]
532 fn elide_common_prefix_shared_dir() {
533 assert_eq!(
534 elide_common_prefix("src/components/A.tsx", "src/components/B.tsx"),
535 "B.tsx"
536 );
537 }
538
539 #[test]
540 fn elide_common_prefix_partial_shared() {
541 assert_eq!(
542 elide_common_prefix("src/components/A.tsx", "src/utils/B.tsx"),
543 "utils/B.tsx"
544 );
545 }
546
547 #[test]
548 fn elide_common_prefix_no_shared() {
549 assert_eq!(
550 elide_common_prefix("pkg-a/src/A.tsx", "pkg-b/src/B.tsx"),
551 "pkg-b/src/B.tsx"
552 );
553 }
554
555 #[test]
556 fn elide_common_prefix_identical_files() {
557 assert_eq!(elide_common_prefix("a/b/x.ts", "a/b/y.ts"), "y.ts");
559 }
560
561 #[test]
562 fn elide_common_prefix_no_dirs() {
563 assert_eq!(elide_common_prefix("foo.ts", "bar.ts"), "bar.ts");
564 }
565
566 #[test]
567 fn elide_common_prefix_deep_monorepo() {
568 assert_eq!(
569 elide_common_prefix(
570 "packages/rap/src/rap/components/SearchSelect/SearchSelect.tsx",
571 "packages/rap/src/rap/components/SearchSelect/SearchSelectItem.tsx"
572 ),
573 "SearchSelectItem.tsx"
574 );
575 }
576
577 #[test]
580 fn split_dir_filename_with_dir() {
581 let (dir, file) = split_dir_filename("src/utils/index.ts");
582 assert_eq!(dir, "src/utils/");
583 assert_eq!(file, "index.ts");
584 }
585
586 #[test]
587 fn split_dir_filename_no_dir() {
588 let (dir, file) = split_dir_filename("file.ts");
589 assert_eq!(dir, "");
590 assert_eq!(file, "file.ts");
591 }
592
593 #[test]
594 fn split_dir_filename_deeply_nested() {
595 let (dir, file) = split_dir_filename("a/b/c/d/e.ts");
596 assert_eq!(dir, "a/b/c/d/");
597 assert_eq!(file, "e.ts");
598 }
599
600 #[test]
601 fn split_dir_filename_trailing_slash() {
602 let (dir, file) = split_dir_filename("src/");
603 assert_eq!(dir, "src/");
604 assert_eq!(file, "");
605 }
606
607 #[test]
608 fn split_dir_filename_empty() {
609 let (dir, file) = split_dir_filename("");
610 assert_eq!(dir, "");
611 assert_eq!(file, "");
612 }
613
614 #[test]
617 fn plural_zero_is_plural() {
618 assert_eq!(plural(0), "s");
619 }
620
621 #[test]
622 fn plural_one_is_singular() {
623 assert_eq!(plural(1), "");
624 }
625
626 #[test]
627 fn plural_two_is_plural() {
628 assert_eq!(plural(2), "s");
629 }
630
631 #[test]
632 fn plural_large_number() {
633 assert_eq!(plural(999), "s");
634 }
635
636 #[test]
639 fn elide_common_prefix_empty_base() {
640 assert_eq!(elide_common_prefix("", "src/foo.ts"), "src/foo.ts");
641 }
642
643 #[test]
644 fn elide_common_prefix_empty_target() {
645 assert_eq!(elide_common_prefix("src/foo.ts", ""), "");
646 }
647
648 #[test]
649 fn elide_common_prefix_both_empty() {
650 assert_eq!(elide_common_prefix("", ""), "");
651 }
652
653 #[test]
654 fn elide_common_prefix_same_file_different_extension() {
655 assert_eq!(
657 elide_common_prefix("src/utils.ts", "src/utils.js"),
658 "utils.js"
659 );
660 }
661
662 #[test]
663 fn elide_common_prefix_partial_filename_match_not_stripped() {
664 assert_eq!(
666 elide_common_prefix("src/App.tsx", "src/AppUtils.tsx"),
667 "AppUtils.tsx"
668 );
669 }
670
671 #[test]
672 fn elide_common_prefix_identical_paths() {
673 assert_eq!(elide_common_prefix("src/foo.ts", "src/foo.ts"), "foo.ts");
674 }
675
676 #[test]
677 fn split_dir_filename_single_slash() {
678 let (dir, file) = split_dir_filename("/file.ts");
679 assert_eq!(dir, "/");
680 assert_eq!(file, "file.ts");
681 }
682
683 #[test]
684 fn emit_json_returns_success_for_valid_value() {
685 let value = serde_json::json!({"key": "value"});
686 let code = emit_json(&value, "test");
687 assert_eq!(code, ExitCode::SUCCESS);
688 }
689
690 mod proptests {
691 use super::*;
692 use proptest::prelude::*;
693
694 proptest! {
695 #[test]
697 fn split_dir_filename_reconstructs_path(path in "[a-zA-Z0-9_./\\-]{0,100}") {
698 let (dir, file) = split_dir_filename(&path);
699 let reconstructed = format!("{dir}{file}");
700 prop_assert_eq!(
701 reconstructed, path,
702 "dir+file should reconstruct the original path"
703 );
704 }
705
706 #[test]
708 fn plural_returns_empty_or_s(n: usize) {
709 let result = plural(n);
710 prop_assert!(
711 result.is_empty() || result == "s",
712 "plural should return \"\" or \"s\", got {:?}",
713 result
714 );
715 }
716
717 #[test]
719 fn plural_singular_only_for_one(n: usize) {
720 let result = plural(n);
721 if n == 1 {
722 prop_assert_eq!(result, "", "plural(1) should be empty");
723 } else {
724 prop_assert_eq!(result, "s", "plural({}) should be \"s\"", n);
725 }
726 }
727
728 #[test]
730 fn normalize_uri_no_backslashes(path in "[a-zA-Z0-9_.\\\\/ \\[\\]%-]{0,100}") {
731 let result = normalize_uri(&path);
732 prop_assert!(
733 !result.contains('\\'),
734 "Result should not contain backslashes: {result}"
735 );
736 }
737
738 #[test]
740 fn normalize_uri_encodes_all_brackets(path in "[a-zA-Z0-9_./\\[\\]%-]{0,80}") {
741 let result = normalize_uri(&path);
742 prop_assert!(
743 !result.contains('[') && !result.contains(']'),
744 "Result should not contain raw brackets: {result}"
745 );
746 }
747
748 #[test]
750 fn elide_common_prefix_returns_suffix_of_target(
751 base in "[a-zA-Z0-9_./]{0,50}",
752 target in "[a-zA-Z0-9_./]{0,50}",
753 ) {
754 let result = elide_common_prefix(&base, &target);
755 prop_assert!(
756 target.ends_with(result),
757 "Result {:?} should be a suffix of target {:?}",
758 result, target
759 );
760 }
761
762 #[test]
764 fn relative_path_never_panics(
765 root in "/[a-zA-Z0-9_/]{0,30}",
766 suffix in "[a-zA-Z0-9_./]{0,30}",
767 ) {
768 let root_path = Path::new(&root);
769 let full = PathBuf::from(format!("{root}/{suffix}"));
770 let _ = relative_path(&full, root_path);
771 }
772 }
773 }
774}