cuke-dedup 0.9.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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
//! Command-line parsing and analysis orchestration.

use crate::analysis;
use crate::config::{CliConfigOverrides, Config, ConfigOverrides, ReporterKind};
use crate::discovery;
use crate::model::{DuplicationThreshold, Rule, Severity};
use crate::source_adapter::ExtractionDiagnosticLevel;
use crate::{gherkin, modes, reporters, source_adapter};
use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;

#[derive(Debug, Parser)]
#[command(
    name = "cuke-dedup",
    version,
    about = "Detect duplicate and reusable Cucumber step definitions",
    after_help = "Examples:\n  cuke-dedup .\n  cuke-dedup check .\n  cuke-dedup . --reporters terminal,json,html\n  cuke-dedup . --reporters jsonl"
)]
struct Cli {
    /// Directory to analyze when no explicit command is used.
    #[arg(value_name = "PATH", default_value = ".")]
    path: PathBuf,

    #[command(subcommand)]
    command: Option<Command>,

    #[command(flatten)]
    options: CheckOptions,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Analyze a repository for duplicate and reusable step definitions.
    Check {
        /// Directory to analyze.
        #[arg(value_name = "PATH")]
        path: PathBuf,
    },
}

#[derive(Debug, Clone, Args, Default)]
struct CheckOptions {
    /// Explicit CukeDedup JSON configuration file.
    #[arg(long, short = 'c', global = true, value_name = "FILE")]
    config: Option<PathBuf>,

    /// Reporters to run (terminal, json, jsonl, html, sarif).
    #[arg(long, global = true, value_delimiter = ',')]
    reporters: Option<Vec<ReporterKind>>,

    /// Directory in which file-based reports are written.
    #[arg(long, global = true, value_name = "DIR")]
    output: Option<PathBuf>,

    /// Maximum percentage of definitions allowed in active duplication errors.
    #[arg(
        long,
        global = true,
        value_name = "PERCENT",
        allow_hyphen_values = true
    )]
    threshold: Option<f64>,

    /// Fail with exit code 2 when no feature files are discovered.
    #[arg(long, global = true)]
    require_features: bool,

    /// Fail with exit code 2 when the corpus or comparison set is incomplete.
    #[arg(long, global = true)]
    fail_on_incomplete: bool,

    /// Fail with exit code 2 when a discovered source file cannot be parsed. By default an
    /// unparseable file still contributes its error-recovered definitions, and the run is reported
    /// as incomplete rather than aborted.
    #[arg(long, global = true)]
    fail_on_unparseable: bool,

    /// Fail with exit code 2 when no step definitions are extracted.
    #[arg(long, global = true)]
    require_definitions: bool,

    /// Maximum unique definition pairs retained, up to the hard safety ceiling.
    #[arg(long, global = true, value_name = "COUNT", value_parser = parse_positive_usize)]
    max_candidate_comparisons: Option<usize>,

    /// Maximum structural proposals per handler class, up to the hard safety ceiling.
    #[arg(long, global = true, value_name = "COUNT", value_parser = parse_positive_usize)]
    max_structural_class_comparisons: Option<usize>,

    /// Glob patterns selecting step-definition source files.
    #[arg(long, global = true, value_delimiter = ',')]
    definitions: Option<Vec<String>>,

    /// Glob patterns selecting Gherkin feature files.
    #[arg(long, global = true, value_delimiter = ',')]
    features: Option<Vec<String>>,

    /// Print the effective feature source and every discovered input.
    #[arg(long, global = true)]
    explain_discovery: bool,

    /// Print the merged effective configuration as JSON and exit.
    #[arg(long, global = true)]
    print_config: bool,

    /// Omit runtime timing metrics from machine reports for reproducible output.
    #[arg(long, global = true)]
    no_metrics: bool,

    /// Glob patterns excluded from discovery.
    #[arg(long, global = true, value_delimiter = ',')]
    exclude: Option<Vec<String>>,

    /// Disable built-in exclusions such as node_modules and target.
    #[arg(long, global = true)]
    no_default_excludes: bool,

    /// Descend into dot-directories such as .steps.
    #[arg(long, global = true)]
    include_hidden: bool,

    /// Override a rule severity, for example duplicate-matcher=warning.
    #[arg(long = "rule", global = true, value_name = "RULE=SEVERITY", value_parser = parse_rule_override)]
    rules: Vec<(Rule, Severity)>,

    /// Report only findings involving files changed since this Git revision.
    #[arg(long, global = true, value_name = "GIT_REF")]
    changed_since: Option<String>,

    /// Suppress findings already present in a versioned semantic baseline.
    #[arg(
        long,
        global = true,
        value_name = "BASELINE.json",
        group = "baseline_source"
    )]
    baseline: Option<PathBuf>,

    /// Compare with a fetched Git revision using the current analysis configuration.
    #[arg(long, global = true, value_name = "GIT_REF", group = "baseline_source",
        conflicts_with_all = ["baseline", "update_baseline"])]
    baseline_from_ref: Option<String>,

    /// Rewrite the configured baseline from the current complete analysis.
    #[arg(
        long,
        global = true,
        requires = "baseline",
        conflicts_with = "changed_since"
    )]
    update_baseline: bool,

    /// Fail when more than COUNT findings are new relative to the baseline.
    #[arg(
        long,
        global = true,
        value_name = "COUNT",
        num_args = 0..=1,
        default_missing_value = "0",
        requires = "baseline_source",
        conflicts_with = "update_baseline"
    )]
    fail_on_new: Option<usize>,
}

