gdck-config 0.5.1

Configuration types and file discovery for gdck (internal)
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
//! What `gdck.toml` may say, and what each setting means.
//!
//! The file is read by the [`toml`] crate. What is left here is the part a
//! deserialiser cannot know: which values are in range, which settings only
//! mean something alongside another, and which unknown key the author probably
//! meant.
//!
//! Every key is listed in [`KEYS`], and one that is not is an error rather than
//! something quietly ignored. A misspelled key that does nothing is the classic
//! way to spend an afternoon wondering why a setting had no effect, and it
//! costs nothing to refuse it — the message names the nearest key that exists.
//!
//! The lint thresholds are named after the rules they configure, so
//! `lint.max-returns` is the limit `max-returns` reports on. `gdtoolkit`'s own
//! spellings live in [`crate::compat`], where they belong.

use serde::Deserialize;
use toml::Spanned;

use crate::{
    ClassDeclaration, CodeOrderFix, Config, DeclarationGroup, FileNameCase, IndentStyle, Problem,
};

/// Named in the error when a declaration group is misspelled.
const DECLARATION_GROUPS: &[&str] = &[
    "tools",
    "classnames",
    "extends",
    "docstrings",
    "signals",
    "enums",
    "consts",
    "staticvars",
    "exports",
    "pubvars",
    "prvvars",
    "onreadypubvars",
    "onreadyprvvars",
    "others",
];

/// Every key `gdck.toml` accepts, in the order [`to_toml`] writes them.
///
/// The structs below are the authority on what is *read*; this list exists so
/// that an unknown key can be answered with the nearest one that is not. A test
/// keeps the two in step.
pub(crate) const KEYS: &[&str] = &[
    "format.line-length",
    "format.indent",
    "format.indent-width",
    "format.class-declaration",
    "format.safety-checks",
    "lint.max-line-length",
    "lint.max-file-lines",
    "lint.max-public-methods",
    "lint.max-returns",
    "lint.max-arguments",
    "lint.code-order",
    "lint.file-name",
    "lint.declaration-order",
    "lint.disable",
    "files.exclude",
    "files.respect-gitignore",
];

/// The shape of the file.
///
/// Every setting is optional, so that leaving one out is distinguishable from
/// writing its default — which matters for `line-length`, where one key moves
/// another that was not named.
///
/// Values are [`Spanned`] so that a setting which parsed but will not do can
/// still be reported at the line it is on.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
struct File {
    #[serde(default)]
    format: FormatTable,
    #[serde(default)]
    lint: LintTable,
    #[serde(default)]
    files: FilesTable,
}

