rumdl 0.2.66

A fast Markdown linter and formatter written in Rust
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
//! Parser and applier for the `--config` flag.
//!
//! Each `--config` value is either a path to a config file or an inline TOML
//! `KEY = VALUE` snippet that overrides specific options. This mirrors Ruff's
//! `--config` flag, so users can do:
//!
//! ```sh
//! rumdl check --config path/to/.rumdl.toml --config 'MD013.line_length = 20'
//! ```
//!
//! Path detection: a value pointing to an existing file is treated as a path;
//! otherwise we try to parse it as a single-line TOML table.

use std::path::{Path, PathBuf};

use clap::builder::TypedValueParser;
use rumdl_lib::config::{
    ConfigSource, SourcedConfig, SourcedRuleConfig, SourcedValue, default_registry, is_global_value_key, normalize_key,
};

/// Stable name for the variant of a `toml::Value`, used in warning messages.
fn toml_value_kind(v: &toml::Value) -> &'static str {
    match v {
        toml::Value::String(_) => "string",
        toml::Value::Integer(_) => "integer",
        toml::Value::Float(_) => "float",
        toml::Value::Boolean(_) => "boolean",
        toml::Value::Datetime(_) => "datetime",
        toml::Value::Array(_) => "array",
        toml::Value::Table(_) => "table",
    }
}

/// One `--config` argument: either a path or a TOML override snippet.
#[derive(Clone, Debug)]
pub enum SingleConfigArgument {
    FilePath(PathBuf),
    InlineOverride(toml::Table),
}

/// Custom clap value parser that distinguishes paths from inline TOML.
#[derive(Clone, Debug)]
pub struct ConfigArgumentParser;

impl clap::builder::ValueParserFactory for SingleConfigArgument {
    type Parser = ConfigArgumentParser;

    fn value_parser() -> Self::Parser {
        ConfigArgumentParser
    }
}

impl TypedValueParser for ConfigArgumentParser {
    type Value = SingleConfigArgument;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, clap::Error> {
        let Some(value_str) = value.to_str() else {
            // Non-UTF-8 input can only be a path; accept verbatim and let the
            // downstream loader report a missing-file error if needed.
            return Ok(SingleConfigArgument::FilePath(PathBuf::from(value)));
        };

        // No `=` means the user can only have meant a path — even if it
        // doesn't exist, accept it so the downstream loader can produce the
        // existing "config file not found" error (which carries the helpful
        // `--category` hint on the `rule` subcommand).
        if !value_str.contains('=') {
            return Ok(SingleConfigArgument::FilePath(PathBuf::from(value_str)));
        }

        // Has `=`: prefer a real file (rare path with `=` in name still works)
        // before treating it as inline TOML.
        let path = Path::new(value_str);
        if path.is_file() {
            return Ok(SingleConfigArgument::FilePath(path.to_path_buf()));
        }

        let toml_error = match toml::from_str::<toml::Table>(value_str) {
            Ok(table) => return Ok(SingleConfigArgument::InlineOverride(table)),
            Err(e) => e,
        };

        let mut err = clap::Error::new(clap::error::ErrorKind::ValueValidation).with_cmd(cmd);
        if let Some(a) = arg {
            err.insert(
                clap::error::ContextKind::InvalidArg,
                clap::error::ContextValue::String(a.to_string()),
            );
        }
        err.insert(
            clap::error::ContextKind::InvalidValue,
            clap::error::ContextValue::String(value_str.to_string()),
        );

        let tip_indent = " ".repeat("  tip: ".len());
        let tip = format!(
            "A `--config` value must either be a path to a TOML configuration file\n\
             {tip_indent}or an inline TOML `KEY = VALUE` pair (e.g. `MD013.line_length = 20`)\n\n\
             Failed to parse as TOML:\n{toml_error}"
        )
        .into();

        err.insert(
            clap::error::ContextKind::Suggested,
            clap::error::ContextValue::StyledStrs(vec![tip]),
        );

        Err(err)
    }
}