struct Invocation {
    config: Config,
    options: CheckOptions,
}

#[derive(Default)]
struct Diagnostics {
    warnings: Vec<String>,
    errors: Vec<String>,
}

struct ExtractedCorpus {
    definitions: Vec<crate::model::StepDefinition>,
    feature_steps: Vec<crate::model::FeatureStep>,
    excluded_sources: Vec<(PathBuf, crate::source_filter::ExcludedSource)>,
    definition_files_with_definitions: usize,
    parsed_feature_files: usize,
    feature_files_without_steps: usize,
    incomplete: bool,
}

struct AnalyzedCorpus {
    result: crate::model::AnalysisResult,
    census: analysis::AnalysisCensus,
    definition_files_with_definitions: usize,
    parsed_feature_files: usize,
    feature_files_without_steps: usize,
    corpus_incomplete: bool,
    run_incomplete: bool,
}

struct PhaseTimings {
    discovery_ms: f64,
    parsing_ms: f64,
    analysis_ms: f64,
}

/// Parses the process arguments, runs the configured analysis, and returns its exit code.
pub fn run_cli() -> Result<i32> {
    execute(Cli::parse())
}

fn execute(cli: Cli) -> Result<i32> {
    let invocation = resolve_invocation(cli)?;
    let config = &invocation.config;
    let options = &invocation.options;
    if options.print_config {
        println!(
            "{}",
            serde_json::to_string_pretty(config)
                .context("failed to serialize effective configuration")?
        );
        return Ok(0);
    }
    let changed_files = resolve_changed_files(config, options.changed_since.as_deref())?;
    let discovery_started = Instant::now();
    let files = discovery::discover(config)?;
    let discovery_ms = elapsed_ms(discovery_started);

    let parsing_started = Instant::now();
    let mut diagnostics = discovery_diagnostics(config, &files, &changed_files);
    let extracted = extract_corpus(config, &files, &changed_files, &mut diagnostics);
    let parsing_ms = elapsed_ms(parsing_started);
    let analysis_started = Instant::now();
    let mut analyzed = analyze_corpus(config, extracted, &mut diagnostics)?;
    let analysis_ms = elapsed_ms(analysis_started);
    apply_finding_modes(
        &mut analyzed.result,
        &files,
        &changed_files,
        analyzed.parsed_feature_files,
        analyzed.feature_files_without_steps,
    );
    let baseline_outcome = apply_baseline_mode(
        config,
        options,
        &mut analyzed.result,
        analyzed.run_incomplete,
        &mut diagnostics,
    )?;
    write_reports(
        config,
        &files,
        &analyzed,
        &diagnostics,
        PhaseTimings {
            discovery_ms,
            parsing_ms,
            analysis_ms,
        },
    )?;
    write_diagnostics(config, options, &files, &diagnostics)?;
    determine_exit_code(
        config,
        options,
        &analyzed.result,
        baseline_outcome,
        &diagnostics,
    )
}

