asbuilt-core 0.3.1

Language-agnostic architecture model, LikeC4 emitter, config and drift check for asbuilt
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
//! `asbuilt.toml`: the release it is written for, the output path, the
//! externals nothing static in the code can state, and every front-end's
//! own table kept raw for it to parse.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use serde::de::{DeserializeOwned, Error as _};
use serde::{Deserialize, Deserializer};

use crate::error::{Error, Result};

/// Where `survey` writes and `check` reads when the config says nothing.
pub const DEFAULT_OUTPUT_PATH: &str = "docs/architecture/model.c4";

/// The config file name, looked up at the surveyed root.
pub const FILE_NAME: &str = "asbuilt.toml";

/// The top-level key that pins the asbuilt release a config is written
/// for: `asbuilt = "0.3.0"`.
pub const PIN_KEY: &str = "asbuilt";

/// asbuilt's own top-level tables, as the file writes them.
const OWN_TABLES: [&str; 4] = ["[output]", "[docs]", "[theme]", "[[externals]]"];

/// The parsed `asbuilt.toml`.
///
/// Other top-level entries stay in `sections`, where a front-end's table
/// (`[rust]`, say) waits to be deserialized with that front-end's schema;
/// [`Config::check_tables`] rejects any that names no front-end. Unknown
/// keys *inside* `[output]` or an `[[externals]]` entry are rejected
/// when parsing.
///
/// ```
/// use asbuilt_core::Config;
///
/// let config: Config = r#"
/// [output]
/// path = "arch/model.c4"
///
/// [rust]
/// include_tests = false
/// "#
/// .parse()
/// .unwrap();
///
/// assert_eq!(config.output.path, "arch/model.c4");
/// assert!(config.sections.contains_key("rust"));
/// ```
#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
pub struct Config {
    /// The asbuilt release this config and its model are written for,
    /// as `cargo install --version` takes it. [`Config::load_for`] checks
    /// it against the running release before reading anything else;
    /// `None` runs under any release.
    #[serde(default, deserialize_with = "release_pin")]
    pub asbuilt: Option<String>,
    #[serde(default)]
    pub output: OutputConfig,
    #[serde(default)]
    pub docs: DocsConfig,
    /// `[theme]`: a color per element kind (`container`, `component`,
    /// `bin`, `tests`, `examples`, or an external kind), emitted as
    /// LikeC4 element styles so the
    /// diagrams come out in the consumer's palette.
    #[serde(default)]
    pub theme: BTreeMap<String, ThemeColor>,
    #[serde(default)]
    pub externals: Vec<External>,
    #[serde(flatten)]
    pub sections: BTreeMap<String, toml::Value>,
    /// Where this config was read from, for error messages. `None` for a
    /// config parsed from a string or defaulted.
    #[serde(skip)]
    pub path: Option<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OutputConfig {
    /// Relative to the surveyed root.
    #[serde(default = "default_output_path")]
    pub path: String,
}

fn default_output_path() -> String {
    DEFAULT_OUTPUT_PATH.to_string()
}

impl Default for OutputConfig {
    fn default() -> Self {
        Self {
            path: default_output_path(),
        }
    }
}

/// A kind's color: one value for every scheme, or a light and a dark
/// one. Written as `"#3b82f6"` or `{ light = "#3b82f6", dark = "#1e40af" }`.
/// Parsed by hand rather than as an untagged enum, whose only error is
/// "did not match any variant": a mistake here names the key or value.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "toml::Value")]
pub struct ThemeColor {
    pub light: String,
    pub dark: Option<String>,
}

impl TryFrom<toml::Value> for ThemeColor {
    type Error = String;

