cuke-dedup 0.12.0

Static analysis for duplicate and reusable Cucumber step definitions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! Configuration loading and precedence.

use crate::framework_config;
use crate::model::{Rule, Severity};
use crate::resource_limits::{
    is_input_limit_error, read_utf8, MAX_CANDIDATE_COMPARISONS, MAX_CONFIG_INPUT_BYTES,
    MAX_STRUCTURAL_CLASS_COMPARISONS, MAX_SUPPRESSION_REASON_CHARS,
};
use anyhow::{bail, Context, Result};
use globset::Glob;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::str::FromStr;

const DEFAULT_EXCLUDES: [&str; 5] = [
    "**/node_modules/**",
    "**/target/**",
    "**/.features-gen/**",
    "**/test-results/**",
    "**/playwright-report/**",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
/// Destination format selected for analysis output.
#[non_exhaustive]
pub enum ReporterKind {
    /// Human-readable output written to the supplied terminal stream.
    Terminal,
    /// Versioned machine-readable JSON output.
    Json,
    /// Compact JSON Lines output written to stdout for streaming consumers.
    Jsonl,
    /// Self-contained interactive HTML output.
    Html,
    /// SARIF 2.1.0 output for GitHub code scanning and other compatible tools.
    Sarif,
}

impl FromStr for ReporterKind {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "terminal" => Ok(Self::Terminal),
            "json" => Ok(Self::Json),
            "jsonl" => Ok(Self::Jsonl),
            "html" => Ok(Self::Html),
            "sarif" => Ok(Self::Sarif),
            _ => Err(format!("unknown reporter `{value}`")),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Default)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct RawConfig {
    #[serde(default)]
    ruby_load_paths: Option<Vec<PathBuf>>,
    #[serde(default)]
    definitions: Option<Vec<String>>,
    #[serde(default)]
    features: Option<Vec<String>>,
    #[serde(default)]
    exclude: Option<Vec<String>>,
    #[serde(default)]
    exclude_defaults: Option<bool>,
    #[serde(default)]
    include_hidden: Option<bool>,
    #[serde(default)]
    reporters: Option<Vec<ReporterKind>>,
    #[serde(default)]
    output: Option<PathBuf>,
    #[serde(default)]
    threshold: Option<f64>,
    #[serde(default)]
    near_duplicate_handler_similarity: Option<f64>,
    #[serde(default)]
    require_features: Option<bool>,
    #[serde(default)]
    require_definitions: Option<bool>,
    #[serde(default)]
    fail_on_incomplete: Option<bool>,
    #[serde(default)]
    fail_on_unparseable: Option<bool>,
    #[serde(default)]
    registrations: Option<Vec<String>>,
    #[serde(default)]
    assertion_modules: Option<Vec<String>>,
    #[serde(default)]
    parameter_types: Option<BTreeMap<String, String>>,
    #[serde(default)]
    max_candidate_comparisons: Option<usize>,
    #[serde(default)]
    max_structural_class_comparisons: Option<usize>,
    #[serde(default)]
    no_metrics: Option<bool>,
    #[serde(default)]
    rules: Option<BTreeMap<String, Severity>>,
    #[serde(default)]
    suppressions: Option<Vec<SuppressionConfig>>,
}

#[derive(Debug, Clone, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct PackageJson {
    #[serde(default)]
    cuke_dedup: Option<RawConfig>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
/// A configuration entry that suppresses matching findings for a documented reason.
pub struct SuppressionConfig {
    /// Rule to suppress.
    pub rule: Rule,
    /// Human-readable justification recorded with suppressed findings.
    pub reason: String,
    #[serde(default)]
    /// Optional glob selecting source paths.
    pub path: Option<String>,
    #[serde(default)]
    /// Optional exact matcher selecting step definitions.
    pub matcher: Option<String>,
}

#[derive(Debug, Clone, Default)]
/// Command-line or embedding overrides applied after file-based configuration.
pub struct ConfigOverrides {
    /// Explicit JSON configuration file, bypassing automatic config-file discovery.
    pub config_file: Option<PathBuf>,
    /// Replacement definition-source globs.
    pub definitions: Option<Vec<String>>,
    /// Replacement feature-file globs.
    pub features: Option<Vec<String>>,
    /// Replacement custom exclusion globs.
    pub exclude: Option<Vec<String>>,
    /// Whether built-in generated-directory exclusions remain enabled.
    pub exclude_defaults: Option<bool>,
    /// Whether discovery descends into dot-directories.
    pub include_hidden: Option<bool>,
    /// Replacement reporter selection.
    pub reporters: Option<Vec<ReporterKind>>,
    /// Replacement report output directory.
    pub output: Option<PathBuf>,
    /// Maximum percentage of definitions allowed in active duplication errors.
    pub threshold: Option<f64>,
    /// Whether a run with no discovered feature files is an operational failure.
    pub require_features: Option<bool>,
    /// Whether machine reports omit runtime measurements.
    pub no_metrics: Option<bool>,
    /// Per-rule severity overrides.
    pub rules: BTreeMap<Rule, Severity>,
}

#[derive(Debug, Clone, Default)]
pub(crate) struct CliConfigOverrides {
    pub(crate) require_definitions: Option<bool>,
    /// Whether bounded or incomplete analysis is an operational failure.
    pub(crate) fail_on_incomplete: Option<bool>,
    /// Whether an unparseable source file is an operational failure rather than tolerated.
    pub(crate) fail_on_unparseable: Option<bool>,
    pub(crate) max_candidate_comparisons: Option<usize>,
    pub(crate) max_structural_class_comparisons: Option<usize>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
/// Fully resolved and validated analyzer configuration.
pub struct Config {
    #[serde(flatten)]
    frontend: crate::source_adapter::FrontendConfig,
    /// Canonical repository root being analyzed.
    pub root: PathBuf,
    /// Globs selecting definition sources, or an empty list for automatic discovery.
    pub definitions: Vec<String>,
    /// Globs selecting classic Gherkin or Gherkin Markdown feature files.
    pub features: Vec<String>,
    /// Human-readable origin of the effective feature globs.
    pub feature_pattern_origin: String,
    /// Non-fatal diagnostics produced while inspecting framework configuration.
    pub config_warnings: Vec<String>,
    /// Standalone or package configuration source selected below CLI overrides.
    pub config_source: String,
    /// Globs excluded from discovery.
    pub exclude: Vec<String>,
    /// Whether built-in generated-directory exclusions are active.
    pub exclude_defaults: bool,
    /// Whether discovery descends into dot-directories.
    pub include_hidden: bool,
    /// Report formats emitted by the analyzer.
    pub reporters: Vec<ReporterKind>,
    /// Directory for file-based reports.
    pub output: PathBuf,
    /// Maximum percentage of definitions allowed in active duplication errors.
    pub threshold: f64,
    /// Minimum handler similarity (0.5–1.0) for a `near-duplicate-step` finding. Raising it demands
    /// more handler evidence, suppressing systematically-named steps whose handlers differ.
    pub near_duplicate_handler_similarity: f64,
    /// Whether finding no feature files is an operational failure.
    pub require_features: bool,
    /// Whether extracting no step definitions is an operational failure.
    pub require_definitions: bool,
    /// Whether an incomplete corpus or truncated analysis is an operational failure.
    pub fail_on_incomplete: bool,
    /// Whether a source file that cannot be parsed is an operational failure rather than a
    /// tolerated, reported incompleteness.
    pub fail_on_unparseable: bool,
    /// Additional local function names that register step definitions.
    pub registrations: Vec<String>,
    /// Additional module specifiers whose `expect` export is a trusted assertion factory.
    pub assertion_modules: Vec<String>,
    /// Project-defined Cucumber Expression parameter types and their regular expressions.
    pub parameter_types: BTreeMap<String, String>,
    /// Maximum unique definition pairs retained for analysis.
    pub max_candidate_comparisons: usize,
    /// Maximum structural candidate proposals considered from one handler class.
    pub max_structural_class_comparisons: usize,
    /// Whether machine reports omit runtime measurements for reproducibility.
    pub no_metrics: bool,
    /// Effective severity for each analysis rule.
    pub rules: BTreeMap<Rule, Severity>,
    /// Explicit, reason-bearing finding suppressions.
    pub suppressions: Vec<SuppressionConfig>,
    #[serde(skip)]
    custom_exclude: Vec<String>,
    #[serde(skip)]
    output_from_project_config: bool,
}

impl Config {
    /// Ordered, explicitly configured Ruby dependency source roots.
    pub fn ruby_load_paths(&self) -> &[PathBuf] {
        self.frontend.ruby_load_paths()
    }

    /// Loads framework, package, and standalone configuration beneath `root`, then applies
    /// `overrides` in precedence order.
    pub fn load(root: &Path, overrides: ConfigOverrides) -> Result<Self> {
        Self::load_internal(root, overrides, CliConfigOverrides::default())
    }

    pub(crate) fn load_for_cli(
        root: &Path,
        overrides: ConfigOverrides,
        cli_overrides: CliConfigOverrides,
    ) -> Result<Self> {
        Self::load_internal(root, overrides, cli_overrides)
    }

    /// Loads the configuration for `root` with the given overrides, resolving `root` to its
    /// canonical, platform-normalized form first.
    fn load_internal(
        root: &Path,
        overrides: ConfigOverrides,
        cli_overrides: CliConfigOverrides,
    ) -> Result<Self> {
        let root = canonical_platform_path(root)
            .with_context(|| format!("cannot access target directory {}", root.display()))?;
        if !root.is_dir() {
            bail!("target {} is not a directory", root.display());
        }

        let package_path = root.join("package.json");
        let (package_config, package_json) = if package_path.is_file() {
            let text = read_utf8(
                &package_path,
                "package configuration",
                MAX_CONFIG_INPUT_BYTES,
            )?;
            // serde_json's default recursion limit remains enabled for untrusted config input.
            let value = serde_json::from_str::<serde_json::Value>(&text)
                .with_context(|| format!("failed to parse {}", package_path.display()))?;
            let package = serde_json::from_value::<PackageJson>(value.clone())
                .with_context(|| format!("failed to parse {}", package_path.display()))?;
            (package.cuke_dedup, Some(value))
        } else {
            (None, None)
        };

        let explicit_config = overrides.config_file.as_ref().map(|path| {
            if path.is_absolute() {
                path.clone()
            } else {
                root.join(path)
            }
        });
        let mut config_warnings = Vec::new();
        let (standalone_config, standalone_path) = if let Some(path) = explicit_config {
            (Some(read_raw_config(&path)?), Some(path))
        } else {
            discover_config_file(&root, &mut config_warnings)?
        };

        let package_config = if standalone_config.is_none() {
            package_config
        } else {
            None
        };

        let has_explicit_features = overrides.features.is_some()
            || standalone_config
                .as_ref()
                .is_some_and(|config| config.features.is_some())
            || package_config
                .as_ref()
                .is_some_and(|config| config.features.is_some());
        let mut config = Self::defaults(root);
        config.config_warnings = config_warnings;
        if !has_explicit_features {
            match framework_config::detect(&config.root, package_json.as_ref()) {
                Ok(Some(framework)) => {
                    config.features = framework.patterns;
                    config.feature_pattern_origin = format!(
                        "{} configuration {}",
                        framework.framework,
                        framework
                            .source
                            .strip_prefix(&config.root)
                            .unwrap_or(&framework.source)
                            .display()
                    );
                    config.config_warnings.extend(framework.warnings);
                }
                Ok(None) => {}
                Err(error) if is_input_limit_error(&error) => return Err(error),
                Err(error) => config.config_warnings.push(format!(
                    "could not inspect framework configuration ({error:#}); using built-in feature patterns"
                )),
            }
        }
        if let Some(raw) = package_config {
            let replaces_features = raw.features.is_some();
            config.apply_raw(raw)?;
            config.config_source = "package.json#cukeDedup".to_owned();
            if replaces_features {
                config.feature_pattern_origin = "package.json#cukeDedup".to_owned();
            }
        }
        if let Some(raw) = standalone_config {
            let replaces_features = raw.features.is_some();
            config.apply_raw(raw)?;
            config.config_source = standalone_path
                .as_ref()
                .map(|path| config_source_name(path, &config.root))
                .unwrap_or_else(|| ".cuke-dedup.json".to_owned());
            if replaces_features {
                config.feature_pattern_origin = config.config_source.clone();
            }
        }
        let cli_replaces_features = overrides.features.is_some();
        config.apply_overrides(overrides);
        if let Some(value) = cli_overrides.require_definitions {
            config.require_definitions = value;
        }
        if let Some(value) = cli_overrides.fail_on_incomplete {
            config.fail_on_incomplete = value;
        }
        if let Some(value) = cli_overrides.fail_on_unparseable {
            config.fail_on_unparseable = value;
        }
        if let Some(value) = cli_overrides.max_candidate_comparisons {
            config.max_candidate_comparisons = value;
        }
        if let Some(value) = cli_overrides.max_structural_class_comparisons {
            config.max_structural_class_comparisons = value;
        }
        if cli_replaces_features {
            config.feature_pattern_origin = "--features".to_owned();
        }
        config.validate()?;
        Ok(config)
    }

    fn defaults(root: PathBuf) -> Self {
        let rules = [
            (Rule::DuplicateMatcher, Severity::Error),
            (Rule::NormalizedMatcher, Severity::Error),
            (Rule::AmbiguousStep, Severity::Error),
            (Rule::OverlappingMatcher, Severity::Warning),
            (Rule::DuplicateHandler, Severity::Error),
            (Rule::NearDuplicateStep, Severity::Warning),
            (Rule::ParameterizationCandidate, Severity::Warning),
            (Rule::UnusedDefinition, Severity::Warning),
        ]
        .into_iter()
        .collect();
        Self {
            frontend: Default::default(),
            root,
            definitions: Vec::new(),
            features: vec!["**/*.{feature,feature.md}".to_owned()],
            feature_pattern_origin: "built-in defaults".to_owned(),
            config_warnings: Vec::new(),
            config_source: "built-in defaults".to_owned(),
            exclude: DEFAULT_EXCLUDES.iter().map(ToString::to_string).collect(),
            exclude_defaults: true,
            include_hidden: false,
            reporters: vec![ReporterKind::Terminal],
            output: PathBuf::from("reports/cuke-dedup"),
            threshold: 0.0,
            near_duplicate_handler_similarity: 0.70,
            require_features: false,
            require_definitions: false,
            fail_on_incomplete: false,
            fail_on_unparseable: false,
            registrations: Vec::new(),
            assertion_modules: Vec::new(),
            parameter_types: BTreeMap::new(),
            max_candidate_comparisons: MAX_CANDIDATE_COMPARISONS,
            max_structural_class_comparisons: MAX_STRUCTURAL_CLASS_COMPARISONS,
            no_metrics: false,
            rules,
            suppressions: Vec::new(),
            custom_exclude: Vec::new(),
            output_from_project_config: false,
        }
    }

    fn apply_raw(&mut self, raw: RawConfig) -> Result<()> {
        if let Some(paths) = raw.ruby_load_paths {
            self.frontend.set_ruby_load_paths(paths);
        }
        if let Some(value) = raw.definitions {
            self.definitions = value;
        }
        if let Some(value) = raw.features {
            self.features = value;
        }
        if let Some(value) = raw.exclude_defaults {
            self.exclude_defaults = value;
        }
        if let Some(value) = raw.include_hidden {
            self.include_hidden = value;
        }
        if let Some(value) = raw.exclude {
            self.custom_exclude = value;
        }
        self.rebuild_excludes();
        if let Some(value) = raw.reporters {
            self.reporters = value;
        }
        if let Some(value) = raw.output {
            self.output = value;
            self.output_from_project_config = true;
        }
        if let Some(value) = raw.threshold {
            self.threshold = value;
        }
        if let Some(value) = raw.near_duplicate_handler_similarity {
            self.near_duplicate_handler_similarity = value;
        }
        if let Some(value) = raw.require_features {
            self.require_features = value;
        }
        if let Some(value) = raw.require_definitions {
            self.require_definitions = value;
        }
        if let Some(value) = raw.fail_on_incomplete {
            self.fail_on_incomplete = value;
        }
        if let Some(value) = raw.fail_on_unparseable {
            self.fail_on_unparseable = value;
        }
        if let Some(value) = raw.registrations {
            self.registrations = value;
        }
        if let Some(value) = raw.assertion_modules {
            self.assertion_modules = value;
        }
        if let Some(value) = raw.parameter_types {
            self.parameter_types = value;
        }
        if let Some(value) = raw.max_candidate_comparisons {
            self.max_candidate_comparisons = value;
        }
        if let Some(value) = raw.max_structural_class_comparisons {
            self.max_structural_class_comparisons = value;
        }
        if let Some(value) = raw.no_metrics {
            self.no_metrics = value;
        }
        if let Some(value) = raw.rules {
            for (name, severity) in value {
                let rule = name.parse::<Rule>().map_err(anyhow::Error::msg)?;
                self.rules.insert(rule, severity);
            }
        }
        if let Some(value) = raw.suppressions {
            self.suppressions = value;
        }
        Ok(())
    }

    fn apply_overrides(&mut self, overrides: ConfigOverrides) {
        if let Some(value) = overrides.definitions {
            self.definitions = value;
        }
        if let Some(value) = overrides.features {
            self.features = value;
        }
        if let Some(value) = overrides.exclude_defaults {
            self.exclude_defaults = value;
        }
        if let Some(value) = overrides.include_hidden {
            self.include_hidden = value;
        }
        if let Some(value) = overrides.exclude {
            self.custom_exclude = value;
        }
        self.rebuild_excludes();
        if let Some(value) = overrides.reporters {
            self.reporters = value;
        }
        if let Some(value) = overrides.output {
            self.output = value;
            self.output_from_project_config = false;
        }
        if let Some(value) = overrides.threshold {
            self.threshold = value;
        }
        if let Some(value) = overrides.require_features {
            self.require_features = value;
        }
        if let Some(value) = overrides.no_metrics {
            self.no_metrics = value;
        }
        self.rules.extend(overrides.rules);
    }

    fn rebuild_excludes(&mut self) {
        self.exclude.clear();
        if self.exclude_defaults {
            self.exclude
                .extend(DEFAULT_EXCLUDES.iter().map(ToString::to_string));
        }
        self.exclude.extend(self.custom_exclude.iter().cloned());
    }

    fn validate(&self) -> Result<()> {
        if self.reporters.is_empty() {
            bail!("at least one reporter must be configured");
        }
        if self.reporters.contains(&ReporterKind::Terminal)
            && self.reporters.contains(&ReporterKind::Jsonl)
        {
            bail!("terminal and jsonl reporters cannot share stdout; select only one of them");
        }
        if !self.threshold.is_finite() || !(0.0..=100.0).contains(&self.threshold) {
            bail!("threshold must be a finite percentage from 0 through 100");
        }
        // A range check also rejects NaN (`contains` is false for it); config files cannot express a
        // non-finite value, so no separate `is_finite` guard is reachable here.
        if !(0.5..=1.0).contains(&self.near_duplicate_handler_similarity) {
            bail!("nearDuplicateHandlerSimilarity must be a value from 0.5 through 1.0");
        }
        for (name, pattern) in &self.parameter_types {
            if name.is_empty() || name.contains(['{', '}']) {
                bail!("parameter type `{name}` must not be empty or contain braces");
            }
            crate::resource_limits::compile_regex(pattern).with_context(|| {
                format!("invalid regular expression for parameter type `{name}`")
            })?;
        }
        for module in &self.assertion_modules {
            // A specifier is matched exactly against the import text, so surrounding whitespace or
            // an empty entry would silently never match and quietly disable the setting.
            if module.is_empty() || module.trim() != module {
                bail!("assertion module `{module}` must be a module specifier without surrounding whitespace");
            }
        }
        for name in &self.registrations {
            if name.is_empty()
                || !name
                    .chars()
                    .all(|character| character.is_alphanumeric() || matches!(character, '_' | '$'))
                || name.starts_with(|character: char| character.is_ascii_digit())
            {
                bail!("registration `{name}` must be a JavaScript identifier");
            }
        }
        self.validate_analysis_limits()?;
        if self.output_from_project_config {
            validate_project_output(&self.root, &self.output)?;
        }
        for suppression in &self.suppressions {
            if suppression.reason.trim().is_empty() {
                bail!(
                    "suppression for {} must include a non-empty reason",
                    suppression.rule
                );
            }
            if suppression.reason.chars().count() > MAX_SUPPRESSION_REASON_CHARS {
                bail!(
                    "suppression reason for {} exceeds the {}-character limit",
                    suppression.rule,
                    MAX_SUPPRESSION_REASON_CHARS
                );
            }
            if suppression.path.is_none() && suppression.matcher.is_none() {
                bail!(
                    "suppression for {} must select a path or matcher",
                    suppression.rule
                );
            }
            if let Some(pattern) = &suppression.path {
                Glob::new(pattern).with_context(|| {
                    format!(
                        "invalid suppression path glob `{pattern}` for {}",
                        suppression.rule
                    )
                })?;
            }
        }
        Ok(())
    }

    pub(crate) fn validate_analysis_limits(&self) -> Result<()> {
        if self.max_candidate_comparisons == 0 {
            bail!("maxCandidateComparisons must be greater than zero");
        }
        if self.max_candidate_comparisons > MAX_CANDIDATE_COMPARISONS {
            bail!(
                "maxCandidateComparisons must not exceed the hard safety limit of {MAX_CANDIDATE_COMPARISONS}"
            );
        }
        if self.max_structural_class_comparisons == 0 {
            bail!("maxStructuralClassComparisons must be greater than zero");
        }
        if self.max_structural_class_comparisons > MAX_STRUCTURAL_CLASS_COMPARISONS {
            bail!(
                "maxStructuralClassComparisons must not exceed the hard safety limit of {MAX_STRUCTURAL_CLASS_COMPARISONS}"
            );
        }
        Ok(())
    }

    /// Returns the configured severity for `rule`, defaulting to [`Severity::Off`].
    pub fn severity(&self, rule: Rule) -> Severity {
        self.rules.get(&rule).copied().unwrap_or(Severity::Off)
    }

    /// Resolves a report filename against the configured output directory.
    pub fn output_path(&self, filename: &str) -> PathBuf {
        if self.output.is_absolute() {
            self.output.join(filename)
        } else {
            self.root.join(&self.output).join(filename)
        }
    }
}

fn validate_project_output(root: &Path, output: &Path) -> Result<()> {
    if output.is_absolute()
        || output.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        })
    {
        bail!(
            "project configuration output `{}` must stay beneath the analyzed root; use --output for an operator-controlled path",
            output.display()
        );
    }

    let candidate = root.join(output);
    let mut existing_ancestor = candidate.as_path();
    while !existing_ancestor.exists() {
        existing_ancestor = existing_ancestor.parent().ok_or_else(|| {
            anyhow::anyhow!(
                "could not resolve project configuration output `{}`",
                output.display()
            )
        })?;
    }
    let canonical_ancestor =
        normalize_platform_path(existing_ancestor.canonicalize().with_context(|| {
            format!(
                "failed to validate project configuration output {}",
                candidate.display()
            )
        })?);
    if !canonical_ancestor.starts_with(root) {
        bail!(
            "project configuration output `{}` resolves outside the analyzed root; use --output for an operator-controlled path",
            output.display()
        );
    }
    Ok(())
}