fn resolve_invocation(cli: Cli) -> Result<Invocation> {
    if cli.command.is_some() && cli.path.as_path() != Path::new(".") {
        bail!("do not place a path before `check`; use `cuke-dedup check <PATH>`");
    }
    let root = match cli.command {
        Some(Command::Check { path }) => path,
        None => cli.path,
    };
    let options = cli.options.clone();
    let config = Config::load_for_cli(
        &root,
        ConfigOverrides {
            config_file: cli.options.config,
            definitions: cli.options.definitions,
            features: cli.options.features,
            exclude: cli.options.exclude,
            exclude_defaults: cli.options.no_default_excludes.then_some(false),
            include_hidden: cli.options.include_hidden.then_some(true),
            reporters: cli.options.reporters,
            output: cli.options.output,
            threshold: cli.options.threshold,
            require_features: cli.options.require_features.then_some(true),
            no_metrics: cli.options.no_metrics.then_some(true),
            rules: cli.options.rules.into_iter().collect::<BTreeMap<_, _>>(),
        },
        CliConfigOverrides {
            require_definitions: cli.options.require_definitions.then_some(true),
            fail_on_incomplete: cli.options.fail_on_incomplete.then_some(true),
            fail_on_unparseable: cli.options.fail_on_unparseable.then_some(true),
            max_candidate_comparisons: cli.options.max_candidate_comparisons,
            max_structural_class_comparisons: cli.options.max_structural_class_comparisons,
        },
    )?;
    Ok(Invocation { config, options })
}

fn resolve_changed_files(
    config: &Config,
    changed_since: Option<&str>,
) -> Result<Option<BTreeSet<PathBuf>>> {
    let Some(base) = changed_since else {
        return Ok(None);
    };
    modes::ensure_changed_root_is_trackable(&config.root)?;
    Ok(Some(modes::git_changed_files(&config.root, base)?))
}

fn discovery_diagnostics(
    config: &Config,
    files: &discovery::DiscoveredFiles,
    changed_files: &Option<BTreeSet<PathBuf>>,
) -> Diagnostics {
    let mut diagnostics = Diagnostics {
        warnings: config.config_warnings.clone(),
        errors: files.errors.clone(),
    };
    for pattern in &files.unmatched_feature_patterns {
        diagnostics.warnings.push(format!(
            "feature pattern `{pattern}` from {} matched no files",
            config.feature_pattern_origin
        ));
    }
    for pattern in &files.unmatched_definition_patterns {
        diagnostics
            .warnings
            .push(format!("definition pattern `{pattern}` matched no files"));
    }
    if files.definitions.is_empty() && config.definitions.is_empty() {
        diagnostics
            .warnings
            .push("automatic discovery found no supported step-definition source files".to_owned());
    }
    if files.features.is_empty() {
        let message = format!(
            "no feature files matched patterns from {}; unused-definition findings are disabled for this incomplete corpus",
            config.feature_pattern_origin
        );
        if config.require_features {
            diagnostics.errors.push(message);
        } else if !files.definitions.is_empty() {
            diagnostics.warnings.push(message);
        }
    }
    if changed_files.as_ref().is_some_and(BTreeSet::is_empty) {
        diagnostics.warnings.push(
            "--changed-since found no tracked or untracked files; no findings will be reported"
                .to_owned(),
        );
    }
    diagnostics
}

fn extract_corpus(
    config: &Config,
    files: &discovery::DiscoveredFiles,
    changed_files: &Option<BTreeSet<PathBuf>>,
    diagnostics: &mut Diagnostics,
) -> ExtractedCorpus {
    let mut corpus = ExtractedCorpus {
        definitions: Vec::new(),
        feature_steps: Vec::new(),
        excluded_sources: Vec::new(),
        definition_files_with_definitions: 0,
        parsed_feature_files: 0,
        feature_files_without_steps: 0,
        incomplete: false,
    };
    extract_definitions(config, files, changed_files, diagnostics, &mut corpus);
    extract_feature_steps(config, files, diagnostics, &mut corpus);
    corpus
}