    fn try_from(value: toml::Value) -> std::result::Result<Self, String> {
        let (light, dark) = match value {
            toml::Value::String(light) => (light, None),
            toml::Value::Table(table) => {
                if let Some(key) = table
                    .keys()
                    .find(|k| !matches!(k.as_str(), "light" | "dark"))
                {
                    return Err(format!(
                        "unknown key \"{key}\" in a theme color (expected light and optionally dark)"
                    ));
                }
                let text = |key: &str| match table.get(key) {
                    None => Ok(None),
                    Some(toml::Value::String(s)) => Ok(Some(s.clone())),
                    Some(other) => Err(format!(
                        "theme color {key} is a {}, not a \"#rrggbb\" string",
                        other.type_str()
                    )),
                };
                let light = text("light")?.ok_or_else(|| {
                    "a theme color table needs light (dark is optional)".to_string()
                })?;
                (light, text("dark")?)
            }
            other => {
                return Err(format!(
                    "a theme color is \"#rrggbb\" or {{ light = \"#rrggbb\", dark = \"#rrggbb\" }}, not a {}",
                    other.type_str()
                ));
            }
        };
        for value in std::iter::once(&light).chain(dark.iter()) {
            if !is_hex_color(value) {
                return Err(format!(
                    "theme color \"{value}\" is not #rrggbb (six hex digits after #)"
                ));
            }
        }
        Ok(ThemeColor { light, dark })
    }
}

/// `#rrggbb`, six hex digits after the `#`.
pub fn is_hex_color(value: &str) -> bool {
    value.len() == 7 && value.starts_with('#') && value[1..].chars().all(|c| c.is_ascii_hexdigit())
}

impl Config {
    /// The light color per themed kind, the emitter's input.
    pub fn light_theme(&self) -> BTreeMap<String, String> {
        self.theme
            .iter()
            .map(|(kind, color)| (kind.clone(), color.light.clone()))
            .collect()
    }
}

/// What `asbuilt docs` cannot read off the code.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct DocsConfig {
    /// The site title; the root directory's name when absent.
    #[serde(default)]
    pub title: Option<String>,
    /// A URL prefix that turns a repo-relative path into a link, e.g.
    /// `https://github.com/owner/repo/blob/main/`. Paths stay plain text
    /// when absent.
    #[serde(default)]
    pub source_url: Option<String>,
    /// A link back to the site that hosts the tree, first in every
    /// page's header trail; relative values (`../`) resolve
    /// from each page's depth. No link when absent.
    #[serde(default)]
    pub home_url: Option<String>,
    /// The text of that link; the URL itself when absent. Every page's
    /// `<title>` starts with it.
    #[serde(default)]
    pub home_title: Option<String>,
    /// A stylesheet linked last in every page, after the tree's own, so
    /// the host can restate the page tokens in its palette. Resolved
    /// like `home_url`.
    #[serde(default)]
    pub stylesheet: Option<String>,
    /// The scheme the pages show before a visitor chooses one; the
    /// system's setting when absent.
    #[serde(default)]
    pub color_scheme: Option<ColorScheme>,
    /// Whether every page carries a System / Light / Dark control, and
    /// with it `theme.js`. On when absent.
    #[serde(default)]
    pub scheme_toggle: Option<bool>,
    /// Whether every inlined view gets the viewer (`viewer.js`): a frame
    /// at a readable scale with Fit, 1:1, Wide, Legend and Fullscreen
    /// controls.
    /// On when absent.
    #[serde(default)]
    pub viewer: Option<bool>,
}

/// The color scheme the documentation pages show before a visitor
/// chooses one: the system's setting, or light or dark regardless of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ColorScheme {
    #[default]
    System,
    Light,
    Dark,
}

impl ColorScheme {
    /// The name as `asbuilt.toml` and the `--color-scheme` flag spell it.
    pub fn as_str(self) -> &'static str {
        match self {
            ColorScheme::System => "system",
            ColorScheme::Light => "light",
            ColorScheme::Dark => "dark",
        }
    }
}

impl FromStr for ColorScheme {
    type Err = String;

    fn from_str(text: &str) -> std::result::Result<Self, String> {
        match text {
            "system" => Ok(ColorScheme::System),
            "light" => Ok(ColorScheme::Light),
            "dark" => Ok(ColorScheme::Dark),
            other => Err(format!(
                "color scheme \"{other}\" is not system, light or dark"
            )),
        }
    }
}

/// Something outside the code that a module talks to: a spawned
/// process, a browser, a service. Nothing static says it exists, so the
/// config does.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct External {
    /// A LikeC4 identifier; must not collide with a generated id.
    pub id: String,
    /// The LikeC4 element kind (`process`, `browser`, ...).
    pub kind: String,
    pub title: String,
    #[serde(default)]
    pub technology: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub relations: Vec<ExternalRelation>,
}