/// Split a list of `--config` arguments into at most one config-file path plus
/// every inline override snippet. Errors if more than one file path is given.
pub fn split_config_args(items: &[SingleConfigArgument]) -> Result<(Option<PathBuf>, Vec<toml::Table>), String> {
    let mut path: Option<PathBuf> = None;
    let mut overrides: Vec<toml::Table> = Vec::new();
    for item in items {
        match item {
            SingleConfigArgument::FilePath(p) => {
                if let Some(existing) = &path {
                    return Err(format!(
                        "multiple --config file paths given: `{}` and `{}`. Use only one config file path.",
                        existing.display(),
                        p.display()
                    ));
                }
                path = Some(p.clone());
            }
            SingleConfigArgument::InlineOverride(t) => overrides.push(t.clone()),
        }
    }
    Ok((path, overrides))
}

/// Resolve a user-provided option key to its canonical form for the given rule.
///
/// Tries, in order: the registry's named-alias map (e.g. `enable_reflow` →
/// `reflow`), then a direct hit in the schema, then snake/kebab variants.
/// Falls back to the input as-is if nothing matches (so unknown keys still
/// flow through to the existing config validator and surface as warnings).
fn canonical_option_key(rule: &str, key: &str) -> String {
    let registry = default_registry();

    // Named aliases from the rule itself: alias -> canonical.
    if let Some(aliases) = registry.rule_aliases.get(rule)
        && let Some(canonical) = aliases.get(key)
    {
        return canonical.clone();
    }

    // Look in the rule's schema for the canonical form.
    if let Some(schema) = registry.rule_schemas.get(rule) {
        if schema.contains_key(key) {
            return key.to_string();
        }
        let kebab = key.replace('_', "-");
        if schema.contains_key(&kebab) {
            return kebab;
        }
        let snake = key.replace('-', "_");
        if schema.contains_key(&snake) {
            return snake;
        }
        let normalized = normalize_key(key);
        if schema.contains_key(&normalized) {
            return normalized;
        }
    }

    key.to_string()
}

/// Variants of an option key that could collide on the same field after
/// deserialization (kebab/snake/normalized + every named alias mapped to the
/// canonical key).
fn option_key_variants(rule: &str, canonical_opt: &str) -> std::collections::HashSet<String> {
    let mut out = std::collections::HashSet::new();
    out.insert(canonical_opt.to_string());
    out.insert(canonical_opt.replace('_', "-"));
    out.insert(canonical_opt.replace('-', "_"));
    out.insert(normalize_key(canonical_opt));

    let registry = default_registry();
    if let Some(aliases) = registry.rule_aliases.get(rule) {
        for (alias, canonical) in aliases {
            if canonical == canonical_opt {
                out.insert(alias.clone());
                out.insert(alias.replace('_', "-"));
                out.insert(alias.replace('-', "_"));
                out.insert(normalize_key(alias));
            }
        }
    }
    out
}

/// Apply inline `--config '...'` overrides to a sourced config.
///
/// Each top-level entry is dispatched based on its key:
/// - `RULE.opt = value` (where `RULE` resolves to a known rule) → rule-level override
/// - `global.opt = value` (explicit `[global]` table) → global override
/// - bare `opt = value` where `opt` is a known global key → global override
/// - a non-rule section (`code-block-tools`, `per-file-ignores`, `per-file-flavor`)
///   → the value that section is stored in, at CLI precedence
/// - everything else → recorded in `unknown_keys` so the existing validator surfaces a warning
///
/// Overrides land at `ConfigSource::Cli` precedence (the highest), so they win
/// over anything loaded from config files.
pub fn apply_inline_overrides(sourced: &mut SourcedConfig, overrides: &[toml::Table]) {
    let registry = default_registry();
    for table in overrides {
        for (top_key, top_value) in table {
            apply_top_level_entry(sourced, top_key, top_value, registry);
        }
    }
}

