Skip to main content

tak_cli/
settings.rs

1//! Settings, and where their values come from.
2//!
3//! The [`Settings`] struct below is the registry: `#[derive(usage_rs::Config)]`
4//! generates the metadata slice (`SETTINGS_PROPS`), the resolver registry
5//! (`SETTINGS_REGISTRY`), the reader that fills the struct from a resolution,
6//! and the spec `config` block that documents it. There is no `settings.toml`
7//! and no build-script generator left to keep in step with this file.
8//!
9//! Precedence, highest first: CLI flag, environment variable, `tak.toml`,
10//! declared default. A source that is absent is skipped rather than treated as
11//! empty, so setting a value in `tak.toml` is not undone by the flag being
12//! unused.
13
14use anyhow::{Context, Result, anyhow};
15use std::path::Path;
16use usage_rs::config::{
17    Layer, LayerCtx, LayerError, LayerOutput, Layers, Origin, SourceKind, Ty, Value,
18};
19
20pub use usage_rs::config::{CliLayer, EnvLayer};
21
22/// Every setting tak supports, resolved.
23///
24/// `PartialEq` but not `Eq`: a float setting has no total equality.
25#[derive(usage_rs::Config, Debug, Clone, PartialEq)]
26pub struct Settings {
27    /// Environment variables removed from every command tak measures.
28    ///
29    /// Two reasons this defaults to a non-empty list rather than to nothing.
30    ///
31    /// **Determinism.** A CLI that finds a forge token in its environment often does
32    /// more with it than without — authenticating, fetching, checking rate limits. A
33    /// measurement that moves depending on whether CI happened to export a token is
34    /// not a measurement of the code under test. It lands in the series as an
35    /// unexplained step change on the day someone edits an unrelated workflow.
36    ///
37    /// **This is not a credential sandbox.** The listed variables are absent from the
38    /// child's direct environment, but a hostile binary can still inspect accessible
39    /// same-user processes and files. In particular, `tak backfill` downloads and
40    /// executes release binaries; run it on an isolated credential-free machine when
41    /// those assets are not fully trusted.
42    ///
43    /// Setting this replaces the default list rather than adding to it. To keep the
44    /// defaults and remove more, list them alongside. To keep the defaults and remove
45    /// fewer, use `env_allow` — it is subtracted from this list, so the two compose
46    /// without either having to restate the other.
47    ///
48    /// Names are matched exactly. There is no globbing: a benchmark whose behaviour
49    /// depends on which variables happen to match a pattern is the problem this
50    /// setting exists to avoid.
51    ///
52    /// tak's own network calls are unaffected. `backfill` authenticates with `curl`
53    /// directly rather than through the measurement path.
54    #[usage(
55        default("GITHUB_TOKEN", "GH_TOKEN"),
56        cli("--env-deny"),
57        env = "TAK_ENV_DENY",
58        parse = "list_by_comma",
59        source("config", "env.deny"),
60        example("tak run --env-deny AWS_PROFILE --env-deny AWS_REGION"),
61        example("TAK_ENV_DENY=GITHUB_TOKEN,GH_TOKEN,NPM_TOKEN tak run"),
62        since = "0.0.3"
63    )]
64    pub env_deny: Vec<String>,
65
66    /// Environment variables kept even though `env_deny` lists them.
67    ///
68    /// Subtracted from `env_deny`, so a project can opt one variable back in without
69    /// restating the whole default list. A CLI whose measured path genuinely requires
70    /// a token — a client that cannot start unauthenticated, say — needs this.
71    ///
72    /// Doing so makes the measurement depend on something outside the repository.
73    /// That is a real cost, not a formality: the numbers become conditional on the
74    /// environment the run happened to have, and a token expiring will read as a
75    /// performance change.
76    ///
77    /// Listing a variable here that `env_deny` does not mention has no effect. This
78    /// setting removes entries from the deny list; it does not add anything to the
79    /// environment.
80    #[usage(
81        default(),
82        cli("--env-allow"),
83        env = "TAK_ENV_ALLOW",
84        parse = "list_by_comma",
85        source("config", "env.allow"),
86        example("tak run --env-deny GITHUB_TOKEN --env-allow GITHUB_TOKEN"),
87        since = "0.0.3"
88    )]
89    pub env_allow: Vec<String>,
90
91    /// How much an instruction count may rise before `tak compare` fails.
92    ///
93    /// A percentage of the base measurement. Only instruction counts are gated. Wall
94    /// clock is reported and never gated: on the same hardware it moves 4-20% run to
95    /// run, so a threshold tight enough to catch a real regression would fire
96    /// constantly, and one loose enough to stay quiet would catch nothing.
97    ///
98    /// The default of 1% is about fifty times the ~0.02% instruction counting
99    /// reproduces to, leaving room for the small differences a compiler or dependency
100    /// bump can produce without turning the gate into noise.
101    ///
102    /// Raise it to report without effectively failing. Setting it to zero fails on any
103    /// increase at all, which sounds appealing and is not: one extra instruction on a
104    /// startup path is not worth blocking a pull request over.
105    #[usage(
106        default = 1.0,
107        cli("--gate-pct"),
108        env = "TAK_GATE_PCT",
109        source("config", "gate.pct"),
110        example("tak compare origin/main --gate-pct 0.5"),
111        example("TAK_GATE_PCT=5 tak compare origin/main"),
112        since = "0.0.4"
113    )]
114    pub gate_pct: f64,
115
116    /// Whether generated reports end with a line naming tak.
117    ///
118    /// On by default. A report that appears in someone's pull request should say what
119    /// put it there — a reader who has never heard of tak needs a way to find out, and
120    /// a maintainer evaluating the comment needs to know what to turn off.
121    ///
122    /// Turn it off with `--no-credit`, `TAK_CREDIT=0`, or `credit = false` under
123    /// `[report]`. Nothing else about the report changes.
124    #[usage(
125        default = true,
126        cli("--no-credit"),
127        env = "TAK_CREDIT",
128        source("config", "report.credit"),
129        example("tak compare origin/main --no-credit"),
130        example("TAK_CREDIT=0 tak compare origin/main"),
131        since = "0.0.4"
132    )]
133    pub credit: bool,
134
135    /// The machine class a measurement is recorded under, and compared within.
136    ///
137    /// Empty means derive it: `gha-<os>-<arch>` under GitHub Actions, `local-<os>-<arch>`
138    /// otherwise. That is right until something about the machine changes without the
139    /// name changing.
140    ///
141    /// Series are partitioned on this, and must be. Absolute instruction counts shift
142    /// between machine types by more than a real regression does, so tak will not
143    /// compare across classes — it reports the old series as removed and the new one as
144    /// added rather than inventing a step change.
145    ///
146    /// Set it when the *environment* changes in a way the derived name cannot see. The
147    /// common case is a toolchain bump: a hosted runner image or a compiler upgrade
148    /// between the base measurement and this one is attributed to the code otherwise,
149    /// and on a one-percent gate that is a false failure. Encoding the compiler version
150    /// into the class starts a fresh series at the bump, which is honest — the numbers
151    /// either side genuinely are not comparable.
152    ///
153    /// tak cannot detect this for you. It measures programs, not build systems, and has
154    /// no way to know what produced the binary it is timing.
155    #[usage(
156        default = "",
157        default_note = "derived from the machine",
158        cli("--runner"),
159        env = "TAK_RUNNER",
160        source("config", "runner.class"),
161        example("TAK_RUNNER=gha-linux-x64-rust1.85 tak run --record"),
162        example("tak run --runner gha-linux-x64-glibc2.39"),
163        since = "0.0.6"
164    )]
165    pub runner_class: String,
166}
167
168/// The source kind `tak.toml` contributes under, for `source(...)` bindings
169/// and for [`TakConfigLayer`].
170pub fn config_source() -> SourceKind {
171    SourceKind::new("config")
172}
173
174/// `tak.toml` as a settings layer.
175///
176/// Not usage's `FileLayer`: `tak.toml` is tak's general config file, so most of
177/// what it holds — `[bench]` above all — is not a setting, and scanning the file
178/// would warn about every one of those keys. This reads the other way around:
179/// it iterates the registry's `source("config", ...)` bindings and looks each
180/// dotted key up in the parsed TOML, so a key nothing declares is simply not
181/// looked at.
182///
183/// A *missing* `tak.toml` is fine. A *syntax-broken* one — or a declared key
184/// holding the wrong type — is an error rather than a warning: the file may
185/// carry `[env]` settings that change what gets scrubbed from a subject's
186/// environment, and quietly applying a weaker filter than the project asked
187/// for is not a good failure.
188pub struct TakConfigLayer {
189    /// The file that was found, if any, and its parsed contents.
190    found: Option<(std::path::PathBuf, toml::Table)>,
191}
192
193impl TakConfigLayer {
194    /// Find and parse `tak.toml`, searching upward from `start`.
195    ///
196    /// Walking up means settings resolve the same from a subdirectory as from
197    /// the repository root, exactly like `Config::find`.
198    pub fn find(start: &Path) -> Result<Self> {
199        for dir in start.ancestors() {
200            let path = dir.join(crate::config::FILE_NAME);
201            if path.is_file() {
202                let text = std::fs::read_to_string(&path)
203                    .with_context(|| format!("could not read {}", path.display()))?;
204                let table: toml::Table = text
205                    .parse()
206                    .with_context(|| format!("could not parse {}", path.display()))?;
207                return Ok(Self {
208                    found: Some((path, table)),
209                });
210            }
211        }
212        Ok(Self { found: None })
213    }
214
215    /// Parse the settings in a given file, for `tak run --config`. Unlike
216    /// `find`, a missing file is an error: it was asked for by name.
217    pub fn at(path: &Path) -> Result<Self> {
218        let text = std::fs::read_to_string(path)
219            .with_context(|| format!("could not read {}", path.display()))?;
220        let table: toml::Table = text
221            .parse()
222            .with_context(|| format!("could not parse {}", path.display()))?;
223        Ok(Self {
224            found: Some((path.to_path_buf(), table)),
225        })
226    }
227
228    /// No file at all — what a missing `tak.toml` resolves with, and what
229    /// `doctor` falls back to when the file cannot be read.
230    pub fn empty() -> Self {
231        Self { found: None }
232    }
233
234    /// A layer over literal TOML text, for tests.
235    #[cfg(test)]
236    fn from_text(text: &str) -> Self {
237        Self {
238            found: Some((
239                std::path::PathBuf::from("tak.toml"),
240                text.parse().expect("test TOML parses"),
241            )),
242        }
243    }
244}
245
246/// A `toml::Value` as the resolver's own value type.
247fn value_of(v: &toml::Value) -> Value {
248    match v {
249        toml::Value::String(s) => Value::String(s.clone()),
250        toml::Value::Integer(i) => Value::Int(*i),
251        toml::Value::Float(f) => Value::Float(*f),
252        toml::Value::Boolean(b) => Value::Bool(*b),
253        toml::Value::Datetime(d) => Value::String(d.to_string()),
254        toml::Value::Array(items) => Value::List(items.iter().map(value_of).collect()),
255        toml::Value::Table(entries) => Value::Map(
256            entries
257                .iter()
258                .map(|(k, v)| (k.clone(), value_of(v)))
259                .collect(),
260        ),
261    }
262}
263
264/// Whether a TOML value is written as the declared type, before any coercion.
265///
266/// The resolver's coercion is deliberately forgiving — `deny = "X"` would become
267/// a one-item list, `credit = "yes"` would become `true`. tak's config file has
268/// always been stricter than that: a value of the wrong TOML type is an error,
269/// not a guess, because guessing here changes what gets scrubbed from a
270/// subject's environment without saying so.
271fn written_as(ty: &Ty, v: &toml::Value) -> bool {
272    match ty {
273        Ty::Bool => v.is_bool(),
274        Ty::Int | Ty::Uint => v.is_integer(),
275        Ty::Float => v.is_float() || v.is_integer(),
276        Ty::String | Ty::Path | Ty::Url | Ty::Duration => v.is_str(),
277        Ty::List(item) | Ty::Set(item) => v
278            .as_array()
279            .is_some_and(|items| items.iter().all(|item_value| written_as(item, item_value))),
280        Ty::Map(value) => v
281            .as_table()
282            .is_some_and(|entries| entries.values().all(|entry| written_as(value, entry))),
283        Ty::Option(inner) => written_as(inner, v),
284        _ => true,
285    }
286}
287
288impl Layer for TakConfigLayer {
289    fn source(&self) -> SourceKind {
290        config_source()
291    }
292
293    fn load(&self, ctx: &LayerCtx) -> Result<LayerOutput, LayerError> {
294        let mut out = LayerOutput::new();
295        let Some((path, table)) = &self.found else {
296            return Ok(out);
297        };
298        let registry = ctx.registry();
299        for (id, config_key) in registry.bindings(self.source()) {
300            // Walk the dotted key. An absent table defers like an absent key;
301            // a *present* name that is not a table means the file says
302            // something this cannot read, which is an error like any other
303            // wrong type here.
304            let mut parts = config_key.split('.');
305            let mut current = table.get(parts.next().unwrap_or_default());
306            for part in parts {
307                current = match current {
308                    None => break,
309                    Some(toml::Value::Table(t)) => t.get(part),
310                    Some(_) => {
311                        return Err(LayerError::Unreadable {
312                            source: path.display().to_string(),
313                            why: format!("`{config_key}` is not a table of settings"),
314                        });
315                    }
316                };
317            }
318            let Some(raw) = current else {
319                continue;
320            };
321            let meta = registry.get(id);
322            if !written_as(&meta.ty, raw) {
323                return Err(LayerError::Unreadable {
324                    source: path.display().to_string(),
325                    why: format!("`{config_key}` expected {}", meta.ty.describe()),
326                });
327            }
328            let origin = Origin::new(self.source(), path.display().to_string());
329            match ctx.entry_from_value(meta.key, value_of(raw), origin) {
330                Ok(entry) => out.push(entry),
331                // The shape check above should have refused everything the
332                // coercion would; anything left is still the file being wrong.
333                Err(warning) => {
334                    return Err(LayerError::Unreadable {
335                        source: path.display().to_string(),
336                        why: warning.message,
337                    });
338                }
339            }
340        }
341        Ok(out)
342    }
343}
344
345/// A layer with a blank `runner_class` treated as not given at all.
346///
347/// Blank means the same thing everywhere: derive the class. Treating a blank
348/// `--runner ""` or an exported-but-empty `TAK_RUNNER=` as a set value would
349/// block every lower-precedence source and record every machine under one
350/// empty class — so a blank entry falls through to the next layer, exactly as
351/// the hand-written resolver always had it.
352struct SkipBlankRunner<'a>(&'a dyn Layer);
353
354impl Layer for SkipBlankRunner<'_> {
355    fn source(&self) -> SourceKind {
356        self.0.source()
357    }
358
359    fn load(&self, ctx: &LayerCtx) -> Result<LayerOutput, LayerError> {
360        let mut out = self.0.load(ctx)?;
361        let runner = ctx.prop("runner_class").map(|found| found.id);
362        out.entries.retain(|entry| {
363            Some(entry.prop) != runner
364                || !matches!(&entry.value, Value::String(s) if s.trim().is_empty())
365        });
366        Ok(out)
367    }
368}
369
370impl Default for Settings {
371    /// The declared defaults, read the same way any other resolution is.
372    fn default() -> Self {
373        let resolved = usage_rs::config::resolve(Self::SETTINGS_REGISTRY, Layers::new())
374            .expect("no layers were given, so there is nothing to fail");
375        Self::read(&resolved).expect("every setting declares a default")
376    }
377}
378
379impl Settings {
380    /// Resolve every setting from the given layers, highest precedence first.
381    pub fn resolve(cli: &CliLayer, env: &EnvLayer, config: &TakConfigLayer) -> Result<Self> {
382        let cli = SkipBlankRunner(cli);
383        let env = SkipBlankRunner(env);
384        let config = SkipBlankRunner(config);
385        let resolved = usage_rs::config::resolve(
386            Self::SETTINGS_REGISTRY,
387            Layers::new().then(&cli).then(&env).then(&config),
388        )
389        .map_err(|e| anyhow!("{e}"))?;
390        // A typo must not silently become the default and let a regression
391        // through a gate the user thought they set — say so, then proceed with
392        // the value the remaining sources produce.
393        for warning in usage_rs::config::explain::warnings(&resolved) {
394            eprintln!("warning: {warning}");
395        }
396        let mut settings = Self::read(&resolved).map_err(|e| anyhow!("{e}"))?;
397        // `TAK_ENV_DENY=A,,B` never named an empty variable; the hand-written
398        // reader dropped blanks and call sites still rely on that.
399        settings.env_deny.retain(|name| !name.is_empty());
400        settings.env_allow.retain(|name| !name.is_empty());
401        Ok(settings)
402    }
403
404    /// Resolve against the real process environment and the `tak.toml` found
405    /// upward from the current directory.
406    pub fn from_process(cli: &CliLayer) -> Result<Self> {
407        Self::from_process_at(cli, None)
408    }
409
410    /// As [`Self::from_process`], reading `config` instead of searching for
411    /// `tak.toml` when one is given.
412    pub fn from_process_at(cli: &CliLayer, config: Option<&Path>) -> Result<Self> {
413        let config = match config {
414            Some(path) => TakConfigLayer::at(path),
415            None => TakConfigLayer::find(&std::env::current_dir()?),
416        }
417        .context("could not read settings")?;
418        Self::resolve(cli, &EnvLayer::from_process(), &config)
419    }
420
421    /// The value of a setting, by its registry key.
422    ///
423    /// Exists so display code cannot silently omit a setting: `SETTINGS_PROPS`
424    /// is generated, so a new entry appears in `tak settings` whether or not
425    /// anything can produce its value. A test asserts this returns `Some` for
426    /// every registry entry, which turns "added a setting, forgot the
427    /// accessor" into a build failure instead of a blank row.
428    pub fn display_value(&self, name: &str) -> Option<String> {
429        match name {
430            "env_allow" => Some(format!("{:?}", self.env_allow)),
431            "env_deny" => Some(format!("{:?}", self.env_deny)),
432            "credit" => Some(format!("{}", self.credit)),
433            "runner_class" => Some(if self.runner_class.is_empty() {
434                "(derived)".to_string()
435            } else {
436                self.runner_class.clone()
437            }),
438            "gate_pct" => Some(format!("{}", self.gate_pct)),
439            _ => None,
440        }
441    }
442
443    /// Variables to remove from a benchmark subject: denied, less allowed.
444    ///
445    /// Allow subtracts from deny rather than sitting beside it, so opting one
446    /// variable back in does not mean restating the whole default list.
447    pub fn scrubbed_env(&self) -> impl Iterator<Item = &str> {
448        self.env_deny
449            .iter()
450            .filter(|name| !self.env_allow.contains(name))
451            .map(String::as_str)
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    fn no_cli() -> CliLayer {
460        CliLayer::new(std::iter::empty::<(String, String)>())
461    }
462
463    fn no_env() -> EnvLayer {
464        EnvLayer::new(std::iter::empty::<(String, String)>())
465    }
466
467    fn env(vars: &[(&str, &str)]) -> EnvLayer {
468        EnvLayer::new(
469            vars.iter()
470                .map(|(k, v)| (k.to_string(), v.to_string()))
471                .collect::<Vec<_>>(),
472        )
473    }
474
475    #[test]
476    fn the_default_scrubs_forge_tokens() {
477        let s = Settings::default();
478        let scrubbed: Vec<_> = s.scrubbed_env().collect();
479        assert!(scrubbed.contains(&"GITHUB_TOKEN"));
480        assert!(scrubbed.contains(&"GH_TOKEN"));
481    }
482
483    #[test]
484    fn allow_subtracts_from_deny() {
485        let s = Settings {
486            env_deny: vec!["A".into(), "B".into()],
487            env_allow: vec!["B".into()],
488            ..Settings::default()
489        };
490        assert_eq!(s.scrubbed_env().collect::<Vec<_>>(), ["A"]);
491    }
492
493    /// Allowing something that is not denied is a no-op, not an error and not
494    /// an addition — this setting only ever removes entries from the deny list.
495    #[test]
496    fn allowing_an_undenied_variable_does_nothing() {
497        let s = Settings {
498            env_deny: vec!["A".into()],
499            env_allow: vec!["ZZZ".into()],
500            ..Settings::default()
501        };
502        assert_eq!(s.scrubbed_env().collect::<Vec<_>>(), ["A"]);
503    }
504
505    #[test]
506    fn cli_beats_env_beats_config() {
507        let cfg = TakConfigLayer::from_text("[env]\ndeny = [\"FROM_CONFIG\"]\n");
508        let with_env = env(&[("TAK_ENV_DENY", "FROM_ENV")]);
509
510        let from_config = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap();
511        assert_eq!(from_config.env_deny, ["FROM_CONFIG"]);
512
513        let from_env = Settings::resolve(&no_cli(), &with_env, &cfg).unwrap();
514        assert_eq!(from_env.env_deny, ["FROM_ENV"]);
515
516        let cli = no_cli().with_value("env_deny", Value::List(vec![Value::from("FROM_CLI")]));
517        let from_cli = Settings::resolve(&cli, &with_env, &cfg).unwrap();
518        assert_eq!(from_cli.env_deny, ["FROM_CLI"]);
519    }
520
521    #[test]
522    fn an_absent_source_defers_rather_than_clearing() {
523        let cfg = TakConfigLayer::from_text("[env]\ndeny = [\"FROM_CONFIG\"]\n");
524        // No CLI flag and no variable: the config value survives.
525        let s = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap();
526        assert_eq!(s.env_deny, ["FROM_CONFIG"]);
527    }
528
529    /// An exported-but-empty variable is a deliberate empty list. Falling
530    /// through to `tak.toml` here would make `TAK_ENV_DENY=` silently do the
531    /// opposite of what it looks like.
532    #[test]
533    fn an_empty_variable_means_an_empty_list() {
534        let cfg = TakConfigLayer::from_text("[env]\ndeny = [\"FROM_CONFIG\"]\n");
535        let s = Settings::resolve(&no_cli(), &env(&[("TAK_ENV_DENY", "")]), &cfg).unwrap();
536        assert!(s.env_deny.is_empty());
537    }
538
539    #[test]
540    fn a_variable_is_split_on_commas_and_trimmed() {
541        let with_env = env(&[("TAK_ENV_DENY", " A , B ,, C ")]);
542        let s = Settings::resolve(&no_cli(), &with_env, &TakConfigLayer::empty()).unwrap();
543        assert_eq!(s.env_deny, ["A", "B", "C"]);
544    }
545
546    /// A blank flag must defer, like a blank variable and a blank config key.
547    /// Otherwise `--runner ""` blocks every lower-precedence source and records
548    /// under an empty class, merging every machine into one series.
549    #[test]
550    fn a_blank_cli_runner_falls_through() {
551        let cfg = TakConfigLayer::from_text("[runner]\nclass = \"from-config\"\n");
552        let cli = no_cli().with("runner_class", "   ");
553        let s = Settings::resolve(&cli, &no_env(), &cfg).unwrap();
554        assert_eq!(s.runner_class, "from-config");
555    }
556
557    /// The same for the environment: exported-but-empty means "derive it".
558    #[test]
559    fn a_blank_runner_variable_falls_through() {
560        let cfg = TakConfigLayer::from_text("[runner]\nclass = \"from-config\"\n");
561        let s = Settings::resolve(&no_cli(), &env(&[("TAK_RUNNER", "")]), &cfg).unwrap();
562        assert_eq!(s.runner_class, "from-config");
563    }
564
565    /// Keys in `tak.toml` that are not settings — `[bench]` above all — are
566    /// none of the resolver's business and must not produce warnings or
567    /// errors. The layer reads the registry's bindings, not the file's keys.
568    #[test]
569    fn non_setting_keys_are_not_looked_at() {
570        let cfg = TakConfigLayer::from_text(
571            "[bench.startup]\ncmd = \"./x --version\"\n[gate]\npct = 0.5\n",
572        );
573        let s = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap();
574        assert_eq!(s.gate_pct, 0.5);
575    }
576
577    /// A declared key holding the wrong TOML type is an error, not a guess.
578    /// The resolver's coercion would read `deny = "X"` as a one-item list;
579    /// tak's config file has always been stricter, because guessing here
580    /// changes what gets scrubbed from a subject's environment.
581    #[test]
582    fn a_wrongly_typed_config_key_is_an_error() {
583        let cfg = TakConfigLayer::from_text("[env]\ndeny = \"not a list\"\n");
584        let err = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap_err();
585        assert!(format!("{err:#}").contains("env.deny"), "{err:#}");
586    }
587
588    /// The drift guard, half one: every declared environment variable actually
589    /// changes the resolved settings. A sentinel that differs from every
590    /// default and parses as every declared type — a list sees `["12345"]`, a
591    /// float sees `12345`; booleans get the opposite of their default.
592    #[test]
593    fn every_declared_env_var_is_honoured() {
594        for meta in Settings::SETTINGS_PROPS {
595            for var in meta.envs {
596                let sentinel = if meta.ty == Ty::Bool {
597                    "false"
598                } else {
599                    "12345"
600                };
601                let with_env = env(&[(var, sentinel)]);
602                let got =
603                    Settings::resolve(&no_cli(), &with_env, &TakConfigLayer::empty()).unwrap();
604                assert_ne!(
605                    got,
606                    Settings::default(),
607                    "`{}` declares {var} but setting it changes nothing",
608                    meta.key
609                );
610            }
611        }
612    }
613
614    /// The TOML literal for a sentinel of this registry type.
615    fn config_sentinel(ty: &Ty) -> String {
616        match ty {
617            Ty::List(_) => "[\"SENTINEL\"]".to_string(),
618            Ty::Float => "12345.0".to_string(),
619            // The opposite of every bool default, so flipping it always shows.
620            Ty::Bool => "false".to_string(),
621            Ty::String => "\"SENTINEL\"".to_string(),
622            other => panic!(
623                "the drift check has no sentinel for type `{}`",
624                other.name()
625            ),
626        }
627    }
628
629    /// The drift guard, half two: every declared `tak.toml` key reaches its
630    /// field. A dotted registry key is valid TOML on its own, so this builds
631    /// the smallest config that sets exactly that key and checks it lands.
632    #[test]
633    fn every_declared_config_key_is_honoured() {
634        let kind = config_source();
635        for meta in Settings::SETTINGS_PROPS {
636            for (source, key) in meta.bindings {
637                if *source != kind.name() {
638                    continue;
639                }
640                let text = format!("{key} = {}\n", config_sentinel(&meta.ty));
641                let cfg = TakConfigLayer::from_text(&text);
642                let got = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap();
643                assert_ne!(
644                    got,
645                    Settings::default(),
646                    "`{}` declares config key `{key}` but setting it changes nothing",
647                    meta.key
648                );
649            }
650        }
651    }
652
653    /// Display code reads values by registry key, and `SETTINGS_PROPS` is
654    /// generated, so a new setting shows up in `tak settings` whether or not
655    /// its value can be produced. This is what stops that being a blank row.
656    #[test]
657    fn every_setting_has_an_accessor() {
658        let s = Settings::default();
659        for meta in Settings::SETTINGS_PROPS {
660            assert!(
661                s.display_value(meta.key).is_some(),
662                "`{}` has no accessor in Settings::display_value",
663                meta.key
664            );
665        }
666    }
667
668    /// Every setting must be reachable somehow, or it is documentation for a
669    /// feature that does not exist.
670    #[test]
671    fn every_setting_declares_a_source() {
672        for meta in Settings::SETTINGS_PROPS {
673            assert!(
674                !meta.cli.is_empty() || !meta.envs.is_empty() || !meta.bindings.is_empty(),
675                "`{}` has no sources",
676                meta.key
677            );
678        }
679    }
680}