// `_` and `-` are the same separator here. Nothing in the schema needs to tell
// them apart, and a reader who guesses wrong is right anyway.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
struct FormatTable {
    #[serde(alias = "line_length")]
    line_length: Option<Spanned<u16>>,
    indent: Option<Spanned<Indent>>,
    #[serde(alias = "indent_width")]
    indent_width: Option<Spanned<u8>>,
    #[serde(alias = "class_declaration")]
    class_declaration: Option<ClassDecl>,
    #[serde(alias = "safety_checks")]
    safety_checks: Option<bool>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
struct LintTable {
    #[serde(alias = "max_line_length")]
    max_line_length: Option<Spanned<u16>>,
    #[serde(alias = "max_file_lines")]
    max_file_lines: Option<u32>,
    #[serde(alias = "max_public_methods")]
    max_public_methods: Option<u32>,
    #[serde(alias = "max_returns")]
    max_returns: Option<u32>,
    #[serde(alias = "max_arguments")]
    max_arguments: Option<u32>,
    #[serde(alias = "code_order")]
    code_order: Option<CodeOrder>,
    #[serde(alias = "file_name")]
    file_name: Option<FileName>,
    #[serde(alias = "declaration_order")]
    declaration_order: Option<Vec<Spanned<String>>>,
    disable: Option<Vec<String>>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
struct FilesTable {
    exclude: Option<Vec<String>>,
    #[serde(alias = "respect_gitignore")]
    respect_gitignore: Option<bool>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Indent {
    Tabs,
    Spaces,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum CodeOrder {
    Report,
    FixWhenSafe,
    Off,
}

/// Named after the shape it produces; see [`ClassDeclaration`].
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum ClassDecl {
    MultiLine,
    SingleLine,
}

impl From<ClassDecl> for ClassDeclaration {
    fn from(shape: ClassDecl) -> Self {
        match shape {
            ClassDecl::MultiLine => Self::MultiLine,
            ClassDecl::SingleLine => Self::SingleLine,
        }
    }
}

/// Named conventions rather than patterns; see [`FileNameCase`].
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum FileName {
    SnakeCase,
    PascalCase,
}

impl From<FileName> for FileNameCase {
    fn from(case: FileName) -> Self {
        match case {
            FileName::SnakeCase => Self::SnakeCase,
            FileName::PascalCase => Self::PascalCase,
        }
    }
}

impl From<CodeOrder> for CodeOrderFix {
    fn from(order: CodeOrder) -> Self {
        match order {
            CodeOrder::Report => Self::ReportOnly,
            CodeOrder::FixWhenSafe => Self::WholeFileWhenSafe,
            CodeOrder::Off => Self::Off,
        }
    }
}

/// Used when `indent = "spaces"` says nothing about how many.
const DEFAULT_INDENT_WIDTH: u8 = 4;

/// Read a whole `gdck.toml` into a [`Config`].
pub(crate) fn read(text: &str) -> Result<Config, Problem> {
    let file: File = toml::from_str(text).map_err(|error| translate(text, &error))?;
    let mut config = Config::default();

    if let Some(checks) = file.format.safety_checks {
        config.format.safety_checks = checks;
    }
    if let Some(lines) = file.lint.max_file_lines {
        config.lint.max_file_lines = lines;
    }
    if let Some(methods) = file.lint.max_public_methods {
        config.lint.max_public_methods = methods;
    }
    if let Some(returns) = file.lint.max_returns {
        config.lint.max_returns = returns;
    }
    if let Some(arguments) = file.lint.max_arguments {
        config.lint.max_function_arguments = arguments;
    }
    if let Some(order) = file.lint.code_order {
        config.lint.code_order = order.into();
    }
    if let Some(case) = file.lint.file_name {
        config.lint.file_name = case.into();
    }
    if let Some(order) = file.lint.declaration_order {
        let mut groups = Vec::with_capacity(order.len());
        for name in order {
            let Some(group) = DeclarationGroup::from_name(name.get_ref()) else {
                return Err(Problem {
                    line: line_of(text, name.span().start),
                    message: format!(
                        "`{}` is not a declaration group; the groups are {}",
                        name.get_ref(),
                        DECLARATION_GROUPS.join(", ")
                    ),
                });
            };
            groups.push(group);
        }
        config.lint.declaration_order = Some(groups);
    }
    if let Some(shape) = file.format.class_declaration {
        config.format.class_declaration = shape.into();
    }
    if let Some(disable) = file.lint.disable {
        config.lint.disabled = disable;
    }
    if let Some(respect) = file.files.respect_gitignore {
        config.respect_gitignore = respect;
    }
    // Replaces the defaults rather than adding to them, so that a project can
    // narrow them: gdUnit4 keeps its own source in `addons`, which the
    // defaults skip, and has to be able to say so.
    if let Some(exclude) = file.files.exclude {
        config.excluded_dirs = exclude;
    }

    config.format.indent = indent_of(text, &file.format)?;

    // A project that widens its lines means both tools. Leaving the linter at
    // 100 would have it report exactly the lines the formatter just produced.
    if let Some(length) = &file.format.line_length {
        config.format.line_length = positive(text, length, "format.line-length")?;
        config.lint.max_line_length = config.format.line_length;
    }
    if let Some(length) = &file.lint.max_line_length {
        config.lint.max_line_length = positive(text, length, "lint.max-line-length")?;
    }

    Ok(config)
}

fn indent_of(text: &str, format: &FormatTable) -> Result<IndentStyle, Problem> {
    let width = match &format.indent_width {
        Some(width) => {
            let value = *width.get_ref();
            if !(1..=16).contains(&value) {
                return Err(Problem {
                    line: line_of(text, width.span().start),
                    message: "`format.indent-width` must be between 1 and 16".to_string(),
                });
            }
            Some(value)
        }
        None => None,
    };

    match (
        format.indent.as_ref().map(Spanned::get_ref),
        &format.indent_width,
    ) {
        (Some(Indent::Spaces), _) => Ok(IndentStyle::Spaces(width.unwrap_or(DEFAULT_INDENT_WIDTH))),
        // Indenting with tabs has no width to set: the formatter measures a tab
        // as four columns because that is what the style guide's samples line
        // up as, and moving it would put the formatter and the linter into
        // disagreement about which lines are too long.
        (_, Some(spanned)) => Err(Problem {
            line: line_of(text, spanned.span().start),
            message: "`format.indent-width` applies only when `format.indent` is \"spaces\""
                .to_string(),
        }),
        _ => Ok(IndentStyle::Tabs),
    }
}

/// A width has to be a width. `u16` already caps the top end.
fn positive(text: &str, value: &Spanned<u16>, key: &str) -> Result<u16, Problem> {
    let width = *value.get_ref();
    if width == 0 {
        return Err(Problem {
            line: line_of(text, value.span().start),
            message: format!("`{key}` must be between 1 and {}", u16::MAX),
        });
    }
    Ok(width)
}

// -- error messages ----------------------------------------------------------

/// Turn one of `toml`'s errors into a line and a sentence.
///
/// Its own message is kept, since it is a good one, except where it says a key
/// is unknown. There the list of every field that would have been accepted is
/// less use than the single one the author probably meant.
fn translate(text: &str, error: &toml::de::Error) -> Problem {
    let line = error.span().map_or(1, |span| line_of(text, span.start));
    let message = error.message();

    if let Some(name) = unknown_field(message) {
        return Problem {
            line,
            message: match nearest(name) {
                Some(nearest) => format!("unknown setting `{name}`; did you mean `{nearest}`?"),
                None => format!("unknown setting `{name}`"),
            },
        };
    }
    Problem {
        line,
        message: message.to_string(),
    }
}

/// The field name out of ``unknown field `x`, expected ...``.
///
/// Reading another crate's message is a thing to do carefully, so a shape that
/// does not match leaves the message alone rather than mangling it.
fn unknown_field(message: &str) -> Option<&str> {
    let rest = message.strip_prefix("unknown field `")?;
    let end = rest.find('`')?;
    Some(&rest[..end])
}

fn line_of(text: &str, offset: usize) -> u32 {
    let offset = offset.min(text.len());
    u32::try_from(text[..offset].bytes().filter(|byte| *byte == b'\n').count() + 1)
        .unwrap_or(u32::MAX)
}

/// The key the author most likely meant, if there is an obvious candidate.
///
/// Two things go wrong often enough to be worth catching: a typo, and putting a
/// setting under the wrong table. The second is the more common of the two,
/// since which table a threshold belongs to is a thing you have to remember —
/// and `toml` reports only the bare name, so matching on the last segment
/// catches it without needing to know which table it was found in.
fn nearest(name: &str) -> Option<&'static str> {
    let name = name.replace('_', "-");
    if let Some(moved) = KEYS.iter().find(|key| last_segment(key) == name) {
        return Some(moved);
    }
    KEYS.iter()
        .map(|key| (distance(&name, last_segment(key)), *key))
        // Beyond a third of the name's length the "suggestion" is a guess, and
        // a wrong one sends the reader looking in the wrong place entirely.
        .filter(|(distance, _)| *distance * 3 <= name.len().max(3))
        .min_by_key(|(distance, _)| *distance)
        .map(|(_, key)| key)
}

fn last_segment(key: &str) -> &str {
    key.rsplit('.').next().unwrap_or(key)
}

/// Levenshtein distance, over the two rows the algorithm actually needs.
fn distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut previous: Vec<usize> = (0..=b.len()).collect();
    let mut current = vec![0; b.len() + 1];
    for (i, from) in a.iter().enumerate() {
        current[0] = i + 1;
        for (j, to) in b.iter().enumerate() {
            let substitute = previous[j] + usize::from(from != to);
            current[j + 1] = substitute.min(previous[j + 1] + 1).min(current[j] + 1);
        }
        std::mem::swap(&mut previous, &mut current);
    }
    previous[b.len()]
}

// -- writing it back out -----------------------------------------------------

/// Write a configuration back out as a `gdck.toml`.
///
/// Every value is written, including the ones left at their default, because
/// the point of `gdck config` is to answer what a run is actually using. Done
/// by hand rather than by serialising [`File`], because that struct is built
/// around what was *left out* — which is the one thing this must not do.
pub(crate) fn to_toml(config: &Config) -> String {
    render(config, Defaults::Write)
}

/// Write a configuration out as a `gdck.toml` for someone to keep.
///
/// See [`Defaults::Comment`] for what makes this different.
pub(crate) fn to_starter_toml(config: &Config) -> String {
    render(config, Defaults::Comment)
}

/// What to do with a setting that is still at its default.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Defaults {
    /// Write it. `gdck config` answers what a run is actually using, and a
    /// value being the default is no reason to leave it out of that answer.
    Write,
    /// Comment it out. `gdck init` writes a file somebody then maintains, and
    /// there the two kinds of line mean different things: a live one is a
    /// decision this project made, and a commented one is a setting it has not
    /// made yet, listed so it can be found without opening the documentation.
    ///
    /// Keeping the defaults commented also means a project inherits later
    /// changes to them, rather than silently pinning today's values forever.
    Comment,
}

/// One setting, commented out or not depending on `defaults`.
fn put(out: &mut String, defaults: Defaults, at_default: bool, setting: &str) {
    use std::fmt::Write;

    // Writing to a String cannot fail, so the result goes nowhere.
    if defaults == Defaults::Comment && at_default {
        let _ = writeln!(out, "# {setting}");
    } else {
        let _ = writeln!(out, "{setting}");
    }
}

fn render(config: &Config, defaults: Defaults) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    // A table header stays live even when every setting under it is commented,
    // so that uncommenting one line is all it takes.
    let _ = writeln!(out, "[format]");
    render_format(&mut out, config, defaults);
    let _ = writeln!(out, "\n[lint]");
    render_lint(&mut out, config, defaults);
    let _ = writeln!(out, "\n[files]");
    render_files(&mut out, config, defaults);
    out
}