fn apply_top_level_entry(
    sourced: &mut SourcedConfig,
    top_key: &str,
    top_value: &toml::Value,
    registry: &rumdl_lib::config::RuleRegistry,
) {
    // Explicit `[global]` table: every entry inside is a global override.
    if normalize_key(top_key) == "global" {
        if let toml::Value::Table(globals) = top_value {
            for (gk, gv) in globals {
                apply_global_override(sourced, gk, gv);
            }
        }
        return;
    }

    // Discriminate by value shape, not by key alone — `line-length` is both a
    // global option and a known alias for MD013, so a bare scalar must take
    // the global path while `[line-length] line_length = 20` (a table) means
    // the rule.
    match top_value {
        toml::Value::Table(opts) => {
            // A non-rule section is stored in its own value on the config, so it
            // has to be routed there before the key is looked up as a rule name:
            // `resolve_rule_name` does not know it and would file the whole
            // section as an unknown rule, dropping the value.
            if apply_section_override(sourced, &normalize_key(top_key), opts) {
                return;
            }
            if let Some(canonical) = registry.resolve_rule_name(top_key) {
                apply_rule_override(sourced, &canonical, opts);
            } else {
                // Unknown rule section — surface via the same warning path as
                // config files.
                sourced.unknown_keys.push((format!("[{top_key}]"), String::new(), None));
            }
        }
        _ => {
            let normalized = normalize_key(top_key);
            if is_global_value_key(&normalized) {
                apply_global_override(sourced, &normalized, top_value);
            } else {
                sourced
                    .unknown_keys
                    .push(("[global]".to_string(), top_key.to_string(), None));
            }
        }
    }
}

/// Report a `--config` value that could not be applied.
///
/// Through `discovery_warnings`, the channel a config file's own unusable
/// values go through: `check`, `config` and `watch` all print it as
/// `[config warning]`, and `--deny-config-warnings` counts it. `log::warn!` is
/// invisible unless `RUST_LOG` is set, and for a mistake in what the user typed
/// on this very command line that leaves no feedback at all - the run simply
/// behaves as if the override had not been given.
fn report_unusable_override(sourced: &mut SourcedConfig, message: String) {
    sourced.discovery_warnings.push(message);
}

/// Route a top-level table to the non-rule section it names, returning whether
/// the key was one.
///
/// These sections live in their own fields on `SourcedConfig` rather than in the
/// rule map, and each merges as a single value, so an override lands through the
/// same `ConfigSource::Cli` precedence a config file's copy would have gone
/// through.
///
/// One rule decides how much of a section an override displaces, the same rule
/// ruff's `--config` follows: it sets the *settings* it names to the values
/// given, and settings it does not name keep what they were configured with.
/// `code-block-tools` holds several settings, so naming one leaves the others
/// alone; `per-file-ignores` and `per-file-flavor` are each a single setting
/// whose value is a map of user-written patterns, so naming one pattern
/// replaces the map.
fn apply_section_override(sourced: &mut SourcedConfig, section: &str, opts: &toml::Table) -> bool {
    match section {
        "code-block-tools" => apply_code_block_tools_override(sourced, opts),
        "per-file-ignores" => apply_per_file_ignores_override(sourced, opts),
        "per-file-flavor" => apply_per_file_flavor_override(sourced, opts),
        _ => return false,
    }
    true
}