fn extract_definitions(
    config: &Config,
    files: &discovery::DiscoveredFiles,
    changed_files: &Option<BTreeSet<PathBuf>>,
    diagnostics: &mut Diagnostics,
    corpus: &mut ExtractedCorpus,
) {
    let mut extraction_session = source_adapter::SourceExtractionSession::with_options(
        &config.root,
        &config.registrations,
        &config.assertion_modules,
    );
    for file in &files.definitions {
        // Generated bundles, compressed payloads and binary blobs reach here whenever they carry
        // a source extension. They cannot contain an authored definition, so they are excluded
        // before parsing rather than analyzed and discarded.
        if let Some(excluded) = crate::source_filter::inspect(&file.path, &config.registrations) {
            // Every one of these signals is a heuristic over file content, not a proof: a NUL
            // byte or an archive header can appear inside an authored comment or string, and
            // minified geometry cannot be told apart from one very long authored line. So the
            // analyzed corpus no longer represents everything discovered, and
            // `--fail-on-incomplete` must fail closed rather than let a duplicate pass the gate.
            corpus.incomplete = true;
            corpus.excluded_sources.push((file.path.clone(), excluded));
            continue;
        }
        let adapter = source_adapter::adapter_for_language(file.language);
        match adapter
            .extract_file_with_session(file, &mut extraction_session)
            .with_context(|| format!("failed to analyze {}", file.path.display()))
        {
            Ok(extracted) => {
                if !extracted.definitions.is_empty() {
                    corpus.definition_files_with_definitions += 1;
                }
                corpus.definitions.extend(extracted.definitions);
                collect_extraction_diagnostics(
                    config,
                    file,
                    changed_files,
                    extracted.diagnostics,
                    diagnostics,
                    &mut corpus.incomplete,
                );
            }
            // Every discovered source contributes to cross-file definition comparisons, even
            // when changed mode later filters findings. Skipping an unreadable source could turn
            // an incomplete run into a false pass.
            Err(error) => diagnostics.errors.push(format!("{error:#}")),
        }
    }
    corpus.definitions.sort_by(|left, right| {
        left.location
            .path
            .cmp(&right.location.path)
            .then(left.location.line.cmp(&right.location.line))
            .then(left.location.column.cmp(&right.location.column))
    });
    report_excluded_sources(config, &corpus.excluded_sources, diagnostics);
    if corpus.definitions.is_empty() {
        let message = if files.definitions.is_empty() {
            "no step definitions were extracted because no definition source files were discovered"
                .to_owned()
        } else {
            format!(
                "definition extraction produced 0 definitions from {} discovered definition source file(s)",
                files.definitions.len()
            )
        };
        if config.require_definitions {
            diagnostics.errors.push(message);
        } else if !files.definitions.is_empty() {
            diagnostics.warnings.push(message);
        }
    }
}

/// Maximum excluded paths named individually before the warning summarizes the remainder.
const MAX_LISTED_EXCLUDED_SOURCES: usize = 10;

/// Records excluded sources as a warning so an exclusion is never silent.
///
/// The exclusion is a heuristic over file content, so a reader has to be able to see which files
/// it removed and why. It stays a warning rather than an error because generated output in a
/// repository is ordinary and must not fail an otherwise clean run.
fn report_excluded_sources(
    config: &Config,
    excluded: &[(PathBuf, crate::source_filter::ExcludedSource)],
    diagnostics: &mut Diagnostics,
) {
    if excluded.is_empty() {
        return;
    }
    let listed = excluded
        .iter()
        .take(MAX_LISTED_EXCLUDED_SOURCES)
        .map(|(path, reason)| {
            let relative = path
                .strip_prefix(&config.root)
                .unwrap_or(path)
                .to_string_lossy()
                .replace('\\', "/");
            format!("{relative} ({})", reason.as_str())
        })
        .collect::<Vec<_>>()
        .join(", ");
    let remainder = excluded.len().saturating_sub(MAX_LISTED_EXCLUDED_SOURCES);
    let suffix = if remainder == 0 {
        String::new()
    } else {
        format!(", and {remainder} more")
    };
    diagnostics.warnings.push(format!(
        "excluded {} discovered definition source file(s) as generated or non-source content: {listed}{suffix}",
        excluded.len()
    ));
}

fn collect_extraction_diagnostics(
    config: &Config,
    file: &source_adapter::SourceFile,
    changed_files: &Option<BTreeSet<PathBuf>>,
    extracted: Vec<source_adapter::ExtractionDiagnostic>,
    diagnostics: &mut Diagnostics,
    corpus_incomplete: &mut bool,
) {
    let changed_or_full_run = changed_files
        .as_ref()
        .is_none_or(|changed| changed.contains(&file.path));
    for diagnostic in extracted {
        let message = format!(
            "{}: {}",
            diagnostic.location.display(&config.root),
            diagnostic.message
        );
        let completeness = source_adapter::is_completeness_diagnostic(&diagnostic);
        let unparseable = source_adapter::is_unparseable_diagnostic(&diagnostic);
        // An unresolved registration import — or a file that could not be parsed — hides every
        // definition it would have introduced, so the corpus is incomplete regardless of which
        // files changed.
        *corpus_incomplete |= completeness;
        match diagnostic.level {
            // An unparseable file is tolerated by default: its error-recovered definitions still
            // contribute and the corpus is marked incomplete above. `--fail-on-unparseable`
            // restores the hard stop without also failing on other kinds of incompleteness.
            ExtractionDiagnosticLevel::Warning if unparseable && config.fail_on_unparseable => {
                diagnostics.errors.push(message);
            }
            ExtractionDiagnosticLevel::Warning if changed_or_full_run || completeness => {
                diagnostics.warnings.push(message);
            }
            ExtractionDiagnosticLevel::Warning => {}
            // Extraction errors can mean definitions were omitted. They remain fatal for
            // unchanged files because those definitions still participate in changed-file pairs.
            ExtractionDiagnosticLevel::Error => diagnostics.errors.push(message),
        }
    }
}

