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