/// `path` without the Windows verbatim prefix, so it compares with `Config::root` and strips to
/// a relative display path; unchanged on other platforms.
pub(crate) fn normalize_platform_path(path: PathBuf) -> PathBuf {
    #[cfg(windows)]
    {
        if let Some(plain) = strip_verbatim_prefix(&path) {
            return plain;
        }
    }
    path
}

/// `path` without its `\\?\X:` or `\\?\UNC\server\share` verbatim prefix, rebuilt from its
/// components without any `OsStr` to `str` conversion. `None` keeps the verbatim form.
#[cfg(windows)]
fn strip_verbatim_prefix(path: &Path) -> Option<PathBuf> {
    use std::ffi::OsStr;
    use std::path::Prefix;
    let mut components = path.components();
    let prefix = match components.next() {
        Some(Component::Prefix(prefix)) => prefix,
        _ => return None, // fail-closed: a path without a prefix has nothing to strip
    };
    let drive;
    let (lead, head) = match prefix.kind() {
        Prefix::VerbatimDisk(letter) => {
            drive = format!("{}:", char::from(letter));
            ("", vec![OsStr::new(&drive)])
        }
        Prefix::VerbatimUNC(server, share) => (r"\\", vec![server, share]),
        _ => return None, // fail-closed: device, volume and non-verbatim prefixes keep their form
    };
    let rest: Vec<_> = components.collect();
    let suffix_len = path.as_os_str().len() - prefix.as_os_str().len();
    plain_verbatim_path(lead, &head, &rest, suffix_len)
}