fn extract_feature_steps(
    config: &Config,
    files: &discovery::DiscoveredFiles,
    diagnostics: &mut Diagnostics,
    corpus: &mut ExtractedCorpus,
) {
    for file in &files.features {
        match gherkin::extract_file_with_format(&file.path, file.format) {
            Ok(extracted) => {
                corpus.parsed_feature_files += 1;
                if extracted.is_empty()
                    && file.format == crate::gherkin::FeatureFormat::GherkinMarkdown
                {
                    corpus.feature_files_without_steps += 1;
                    corpus.incomplete = true;
                    let display = file
                        .path
                        .strip_prefix(&config.root)
                        .unwrap_or(&file.path)
                        .to_string_lossy()
                        .replace('\\', "/");
                    diagnostics.warnings.push(format!(
                        "Gherkin Markdown file {display} parsed successfully but produced 0 feature steps; unused-definition findings are disabled for this incomplete corpus"
                    ));
                } else {
                    corpus.feature_steps.extend(extracted);
                }
            }
            // Changed definitions still depend on the full feature corpus for usage and ambiguity.
            Err(error) => diagnostics.errors.push(format!("{error:#}")),
        }
    }
    if !files.features.is_empty() && corpus.parsed_feature_files < files.features.len() {
        let message = if corpus.parsed_feature_files == 0 {
            "no discovered feature file was parsed successfully; unused-definition findings are disabled for this incomplete corpus".to_owned()
        } else {
            format!(
                "{} discovered feature file(s) could not be parsed; unused-definition findings are disabled for this incomplete corpus",
                files.features.len() - corpus.parsed_feature_files
            )
        };
        if config.require_features {
            diagnostics.errors.push(message);
        } else if !files.definitions.is_empty() {
            diagnostics.warnings.push(message);
        }
    }
    corpus.feature_steps.sort_by(|left, right| {
        left.location
            .path
            .cmp(&right.location.path)
            .then(left.location.line.cmp(&right.location.line))
            .then(left.location.column.cmp(&right.location.column))
    });
}

fn analyze_corpus(
    config: &Config,
    extracted: ExtractedCorpus,
    diagnostics: &mut Diagnostics,
) -> Result<AnalyzedCorpus> {
    let ExtractedCorpus {
        definitions,
        feature_steps,
        // Reported during extraction; analysis works only from what survived exclusion.
        excluded_sources: _,
        definition_files_with_definitions,
        parsed_feature_files,
        feature_files_without_steps,
        incomplete: corpus_incomplete,
    } = extracted;
    let (analysis, census, unmatched_suppressions) =
        analysis::analyze_for_cli(definitions, feature_steps, config)?;
    for index in unmatched_suppressions.indices {
        let suppression = &config.suppressions[index];
        diagnostics.warnings.push(format!(
            "suppression {} for {} matched no step definitions",
            index + 1,
            suppression.rule
        ));
    }
    if unmatched_suppressions.truncated {
        diagnostics.warnings.push(
            "unmatched suppression validation stopped after its safety limit; analysis findings are unaffected"
                .to_owned(),
        );
    }

    // Bounded work that could not finish makes findings a subset of a complete run, but every
    // reported finding remains valid. `--fail-on-incomplete` restores strict CI gating.
    let run_incomplete = corpus_incomplete || !analysis.incomplete.is_empty();
    if config.fail_on_incomplete {
        diagnostics.errors.extend(analysis.incomplete);
        if corpus_incomplete {
            diagnostics.errors.push(
                "input extraction did not fully represent every discovered definition or feature file, so the analyzed corpus is incomplete".to_owned(),
            );
        }
    } else {
        diagnostics.warnings.extend(analysis.incomplete);
    }
    Ok(AnalyzedCorpus {
        result: analysis.result,
        census,
        definition_files_with_definitions,
        parsed_feature_files,
        feature_files_without_steps,
        corpus_incomplete,
        run_incomplete,
    })
}