/// Override individual `[code-block-tools]` settings, keeping the rest of the
/// section.
///
/// A command line names one setting at a time: `--config
/// 'code-block-tools.enabled = false'` means "run everything else as
/// configured, without the tools", so the languages and tool definitions the
/// run was configured with have to survive it. The override is therefore
/// applied key by key onto the section as merged so far, at top-level
/// granularity: naming `languages` sets that setting, replacing the whole map
/// it holds.
fn apply_code_block_tools_override(sourced: &mut SourcedConfig, opts: &toml::Table) {
    use rumdl_lib::code_block_tools::CodeBlockToolsConfig;

    let current = sourced.code_block_tools.value.clone();
    let mut table = match toml::Table::try_from(current.clone()) {
        Ok(table) => table,
        Err(e) => {
            report_unusable_override(
                sourced,
                format!(
                    "--config [code-block-tools]: could not read the section as configured: {e}. The override was not applied."
                ),
            );
            return;
        }
    };

    for (key, value) in opts {
        table.insert(normalize_key(key), value.clone());
    }

    match toml::Value::Table(table).try_into::<CodeBlockToolsConfig>() {
        Ok(mut new_config) => {
            // Provenance, not configuration: the settings that were not named
            // still came from wherever they came from, and the section is what
            // carries the mark, so a run that overrides one key does not make
            // the rest quotable.
            new_config.values_withheld = current.values_withheld;
            sourced
                .code_block_tools
                .merge_override(new_config, ConfigSource::Cli, None);
        }
        Err(e) => {
            report_unusable_override(
                sourced,
                // `message()` rather than the whole error: a `toml` deserialize
                // error renders its span across several lines, and there is no
                // document here to point into.
                format!(
                    "--config [code-block-tools]: {}. The section was left as configured.",
                    e.message()
                ),
            );
        }
    }
}

/// Set `[per-file-ignores]` to the patterns this run names.
///
/// The map is the value of one setting, so an override replaces it whole, the
/// way a higher-precedence config file's copy does and the way ruff's own
/// `--config` treats `lint.per-file-ignores`. A run that wants to keep the
/// project's other exemptions names them too.
fn apply_per_file_ignores_override(sourced: &mut SourcedConfig, opts: &toml::Table) {
    let registry = default_registry();
    let mut map = std::collections::BTreeMap::new();

    for (pattern, value) in opts {
        let toml::Value::Array(items) = value else {
            report_unusable_override(
                sourced,
                format!(
                    "--config per-file-ignores.\"{pattern}\": expected an array of rule names, got {}. That pattern was skipped; the rest of the override still applies.",
                    toml_value_kind(value)
                ),
            );
            continue;
        };
        let rules: Vec<String> = items
            .iter()
            .filter_map(|item| item.as_str())
            .map(|s| registry.resolve_rule_name(s).unwrap_or_else(|| normalize_key(s)))
            .collect();
        map.insert(pattern.clone(), rules);
    }

    sourced.per_file_ignores.merge_override(map, ConfigSource::Cli, None);
}

/// Set `[per-file-flavor]` to the patterns this run names, replacing the
/// configured map as for `[per-file-ignores]`.
///
/// Replacing it also settles the ordering question the section carries - a file
/// takes the flavor of the first pattern it matches - since the patterns the
/// override installs are the only ones there are to match.
fn apply_per_file_flavor_override(sourced: &mut SourcedConfig, opts: &toml::Table) {
    use rumdl_lib::config::MarkdownFlavor;
    use serde::Deserialize;

    let mut map = indexmap::IndexMap::new();

    for (pattern, value) in opts {
        let toml::Value::String(flavor_str) = value else {
            report_unusable_override(
                sourced,
                format!(
                    "--config per-file-flavor.\"{pattern}\": expected a flavor name, got {}. That pattern was skipped; the rest of the override still applies.",
                    toml_value_kind(value)
                ),
            );
            continue;
        };
        match MarkdownFlavor::deserialize(toml::Value::String(flavor_str.clone())) {
            Ok(flavor) => {
                map.insert(pattern.clone(), flavor);
            }
            Err(_) => {
                report_unusable_override(
                    sourced,
                    format!(
                        "--config per-file-flavor.\"{pattern}\": invalid flavor '{flavor_str}'. Valid values: {}. That pattern was skipped; the rest of the override still applies.",
                        rumdl_lib::config::CANONICAL_MARKDOWN_FLAVORS
                    ),
                );
            }
        }
    }

    sourced.per_file_flavor.merge_override(map, ConfigSource::Cli, None);
}