fn render_format(out: &mut String, config: &Config, defaults: Defaults) {
    let base = Config::default();
    let format = &config.format;
    put(
        out,
        defaults,
        format.line_length == base.format.line_length,
        &format!("line-length = {}", format.line_length),
    );
    match format.indent {
        IndentStyle::Tabs => put(
            out,
            defaults,
            base.format.indent == IndentStyle::Tabs,
            "indent = \"tabs\"",
        ),
        IndentStyle::Spaces(width) => {
            put(out, defaults, false, "indent = \"spaces\"");
            put(out, defaults, false, &format!("indent-width = {width}"));
        }
    }
    let shape = match format.class_declaration {
        ClassDeclaration::MultiLine => "multi-line",
        ClassDeclaration::SingleLine => "single-line",
    };
    put(
        out,
        defaults,
        format.class_declaration == base.format.class_declaration,
        &format!("class-declaration = {}", quoted(shape)),
    );
    put(
        out,
        defaults,
        format.safety_checks == base.format.safety_checks,
        &format!("safety-checks = {}", format.safety_checks),
    );
}

fn render_lint(out: &mut String, config: &Config, defaults: Defaults) {
    let base = Config::default();
    let lint = &config.lint;
    put(
        out,
        defaults,
        lint.max_line_length == base.lint.max_line_length,
        &format!("max-line-length = {}", lint.max_line_length),
    );
    put(
        out,
        defaults,
        lint.max_file_lines == base.lint.max_file_lines,
        &format!("max-file-lines = {}", lint.max_file_lines),
    );
    put(
        out,
        defaults,
        lint.max_public_methods == base.lint.max_public_methods,
        &format!("max-public-methods = {}", lint.max_public_methods),
    );
    put(
        out,
        defaults,
        lint.max_returns == base.lint.max_returns,
        &format!("max-returns = {}", lint.max_returns),
    );
    put(
        out,
        defaults,
        lint.max_function_arguments == base.lint.max_function_arguments,
        &format!("max-arguments = {}", lint.max_function_arguments),
    );
    let order = match lint.code_order {
        CodeOrderFix::ReportOnly => "report",
        CodeOrderFix::WholeFileWhenSafe => "fix-when-safe",
        CodeOrderFix::Off => "off",
    };
    put(
        out,
        defaults,
        lint.code_order == base.lint.code_order,
        &format!("code-order = {}", quoted(order)),
    );
    let case = match lint.file_name {
        FileNameCase::SnakeCase => "snake-case",
        FileNameCase::PascalCase => "pascal-case",
    };
    put(
        out,
        defaults,
        lint.file_name == base.lint.file_name,
        &format!("file-name = {}", quoted(case)),
    );
    // Only written when a project has one, so it is never at the default.
    if let Some(order) = &lint.declaration_order {
        let names: Vec<String> = order.iter().map(|g| g.name().to_string()).collect();
        put(
            out,
            defaults,
            false,
            &format!("declaration-order = {}", array(&names)),
        );
    }
    put(
        out,
        defaults,
        lint.disabled == base.lint.disabled,
        &format!("disable = {}", array(&lint.disabled)),
    );
}