/// An edge from a generated element (or another external) to this one.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExternalRelation {
    /// A dotted id that must name a surveyed element or a sibling external.
    pub from: String,
    /// The label.
    pub title: String,
    #[serde(default)]
    pub technology: Option<String>,
}

/// Parsing alone: the pin's place and shape are checked by the loaders,
/// which know the file to name.
impl FromStr for Config {
    type Err = toml::de::Error;

    fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
        toml::from_str(text)
    }
}

impl Config {
    /// The config at `root/asbuilt.toml`, or the defaults when there is
    /// no such file.
    pub fn load(root: &Path) -> Result<Self> {
        Self::locate_and_parse(root, None, None)
    }

    /// A config from an explicit path (`--config`); a missing file is an
    /// error here, unlike [`Config::load`].
    pub fn load_file(path: &Path) -> Result<Self> {
        Self::parse_file(path, None)
    }

    /// The config a binary at release `running` reads: `config_path`
    /// when given, else `root/asbuilt.toml`, else the defaults. The pin
    /// is checked against `running` before the rest of the file is
    /// deserialized, so a config written for another release fails on
    /// the version, not on a table or key this release does not know.
    pub fn load_for(root: &Path, config_path: Option<&Path>, running: &str) -> Result<Self> {
        Self::locate_and_parse(root, config_path, Some(running))
    }

    fn locate_and_parse(
        root: &Path,
        config_path: Option<&Path>,
        running: Option<&str>,
    ) -> Result<Self> {
        let path = match config_path {
            Some(path) => path.to_path_buf(),
            None => {
                let path = root.join(FILE_NAME);
                if !path.is_file() {
                    return Ok(Self::default());
                }
                path
            }
        };
        Self::parse_file(&path, running)
    }

    /// The file at `path`, its pin compared with `running` (when given)
    /// before the rest is deserialized.
    fn parse_file(path: &Path, running: Option<&str>) -> Result<Self> {
        let text = std::fs::read_to_string(path).map_err(|source| Error::Io {
            path: path.to_path_buf(),
            source,
        })?;
        let config_error = |source| Error::Config {
            path: path.to_path_buf(),
            source,
        };
        // Parsed twice: once for the pin alone, so a config written for
        // another release fails on the version before any key this one
        // does not know, then whole from the text, so a schema error
        // keeps its line and column.
        let table: toml::Table = toml::from_str(&text).map_err(config_error)?;
        if let Some(running) = running {
            check_pin(&table, path, running)?;
        }
        let mut config: Config = text.parse().map_err(config_error)?;
        config.path = Some(path.to_path_buf());
        Ok(config)
    }

    /// The file this config came from, for error messages: `asbuilt.toml`
    /// when it was parsed from a string or defaulted.
    pub fn file_path(&self) -> PathBuf {
        self.path
            .clone()
            .unwrap_or_else(|| PathBuf::from(FILE_NAME))
    }

    /// Every top-level entry is asbuilt's own or the table of one of
    /// `frontends` (by [`Frontend::name`](crate::Frontend::name)); the
    /// first that is neither is an error naming it as written.
    pub fn check_tables(&self, frontends: &[&str]) -> Result<()> {
        let Some((name, value)) = self
            .sections
            .iter()
            .find(|(name, _)| !frontends.contains(&name.as_str()))
        else {
            return Ok(());
        };
        let entry = match value {
            toml::Value::Table(_) => format!("[{name}]"),
            toml::Value::Array(items)
                if !items.is_empty() && items.iter().all(toml::Value::is_table) =>
            {
                format!("[[{name}]]")
            }
            _ => format!("{name} = ..."),
        };
        let known = std::iter::once(format!("{PIN_KEY} = \"X.Y.Z\""))
            .chain(OWN_TABLES.iter().map(|t| t.to_string()))
            .chain(frontends.iter().map(|name| format!("[{name}]")))
            .collect::<Vec<_>>()
            .join(", ");
        Err(Error::UnknownTopLevel {
            path: self.file_path(),
            entry,
            known,
        })
    }