fn apply_rule_override(sourced: &mut SourcedConfig, canonical_rule: &str, opts: &toml::Table) {
    let entry = sourced
        .rules
        .entry(canonical_rule.to_string())
        .or_insert_with(SourcedRuleConfig::default);

    for (opt_key, opt_value) in opts {
        let canonical_opt = canonical_option_key(canonical_rule, opt_key);

        // Remove any other variants of this option that might already be
        // present (e.g. `line-length` when overriding `line_length`).
        // Otherwise serde sees both keys and errors out with "duplicate
        // field" because the canonical and alias forms collide.
        let variants = option_key_variants(canonical_rule, &canonical_opt);
        entry
            .values
            .retain(|k, _| !variants.contains(k.as_str()) || k == &canonical_opt);

        let sv = entry
            .values
            .entry(canonical_opt.clone())
            .or_insert_with(|| SourcedValue::new(opt_value.clone(), ConfigSource::Default));
        sv.merge_override(opt_value.clone(), ConfigSource::Cli, None);
    }
}

/// Apply a single global config entry through the shared global-key
/// dispatch, recording unrecognized keys for the validator's did-you-mean
/// warnings.
fn apply_global_override(sourced: &mut SourcedConfig, key: &str, value: &toml::Value) {
    use rumdl_lib::config::global_keys::{ApplyOutcome, apply_global_key};

    let normalized = normalize_key(key);
    match apply_global_key(
        &mut sourced.global,
        &normalized,
        value,
        ConfigSource::Cli,
        None,
        default_registry(),
    ) {
        ApplyOutcome::Applied => {}
        ApplyOutcome::TypeMismatch { expected } => {
            report_unusable_override(
                sourced,
                format!(
                    "--config: expected {expected} for global key '{normalized}', got {}. The setting was left as configured.",
                    toml_value_kind(value)
                ),
            );
        }
        ApplyOutcome::InvalidValue { message } => {
            report_unusable_override(sourced, format!("--config: {message}"));
        }
        ApplyOutcome::Unrecognized => {
            // Unknown global key — record so the existing validator surfaces a
            // "Unknown global option" warning with did-you-mean suggestions.
            sourced
                .unknown_keys
                .push(("[global]".to_string(), key.to_string(), None));
        }
    }
}

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

    fn parse(snippet: &str) -> toml::Table {
        toml::from_str(snippet).expect("test TOML must parse")
    }

    fn applied(snippet: &str) -> SourcedConfig {
        let mut sourced = SourcedConfig::default();
        apply_inline_overrides(&mut sourced, &[parse(snippet)]);
        sourced
    }

    #[test]
    fn rule_dotted_key_lands_in_rules_with_cli_source() {
        let sourced = applied("MD013.line_length = 20");
        let rule = sourced.rules.get("MD013").expect("MD013 entry created");
        let lv = rule.values.get("line-length").expect("canonical kebab key");
        assert_eq!(lv.value.as_integer(), Some(20));
        assert_eq!(lv.source, ConfigSource::Cli);
    }

    #[test]
    fn rule_alias_resolves_to_canonical() {
        let sourced = applied("line-length.line_length = 40");
        // `line-length` is a known alias for MD013.
        assert!(sourced.rules.contains_key("MD013"));
    }

    #[test]
    fn bare_global_key_lands_in_global_not_rules() {
        let sourced = applied("line-length = 100");
        assert_eq!(sourced.global.line_length.value.get(), 100);
        assert_eq!(sourced.global.line_length.source, ConfigSource::Cli);
        assert!(
            !sourced.rules.contains_key("MD013"),
            "bare line-length should NOT create an MD013 entry"
        );
    }

    #[test]
    fn explicit_global_table_routes_to_global() {
        let sourced = applied("global.line-length = 50");
        assert_eq!(sourced.global.line_length.value.get(), 50);
    }

    #[test]
    fn array_for_disable_resolves_aliases() {
        let sourced = applied(r#"disable = ["line-length", "MD003"]"#);
        // disable resolves rule aliases so "line-length" -> "MD013".
        let v = &sourced.global.disable.value;
        assert!(v.contains(&"MD013".to_string()));
        assert!(v.contains(&"MD003".to_string()));
    }

    #[test]
    fn type_mismatch_for_global_is_silent_no_panic() {
        // String for line-length should NOT panic and NOT corrupt the value.
        let sourced = applied(r#"line-length = "huge""#);
        // Default remains unchanged.
        assert_eq!(sourced.global.line_length.source, ConfigSource::Default);
    }

    #[test]
    fn unknown_top_level_key_records_unknown() {
        let sourced = applied("definitely_not_a_setting = 1");
        let entry = sourced
            .unknown_keys
            .iter()
            .find(|(s, k, _)| s == "[global]" && k == "definitely_not_a_setting");
        assert!(entry.is_some(), "unknown top-level key should be recorded");
    }

    #[test]
    fn unknown_rule_id_records_unknown_section() {
        let sourced = applied("MD9999.foo = 1");
        let entry = sourced
            .unknown_keys
            .iter()
            .find(|(s, k, _)| s == "[MD9999]" && k.is_empty());
        assert!(entry.is_some(), "unknown rule should be recorded as unknown section");
    }

    #[test]
    fn cli_overrides_beat_lower_precedence_sources() {
        let mut sourced = SourcedConfig::default();
        // Simulate a value loaded from a project config file.
        sourced
            .global
            .line_length
            .merge_override(LineLength::new(80), ConfigSource::ProjectConfig, None);
        apply_inline_overrides(&mut sourced, &[parse("line-length = 200")]);
        assert_eq!(sourced.global.line_length.value.get(), 200);
        assert_eq!(sourced.global.line_length.source, ConfigSource::Cli);
    }

    #[test]
    fn collision_kebab_and_snake_does_not_duplicate() {
        // Pre-seed a rule entry with the kebab form (as a config file would).
        let mut sourced = SourcedConfig::default();
        sourced.rules.entry("MD013".to_string()).or_default().values.insert(
            "line-length".to_string(),
            SourcedValue::new(toml::Value::Integer(80), ConfigSource::ProjectConfig),
        );
        // Inline override using the snake form must REPLACE, not duplicate.
        apply_inline_overrides(&mut sourced, &[parse("MD013.line_length = 20")]);
        let rule = sourced.rules.get("MD013").unwrap();
        assert_eq!(
            rule.values.len(),
            1,
            "kebab/snake variants must collapse to one key, got: {:?}",
            rule.values.keys().collect::<Vec<_>>()
        );
        assert_eq!(rule.values["line-length"].value.as_integer(), Some(20));
    }

    #[test]
    fn split_rejects_two_file_paths() {
        let args = vec![
            SingleConfigArgument::FilePath(PathBuf::from("a.toml")),
            SingleConfigArgument::FilePath(PathBuf::from("b.toml")),
        ];
        assert!(split_config_args(&args).is_err());
    }

    #[test]
    fn split_accepts_one_path_plus_overrides() {
        let args = vec![
            SingleConfigArgument::FilePath(PathBuf::from("a.toml")),
            SingleConfigArgument::InlineOverride(parse("MD013.line_length = 20")),
            SingleConfigArgument::InlineOverride(parse("line-length = 200")),
        ];
        let (path, overrides) = split_config_args(&args).unwrap();
        assert_eq!(path, Some(PathBuf::from("a.toml")));
        assert_eq!(overrides.len(), 2);
    }

    /// The section names are matched before the key is looked up as a rule, so
    /// a rule that answered to one of them would be shadowed without a word.
    /// No rule does today, and this says so out loud rather than leaving the
    /// dispatch order resting on it silently.
    #[test]
    fn no_rule_answers_to_a_section_name() {
        let registry = default_registry();
        assert!(
            registry.resolve_rule_name("code-block-style").is_some(),
            "control: the registry does resolve a name of this shape, so the assertions below can fail"
        );
        for section in ["code-block-tools", "per-file-ignores", "per-file-flavor"] {
            assert_eq!(
                registry.resolve_rule_name(section),
                None,
                "a rule now answers to '{section}', which the section dispatch would shadow"
            );
        }
    }
}