fn render_files(out: &mut String, config: &Config, defaults: Defaults) {
    let base = Config::default();
    let exclusions = effective_exclusions(config);
    let untouched = exclusions.iter().eq(crate::DEFAULT_EXCLUDED_DIRS.iter());
    put(
        out,
        defaults,
        untouched,
        &format!("exclude = {}", array(&exclusions)),
    );
    put(
        out,
        defaults,
        config.respect_gitignore == base.respect_gitignore,
        &format!("respect-gitignore = {}", config.respect_gitignore),
    );
}

/// What the walker will actually skip, which is the defaults when nothing was
/// configured.
fn effective_exclusions(config: &Config) -> Vec<String> {
    if config.excluded_dirs.is_empty() {
        return crate::DEFAULT_EXCLUDED_DIRS
            .iter()
            .map(|dir| (*dir).to_string())
            .collect();
    }
    config.excluded_dirs.clone()
}

fn array(items: &[String]) -> String {
    let items: Vec<String> = items.iter().map(|item| quoted(item)).collect();
    format!("[{}]", items.join(", "))
}

fn quoted(text: &str) -> String {
    format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}

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

    fn read_ok(text: &str) -> Config {
        read(text).expect("should read")
    }

    fn message(text: &str) -> String {
        read(text).expect_err("should not read").message
    }

    #[test]
    fn an_empty_file_leaves_every_default_alone() {
        assert_eq!(read_ok(""), Config::default());
        assert_eq!(read_ok("# nothing to say\n"), Config::default());
    }

    #[test]
    fn every_setting_can_be_read() {
        let config = read_ok(
            "[format]\n\
             line-length = 120\n\
             indent = \"spaces\"\n\
             indent-width = 2\n\
             safety-checks = false\n\
             \n\
             [lint]\n\
             max-line-length = 110\n\
             max-file-lines = 500\n\
             max-public-methods = 12\n\
             max-returns = 3\n\
             max-arguments = 5\n\
             code-order = \"fix-when-safe\"\n\
             disable = [\"max-returns\", \"line-too-long\"]\n\
             \n\
             [files]\n\
             exclude = [\"vendor\"]\n",
        );
        assert_eq!(config.format.line_length, 120);
        assert_eq!(config.format.indent, IndentStyle::Spaces(2));
        assert!(!config.format.safety_checks);
        assert_eq!(config.lint.max_line_length, 110);
        assert_eq!(config.lint.max_file_lines, 500);
        assert_eq!(config.lint.max_public_methods, 12);
        assert_eq!(config.lint.max_returns, 3);
        assert_eq!(config.lint.max_function_arguments, 5);
        assert_eq!(config.lint.code_order, CodeOrderFix::WholeFileWhenSafe);
        assert_eq!(config.lint.disabled, ["max-returns", "line-too-long"]);
        assert_eq!(config.excluded_dirs, ["vendor"]);
    }

    #[test]
    fn exclude_replaces_the_defaults_so_a_project_can_narrow_them() {
        // Replacing rather than adding is what lets a project *narrow* the
        // list, which gdUnit4 needs: its own source lives in `addons`, which
        // the defaults skip. `gdck init` writes the effective list, so a
        // generated file shows every name rather than only the change.
        let config = read_ok("[files]\nexclude = [\".git\"]\n");
        assert_eq!(config.excluded_dirs, [".git"]);
        assert!(!config.is_excluded_dir("addons"));
    }

    #[test]
    fn underscores_and_dashes_are_the_same_separator() {
        assert_eq!(
            read_ok("[format]\nline_length = 120\n").format.line_length,
            120
        );
        assert_eq!(read_ok("[lint]\nmax_returns = 2\n").lint.max_returns, 2);
    }

    #[test]
    fn a_dotted_key_means_the_same_as_a_table() {
        assert_eq!(
            read_ok("format.line-length = 120\n").format.line_length,
            120
        );
    }

    #[test]
    fn spaces_default_to_four_of_them() {
        assert_eq!(
            read_ok("[format]\nindent = \"spaces\"\n").format.indent,
            IndentStyle::Spaces(4)
        );
    }

    #[test]
    fn tabs_have_no_width_to_set() {
        // The formatter measures a tab as four columns and the linter has to
        // agree with it, so this would not do what it looks like it does.
        let reported = message("[format]\nindent = \"tabs\"\nindent-width = 2\n");
        assert!(reported.contains("only when"), "{reported}");
        // And the order the two are written in makes no difference.
        assert!(message("[format]\nindent-width = 2\nindent = \"tabs\"\n").contains("only when"));
        // Nor does leaving `indent` out entirely, since tabs is the default.
        assert!(message("[format]\nindent-width = 2\n").contains("only when"));
    }

    #[test]
    fn widening_the_lines_widens_them_for_the_linter_too() {
        // Otherwise the linter reports exactly the lines the formatter made.
        let config = read_ok("[format]\nline-length = 120\n");
        assert_eq!(config.lint.max_line_length, 120);
        // Unless the file asks for something else, which it is allowed to.
        let config = read_ok("[format]\nline-length = 120\n\n[lint]\nmax-line-length = 100\n");
        assert_eq!(config.format.line_length, 120);
        assert_eq!(config.lint.max_line_length, 100);
    }

    #[test]
    fn an_unknown_setting_is_refused_rather_than_ignored() {
        assert!(message("[lint]\nmax-recursion = 3\n").contains("unknown setting"));
        // Including a table nobody has heard of.
        assert!(message("[linting]\nmax-returns = 3\n").contains("unknown setting"));
    }

    #[test]
    fn a_near_miss_is_named() {
        assert_eq!(
            message("[format]\nline-lenght = 100\n"),
            "unknown setting `line-lenght`; did you mean `format.line-length`?"
        );
        // The commonest mistake of all: the right key under the wrong table.
        assert_eq!(
            message("[format]\nmax-returns = 3\n"),
            "unknown setting `max-returns`; did you mean `lint.max-returns`?"
        );
    }

    #[test]
    fn a_wild_guess_is_not_offered_as_a_suggestion() {
        let reported = message("[lint]\nfavourite-colour = \"blue\"\n");
        assert_eq!(reported, "unknown setting `favourite-colour`");
    }

    #[test]
    fn the_wrong_kind_of_value_says_what_it_wanted() {
        assert!(message("[format]\nline-length = \"100\"\n").contains("expected u16"));
        assert!(message("[format]\nsafety-checks = 1\n").contains("expected a boolean"));
        assert!(message("[lint]\ndisable = \"max-returns\"\n").contains("expected a sequence"));
        assert!(message("[lint]\ndisable = [1]\n").contains("expected a string"));
    }

    #[test]
    fn a_value_outside_its_range_is_refused() {
        assert!(message("[format]\nline-length = 0\n").contains("must be between 1 and 65535"));
        assert!(message("[format]\nline-length = 70000\n").contains("expected u16"));
        assert!(message("[lint]\nmax-returns = -1\n").contains("expected u32"));
        assert!(message("[format]\nindent-width = 0\n").contains("must be between 1 and 16"));
    }

    #[test]
    fn a_choice_lists_the_choices() {
        let reported = message("[lint]\ncode-order = \"sometimes\"\n");
        assert!(
            reported.contains("unknown variant `sometimes`"),
            "{reported}"
        );
        assert!(reported.contains("fix-when-safe"), "{reported}");
    }

    #[test]
    fn a_project_can_name_the_file_convention_it_keeps() {
        let config = read("[lint]\nfile-name = \"pascal-case\"\n").expect("should read");
        assert_eq!(config.lint.file_name, FileNameCase::PascalCase);
        // The underscored spelling is accepted wherever the kebab one is.
        let config = read("[lint]\nfile_name = \"snake-case\"\n").expect("should read");
        assert_eq!(config.lint.file_name, FileNameCase::SnakeCase);
        // And a convention nobody keeps is an error naming the two that exist.
        let reported = message("[lint]\nfile-name = \"kebab-case\"\n");
        assert!(
            reported.contains("unknown variant `kebab-case`"),
            "{reported}"
        );
        assert!(reported.contains("pascal-case"), "{reported}");
    }

    #[test]
    fn a_syntax_error_is_reported_as_one() {
        assert!(read("[format\n").is_err());
        assert!(read("line-length = = 1\n").is_err());
    }

    #[test]
    fn the_line_number_is_the_settings_own() {
        // Both when the deserialiser found it...
        let problem = read("[format]\n\n# a note\nline-length = true\n").expect_err("should fail");
        assert_eq!(problem.line, 4);
        // ...and when the validation after it did.
        let problem = read("[format]\n\n\nindent-width = 2\n").expect_err("should fail");
        assert_eq!(problem.line, 4);
    }

    #[test]
    fn what_is_written_out_can_be_read_back_in() {
        // Which also proves every key in the schema has a spelling `read`
        // accepts, since `to_toml` writes all of them.
        let config = Config {
            format: crate::FormatConfig {
                line_length: 120,
                indent: IndentStyle::Spaces(2),
                class_declaration: ClassDeclaration::SingleLine,
                safety_checks: false,
            },
            lint: crate::LintConfig {
                max_line_length: 110,
                max_file_lines: 500,
                max_public_methods: 12,
                max_returns: 3,
                max_function_arguments: 5,
                code_order: CodeOrderFix::Off,
                file_name: FileNameCase::PascalCase,
                declaration_order: Some(vec![
                    DeclarationGroup::Tools,
                    DeclarationGroup::Extends,
                    DeclarationGroup::Others,
                ]),
                disabled: vec!["max-returns".to_string()],
            },
            excluded_dirs: vec!["vendor".to_string()],
            respect_gitignore: false,
        };
        assert_eq!(read_ok(&config.to_toml()), config);
    }

    #[test]
    fn the_defaults_round_trip_as_the_defaults() {
        let read_back = read_ok(&Config::default().to_toml());
        // The one difference is deliberate: an empty exclusion list means the
        // defaults, and `gdck config` writes out what they are.
        assert_eq!(read_back.format, Config::default().format);
        assert_eq!(read_back.lint, Config::default().lint);
        assert_eq!(read_back.excluded_dirs, crate::DEFAULT_EXCLUDED_DIRS);
    }

    #[test]
    fn every_key_in_the_catalogue_is_one_read_accepts() {
        for key in KEYS {
            let reported = message(&format!("{key} = \"probe\"\n"));
            assert!(
                !reported.contains("unknown setting"),
                "`{key}` is listed but not read: {reported}"
            );
        }
    }
}