    /// A front-end's own table, deserialized with its schema. `Ok(None)`
    /// when the table is absent; a `Config` error naming the file when
    /// it is present and does not fit.
    pub fn section<T: DeserializeOwned>(&self, name: &str) -> Result<Option<T>> {
        let Some(value) = self.sections.get(name) else {
            return Ok(None);
        };
        value
            .clone()
            .try_into()
            .map(Some)
            .map_err(|source| Error::Config {
                path: self.file_path(),
                source,
            })
    }
}

/// The pin against the `running` release. A pin that is not a release
/// version passes here and fails deserializing, which says where.
fn check_pin(table: &toml::Table, path: &Path, running: &str) -> Result<()> {
    match table.get(PIN_KEY).and_then(toml::Value::as_str) {
        Some(pinned) if is_release_version(pinned) && pinned != running => {
            Err(Error::PinMismatch {
                path: path.to_path_buf(),
                pinned: pinned.to_string(),
                running: running.to_string(),
            })
        }
        _ => Ok(()),
    }
}

/// `asbuilt = "X.Y.Z"`, refused unless it is a release version.
fn release_pin<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<Option<String>, D::Error> {
    let pin = String::deserialize(deserializer)?;
    if !is_release_version(&pin) {
        return Err(D::Error::custom(format!(
            "asbuilt = \"{pin}\" is not a release version (\"X.Y.Z\", as `cargo install --version` takes it)"
        )));
    }
    Ok(Some(pin))
}

/// A release as `cargo install --version` takes it and
/// `CARGO_PKG_VERSION` reports it: `MAJOR.MINOR.PATCH` with an optional
/// `-pre` release, as semver writes them. No `+build`: the pin is
/// compared as written, and build metadata never tells releases apart.
fn is_release_version(text: &str) -> bool {
    let (core, pre) = match text.split_once('-') {
        Some((core, pre)) => (core, Some(pre)),
        None => (text, None),
    };
    let numbers: Vec<&str> = core.split('.').collect();
    numbers.len() == 3
        && numbers.iter().all(|n| is_number(n))
        && pre.is_none_or(|pre| {
            pre.split('.').all(|id| {
                !id.is_empty()
                    && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
                    && (!id.bytes().all(|b| b.is_ascii_digit()) || is_number(id))
            })
        })
}

/// Digits that fit a u64, with no leading zero unless it is `0`.
fn is_number(text: &str) -> bool {
    text.bytes().all(|b| b.is_ascii_digit())
        && text.parse::<u64>().is_ok()
        && (text == "0" || !text.starts_with('0'))
}

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

    const BRIEF_EXAMPLE: &str = r#"
[output]
path = "docs/architecture/model.c4"

[rust]
extra_manifests = ["crates/site/Cargo.toml", "crates/site-e2e/Cargo.toml"]
include_tests = true

[[externals]]
id = "node_driver"
kind = "process"
title = "Playwright driver"
technology = "Node.js process"
description = "The official Playwright server, assembled by build.rs."