fn apply_finding_modes(
    result: &mut crate::model::AnalysisResult,
    files: &discovery::DiscoveredFiles,
    changed_files: &Option<BTreeSet<PathBuf>>,
    parsed_feature_files: usize,
    feature_files_without_steps: usize,
) {
    // A converter can produce a syntactically valid but empty document when it fails to
    // recognize markup or a dialect. Such an input cannot prove that a definition is unused,
    // so use the same conservative suppression as a feature parse failure.
    if parsed_feature_files < files.features.len()
        || feature_files_without_steps > 0
        || files.features.is_empty()
    {
        result
            .findings
            .retain(|finding| finding.rule != Rule::UnusedDefinition);
    }
    if let Some(changed) = changed_files {
        modes::retain_changed_findings(&mut result.findings, changed);
    }
}

fn apply_baseline_mode(
    config: &Config,
    options: &CheckOptions,
    result: &mut crate::model::AnalysisResult,
    run_incomplete: bool,
    diagnostics: &mut Diagnostics,
) -> Result<Option<modes::BaselineOutcome>> {
    if let Some(revision) = &options.baseline_from_ref {
        let (_snapshot, root) = modes::baseline_snapshot(&config.root, revision)?;
        // Freeze the current policy instead of loading historical rule/config overrides. The
        // baseline revision inherits the run's own strictness rather than being forced strict: an
        // incomplete history (a vendored bundle excluded, an unparseable file, a bounded analysis)
        // still yields a sound subtraction for the findings it did extract, so it is tolerated by
        // default and reported. `--fail-on-incomplete` flows through `base_config` to surface that
        // incompleteness as an error and reject the baseline.
        let mut base_config = config.clone();
        base_config.root = root;
        let files = discovery::discover(&base_config)?;
        let mut base_diagnostics = discovery_diagnostics(&base_config, &files, &None);
        let extracted = extract_corpus(&base_config, &files, &None, &mut base_diagnostics);
        let mut base = analyze_corpus(&base_config, extracted, &mut base_diagnostics)?;
        // A baseline that produced a hard error, or that discovered definition files yet extracted
        // no definitions, or that has no features to anchor usage, cannot be subtracted at all —
        // those always bail. Soft incompleteness only bails under `--fail-on-incomplete`, which
        // routes through `base_diagnostics.errors` above.
        if !base_diagnostics.errors.is_empty()
            || (!files.definitions.is_empty() && base.result.definitions.is_empty())
            || (files.features.is_empty() && !base.result.definitions.is_empty())
        {
            bail!(
                "baseline revision `{revision}` is incomplete: {}",
                base_diagnostics
                    .errors
                    .iter()
                    .chain(&base_diagnostics.warnings)
                    .cloned()
                    .collect::<Vec<_>>()
                    .join("; ")
            );
        }
        if base.run_incomplete {
            diagnostics.warnings.push(format!(
                "baseline revision `{revision}` is incomplete, so a finding it did not extract may appear as new; pass --fail-on-incomplete to reject an incomplete baseline"
            ));
        }
        apply_finding_modes(
            &mut base.result,
            &files,
            &None,
            base.parsed_feature_files,
            base.feature_files_without_steps,
        );
        return modes::apply_reference_baseline(
            &mut result.findings,
            &base.result.findings,
            revision,
        )
        .map(Some);
    }
    let Some(path) = &options.baseline else {
        return Ok(None);
    };
    let path = if path.is_absolute() {
        path.clone()
    } else {
        config.root.join(path)
    };
    if options.update_baseline && (run_incomplete || !diagnostics.errors.is_empty()) {
        diagnostics.warnings.push(format!(
            "baseline {} was not updated because analysis is incomplete",
            path.display()
        ));
        return Ok(None);
    }
    let outcome = if options.update_baseline {
        modes::update_baseline(&mut result.findings, &path)?
    } else {
        modes::apply_baseline(&mut result.findings, &path)?
    };
    if options.update_baseline {
        diagnostics.warnings.push(format!(
            "updated baseline {}: {} added, {} removed, {} total",
            path.display(),
            outcome.added,
            outcome.removed,
            outcome.suppressed
        ));
    }
    Ok(Some(outcome))
}

