Skip to main content

fallow_cli/report/
mod.rs

1mod badge;
2mod codeclimate;
3mod compact;
4pub mod grouping;
5mod human;
6mod json;
7mod markdown;
8mod sarif;
9#[cfg(test)]
10mod test_helpers;
11
12use std::path::Path;
13use std::process::ExitCode;
14use std::time::Duration;
15
16use fallow_config::{OutputFormat, RulesConfig, Severity};
17use fallow_core::duplicates::DuplicationReport;
18use fallow_core::results::AnalysisResults;
19use fallow_core::trace::{CloneTrace, DependencyTrace, ExportTrace, FileTrace, PipelineTimings};
20
21pub use grouping::OwnershipResolver;
22#[allow(
23    unused_imports,
24    reason = "used by binary crate modules (combined.rs, audit.rs)"
25)]
26pub use json::strip_root_prefix;
27
28/// Shared context for all report dispatch functions.
29///
30/// Bundles the common parameters that every format renderer needs,
31/// replacing per-parameter threading through the dispatch match arms.
32pub struct ReportContext<'a> {
33    pub root: &'a Path,
34    pub rules: &'a RulesConfig,
35    pub elapsed: Duration,
36    pub quiet: bool,
37    pub explain: bool,
38    /// When set, group all output by this resolver.
39    pub group_by: Option<OwnershipResolver>,
40    /// Limit displayed items per section (--top N).
41    pub top: Option<usize>,
42    /// When set, print a concise summary instead of the full report.
43    pub summary: bool,
44    /// When a baseline was loaded: (total entries in baseline, entries that matched).
45    pub baseline_matched: Option<(usize, usize)>,
46}
47
48/// Strip the project root prefix from a path for display, falling back to the full path.
49#[must_use]
50pub fn relative_path<'a>(path: &'a Path, root: &Path) -> &'a Path {
51    path.strip_prefix(root).unwrap_or(path)
52}
53
54/// Split a path string into (directory, filename) for display.
55/// Directory includes the trailing `/`. If no directory, returns `("", filename)`.
56#[must_use]
57pub fn split_dir_filename(path: &str) -> (&str, &str) {
58    path.rfind('/')
59        .map_or(("", path), |pos| (&path[..=pos], &path[pos + 1..]))
60}
61
62/// Return `"s"` for plural or `""` for singular.
63#[must_use]
64pub const fn plural(n: usize) -> &'static str {
65    if n == 1 { "" } else { "s" }
66}
67
68/// Serialize a JSON value to pretty-printed stdout, returning the appropriate exit code.
69///
70/// On success prints the JSON and returns `ExitCode::SUCCESS`.
71/// On serialization failure prints an error to stderr and returns exit code 2.
72#[must_use]
73pub fn emit_json(value: &serde_json::Value, kind: &str) -> ExitCode {
74    match serde_json::to_string_pretty(value) {
75        Ok(json) => {
76            println!("{json}");
77            ExitCode::SUCCESS
78        }
79        Err(e) => {
80            eprintln!("Error: failed to serialize {kind} output: {e}");
81            ExitCode::from(2)
82        }
83    }
84}
85
86/// Elide the common directory prefix between a base path and a target path.
87/// Only strips complete directory segments (never partial filenames).
88/// Returns the remaining suffix of `target`.
89///
90/// Example: `elide_common_prefix("a/b/c/foo.ts", "a/b/d/bar.ts")` → `"d/bar.ts"`
91#[must_use]
92pub fn elide_common_prefix<'a>(base: &str, target: &'a str) -> &'a str {
93    let mut last_sep = 0;
94    for (i, (a, b)) in base.bytes().zip(target.bytes()).enumerate() {
95        if a != b {
96            break;
97        }
98        if a == b'/' {
99            last_sep = i + 1;
100        }
101    }
102    if last_sep > 0 && last_sep <= target.len() {
103        &target[last_sep..]
104    } else {
105        target
106    }
107}
108
109/// Compute a SARIF-compatible relative URI from an absolute path and project root.
110fn relative_uri(path: &Path, root: &Path) -> String {
111    normalize_uri(&relative_path(path, root).display().to_string())
112}
113
114/// Normalize a path string to a valid URI: forward slashes and percent-encoded brackets.
115///
116/// Brackets (`[`, `]`) are not valid in URI path segments per RFC 3986 and cause
117/// SARIF validation warnings (e.g., Next.js dynamic routes like `[slug]`).
118#[must_use]
119pub fn normalize_uri(path_str: &str) -> String {
120    path_str
121        .replace('\\', "/")
122        .replace('[', "%5B")
123        .replace(']', "%5D")
124}
125
126/// Severity level for human-readable output.
127#[derive(Clone, Copy, Debug)]
128pub enum Level {
129    Warn,
130    Info,
131    Error,
132}
133
134#[must_use]
135pub const fn severity_to_level(s: Severity) -> Level {
136    match s {
137        Severity::Error => Level::Error,
138        Severity::Warn => Level::Warn,
139        // Off issues are filtered before reporting; fall back to Info.
140        Severity::Off => Level::Info,
141    }
142}
143
144/// Print analysis results in the configured format.
145/// Returns exit code 2 if serialization fails, SUCCESS otherwise.
146///
147/// When `regression` is `Some`, the JSON format includes a `regression` key in the output envelope.
148/// When `ctx.group_by` is `Some`, results are partitioned into labeled groups before rendering.
149#[must_use]
150pub fn print_results(
151    results: &AnalysisResults,
152    ctx: &ReportContext<'_>,
153    output: OutputFormat,
154    regression: Option<&crate::regression::RegressionOutcome>,
155) -> ExitCode {
156    // Grouped output: partition results and render per-group
157    if let Some(ref resolver) = ctx.group_by {
158        let groups = grouping::group_analysis_results(results, ctx.root, resolver);
159        return print_grouped_results(&groups, results, ctx, output, resolver);
160    }
161
162    match output {
163        OutputFormat::Human => {
164            if ctx.summary {
165                human::check::print_check_summary(results, ctx.rules, ctx.elapsed, ctx.quiet);
166            } else {
167                human::print_human(
168                    results,
169                    ctx.root,
170                    ctx.rules,
171                    ctx.elapsed,
172                    ctx.quiet,
173                    ctx.top,
174                );
175            }
176            ExitCode::SUCCESS
177        }
178        OutputFormat::Json => json::print_json(
179            results,
180            ctx.root,
181            ctx.elapsed,
182            ctx.explain,
183            regression,
184            ctx.baseline_matched,
185        ),
186        OutputFormat::Compact => {
187            compact::print_compact(results, ctx.root);
188            ExitCode::SUCCESS
189        }
190        OutputFormat::Sarif => sarif::print_sarif(results, ctx.root, ctx.rules),
191        OutputFormat::Markdown => {
192            markdown::print_markdown(results, ctx.root);
193            ExitCode::SUCCESS
194        }
195        OutputFormat::CodeClimate => codeclimate::print_codeclimate(results, ctx.root, ctx.rules),
196        OutputFormat::Badge => {
197            eprintln!("Error: badge format is only supported for the health command");
198            ExitCode::from(2)
199        }
200    }
201}
202
203/// Render grouped results across all output formats.
204#[must_use]
205fn print_grouped_results(
206    groups: &[grouping::ResultGroup],
207    original: &AnalysisResults,
208    ctx: &ReportContext<'_>,
209    output: OutputFormat,
210    resolver: &OwnershipResolver,
211) -> ExitCode {
212    match output {
213        OutputFormat::Human => {
214            human::print_grouped_human(
215                groups,
216                ctx.root,
217                ctx.rules,
218                ctx.elapsed,
219                ctx.quiet,
220                Some(resolver),
221            );
222            ExitCode::SUCCESS
223        }
224        OutputFormat::Json => json::print_grouped_json(
225            groups,
226            original,
227            ctx.root,
228            ctx.elapsed,
229            ctx.explain,
230            resolver,
231        ),
232        OutputFormat::Compact => {
233            compact::print_grouped_compact(groups, ctx.root);
234            ExitCode::SUCCESS
235        }
236        OutputFormat::Markdown => {
237            markdown::print_grouped_markdown(groups, ctx.root);
238            ExitCode::SUCCESS
239        }
240        OutputFormat::Sarif => sarif::print_grouped_sarif(original, ctx.root, ctx.rules, resolver),
241        OutputFormat::CodeClimate => {
242            codeclimate::print_grouped_codeclimate(original, ctx.root, ctx.rules, resolver)
243        }
244        OutputFormat::Badge => {
245            eprintln!("Error: badge format is only supported for the health command");
246            ExitCode::from(2)
247        }
248    }
249}
250
251// ── Duplication report ────────────────────────────────────────────
252
253/// Print duplication analysis results in the configured format.
254#[must_use]
255pub fn print_duplication_report(
256    report: &DuplicationReport,
257    ctx: &ReportContext<'_>,
258    output: OutputFormat,
259) -> ExitCode {
260    match output {
261        OutputFormat::Human => {
262            if ctx.summary {
263                human::dupes::print_duplication_summary(report, ctx.elapsed, ctx.quiet);
264            } else {
265                human::print_duplication_human(report, ctx.root, ctx.elapsed, ctx.quiet);
266            }
267            ExitCode::SUCCESS
268        }
269        OutputFormat::Json => {
270            json::print_duplication_json(report, ctx.root, ctx.elapsed, ctx.explain)
271        }
272        OutputFormat::Compact => {
273            compact::print_duplication_compact(report, ctx.root);
274            ExitCode::SUCCESS
275        }
276        OutputFormat::Sarif => sarif::print_duplication_sarif(report, ctx.root),
277        OutputFormat::Markdown => {
278            markdown::print_duplication_markdown(report, ctx.root);
279            ExitCode::SUCCESS
280        }
281        OutputFormat::CodeClimate => codeclimate::print_duplication_codeclimate(report, ctx.root),
282        OutputFormat::Badge => {
283            eprintln!("Error: badge format is only supported for the health command");
284            ExitCode::from(2)
285        }
286    }
287}
288
289// ── Health / complexity report ─────────────────────────────────────
290
291/// Print health (complexity) analysis results in the configured format.
292#[must_use]
293pub fn print_health_report(
294    report: &crate::health_types::HealthReport,
295    ctx: &ReportContext<'_>,
296    output: OutputFormat,
297) -> ExitCode {
298    match output {
299        OutputFormat::Human => {
300            if ctx.summary {
301                human::health::print_health_summary(report, ctx.elapsed, ctx.quiet);
302            } else {
303                human::print_health_human(report, ctx.root, ctx.elapsed, ctx.quiet);
304            }
305            ExitCode::SUCCESS
306        }
307        OutputFormat::Compact => {
308            compact::print_health_compact(report, ctx.root);
309            ExitCode::SUCCESS
310        }
311        OutputFormat::Markdown => {
312            markdown::print_health_markdown(report, ctx.root);
313            ExitCode::SUCCESS
314        }
315        OutputFormat::Sarif => sarif::print_health_sarif(report, ctx.root),
316        OutputFormat::Json => json::print_health_json(report, ctx.root, ctx.elapsed, ctx.explain),
317        OutputFormat::CodeClimate => codeclimate::print_health_codeclimate(report, ctx.root),
318        OutputFormat::Badge => badge::print_health_badge(report),
319    }
320}
321
322/// Print cross-reference findings (duplicated code that is also dead code).
323///
324/// Only emits output in human format to avoid corrupting structured JSON/SARIF output.
325pub fn print_cross_reference_findings(
326    cross_ref: &fallow_core::cross_reference::CrossReferenceResult,
327    root: &Path,
328    quiet: bool,
329    output: OutputFormat,
330) {
331    human::print_cross_reference_findings(cross_ref, root, quiet, output);
332}
333
334// ── Trace output ──────────────────────────────────────────────────
335
336/// Print export trace results.
337pub fn print_export_trace(trace: &ExportTrace, format: OutputFormat) {
338    match format {
339        OutputFormat::Json => json::print_trace_json(trace),
340        _ => human::print_export_trace_human(trace),
341    }
342}
343
344/// Print file trace results.
345pub fn print_file_trace(trace: &FileTrace, format: OutputFormat) {
346    match format {
347        OutputFormat::Json => json::print_trace_json(trace),
348        _ => human::print_file_trace_human(trace),
349    }
350}
351
352/// Print dependency trace results.
353pub fn print_dependency_trace(trace: &DependencyTrace, format: OutputFormat) {
354    match format {
355        OutputFormat::Json => json::print_trace_json(trace),
356        _ => human::print_dependency_trace_human(trace),
357    }
358}
359
360/// Print clone trace results.
361pub fn print_clone_trace(trace: &CloneTrace, root: &Path, format: OutputFormat) {
362    match format {
363        OutputFormat::Json => json::print_trace_json(trace),
364        _ => human::print_clone_trace_human(trace, root),
365    }
366}
367
368/// Print pipeline performance timings.
369/// In JSON mode, outputs to stderr to avoid polluting the JSON analysis output on stdout.
370pub fn print_performance(timings: &PipelineTimings, format: OutputFormat) {
371    match format {
372        OutputFormat::Json => match serde_json::to_string_pretty(timings) {
373            Ok(json) => eprintln!("{json}"),
374            Err(e) => eprintln!("Error: failed to serialize timings: {e}"),
375        },
376        _ => human::print_performance_human(timings),
377    }
378}
379
380/// Print health pipeline performance timings.
381/// In JSON mode, outputs to stderr to avoid polluting the JSON analysis output on stdout.
382pub fn print_health_performance(
383    timings: &crate::health_types::HealthTimings,
384    format: OutputFormat,
385) {
386    match format {
387        OutputFormat::Json => match serde_json::to_string_pretty(timings) {
388            Ok(json) => eprintln!("{json}"),
389            Err(e) => eprintln!("Error: failed to serialize timings: {e}"),
390        },
391        _ => human::print_health_performance_human(timings),
392    }
393}
394
395// Re-exported for snapshot testing via the lib target.
396// Uses #[allow] because unused_imports is target-dependent (used in lib, unused in bin).
397#[allow(
398    unused_imports,
399    reason = "target-dependent: used in lib, unused in bin"
400)]
401pub use codeclimate::build_codeclimate;
402#[allow(
403    unused_imports,
404    reason = "target-dependent: used in lib, unused in bin"
405)]
406pub use codeclimate::build_duplication_codeclimate;
407#[allow(
408    unused_imports,
409    reason = "target-dependent: used in lib, unused in bin"
410)]
411pub use codeclimate::build_health_codeclimate;
412#[allow(
413    unused_imports,
414    reason = "target-dependent: used in lib, unused in bin"
415)]
416pub use compact::build_compact_lines;
417pub use json::build_baseline_deltas_json;
418#[allow(
419    unused_imports,
420    reason = "target-dependent: used in lib, unused in bin"
421)]
422pub use json::build_json;
423#[allow(
424    unused_imports,
425    reason = "target-dependent: used in bin audit.rs, unused in lib"
426)]
427#[allow(
428    clippy::redundant_pub_crate,
429    reason = "pub(crate) deliberately limits visibility — report is pub but these are internal"
430)]
431pub(crate) use json::inject_dupes_actions;
432#[allow(
433    unused_imports,
434    reason = "target-dependent: used in bin audit.rs, unused in lib"
435)]
436#[allow(
437    clippy::redundant_pub_crate,
438    reason = "pub(crate) deliberately limits visibility — report is pub but these are internal"
439)]
440pub(crate) use json::inject_health_actions;
441#[allow(
442    unused_imports,
443    reason = "target-dependent: used in lib, unused in bin"
444)]
445pub use markdown::build_duplication_markdown;
446#[allow(
447    unused_imports,
448    reason = "target-dependent: used in lib, unused in bin"
449)]
450pub use markdown::build_health_markdown;
451#[allow(
452    unused_imports,
453    reason = "target-dependent: used in lib, unused in bin"
454)]
455pub use markdown::build_markdown;
456#[allow(
457    unused_imports,
458    reason = "target-dependent: used in lib, unused in bin"
459)]
460pub use sarif::build_health_sarif;
461#[allow(
462    unused_imports,
463    reason = "target-dependent: used in lib, unused in bin"
464)]
465pub use sarif::build_sarif;
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use std::path::PathBuf;
471
472    // ── normalize_uri ────────────────────────────────────────────────
473
474    #[test]
475    fn normalize_uri_forward_slashes_unchanged() {
476        assert_eq!(normalize_uri("src/utils.ts"), "src/utils.ts");
477    }
478
479    #[test]
480    fn normalize_uri_backslashes_replaced() {
481        assert_eq!(normalize_uri("src\\utils\\index.ts"), "src/utils/index.ts");
482    }
483
484    #[test]
485    fn normalize_uri_mixed_slashes() {
486        assert_eq!(normalize_uri("src\\utils/index.ts"), "src/utils/index.ts");
487    }
488
489    #[test]
490    fn normalize_uri_path_with_spaces() {
491        assert_eq!(
492            normalize_uri("src\\my folder\\file.ts"),
493            "src/my folder/file.ts"
494        );
495    }
496
497    #[test]
498    fn normalize_uri_empty_string() {
499        assert_eq!(normalize_uri(""), "");
500    }
501
502    // ── relative_path ────────────────────────────────────────────────
503
504    #[test]
505    fn relative_path_strips_root_prefix() {
506        let root = Path::new("/project");
507        let path = Path::new("/project/src/utils.ts");
508        assert_eq!(relative_path(path, root), Path::new("src/utils.ts"));
509    }
510
511    #[test]
512    fn relative_path_returns_full_path_when_no_prefix() {
513        let root = Path::new("/other");
514        let path = Path::new("/project/src/utils.ts");
515        assert_eq!(relative_path(path, root), path);
516    }
517
518    #[test]
519    fn relative_path_at_root_returns_empty_or_file() {
520        let root = Path::new("/project");
521        let path = Path::new("/project/file.ts");
522        assert_eq!(relative_path(path, root), Path::new("file.ts"));
523    }
524
525    #[test]
526    fn relative_path_deeply_nested() {
527        let root = Path::new("/project");
528        let path = Path::new("/project/packages/ui/src/components/Button.tsx");
529        assert_eq!(
530            relative_path(path, root),
531            Path::new("packages/ui/src/components/Button.tsx")
532        );
533    }
534
535    // ── relative_uri ─────────────────────────────────────────────────
536
537    #[test]
538    fn relative_uri_produces_forward_slash_path() {
539        let root = PathBuf::from("/project");
540        let path = root.join("src").join("utils.ts");
541        let uri = relative_uri(&path, &root);
542        assert_eq!(uri, "src/utils.ts");
543    }
544
545    #[test]
546    fn relative_uri_encodes_brackets() {
547        let root = PathBuf::from("/project");
548        let path = root.join("src/app/[...slug]/page.tsx");
549        let uri = relative_uri(&path, &root);
550        assert_eq!(uri, "src/app/%5B...slug%5D/page.tsx");
551    }
552
553    #[test]
554    fn relative_uri_encodes_nested_dynamic_routes() {
555        let root = PathBuf::from("/project");
556        let path = root.join("src/app/[slug]/[id]/page.tsx");
557        let uri = relative_uri(&path, &root);
558        assert_eq!(uri, "src/app/%5Bslug%5D/%5Bid%5D/page.tsx");
559    }
560
561    #[test]
562    fn relative_uri_no_common_prefix_returns_full() {
563        let root = PathBuf::from("/other");
564        let path = PathBuf::from("/project/src/utils.ts");
565        let uri = relative_uri(&path, &root);
566        assert!(uri.contains("project"));
567        assert!(uri.contains("utils.ts"));
568    }
569
570    // ── severity_to_level ────────────────────────────────────────────
571
572    #[test]
573    fn severity_error_maps_to_level_error() {
574        assert!(matches!(severity_to_level(Severity::Error), Level::Error));
575    }
576
577    #[test]
578    fn severity_warn_maps_to_level_warn() {
579        assert!(matches!(severity_to_level(Severity::Warn), Level::Warn));
580    }
581
582    #[test]
583    fn severity_off_maps_to_level_info() {
584        assert!(matches!(severity_to_level(Severity::Off), Level::Info));
585    }
586
587    // ── normalize_uri bracket encoding ──────────────────────────────
588
589    #[test]
590    fn normalize_uri_single_bracket_pair() {
591        assert_eq!(normalize_uri("app/[id]/page.tsx"), "app/%5Bid%5D/page.tsx");
592    }
593
594    #[test]
595    fn normalize_uri_catch_all_route() {
596        assert_eq!(
597            normalize_uri("app/[...slug]/page.tsx"),
598            "app/%5B...slug%5D/page.tsx"
599        );
600    }
601
602    #[test]
603    fn normalize_uri_optional_catch_all_route() {
604        assert_eq!(
605            normalize_uri("app/[[...slug]]/page.tsx"),
606            "app/%5B%5B...slug%5D%5D/page.tsx"
607        );
608    }
609
610    #[test]
611    fn normalize_uri_multiple_dynamic_segments() {
612        assert_eq!(
613            normalize_uri("app/[lang]/posts/[id]"),
614            "app/%5Blang%5D/posts/%5Bid%5D"
615        );
616    }
617
618    #[test]
619    fn normalize_uri_no_special_chars() {
620        let plain = "src/components/Button.tsx";
621        assert_eq!(normalize_uri(plain), plain);
622    }
623
624    #[test]
625    fn normalize_uri_only_backslashes() {
626        assert_eq!(normalize_uri("a\\b\\c"), "a/b/c");
627    }
628
629    // ── relative_path edge cases ────────────────────────────────────
630
631    #[test]
632    fn relative_path_identical_paths_returns_empty() {
633        let root = Path::new("/project");
634        assert_eq!(relative_path(root, root), Path::new(""));
635    }
636
637    #[test]
638    fn relative_path_partial_name_match_not_stripped() {
639        // "/project-two/src/a.ts" should NOT strip "/project" because
640        // "/project" is not a proper prefix of "/project-two".
641        let root = Path::new("/project");
642        let path = Path::new("/project-two/src/a.ts");
643        assert_eq!(relative_path(path, root), path);
644    }
645
646    // ── relative_uri edge cases ─────────────────────────────────────
647
648    #[test]
649    fn relative_uri_combines_stripping_and_encoding() {
650        let root = PathBuf::from("/project");
651        let path = root.join("src/app/[slug]/page.tsx");
652        let uri = relative_uri(&path, &root);
653        // Should both strip the prefix AND encode brackets.
654        assert_eq!(uri, "src/app/%5Bslug%5D/page.tsx");
655        assert!(!uri.starts_with('/'));
656    }
657
658    #[test]
659    fn relative_uri_at_root_file() {
660        let root = PathBuf::from("/project");
661        let path = root.join("index.ts");
662        assert_eq!(relative_uri(&path, &root), "index.ts");
663    }
664
665    // ── severity_to_level exhaustiveness ────────────────────────────
666
667    #[test]
668    fn severity_to_level_is_const_evaluable() {
669        // Verify the function can be used in const context.
670        const LEVEL_FROM_ERROR: Level = severity_to_level(Severity::Error);
671        const LEVEL_FROM_WARN: Level = severity_to_level(Severity::Warn);
672        const LEVEL_FROM_OFF: Level = severity_to_level(Severity::Off);
673        assert!(matches!(LEVEL_FROM_ERROR, Level::Error));
674        assert!(matches!(LEVEL_FROM_WARN, Level::Warn));
675        assert!(matches!(LEVEL_FROM_OFF, Level::Info));
676    }
677
678    // ── Level is Copy ───────────────────────────────────────────────
679
680    #[test]
681    fn level_is_copy() {
682        let level = severity_to_level(Severity::Error);
683        let copy = level;
684        // Both should still be usable (Copy semantics).
685        assert!(matches!(level, Level::Error));
686        assert!(matches!(copy, Level::Error));
687    }
688
689    // ── elide_common_prefix ─────────────────────────────────────────
690
691    #[test]
692    fn elide_common_prefix_shared_dir() {
693        assert_eq!(
694            elide_common_prefix("src/components/A.tsx", "src/components/B.tsx"),
695            "B.tsx"
696        );
697    }
698
699    #[test]
700    fn elide_common_prefix_partial_shared() {
701        assert_eq!(
702            elide_common_prefix("src/components/A.tsx", "src/utils/B.tsx"),
703            "utils/B.tsx"
704        );
705    }
706
707    #[test]
708    fn elide_common_prefix_no_shared() {
709        assert_eq!(
710            elide_common_prefix("pkg-a/src/A.tsx", "pkg-b/src/B.tsx"),
711            "pkg-b/src/B.tsx"
712        );
713    }
714
715    #[test]
716    fn elide_common_prefix_identical_files() {
717        // Same dir, different file
718        assert_eq!(elide_common_prefix("a/b/x.ts", "a/b/y.ts"), "y.ts");
719    }
720
721    #[test]
722    fn elide_common_prefix_no_dirs() {
723        assert_eq!(elide_common_prefix("foo.ts", "bar.ts"), "bar.ts");
724    }
725
726    #[test]
727    fn elide_common_prefix_deep_monorepo() {
728        assert_eq!(
729            elide_common_prefix(
730                "packages/rap/src/rap/components/SearchSelect/SearchSelect.tsx",
731                "packages/rap/src/rap/components/SearchSelect/SearchSelectItem.tsx"
732            ),
733            "SearchSelectItem.tsx"
734        );
735    }
736
737    // ── split_dir_filename ───────────────────────────────────────
738
739    #[test]
740    fn split_dir_filename_with_dir() {
741        let (dir, file) = split_dir_filename("src/utils/index.ts");
742        assert_eq!(dir, "src/utils/");
743        assert_eq!(file, "index.ts");
744    }
745
746    #[test]
747    fn split_dir_filename_no_dir() {
748        let (dir, file) = split_dir_filename("file.ts");
749        assert_eq!(dir, "");
750        assert_eq!(file, "file.ts");
751    }
752
753    #[test]
754    fn split_dir_filename_deeply_nested() {
755        let (dir, file) = split_dir_filename("a/b/c/d/e.ts");
756        assert_eq!(dir, "a/b/c/d/");
757        assert_eq!(file, "e.ts");
758    }
759
760    #[test]
761    fn split_dir_filename_trailing_slash() {
762        let (dir, file) = split_dir_filename("src/");
763        assert_eq!(dir, "src/");
764        assert_eq!(file, "");
765    }
766
767    #[test]
768    fn split_dir_filename_empty() {
769        let (dir, file) = split_dir_filename("");
770        assert_eq!(dir, "");
771        assert_eq!(file, "");
772    }
773
774    // ── plural ──────────────────────────────────────────────────
775
776    #[test]
777    fn plural_zero_is_plural() {
778        assert_eq!(plural(0), "s");
779    }
780
781    #[test]
782    fn plural_one_is_singular() {
783        assert_eq!(plural(1), "");
784    }
785
786    #[test]
787    fn plural_two_is_plural() {
788        assert_eq!(plural(2), "s");
789    }
790
791    #[test]
792    fn plural_large_number() {
793        assert_eq!(plural(999), "s");
794    }
795
796    // ── elide_common_prefix edge cases ──────────────────────────
797
798    #[test]
799    fn elide_common_prefix_empty_base() {
800        assert_eq!(elide_common_prefix("", "src/foo.ts"), "src/foo.ts");
801    }
802
803    #[test]
804    fn elide_common_prefix_empty_target() {
805        assert_eq!(elide_common_prefix("src/foo.ts", ""), "");
806    }
807
808    #[test]
809    fn elide_common_prefix_both_empty() {
810        assert_eq!(elide_common_prefix("", ""), "");
811    }
812
813    #[test]
814    fn elide_common_prefix_same_file_different_extension() {
815        // "src/utils.ts" vs "src/utils.js" — common prefix is "src/"
816        assert_eq!(
817            elide_common_prefix("src/utils.ts", "src/utils.js"),
818            "utils.js"
819        );
820    }
821
822    #[test]
823    fn elide_common_prefix_partial_filename_match_not_stripped() {
824        // "src/App.tsx" vs "src/AppUtils.tsx" — both in src/, but file names differ
825        assert_eq!(
826            elide_common_prefix("src/App.tsx", "src/AppUtils.tsx"),
827            "AppUtils.tsx"
828        );
829    }
830
831    #[test]
832    fn elide_common_prefix_identical_paths() {
833        assert_eq!(elide_common_prefix("src/foo.ts", "src/foo.ts"), "foo.ts");
834    }
835
836    #[test]
837    fn split_dir_filename_single_slash() {
838        let (dir, file) = split_dir_filename("/file.ts");
839        assert_eq!(dir, "/");
840        assert_eq!(file, "file.ts");
841    }
842
843    #[test]
844    fn emit_json_returns_success_for_valid_value() {
845        let value = serde_json::json!({"key": "value"});
846        let code = emit_json(&value, "test");
847        assert_eq!(code, ExitCode::SUCCESS);
848    }
849
850    mod proptests {
851        use super::*;
852        use proptest::prelude::*;
853
854        proptest! {
855            /// split_dir_filename always reconstructs the original path.
856            #[test]
857            fn split_dir_filename_reconstructs_path(path in "[a-zA-Z0-9_./\\-]{0,100}") {
858                let (dir, file) = split_dir_filename(&path);
859                let reconstructed = format!("{dir}{file}");
860                prop_assert_eq!(
861                    reconstructed, path,
862                    "dir+file should reconstruct the original path"
863                );
864            }
865
866            /// plural returns either "" or "s", nothing else.
867            #[test]
868            fn plural_returns_empty_or_s(n: usize) {
869                let result = plural(n);
870                prop_assert!(
871                    result.is_empty() || result == "s",
872                    "plural should return \"\" or \"s\", got {:?}",
873                    result
874                );
875            }
876
877            /// plural(1) is always "" and plural(n != 1) is always "s".
878            #[test]
879            fn plural_singular_only_for_one(n: usize) {
880                let result = plural(n);
881                if n == 1 {
882                    prop_assert_eq!(result, "", "plural(1) should be empty");
883                } else {
884                    prop_assert_eq!(result, "s", "plural({}) should be \"s\"", n);
885                }
886            }
887
888            /// normalize_uri never panics and always replaces backslashes.
889            #[test]
890            fn normalize_uri_no_backslashes(path in "[a-zA-Z0-9_.\\\\/ \\[\\]%-]{0,100}") {
891                let result = normalize_uri(&path);
892                prop_assert!(
893                    !result.contains('\\'),
894                    "Result should not contain backslashes: {result}"
895                );
896            }
897
898            /// normalize_uri always encodes brackets.
899            #[test]
900            fn normalize_uri_encodes_all_brackets(path in "[a-zA-Z0-9_./\\[\\]%-]{0,80}") {
901                let result = normalize_uri(&path);
902                prop_assert!(
903                    !result.contains('[') && !result.contains(']'),
904                    "Result should not contain raw brackets: {result}"
905                );
906            }
907
908            /// elide_common_prefix always returns a suffix of or equal to target.
909            #[test]
910            fn elide_common_prefix_returns_suffix_of_target(
911                base in "[a-zA-Z0-9_./]{0,50}",
912                target in "[a-zA-Z0-9_./]{0,50}",
913            ) {
914                let result = elide_common_prefix(&base, &target);
915                prop_assert!(
916                    target.ends_with(result),
917                    "Result {:?} should be a suffix of target {:?}",
918                    result, target
919                );
920            }
921
922            /// relative_path never panics.
923            #[test]
924            fn relative_path_never_panics(
925                root in "/[a-zA-Z0-9_/]{0,30}",
926                suffix in "[a-zA-Z0-9_./]{0,30}",
927            ) {
928                let root_path = Path::new(&root);
929                let full = PathBuf::from(format!("{root}/{suffix}"));
930                let _ = relative_path(&full, root_path);
931            }
932        }
933    }
934}