[[externals.relations]]
from = "playwright_rs.server.playwright_server"
title = "spawns"
technology = "stdio"
"#;

    #[derive(Debug, PartialEq, Deserialize)]
    #[serde(deny_unknown_fields)]
    struct RustLike {
        extra_manifests: Vec<String>,
        include_tests: bool,
    }

    fn unknown(text: &str) -> (PathBuf, String, String) {
        let config: Config = text.parse().unwrap();
        match config.check_tables(&["rust"]) {
            Err(Error::UnknownTopLevel { path, entry, known }) => (path, entry, known),
            other => panic!("expected UnknownTopLevel, got {other:?}"),
        }
    }

    #[test]
    fn a_misspelled_table_is_named_as_written() {
        assert_eq!(unknown("[rsut]\ninclude_tests = false\n").1, "[rsut]");
    }

    #[test]
    fn a_singular_externals_table_is_named_as_an_array_of_tables() {
        let (_, entry, _) =
            unknown("[[external]]\nid = \"d\"\nkind = \"process\"\ntitle = \"D\"\n");
        assert_eq!(entry, "[[external]]");
    }

    #[test]
    fn a_stray_top_level_key_is_named_as_a_key() {
        assert_eq!(unknown("title = \"My docs\"\n").1, "title = ...");
    }

    #[test]
    fn a_stray_top_level_list_is_named_as_a_key() {
        assert_eq!(unknown("tags = [\"a\"]\n").1, "tags = ...");
    }

    #[test]
    fn a_stray_empty_list_is_named_as_a_key() {
        assert_eq!(unknown("tags = []\n").1, "tags = ...");
    }

    #[test]
    fn an_unknown_entry_lists_asbuilts_tables_then_the_front_ends() {
        assert_eq!(
            unknown("[rsut]\n").2,
            "asbuilt = \"X.Y.Z\", [output], [docs], [theme], [[externals]], [rust]"
        );
    }

    #[test]
    fn an_unknown_entry_in_a_defaulted_config_names_the_default_file() {
        assert_eq!(unknown("[rsut]\n").0, PathBuf::from("asbuilt.toml"));
    }

    #[test]
    fn an_unknown_entry_in_a_loaded_config_names_that_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("elsewhere.toml");
        std::fs::write(&path, "[rsut]\n").unwrap();
        let config = Config::load_file(&path).unwrap();
        assert!(matches!(
            config.check_tables(&["rust"]),
            Err(Error::UnknownTopLevel { path: named, .. }) if named == path
        ));
    }

    #[test]
    fn a_front_ends_table_and_asbuilts_own_pass_the_check() {
        let config: Config = BRIEF_EXAMPLE.parse().unwrap();
        assert!(config.check_tables(&["rust"]).is_ok());
    }

    #[test]
    fn the_brief_example_parses_to_its_values() {
        let config: Config = BRIEF_EXAMPLE.parse().unwrap();
        assert_eq!(config.output.path, "docs/architecture/model.c4");
        assert_eq!(config.externals.len(), 1);
        let ext = &config.externals[0];
        assert_eq!(ext.id, "node_driver");
        assert_eq!(ext.kind, "process");
        assert_eq!(ext.technology.as_deref(), Some("Node.js process"));
        assert_eq!(
            ext.relations,
            vec![ExternalRelation {
                from: "playwright_rs.server.playwright_server".into(),
                title: "spawns".into(),
                technology: Some("stdio".into()),
            }]
        );
    }

    #[test]
    fn a_front_end_table_round_trips_through_its_own_schema() {
        let config: Config = BRIEF_EXAMPLE.parse().unwrap();
        let rust: Option<RustLike> = config.section("rust").unwrap();
        assert_eq!(
            rust,
            Some(RustLike {
                extra_manifests: vec![
                    "crates/site/Cargo.toml".into(),
                    "crates/site-e2e/Cargo.toml".into()
                ],
                include_tests: true,
            })
        );
    }

    #[test]
    fn an_absent_section_is_none() {
        let config: Config = "".parse().unwrap();
        let rust: Option<RustLike> = config.section("rust").unwrap();
        assert_eq!(rust, None);
    }

    #[test]
    fn a_section_that_does_not_fit_its_schema_is_a_config_error_naming_the_file() {
        let mut config: Config = "[rust]\ninclude_test = true\n".parse().unwrap();
        config.path = Some(PathBuf::from("here/asbuilt.toml"));
        match config.section::<RustLike>("rust") {
            Err(Error::Config { path, .. }) => assert_eq!(path, PathBuf::from("here/asbuilt.toml")),
            other => panic!("expected Config error, got {other:?}"),
        }
    }

    #[test]
    fn an_empty_config_has_the_default_output_path() {
        let config: Config = "".parse().unwrap();
        assert_eq!(config.output.path, DEFAULT_OUTPUT_PATH);
    }

    #[test]
    fn an_unknown_key_under_output_is_rejected() {
        let result: std::result::Result<Config, _> = "[output]\npth = \"x\"\n".parse();
        assert!(result.is_err(), "got {result:?}");
    }

    #[test]
    fn an_unknown_key_in_an_external_is_rejected() {
        let result: std::result::Result<Config, _> =
            "[[externals]]\nid = \"x\"\nkind = \"k\"\ntitle = \"t\"\nlabel = \"no\"\n".parse();
        assert!(result.is_err(), "got {result:?}");
    }

    #[test]
    fn the_docs_table_parses_and_defaults_to_nothing() {
        let config: Config = "[docs]\ntitle = \"asbuilt\"\nsource_url = \"https://x/blob/main/\"\nhome_url = \"../\"\nhome_title = \"Home\"\nstylesheet = \"../site.css\"\n"
            .parse()
            .unwrap();
        assert_eq!(config.docs.title.as_deref(), Some("asbuilt"));
        assert_eq!(
            config.docs.source_url.as_deref(),
            Some("https://x/blob/main/")
        );
        assert_eq!(config.docs.home_url.as_deref(), Some("../"));
        assert_eq!(config.docs.home_title.as_deref(), Some("Home"));
        assert_eq!(config.docs.stylesheet.as_deref(), Some("../site.css"));
        let empty: Config = "".parse().unwrap();
        assert_eq!(empty.docs, DocsConfig::default());
    }

    #[test]
    fn a_theme_color_is_a_string_or_a_light_dark_pair() {
        let config: Config =
            "[theme]\ncontainer = \"#3b82f6\"\nprocess = { light = \"#c9c9c9\", dark = \"#444444\" }\n"
                .parse()
                .unwrap();
        assert_eq!(
            config.theme["container"],
            ThemeColor {
                light: "#3b82f6".into(),
                dark: None
            }
        );
        assert_eq!(
            config.theme["process"],
            ThemeColor {
                light: "#c9c9c9".into(),
                dark: Some("#444444".into())
            }
        );
        assert_eq!(
            config.light_theme(),
            BTreeMap::from([
                ("container".to_string(), "#3b82f6".to_string()),
                ("process".to_string(), "#c9c9c9".to_string()),
            ])
        );
    }

    #[test]
    fn a_theme_color_that_is_not_six_hex_digits_is_rejected_naming_the_value() {
        for bad in ["blue", "#fff", "#12345g", "3b82f6"] {
            let result: std::result::Result<Config, _> =
                format!("[theme]\ncontainer = \"{bad}\"\n").parse();
            let err = result.err().map(|e| e.to_string()).unwrap_or_default();
            assert!(err.contains(bad), "{bad}: {err}");
        }
        let result: std::result::Result<Config, _> =
            "[theme]\ncontainer = { light = \"#3b82f6\", dark = \"nope\" }\n".parse();
        assert!(result.is_err(), "{result:?}");
    }

    fn theme_error(color: &str) -> String {
        format!("[theme]\ncontainer = {color}\n")
            .parse::<Config>()
            .err()
            .map(|e| e.to_string())
            .unwrap_or_default()
    }

    #[test]
    fn an_unknown_key_in_a_theme_color_is_rejected_naming_it() {
        let err = theme_error("{ light = \"#f0a884\", drak = \"#b5673f\" }");
        assert!(err.contains("unknown key \"drak\""), "{err}");
    }

    #[test]
    fn a_theme_color_table_without_light_is_rejected_saying_so() {
        let err = theme_error("{ dark = \"#b5673f\" }");
        assert!(err.contains("needs light"), "{err}");
    }

    #[test]
    fn a_theme_color_of_another_type_is_rejected_naming_the_type() {
        assert!(
            theme_error("3").contains("not a integer"),
            "{}",
            theme_error("3")
        );
        let err = theme_error("{ light = 3 }");
        assert!(err.contains("light is a integer"), "{err}");
    }

    #[test]
    fn the_docs_viewer_key_parses_and_defaults_to_nothing() {
        let config: Config = "[docs]\nviewer = false\n".parse().unwrap();
        assert_eq!(config.docs.viewer, Some(false));
        let empty: Config = "[docs]\n".parse().unwrap();
        assert_eq!(empty.docs.viewer, None);
    }

    #[test]
    fn the_docs_color_scheme_and_toggle_parse_and_default_to_nothing() {
        let config: Config = "[docs]\ncolor_scheme = \"dark\"\nscheme_toggle = false\n"
            .parse()
            .unwrap();
        assert_eq!(config.docs.color_scheme, Some(ColorScheme::Dark));
        assert_eq!(config.docs.scheme_toggle, Some(false));
        let empty: Config = "[docs]\n".parse().unwrap();
        assert_eq!(empty.docs.color_scheme, None);
        assert_eq!(empty.docs.scheme_toggle, None);
    }

    #[test]
    fn a_color_scheme_that_is_not_one_of_the_three_is_rejected_naming_them() {
        let err = "[docs]\ncolor_scheme = \"sepia\"\n"
            .parse::<Config>()
            .unwrap_err()
            .to_string();
        assert!(err.contains("sepia") && err.contains("dark"), "{err}");
    }

    #[test]
    fn a_color_scheme_reads_from_its_name_and_prints_back_the_same() {
        for scheme in [ColorScheme::System, ColorScheme::Light, ColorScheme::Dark] {
            assert_eq!(scheme.as_str().parse::<ColorScheme>(), Ok(scheme));
        }
        assert_eq!(
            "sepia".parse::<ColorScheme>(),
            Err("color scheme \"sepia\" is not system, light or dark".to_string())
        );
    }

    #[test]
    fn an_unknown_key_under_docs_is_rejected() {
        let result: std::result::Result<Config, _> = "[docs]\ntitel = \"x\"\n".parse();
        assert!(result.is_err(), "got {result:?}");
    }

    #[test]
    fn an_external_without_relations_has_none() {
        let config: Config = "[[externals]]\nid = \"x\"\nkind = \"k\"\ntitle = \"t\"\n"
            .parse()
            .unwrap();
        assert!(config.externals[0].relations.is_empty());
    }

    #[test]
    fn a_missing_file_at_the_root_loads_the_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert_eq!(config, Config::default());
    }

    #[test]
    fn a_file_at_the_root_is_loaded_and_remembers_its_path() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(FILE_NAME);
        std::fs::write(&path, "[output]\npath = \"m.c4\"\n").unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert_eq!(config.output.path, "m.c4");
        assert_eq!(config.path, Some(path));
    }

    #[test]
    fn a_malformed_file_is_a_config_error_naming_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(FILE_NAME);
        std::fs::write(&path, "[output\n").unwrap();
        match Config::load(dir.path()) {
            Err(Error::Config { path: p, .. }) => assert_eq!(p, path),
            other => panic!("expected Config error, got {other:?}"),
        }
    }

    /// `text` as the root's `asbuilt.toml`, loaded by a binary at
    /// `running`, with the file's path.
    fn load_pinned(text: &str, running: &str) -> (Result<Config>, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(FILE_NAME);
        std::fs::write(&path, text).unwrap();
        (Config::load_for(dir.path(), None, running), path)
    }

    #[test]
    fn a_pin_naming_the_running_release_loads_and_keeps_the_pin() {
        let (config, _) = load_pinned("asbuilt = \"0.3.0\"\n", "0.3.0");
        assert_eq!(config.unwrap().asbuilt.as_deref(), Some("0.3.0"));
    }

    #[test]
    fn a_pin_naming_another_release_is_a_mismatch_naming_the_file_and_both_releases() {
        let (config, path) = load_pinned("asbuilt = \"0.3.0\"\n", "0.2.0");
        assert!(matches!(
            config,
            Err(Error::PinMismatch { path: p, pinned, running })
                if p == path && pinned == "0.3.0" && running == "0.2.0"
        ));
    }

    #[test]
    fn a_pre_release_is_another_release() {
        let (config, _) = load_pinned("asbuilt = \"0.3.0-rc.1\"\n", "0.3.0");
        assert!(
            matches!(config, Err(Error::PinMismatch { .. })),
            "{config:?}"
        );
    }

    #[test]
    fn load_without_a_running_release_accepts_any_pin() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(FILE_NAME), "asbuilt = \"9.9.9\"\n").unwrap();
        let config = Config::load(dir.path()).unwrap();
        assert_eq!(config.asbuilt.as_deref(), Some("9.9.9"));
    }

    #[test]
    fn a_schema_error_from_a_file_keeps_its_place_in_the_text() {
        let (config, _) = load_pinned("[output]\npth = \"x\"\n", "0.3.0");
        match config {
            Err(Error::Config { source, .. }) => assert!(source.span().is_some(), "{source}"),
            other => panic!("expected Config error, got {other:?}"),
        }
    }

    #[test]
    fn the_pin_is_checked_before_a_key_this_release_does_not_know() {
        let (config, _) = load_pinned("asbuilt = \"0.9.0\"\n\n[docs]\nnewer = true\n", "0.3.0");
        assert!(
            matches!(config, Err(Error::PinMismatch { .. })),
            "{config:?}"
        );
    }

    #[test]
    fn a_config_without_a_pin_loads_under_any_release() {
        let (config, _) = load_pinned("[output]\npath = \"m.c4\"\n", "0.3.0");
        assert_eq!(config.unwrap().asbuilt, None);
    }

    #[test]
    fn no_file_at_the_root_loads_the_defaults_for_any_release() {
        let dir = tempfile::tempdir().unwrap();
        let config = Config::load_for(dir.path(), None, "0.3.0").unwrap();
        assert_eq!(config, Config::default());
    }

    #[test]
    fn an_explicit_path_is_read_in_place_of_the_roots_file() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(FILE_NAME), "asbuilt = \"0.1.0\"\n").unwrap();
        let other = dir.path().join("other.toml");
        std::fs::write(&other, "asbuilt = \"0.3.0\"\n").unwrap();
        let config = Config::load_for(dir.path(), Some(&other), "0.3.0").unwrap();
        assert_eq!(config.path, Some(other));
    }

    #[test]
    fn a_malformed_file_is_still_a_config_error_when_loaded_for_a_release() {
        let (config, path) = load_pinned("asbuilt = \"0.3.0\"\n[output\n", "0.3.0");
        assert!(matches!(config, Err(Error::Config { path: p, .. }) if p == path));
    }

    /// The error from parsing `text`, with where it points.
    fn pin_error(text: &str) -> Option<std::ops::Range<usize>> {
        text.parse::<Config>().err().and_then(|e| e.span())
    }

    #[test]
    fn a_pin_that_is_not_a_release_version_is_refused_where_it_is_written() {
        let text = "asbuilt = \"v0.3.0\"\n";
        assert_eq!(pin_error(text), Some(10..18));
    }

    #[test]
    fn a_pin_that_is_not_a_string_is_refused_where_it_is_written() {
        assert_eq!(pin_error("asbuilt = 3\n"), Some(10..11));
    }

    #[test]
    fn a_pin_written_as_a_table_is_refused() {
        assert!(
            "[asbuilt]\nversion = \"0.3.0\"\n"
                .parse::<Config>()
                .is_err()
        );
    }

    #[test]
    fn an_invalid_pin_from_a_file_is_a_config_error_naming_it() {
        let (config, path) = load_pinned("asbuilt = \"v0.3.0\"\n", "0.3.0");
        assert!(matches!(config, Err(Error::Config { path: p, .. }) if p == path));
    }

    #[test]
    fn a_release_version_is_semver_as_cargo_install_takes_it() {
        for good in [
            "0.3.0",
            "10.20.30",
            "1.0.0-rc.1",
            "1.0.0-alpha-2",
            "1.0.0-0",
            "1.0.0-0a.01x",
        ] {
            assert!(is_release_version(good), "{good}");
        }
        for bad in [
            "",
            "v0.3.0",
            "0.3",
            "0.3.0.1",
            "0.3.x",
            "0..3",
            "0.3.0-",
            "0.3.0-rc!",
            "0.03.0",
            "01.2.3",
            "1.0.0-01",
            "1.0.0-rc..1",
            "1.0.0+build",
            "1.0.0-rc.1+b",
            "99999999999999999999.0.0",
        ] {
            assert!(!is_release_version(bad), "{bad}");
        }
    }

    #[test]
    fn an_explicit_path_that_does_not_exist_is_an_io_error_naming_it() {
        let missing = PathBuf::from("/no/such/asbuilt.toml");
        match Config::load_file(&missing) {
            Err(Error::Io { path, .. }) => assert_eq!(path, missing),
            other => panic!("expected Io error, got {other:?}"),
        }
    }
}