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