fn write_reports(
    config: &Config,
    files: &discovery::DiscoveredFiles,
    analyzed: &AnalyzedCorpus,
    diagnostics: &Diagnostics,
    timings: PhaseTimings,
) -> Result<()> {
    let corpus = reporters::CorpusCensus {
        definition_files: files.definitions.len(),
        definition_files_with_definitions: analyzed.definition_files_with_definitions,
        definitions_extracted: analyzed.result.definitions.len(),
        feature_files: files.features.len(),
        feature_files_parsed: analyzed.parsed_feature_files,
        feature_files_without_steps: analyzed.feature_files_without_steps,
        incomplete: analyzed.corpus_incomplete,
    };
    let metrics = reporters::ExecutionMetrics::new(
        files.definitions.len(),
        files.features.len(),
        timings.discovery_ms,
        timings.parsing_ms,
        timings.analysis_ms,
    );
    let report_metadata = reporters::CliReportMetadata {
        corpus: &corpus,
        analysis: &analyzed.census,
        // SARIF consumers treat a successful invocation as proof the tool covered its input.
        execution_successful: diagnostics.errors.is_empty() && !analyzed.run_incomplete,
    };
    let terminal_color = terminal_color_enabled(
        io::stdout().is_terminal(),
        std::env::var_os("NO_COLOR").as_deref(),
    );
    let mut stdout = io::stdout().lock();
    reporters::write_cli_reports(
        &analyzed.result,
        config,
        (!config.no_metrics).then_some(&metrics),
        &report_metadata,
        &mut stdout,
        terminal_color,
    )?;
    Ok(())
}

fn terminal_color_enabled(is_terminal: bool, no_color: Option<&std::ffi::OsStr>) -> bool {
    is_terminal && !no_color.is_some_and(|value| !value.is_empty())
}

fn write_diagnostics(
    config: &Config,
    options: &CheckOptions,
    files: &discovery::DiscoveredFiles,
    diagnostics: &Diagnostics,
) -> Result<()> {
    if !options.explain_discovery
        && diagnostics.warnings.is_empty()
        && diagnostics.errors.is_empty()
    {
        return Ok(());
    }
    let mut stderr = io::stderr().lock();
    if options.explain_discovery {
        writeln!(
            stderr,
            "cuke-dedup: feature patterns: {} ({})",
            config.features.join(", "),
            config.feature_pattern_origin
        )?;
        for file in &files.features {
            let relative = file.path.strip_prefix(&config.root).unwrap_or(&file.path);
            writeln!(
                stderr,
                "cuke-dedup: feature {} [{}] via {}",
                relative.display(),
                file.format.as_str(),
                file.pattern
            )?;
        }
        for file in &files.definitions {
            let relative = file.path.strip_prefix(&config.root).unwrap_or(&file.path);
            writeln!(stderr, "cuke-dedup: definition {}", relative.display())?;
        }
    }
    for warning in &diagnostics.warnings {
        writeln!(stderr, "cuke-dedup: warning: {warning}")?;
    }
    for error in &diagnostics.errors {
        writeln!(stderr, "cuke-dedup: {error}")?;
    }
    Ok(())
}

fn determine_exit_code(
    config: &Config,
    options: &CheckOptions,
    result: &crate::model::AnalysisResult,
    baseline: Option<modes::BaselineOutcome>,
    diagnostics: &Diagnostics,
) -> Result<i32> {
    if !diagnostics.errors.is_empty() {
        return Ok(2);
    }
    let duplication = DuplicationThreshold::from_result(result, config.threshold);
    let has_non_duplication_errors = result.findings.iter().any(|finding| {
        finding.is_active()
            && finding.severity == Severity::Error
            && !finding.rule.contributes_to_duplication_threshold()
    });
    let new_findings_exceeded = options
        .fail_on_new
        .is_some_and(|limit| baseline.is_some_and(|outcome| outcome.new_findings > limit));
    Ok(i32::from(
        has_non_duplication_errors || !duplication.passed || new_findings_exceeded,
    ))
}

fn elapsed_ms(started: Instant) -> f64 {
    started.elapsed().as_secs_f64() * 1_000.0
}

fn parse_rule_override(value: &str) -> std::result::Result<(Rule, Severity), String> {
    let (rule, severity) = value
        .split_once('=')
        .ok_or_else(|| "expected RULE=SEVERITY".to_owned())?;
    Ok((rule.parse()?, severity.parse()?))
}

