Skip to main content

rushls_common/config/
reference.rs

1//! Configuration reference generated from the schema itself.
2//!
3//! A hand-written reference drifts: a default changes in code and nobody
4//! edits the table. Rendering it from `conf`'s introspection means it can only
5//! describe settings that exist, with the defaults they really have, and an
6//! application test that compares the rendering with the committed file fails
7//! when either moves alone.
8
9use std::fmt::Write as _;
10
11use conf::{Conf, introspection::ProgramOptionMeta};
12
13/// How one application's schema maps onto its reference document.
14pub struct Reference<'a> {
15    /// Everything above the first section: title, regeneration instructions,
16    /// and conventions.
17    pub preamble: &'a str,
18    /// The TOML path of a schema option ID, or `None` for an option that is
19    /// not a TOML setting (command-line-only flags, credential file flags).
20    pub toml_path: &'a dyn Fn(&str) -> Option<String>,
21    /// Credential file flags, as TOML-style paths (`metrics.token_file`).
22    ///
23    /// `conf` refuses a flag on a secret field, so each credential with a
24    /// flag has a CLI-only `<name>_file` sibling; the reference shows that
25    /// flag on the credential's own row.
26    pub credential_file_flags: &'a [&'a str],
27    /// Whole-table settings `conf` treats as one opaque value, with the keys
28    /// each accepts, so the reference can still list them.
29    pub tables: &'a [(&'a str, &'a [TableKey<'a>])],
30}
31
32/// One key inside a whole-table setting.
33pub struct TableKey<'a> {
34    /// Appended to the table's path, e.g. `.<name>.url`.
35    pub suffix: &'a str,
36    /// Empty when there is no default.
37    pub default: &'a str,
38    pub description: &'a str,
39}
40
41/// Renders the reference: one Markdown table per top-level section, in schema
42/// order. The description is each field's first doc paragraph; rationale
43/// below it stays in the source.
44pub fn reference_markdown<T: Conf>(reference: &Reference<'_>) -> String {
45    let cell = |text: String| text.replace('|', "\\|");
46    let code =
47        |value: Option<String>| value.map_or_else(|| "—".to_owned(), |value| format!("`{value}`"));
48    let mut output = reference.preamble.to_owned();
49    let mut section = None;
50    for option in T::program_options() {
51        let Some(path) = (reference.toml_path)(&option.id().to_string()) else {
52            continue;
53        };
54        let table_keys = reference
55            .tables
56            .iter()
57            .find(|(table, _)| *table == path)
58            .map(|(_, keys)| *keys);
59        let top = match path.split_once('.') {
60            Some((top, _)) => top.to_owned(),
61            // Whole-table settings head their own section.
62            None if table_keys.is_some() => path.clone(),
63            None => "(top level)".to_owned(),
64        };
65        if section.as_ref() != Some(&top) {
66            write!(
67                output,
68                "\n## {}\n\n| Setting | Default | Environment | CLI | Description |\n|---|---|---|---|---|\n",
69                if top == "(top level)" {
70                    top.clone()
71                } else {
72                    format!("[{top}]")
73                }
74            )
75            .expect("writing to a String cannot fail");
76            section = Some(top);
77        }
78        let description = option
79            .description()
80            .map(ToString::to_string)
81            .unwrap_or_default();
82        let summary = description
83            .split("\n\n")
84            .next()
85            .unwrap_or_default()
86            .split_whitespace()
87            .collect::<Vec<_>>()
88            .join(" ");
89        let flag = option
90            .long_form()
91            .map(|value| format!("--{value}"))
92            .or_else(|| {
93                let sibling = format!("{path}_file");
94                reference
95                    .credential_file_flags
96                    .contains(&sibling.as_str())
97                    .then(|| format!("--{} <PATH>", path.replace(['.', '_'], "-")))
98            });
99        writeln!(
100            output,
101            "| `{path}` | {} | {} | {} | {} |",
102            cell(code(option.default_help_str().map(ToString::to_string))),
103            cell(code(option.env_form().map(ToString::to_string))),
104            cell(code(flag)),
105            cell(summary),
106        )
107        .expect("writing to a String cannot fail");
108        for key in table_keys.unwrap_or_default() {
109            writeln!(
110                output,
111                "| `{path}{}` | {} | — | — | {} |",
112                key.suffix,
113                cell(if key.default.is_empty() {
114                    "—".to_owned()
115                } else {
116                    format!("`{}`", key.default)
117                }),
118                cell(key.description.to_owned()),
119            )
120            .expect("writing to a String cannot fail");
121        }
122    }
123    output
124}