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_health_json;
423#[allow(
424    unused_imports,
425    reason = "target-dependent: used in lib, unused in bin"
426)]
427pub use json::build_json;
428#[allow(
429    unused_imports,
430    reason = "target-dependent: used in bin audit.rs, unused in lib"
431)]
432#[allow(
433    clippy::redundant_pub_crate,
434    reason = "pub(crate) deliberately limits visibility — report is pub but these are internal"
435)]
436pub(crate) use json::inject_dupes_actions;
437#[allow(
438    unused_imports,
439    reason = "target-dependent: used in bin audit.rs, unused in lib"
440)]
441#[allow(
442    clippy::redundant_pub_crate,
443    reason = "pub(crate) deliberately limits visibility — report is pub but these are internal"
444)]
445pub(crate) use json::inject_health_actions;
446#[allow(
447    unused_imports,
448    reason = "target-dependent: used in lib, unused in bin"
449)]
450pub use markdown::build_duplication_markdown;
451#[allow(
452    unused_imports,
453    reason = "target-dependent: used in lib, unused in bin"
454)]
455pub use markdown::build_health_markdown;
456#[allow(
457    unused_imports,
458    reason = "target-dependent: used in lib, unused in bin"
459)]
460pub use markdown::build_markdown;
461#[allow(
462    unused_imports,
463    reason = "target-dependent: used in lib, unused in bin"
464)]
465pub use sarif::build_health_sarif;
466#[allow(
467    unused_imports,
468    reason = "target-dependent: used in lib, unused in bin"
469)]
470pub use sarif::build_sarif;
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use std::path::PathBuf;
476
477    // ── normalize_uri ────────────────────────────────────────────────
478
479    #[test]
480    fn normalize_uri_forward_slashes_unchanged() {
481        assert_eq!(normalize_uri("src/utils.ts"), "src/utils.ts");
482    }
483
484    #[test]
485    fn normalize_uri_backslashes_replaced() {
486        assert_eq!(normalize_uri("src\\utils\\index.ts"), "src/utils/index.ts");
487    }
488
489    #[test]
490    fn normalize_uri_mixed_slashes() {
491        assert_eq!(normalize_uri("src\\utils/index.ts"), "src/utils/index.ts");
492    }
493
494    #[test]
495    fn normalize_uri_path_with_spaces() {
496        assert_eq!(
497            normalize_uri("src\\my folder\\file.ts"),
498            "src/my folder/file.ts"
499        );
500    }
501
502    #[test]
503    fn normalize_uri_empty_string() {
504        assert_eq!(normalize_uri(""), "");
505    }
506
507    // ── relative_path ────────────────────────────────────────────────
508
509    #[test]
510    fn relative_path_strips_root_prefix() {
511        let root = Path::new("/project");
512        let path = Path::new("/project/src/utils.ts");
513        assert_eq!(relative_path(path, root), Path::new("src/utils.ts"));
514    }
515
516    #[test]
517    fn relative_path_returns_full_path_when_no_prefix() {
518        let root = Path::new("/other");
519        let path = Path::new("/project/src/utils.ts");
520        assert_eq!(relative_path(path, root), path);
521    }
522
523    #[test]
524    fn relative_path_at_root_returns_empty_or_file() {
525        let root = Path::new("/project");
526        let path = Path::new("/project/file.ts");
527        assert_eq!(relative_path(path, root), Path::new("file.ts"));
528    }
529
530    #[test]
531    fn relative_path_deeply_nested() {
532        let root = Path::new("/project");
533        let path = Path::new("/project/packages/ui/src/components/Button.tsx");
534        assert_eq!(
535            relative_path(path, root),
536            Path::new("packages/ui/src/components/Button.tsx")
537        );
538    }
539
540    // ── relative_uri ─────────────────────────────────────────────────
541
542    #[test]
543    fn relative_uri_produces_forward_slash_path() {
544        let root = PathBuf::from("/project");
545        let path = root.join("src").join("utils.ts");
546        let uri = relative_uri(&path, &root);
547        assert_eq!(uri, "src/utils.ts");
548    }
549
550    #[test]
551    fn relative_uri_encodes_brackets() {
552        let root = PathBuf::from("/project");
553        let path = root.join("src/app/[...slug]/page.tsx");
554        let uri = relative_uri(&path, &root);
555        assert_eq!(uri, "src/app/%5B...slug%5D/page.tsx");
556    }
557
558    #[test]
559    fn relative_uri_encodes_nested_dynamic_routes() {
560        let root = PathBuf::from("/project");
561        let path = root.join("src/app/[slug]/[id]/page.tsx");
562        let uri = relative_uri(&path, &root);
563        assert_eq!(uri, "src/app/%5Bslug%5D/%5Bid%5D/page.tsx");
564    }
565
566    #[test]
567    fn relative_uri_no_common_prefix_returns_full() {
568        let root = PathBuf::from("/other");
569        let path = PathBuf::from("/project/src/utils.ts");
570        let uri = relative_uri(&path, &root);
571        assert!(uri.contains("project"));
572        assert!(uri.contains("utils.ts"));
573    }
574
575    // ── severity_to_level ────────────────────────────────────────────
576
577    #[test]
578    fn severity_error_maps_to_level_error() {
579        assert!(matches!(severity_to_level(Severity::Error), Level::Error));
580    }
581
582    #[test]
583    fn severity_warn_maps_to_level_warn() {
584        assert!(matches!(severity_to_level(Severity::Warn), Level::Warn));
585    }
586
587    #[test]
588    fn severity_off_maps_to_level_info() {
589        assert!(matches!(severity_to_level(Severity::Off), Level::Info));
590    }
591
592    // ── normalize_uri bracket encoding ──────────────────────────────
593
594    #[test]
595    fn normalize_uri_single_bracket_pair() {
596        assert_eq!(normalize_uri("app/[id]/page.tsx"), "app/%5Bid%5D/page.tsx");
597    }
598
599    #[test]
600    fn normalize_uri_catch_all_route() {
601        assert_eq!(
602            normalize_uri("app/[...slug]/page.tsx"),
603            "app/%5B...slug%5D/page.tsx"
604        );
605    }
606
607    #[test]
608    fn normalize_uri_optional_catch_all_route() {
609        assert_eq!(
610            normalize_uri("app/[[...slug]]/page.tsx"),
611            "app/%5B%5B...slug%5D%5D/page.tsx"
612        );
613    }
614
615    #[test]
616    fn normalize_uri_multiple_dynamic_segments() {
617        assert_eq!(
618            normalize_uri("app/[lang]/posts/[id]"),
619            "app/%5Blang%5D/posts/%5Bid%5D"
620        );
621    }
622
623    #[test]
624    fn normalize_uri_no_special_chars() {
625        let plain = "src/components/Button.tsx";
626        assert_eq!(normalize_uri(plain), plain);
627    }
628
629    #[test]
630    fn normalize_uri_only_backslashes() {
631        assert_eq!(normalize_uri("a\\b\\c"), "a/b/c");
632    }
633
634    // ── relative_path edge cases ────────────────────────────────────
635
636    #[test]
637    fn relative_path_identical_paths_returns_empty() {
638        let root = Path::new("/project");
639        assert_eq!(relative_path(root, root), Path::new(""));
640    }
641
642    #[test]
643    fn relative_path_partial_name_match_not_stripped() {
644        // "/project-two/src/a.ts" should NOT strip "/project" because
645        // "/project" is not a proper prefix of "/project-two".
646        let root = Path::new("/project");
647        let path = Path::new("/project-two/src/a.ts");
648        assert_eq!(relative_path(path, root), path);
649    }
650
651    // ── relative_uri edge cases ─────────────────────────────────────
652
653    #[test]
654    fn relative_uri_combines_stripping_and_encoding() {
655        let root = PathBuf::from("/project");
656        let path = root.join("src/app/[slug]/page.tsx");
657        let uri = relative_uri(&path, &root);
658        // Should both strip the prefix AND encode brackets.
659        assert_eq!(uri, "src/app/%5Bslug%5D/page.tsx");
660        assert!(!uri.starts_with('/'));
661    }
662
663    #[test]
664    fn relative_uri_at_root_file() {
665        let root = PathBuf::from("/project");
666        let path = root.join("index.ts");
667        assert_eq!(relative_uri(&path, &root), "index.ts");
668    }
669
670    // ── severity_to_level exhaustiveness ────────────────────────────
671
672    #[test]
673    fn severity_to_level_is_const_evaluable() {
674        // Verify the function can be used in const context.
675        const LEVEL_FROM_ERROR: Level = severity_to_level(Severity::Error);
676        const LEVEL_FROM_WARN: Level = severity_to_level(Severity::Warn);
677        const LEVEL_FROM_OFF: Level = severity_to_level(Severity::Off);
678        assert!(matches!(LEVEL_FROM_ERROR, Level::Error));
679        assert!(matches!(LEVEL_FROM_WARN, Level::Warn));
680        assert!(matches!(LEVEL_FROM_OFF, Level::Info));
681    }
682
683    // ── Level is Copy ───────────────────────────────────────────────
684
685    #[test]
686    fn level_is_copy() {
687        let level = severity_to_level(Severity::Error);
688        let copy = level;
689        // Both should still be usable (Copy semantics).
690        assert!(matches!(level, Level::Error));
691        assert!(matches!(copy, Level::Error));
692    }
693
694    // ── elide_common_prefix ─────────────────────────────────────────
695
696    #[test]
697    fn elide_common_prefix_shared_dir() {
698        assert_eq!(
699            elide_common_prefix("src/components/A.tsx", "src/components/B.tsx"),
700            "B.tsx"
701        );
702    }
703
704    #[test]
705    fn elide_common_prefix_partial_shared() {
706        assert_eq!(
707            elide_common_prefix("src/components/A.tsx", "src/utils/B.tsx"),
708            "utils/B.tsx"
709        );
710    }
711
712    #[test]
713    fn elide_common_prefix_no_shared() {
714        assert_eq!(
715            elide_common_prefix("pkg-a/src/A.tsx", "pkg-b/src/B.tsx"),
716            "pkg-b/src/B.tsx"
717        );
718    }
719
720    #[test]
721    fn elide_common_prefix_identical_files() {
722        // Same dir, different file
723        assert_eq!(elide_common_prefix("a/b/x.ts", "a/b/y.ts"), "y.ts");
724    }
725
726    #[test]
727    fn elide_common_prefix_no_dirs() {
728        assert_eq!(elide_common_prefix("foo.ts", "bar.ts"), "bar.ts");
729    }
730
731    #[test]
732    fn elide_common_prefix_deep_monorepo() {
733        assert_eq!(
734            elide_common_prefix(
735                "packages/rap/src/rap/components/SearchSelect/SearchSelect.tsx",
736                "packages/rap/src/rap/components/SearchSelect/SearchSelectItem.tsx"
737            ),
738            "SearchSelectItem.tsx"
739        );
740    }
741
742    // ── split_dir_filename ───────────────────────────────────────
743
744    #[test]
745    fn split_dir_filename_with_dir() {
746        let (dir, file) = split_dir_filename("src/utils/index.ts");
747        assert_eq!(dir, "src/utils/");
748        assert_eq!(file, "index.ts");
749    }
750
751    #[test]
752    fn split_dir_filename_no_dir() {
753        let (dir, file) = split_dir_filename("file.ts");
754        assert_eq!(dir, "");
755        assert_eq!(file, "file.ts");
756    }
757
758    #[test]
759    fn split_dir_filename_deeply_nested() {
760        let (dir, file) = split_dir_filename("a/b/c/d/e.ts");
761        assert_eq!(dir, "a/b/c/d/");
762        assert_eq!(file, "e.ts");
763    }
764
765    #[test]
766    fn split_dir_filename_trailing_slash() {
767        let (dir, file) = split_dir_filename("src/");
768        assert_eq!(dir, "src/");
769        assert_eq!(file, "");
770    }
771
772    #[test]
773    fn split_dir_filename_empty() {
774        let (dir, file) = split_dir_filename("");
775        assert_eq!(dir, "");
776        assert_eq!(file, "");
777    }
778
779    // ── plural ──────────────────────────────────────────────────
780
781    #[test]
782    fn plural_zero_is_plural() {
783        assert_eq!(plural(0), "s");
784    }
785
786    #[test]
787    fn plural_one_is_singular() {
788        assert_eq!(plural(1), "");
789    }
790
791    #[test]
792    fn plural_two_is_plural() {
793        assert_eq!(plural(2), "s");
794    }
795
796    #[test]
797    fn plural_large_number() {
798        assert_eq!(plural(999), "s");
799    }
800
801    // ── elide_common_prefix edge cases ──────────────────────────
802
803    #[test]
804    fn elide_common_prefix_empty_base() {
805        assert_eq!(elide_common_prefix("", "src/foo.ts"), "src/foo.ts");
806    }
807
808    #[test]
809    fn elide_common_prefix_empty_target() {
810        assert_eq!(elide_common_prefix("src/foo.ts", ""), "");
811    }
812
813    #[test]
814    fn elide_common_prefix_both_empty() {
815        assert_eq!(elide_common_prefix("", ""), "");
816    }
817
818    #[test]
819    fn elide_common_prefix_same_file_different_extension() {
820        // "src/utils.ts" vs "src/utils.js" — common prefix is "src/"
821        assert_eq!(
822            elide_common_prefix("src/utils.ts", "src/utils.js"),
823            "utils.js"
824        );
825    }
826
827    #[test]
828    fn elide_common_prefix_partial_filename_match_not_stripped() {
829        // "src/App.tsx" vs "src/AppUtils.tsx" — both in src/, but file names differ
830        assert_eq!(
831            elide_common_prefix("src/App.tsx", "src/AppUtils.tsx"),
832            "AppUtils.tsx"
833        );
834    }
835
836    #[test]
837    fn elide_common_prefix_identical_paths() {
838        assert_eq!(elide_common_prefix("src/foo.ts", "src/foo.ts"), "foo.ts");
839    }
840
841    #[test]
842    fn split_dir_filename_single_slash() {
843        let (dir, file) = split_dir_filename("/file.ts");
844        assert_eq!(dir, "/");
845        assert_eq!(file, "file.ts");
846    }
847
848    #[test]
849    fn emit_json_returns_success_for_valid_value() {
850        let value = serde_json::json!({"key": "value"});
851        let code = emit_json(&value, "test");
852        assert_eq!(code, ExitCode::SUCCESS);
853    }
854
855    mod proptests {
856        use super::*;
857        use proptest::prelude::*;
858
859        proptest! {
860            /// split_dir_filename always reconstructs the original path.
861            #[test]
862            fn split_dir_filename_reconstructs_path(path in "[a-zA-Z0-9_./\\-]{0,100}") {
863                let (dir, file) = split_dir_filename(&path);
864                let reconstructed = format!("{dir}{file}");
865                prop_assert_eq!(
866                    reconstructed, path,
867                    "dir+file should reconstruct the original path"
868                );
869            }
870
871            /// plural returns either "" or "s", nothing else.
872            #[test]
873            fn plural_returns_empty_or_s(n: usize) {
874                let result = plural(n);
875                prop_assert!(
876                    result.is_empty() || result == "s",
877                    "plural should return \"\" or \"s\", got {:?}",
878                    result
879                );
880            }
881
882            /// plural(1) is always "" and plural(n != 1) is always "s".
883            #[test]
884            fn plural_singular_only_for_one(n: usize) {
885                let result = plural(n);
886                if n == 1 {
887                    prop_assert_eq!(result, "", "plural(1) should be empty");
888                } else {
889                    prop_assert_eq!(result, "s", "plural({}) should be \"s\"", n);
890                }
891            }
892
893            /// normalize_uri never panics and always replaces backslashes.
894            #[test]
895            fn normalize_uri_no_backslashes(path in "[a-zA-Z0-9_.\\\\/ \\[\\]%-]{0,100}") {
896                let result = normalize_uri(&path);
897                prop_assert!(
898                    !result.contains('\\'),
899                    "Result should not contain backslashes: {result}"
900                );
901            }
902
903            /// normalize_uri always encodes brackets.
904            #[test]
905            fn normalize_uri_encodes_all_brackets(path in "[a-zA-Z0-9_./\\[\\]%-]{0,80}") {
906                let result = normalize_uri(&path);
907                prop_assert!(
908                    !result.contains('[') && !result.contains(']'),
909                    "Result should not contain raw brackets: {result}"
910                );
911            }
912
913            /// elide_common_prefix always returns a suffix of or equal to target.
914            #[test]
915            fn elide_common_prefix_returns_suffix_of_target(
916                base in "[a-zA-Z0-9_./]{0,50}",
917                target in "[a-zA-Z0-9_./]{0,50}",
918            ) {
919                let result = elide_common_prefix(&base, &target);
920                prop_assert!(
921                    target.ends_with(result),
922                    "Result {:?} should be a suffix of target {:?}",
923                    result, target
924                );
925            }
926
927            /// relative_path never panics.
928            #[test]
929            fn relative_path_never_panics(
930                root in "/[a-zA-Z0-9_/]{0,30}",
931                suffix in "[a-zA-Z0-9_./]{0,30}",
932            ) {
933                let root_path = Path::new(&root);
934                let full = PathBuf::from(format!("{root}/{suffix}"));
935                let _ = relative_path(&full, root_path);
936            }
937        }
938    }
939}