fn parse_positive_usize(value: &str) -> std::result::Result<usize, String> {
    value
        .parse::<usize>()
        .ok()
        .filter(|value| *value > 0)
        .ok_or_else(|| "expected an integer greater than zero".to_owned())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn terminal_color_requires_tty_and_allows_no_color_opt_out() {
        use std::ffi::OsStr;

        assert!(terminal_color_enabled(true, None));
        assert!(terminal_color_enabled(true, Some(OsStr::new(""))));
        assert!(!terminal_color_enabled(true, Some(OsStr::new("1"))));
        assert!(!terminal_color_enabled(false, None));
        assert!(!terminal_color_enabled(false, Some(OsStr::new(""))));
    }

    #[test]
    fn parses_rule_override() {
        assert_eq!(
            parse_rule_override("duplicate-matcher=warning"),
            Ok((Rule::DuplicateMatcher, Severity::Warning))
        );
        assert!(parse_rule_override("unknown=error").is_err());
    }

    #[test]
    fn candidate_limit_cli_values_must_be_positive() {
        assert_eq!(parse_positive_usize("7"), Ok(7));
        assert!(parse_positive_usize("0").is_err());
        assert!(parse_positive_usize("-1").is_err());
        assert!(parse_positive_usize("many").is_err());
    }

    #[test]
    fn unparseable_diagnostics_are_tolerated_by_default_and_escalated_by_the_flag() {
        use crate::discovery::SourceLanguage;
        use crate::model::SourceLocation;
        use crate::source_adapter::{ExtractionDiagnostic, SourceFile};

        let directory = tempfile::tempdir().unwrap();
        let file = SourceFile {
            path: directory.path().join("steps.ts"),
            language: SourceLanguage::TypeScript,
        };
        let unparseable = || {
            ExtractionDiagnostic::new(
                ExtractionDiagnosticLevel::Warning,
                SourceLocation::new("steps.ts", 1, 1, 1, 1),
                format!(
                    "{}, so analysis is incomplete",
                    source_adapter::UNPARSEABLE_SOURCE_DIAGNOSTIC_PREFIX
                ),
            )
        };
        let route = |config: &Config, diagnostic: ExtractionDiagnostic| {
            let mut diagnostics = Diagnostics {
                warnings: Vec::new(),
                errors: Vec::new(),
            };
            let mut incomplete = false;
            collect_extraction_diagnostics(
                config,
                &file,
                &None,
                vec![diagnostic],
                &mut diagnostics,
                &mut incomplete,
            );
            (diagnostics, incomplete)
        };

        let mut config =
            Config::load(directory.path(), ConfigOverrides::default()).expect("config loads");

        // Default: an unparseable file is a completeness warning, not an error.
        let (diagnostics, incomplete) = route(&config, unparseable());
        assert!(incomplete);
        assert!(diagnostics.errors.is_empty());
        assert_eq!(diagnostics.warnings.len(), 1);

        // `--fail-on-unparseable`: the same diagnostic becomes a hard error, still marking the
        // corpus incomplete.
        config.fail_on_unparseable = true;
        let (diagnostics, incomplete) = route(&config, unparseable());
        assert!(incomplete);
        assert_eq!(diagnostics.errors.len(), 1);
        assert!(diagnostics.warnings.is_empty());

        // Opposite-answer control: an unrelated warning is neither escalated by the flag nor
        // treated as a completeness signal, so the flag targets only the unparseable case.
        let dynamic = ExtractionDiagnostic::new(
            ExtractionDiagnosticLevel::Warning,
            SourceLocation::new("steps.ts", 2, 1, 2, 1),
            "dynamic or unsupported step matcher cannot be analyzed statically",
        );
        let (diagnostics, incomplete) = route(&config, dynamic);
        assert!(!incomplete);
        assert!(diagnostics.errors.is_empty());
        assert_eq!(diagnostics.warnings.len(), 1);
    }

    #[test]
    fn supports_implicit_and_explicit_check_forms() {
        let implicit = Cli::try_parse_from(["cuke-dedup", ".", "--reporters", "json"])
            .expect("implicit invocation");
        assert!(implicit.command.is_none());
        let explicit = Cli::try_parse_from(["cuke-dedup", "check", ".", "--reporters", "json"])
            .expect("explicit invocation");
        assert!(matches!(explicit.command, Some(Command::Check { .. })));
        assert!(Cli::try_parse_from(["cuke-dedup", "check"]).is_err());
    }
}