/// The plain form `lead` + `head` + `\` + the `Normal` names of `rest` when it names the same
/// file: every name passes `plain_name`, and its length equals the head plus `suffix_len` (the
/// verbatim length after the prefix), which holds only when `rest` is one root followed by
/// `\`-separated names, so no `.`, `..`, empty or trailing component was dropped. An empty suffix
/// is a UNC share root (`\\server\share`); a drive has none, since plain `C:` names its current
/// directory. Length is not
/// limited: std re-adds the verbatim prefix to long paths, and a limit would leave a long path
/// verbatim under a plain `Config::root`, failing containment. `None` keeps the verbatim form.
#[cfg(any(windows, test))]
fn plain_verbatim_path(
    lead: &str,
    head: &[&std::ffi::OsStr],
    rest: &[Component<'_>],
    suffix_len: usize,
) -> Option<PathBuf> {
    let names: Vec<_> = rest
        .iter()
        .filter_map(|component| match component {
            Component::Normal(name) => Some(*name),
            _ => None, // fail-closed: the length check rejects any dropped component but the root
        })
        .collect();
    let mut plain = std::ffi::OsString::from(lead);
    plain.push(join_with_separator(head));
    let head_len = plain.len();
    if suffix_len > 0 {
        plain.push(r"\");
        plain.push(join_with_separator(&names));
    }
    (plain.len() == head_len + suffix_len
        && (suffix_len > 0 || !lead.is_empty())
        && head.iter().all(|name| plain_name(name))
        && names
            .iter()
            .all(|name| plain_name(name) && plain_chars(name)))
    .then(|| plain.into())
}

/// `parts` joined with `\`, built without the unstable `OsStr` slice `join`.
#[cfg(any(windows, test))]
fn join_with_separator(parts: &[&std::ffi::OsStr]) -> std::ffi::OsString {
    let mut joined = std::ffi::OsString::new();
    for (index, part) in parts.iter().enumerate() {
        if index > 0 {
            joined.push(r"\");
        }
        joined.push(part);
    }
    joined
}

/// Whether `name` holds no character Win32 rejects or reinterprets: the reserved `<>:"|?*`
/// (`:` starts a stream name) and control characters below U+0020. Checked on the `names` only;
/// the head is a drive or server name the verbatim form already validated.
#[cfg(any(windows, test))]
fn plain_chars(name: &std::ffi::OsStr) -> bool {
    name.as_encoded_bytes()
        .iter()
        .all(|&byte| byte >= 0x20 && !br#"<>:"|?*"#.contains(&byte))
}

/// Whether Win32 keeps `name` unchanged in a plain path: not a DOS device name (superscript
/// aliases and console handles included), no trailing dot or space, no `/`. Device checks run on
/// the encoded bytes, so names that are not valid Unicode are checked too; `plain_chars` covers
/// the remaining characters.
#[cfg(any(windows, test))]
fn plain_name(name: &std::ffi::OsStr) -> bool {
    // Reserved names from "Naming Files, Paths, and Namespaces", and the console handles from
    // "CreateFileW".
    const RESERVED: [&[u8]; 32] = [
        b"CON",
        b"CONIN$",
        b"CONOUT$",
        b"PRN",
        b"AUX",
        b"NUL",
        b"COM0",
        b"COM1",
        b"COM2",
        b"COM3",
        b"COM4",
        b"COM5",
        b"COM6",
        b"COM7",
        b"COM8",
        b"COM9",
        "COM¹".as_bytes(),
        "COM²".as_bytes(),
        "COM³".as_bytes(),
        b"LPT0",
        b"LPT1",
        b"LPT2",
        b"LPT3",
        b"LPT4",
        b"LPT5",
        b"LPT6",
        b"LPT7",
        b"LPT8",
        b"LPT9",
        "LPT¹".as_bytes(),
        "LPT²".as_bytes(),
        "LPT³".as_bytes(),
    ];
    let bytes = name.as_encoded_bytes();
    let stem = bytes
        .split(|&byte| byte == b'.')
        .next()
        .unwrap_or_default()
        .trim_ascii_end();
    let device = RESERVED
        .iter()
        .any(|reserved| stem.eq_ignore_ascii_case(reserved));
    !bytes.ends_with(b".") && !bytes.ends_with(b" ") && !bytes.contains(&b'/') && !device
}

/// `path` canonicalized and normalized like `Config::root`, so paths reached through the
/// filesystem compare with, and strip to relative paths under, the analysis root on every platform.
pub(crate) fn canonical_platform_path(path: &Path) -> std::io::Result<PathBuf> {
    path.canonicalize().map(normalize_platform_path)
}

fn read_raw_config(path: &Path) -> Result<RawConfig> {
    let text = read_utf8(path, "CukeDedup configuration", MAX_CONFIG_INPUT_BYTES)?;
    // serde_json's default recursion limit remains enabled for untrusted config input.
    serde_json::from_str::<RawConfig>(&text)
        .with_context(|| format!("failed to parse {}", path.display()))
}

fn discover_config_file(
    root: &Path,
    warnings: &mut Vec<String>,
) -> Result<(Option<RawConfig>, Option<PathBuf>)> {
    const CANDIDATES: [&str; 4] = [
        ".cuke-dedup.json",
        ".config/cuke-dedup.json",
        ".config/.cuke-dedup.json",
        "cuke-dedup.config.json",
    ];
    for candidate in CANDIDATES {
        let path = root.join(candidate);
        if !path.is_file() {
            continue;
        }
        match read_raw_config(&path) {
            Ok(config) => return Ok((Some(config), Some(path))),
            Err(error) if is_input_limit_error(&error) => return Err(error),
            Err(error) => warnings.push(format!(
                "could not load auto-discovered config {} ({error:#}); trying the next configuration source",
                path.display()
            )),
        }
    }
    Ok((None, None))
}

fn config_source_name(path: &Path, root: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .to_string_lossy()
        .replace('\\', "/")
}

#[cfg(test)]
mod tests;