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` or `tak detect` 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 ///
106 /// This is the gate for every series without its own. A benchmark or subject can
107 /// set one with `gate = { pct = N }` in `tak.toml`, and that wins over this setting
108 /// from any source, `--gate-pct` included: the flag moves the default, not the
109 /// benchmarks a project has singled out.
110 #[usage(
111 default = 1.0,
112 cli("--gate-pct"),
113 env = "TAK_GATE_PCT",
114 source("config", "gate.pct"),
115 example("tak compare origin/main --gate-pct 0.5"),
116 example("TAK_GATE_PCT=5 tak compare origin/main"),
117 since = "0.0.4"
118 )]
119 pub gate_pct: f64,
120
121 /// Whether `tak compare` and `tak detect` honour `Tak-Accept:` trailers on the commits
122 /// they compare.
123 ///
124 /// Off by default, because of who writes those trailers. A trailer is part of a
125 /// commit message, and the commits `tak compare` reads are the change being gated —
126 /// on a pull request, the author's own. Honouring them by default would let any
127 /// change waive its own gate by adding one line, which makes the gate advisory for
128 /// exactly the changes it exists to stop. The acceptance would be visible in the
129 /// report, but visible is not the same as approved.
130 ///
131 /// With this off, trailers are ignored entirely; if the compared range carries any,
132 /// the report says so in one line, so an author is not left wondering why theirs did
133 /// nothing. `tak compare --accept BENCH` works either way, and is the recommended
134 /// route in CI: pass it from a workflow step driven by something only maintainers
135 /// can do, such as applying a pull-request label.
136 ///
137 /// Turn it on where every commit in the compared range has already been reviewed by
138 /// the time the result matters, or where everyone who can push is trusted to waive
139 /// the gate — a solo project, or comparisons along an already-reviewed main branch.
140 ///
141 /// `tak compare` reads this key, like the rest of its gate, from the base revision's
142 /// `tak.toml` rather than the checkout being measured, so a pull request cannot turn
143 /// trailers on for itself; turning them on takes effect once that change is merged.
144 /// `tak detect` reads the working tree's, which on a main-branch run is merged
145 /// history. The environment takes precedence over either file.
146 #[usage(
147 default = false,
148 env = "TAK_ACCEPT_TRAILERS",
149 source("config", "gate.accept_trailers"),
150 example("TAK_ACCEPT_TRAILERS=1 tak compare origin/main"),
151 since = "0.0.14"
152 )]
153 pub accept_trailers: bool,
154
155 /// How many instructions a count may rise by before `tak compare` or `tak detect` fails,
156 /// whatever the percentage.
157 ///
158 /// A regression has to exceed both this and `gate_pct`. A percentage alone serves
159 /// small benchmarks badly: on a 450k-instruction startup check, 1% is 4,500
160 /// instructions, which one new dependency's relocations in the dynamic loader can
161 /// account for before `main` runs. A floor lets such a benchmark keep a tight
162 /// percentage without failing on a handful of instructions.
163 ///
164 /// The default of 0 means no floor: any rise beyond `gate_pct` fails. A benchmark or
165 /// subject can set its own with `gate = { min_delta = N }` in `tak.toml`.
166 #[usage(
167 default = 0,
168 cli("--gate-min-delta"),
169 env = "TAK_GATE_MIN_DELTA",
170 source("config", "gate.min_delta"),
171 example("tak compare origin/main --gate-min-delta 20000"),
172 since = "0.0.14"
173 )]
174 pub gate_min_delta: u64,
175
176 /// Whether a comparison that compared nothing passes, with a warning, instead of failing.
177 ///
178 /// Applies to `tak compare`, `tak detect` and `tak run --baseline --gate`: the case
179 /// where no series was measured on both sides, so the gate had nothing to check. Off
180 /// by default, because a gate that passed without running reads exactly like one that
181 /// ran clean, and the causes nobody notices — a base never recorded, notes never
182 /// fetched, a recording that stopped producing instruction counts — are the ones a
183 /// green check hides.
184 ///
185 /// Turn it on where comparing nothing is routine rather than a symptom: a runner
186 /// class that encodes an image or toolchain version, so every update starts a new
187 /// series and the first comparison after it has no base; or a project still adopting,
188 /// whose pull requests branch from commits measured before tak was. With it on, those
189 /// runs exit successfully, the report says `allow_empty` let them through, and a
190 /// warning goes to stderr — as a `::warning::` annotation under GitHub Actions.
191 ///
192 /// The cost is that the broken causes above warn as well instead of failing. Only the
193 /// empty case is waived: a regression still fails, and so do a failed check and a
194 /// failed instruction count against a baseline.
195 ///
196 /// `--allow-empty` turns it on for one run, and `TAK_ALLOW_EMPTY=0` off. Like the rest
197 /// of its gate, `tak compare` reads it from the base revision's `tak.toml`, so a pull
198 /// request cannot waive its own empty comparison; turning it on takes effect once the
199 /// change is merged. `tak detect` and `tak run --baseline` read the working tree's.
200 #[usage(
201 default = false,
202 cli("--allow-empty"),
203 env = "TAK_ALLOW_EMPTY",
204 source("config", "gate.allow_empty"),
205 example("tak compare origin/main --allow-empty"),
206 example("TAK_ALLOW_EMPTY=0 tak detect"),
207 since = "0.0.14"
208 )]
209 pub allow_empty: bool,
210
211 /// Whether generated reports end with a line naming tak.
212 ///
213 /// On by default. A report that appears in someone's pull request should say what
214 /// put it there — a reader who has never heard of tak needs a way to find out, and
215 /// a maintainer evaluating the comment needs to know what to turn off.
216 ///
217 /// Turn it off with `--no-credit`, `TAK_CREDIT=0`, or `credit = false` under
218 /// `[report]`. Nothing else about the report changes.
219 #[usage(
220 default = true,
221 cli("--no-credit"),
222 env = "TAK_CREDIT",
223 source("config", "report.credit"),
224 example("tak compare origin/main --no-credit"),
225 example("TAK_CREDIT=0 tak compare origin/main"),
226 since = "0.0.4"
227 )]
228 pub credit: bool,
229
230 /// The machine class a measurement is recorded under, and compared within.
231 ///
232 /// Empty means derive it: `gha-<os>-<arch>` under GitHub Actions, `local-<os>-<arch>`
233 /// otherwise. That is right until something about the machine changes without the
234 /// name changing.
235 ///
236 /// Series are partitioned on this, and must be. Absolute instruction counts shift
237 /// between machine types by more than a real regression does, so tak will not
238 /// compare across classes — it reports the old series as removed and the new one as
239 /// added rather than inventing a step change.
240 ///
241 /// Set it when the *environment* changes in a way the derived name cannot see. The
242 /// common case is a toolchain bump: a hosted runner image or a compiler upgrade
243 /// between the base measurement and this one is attributed to the code otherwise,
244 /// and on a one-percent gate that is a false failure. Encoding the compiler version
245 /// into the class starts a fresh series at the bump, which is honest — the numbers
246 /// either side genuinely are not comparable.
247 ///
248 /// tak cannot detect this for you. It measures programs, not build systems, and has
249 /// no way to know what produced the binary it is timing.
250 #[usage(
251 default = "",
252 default_note = "derived from the machine",
253 cli("--runner"),
254 env = "TAK_RUNNER",
255 source("config", "runner.class"),
256 example("TAK_RUNNER=gha-linux-x64-rust1.85 tak run --record"),
257 example("tak run --runner gha-linux-x64-glibc2.39"),
258 since = "0.0.6"
259 )]
260 pub runner_class: String,
261}
262
263/// The source kind `tak.toml` contributes under, for `source(...)` bindings
264/// and for [`TakConfigLayer`].
265pub fn config_source() -> SourceKind {
266 SourceKind::new("config")
267}
268
269/// `tak.toml` as a settings layer.
270///
271/// Not usage's `FileLayer`: `tak.toml` is tak's general config file, so most of
272/// what it holds — `[bench]` above all — is not a setting, and scanning the file
273/// would warn about every one of those keys. This reads the other way around:
274/// it iterates the registry's `source("config", ...)` bindings and looks each
275/// dotted key up in the parsed TOML, so a key nothing declares is simply not
276/// looked at.
277///
278/// A *missing* `tak.toml` is fine. A *syntax-broken* one — or a declared key
279/// holding the wrong type — is an error rather than a warning: the file may
280/// carry `[env]` settings that change what gets scrubbed from a subject's
281/// environment, and quietly applying a weaker filter than the project asked
282/// for is not a good failure.
283pub struct TakConfigLayer {
284 /// The file that was found, if any, and its parsed contents.
285 found: Option<(std::path::PathBuf, toml::Table)>,
286}
287
288impl TakConfigLayer {
289 /// Find and parse `tak.toml`, searching upward from `start`.
290 ///
291 /// Walking up means settings resolve the same from a subdirectory as from
292 /// the repository root, exactly like `Config::find`.
293 pub fn find(start: &Path) -> Result<Self> {
294 for dir in start.ancestors() {
295 let path = dir.join(crate::config::FILE_NAME);
296 if path.is_file() {
297 let text = std::fs::read_to_string(&path)
298 .with_context(|| format!("could not read {}", path.display()))?;
299 let table: toml::Table = text
300 .parse()
301 .with_context(|| format!("could not parse {}", path.display()))?;
302 return Ok(Self {
303 found: Some((path, table)),
304 });
305 }
306 }
307 Ok(Self { found: None })
308 }
309
310 /// Parse the settings in a given file, for `tak run --config`. Unlike
311 /// `find`, a missing file is an error: it was asked for by name.
312 pub fn at(path: &Path) -> Result<Self> {
313 let text = std::fs::read_to_string(path)
314 .with_context(|| format!("could not read {}", path.display()))?;
315 let table: toml::Table = text
316 .parse()
317 .with_context(|| format!("could not parse {}", path.display()))?;
318 Ok(Self {
319 found: Some((path.to_path_buf(), table)),
320 })
321 }
322
323 /// Parse settings from text that is not a file on disk, for `tak compare`
324 /// reading the base revision's `tak.toml` out of git. `origin` names it in
325 /// errors, as a path would.
326 pub fn parse(origin: &str, text: &str) -> Result<Self> {
327 let table: toml::Table = text
328 .parse()
329 .with_context(|| format!("could not parse {origin}"))?;
330 Ok(Self {
331 found: Some((std::path::PathBuf::from(origin), table)),
332 })
333 }
334
335 /// No file at all — what a missing `tak.toml` resolves with, and what
336 /// `doctor` falls back to when the file cannot be read.
337 pub fn empty() -> Self {
338 Self { found: None }
339 }
340
341 /// A layer over literal TOML text, for tests.
342 #[cfg(test)]
343 fn from_text(text: &str) -> Self {
344 Self {
345 found: Some((
346 std::path::PathBuf::from("tak.toml"),
347 text.parse().expect("test TOML parses"),
348 )),
349 }
350 }
351}
352
353/// A `toml::Value` as the resolver's own value type.
354fn value_of(v: &toml::Value) -> Value {
355 match v {
356 toml::Value::String(s) => Value::String(s.clone()),
357 toml::Value::Integer(i) => Value::Int(*i),
358 toml::Value::Float(f) => Value::Float(*f),
359 toml::Value::Boolean(b) => Value::Bool(*b),
360 toml::Value::Datetime(d) => Value::String(d.to_string()),
361 toml::Value::Array(items) => Value::List(items.iter().map(value_of).collect()),
362 toml::Value::Table(entries) => Value::Map(
363 entries
364 .iter()
365 .map(|(k, v)| (k.clone(), value_of(v)))
366 .collect(),
367 ),
368 }
369}
370
371/// Whether a TOML value is written as the declared type, before any coercion.
372///
373/// The resolver's coercion is deliberately forgiving — `deny = "X"` would become
374/// a one-item list, `credit = "yes"` would become `true`. tak's config file has
375/// always been stricter than that: a value of the wrong TOML type is an error,
376/// not a guess, because guessing here changes what gets scrubbed from a
377/// subject's environment without saying so.
378fn written_as(ty: &Ty, v: &toml::Value) -> bool {
379 match ty {
380 Ty::Bool => v.is_bool(),
381 Ty::Int | Ty::Uint => v.is_integer(),
382 Ty::Float => v.is_float() || v.is_integer(),
383 Ty::String | Ty::Path | Ty::Url | Ty::Duration => v.is_str(),
384 Ty::List(item) | Ty::Set(item) => v
385 .as_array()
386 .is_some_and(|items| items.iter().all(|item_value| written_as(item, item_value))),
387 Ty::Map(value) => v
388 .as_table()
389 .is_some_and(|entries| entries.values().all(|entry| written_as(value, entry))),
390 Ty::Option(inner) => written_as(inner, v),
391 _ => true,
392 }
393}
394
395impl Layer for TakConfigLayer {
396 fn source(&self) -> SourceKind {
397 config_source()
398 }
399
400 fn load(&self, ctx: &LayerCtx) -> Result<LayerOutput, LayerError> {
401 let mut out = LayerOutput::new();
402 let Some((path, table)) = &self.found else {
403 return Ok(out);
404 };
405 let registry = ctx.registry();
406 for (id, config_key) in registry.bindings(self.source()) {
407 // Walk the dotted key. An absent table defers like an absent key;
408 // a *present* name that is not a table means the file says
409 // something this cannot read, which is an error like any other
410 // wrong type here.
411 let mut parts = config_key.split('.');
412 let mut current = table.get(parts.next().unwrap_or_default());
413 for part in parts {
414 current = match current {
415 None => break,
416 Some(toml::Value::Table(t)) => t.get(part),
417 Some(_) => {
418 return Err(LayerError::Unreadable {
419 source: path.display().to_string(),
420 why: format!("`{config_key}` is not a table of settings"),
421 });
422 }
423 };
424 }
425 let Some(raw) = current else {
426 continue;
427 };
428 let meta = registry.get(id);
429 if !written_as(&meta.ty, raw) {
430 return Err(LayerError::Unreadable {
431 source: path.display().to_string(),
432 why: format!("`{config_key}` expected {}", meta.ty.describe()),
433 });
434 }
435 let origin = Origin::new(self.source(), path.display().to_string());
436 match ctx.entry_from_value(meta.key, value_of(raw), origin) {
437 Ok(entry) => out.push(entry),
438 // The shape check above should have refused everything the
439 // coercion would; anything left is still the file being wrong.
440 Err(warning) => {
441 return Err(LayerError::Unreadable {
442 source: path.display().to_string(),
443 why: warning.message,
444 });
445 }
446 }
447 }
448 Ok(out)
449 }
450}
451
452/// A layer with a blank `runner_class` treated as not given at all.
453///
454/// Blank means the same thing everywhere: derive the class. Treating a blank
455/// `--runner ""` or an exported-but-empty `TAK_RUNNER=` as a set value would
456/// block every lower-precedence source and record every machine under one
457/// empty class — so a blank entry falls through to the next layer, exactly as
458/// the hand-written resolver always had it.
459struct SkipBlankRunner<'a>(&'a dyn Layer);
460
461impl Layer for SkipBlankRunner<'_> {
462 fn source(&self) -> SourceKind {
463 self.0.source()
464 }
465
466 fn load(&self, ctx: &LayerCtx) -> Result<LayerOutput, LayerError> {
467 let mut out = self.0.load(ctx)?;
468 let runner = ctx.prop("runner_class").map(|found| found.id);
469 out.entries.retain(|entry| {
470 Some(entry.prop) != runner
471 || !matches!(&entry.value, Value::String(s) if s.trim().is_empty())
472 });
473 Ok(out)
474 }
475}
476
477impl Default for Settings {
478 /// The declared defaults, read the same way any other resolution is.
479 fn default() -> Self {
480 let resolved = usage_rs::config::resolve(Self::SETTINGS_REGISTRY, Layers::new())
481 .expect("no layers were given, so there is nothing to fail");
482 Self::read(&resolved).expect("every setting declares a default")
483 }
484}
485
486impl Settings {
487 /// Resolve every setting from the given layers, highest precedence first.
488 pub fn resolve(cli: &CliLayer, env: &EnvLayer, config: &TakConfigLayer) -> Result<Self> {
489 let cli = SkipBlankRunner(cli);
490 let env = SkipBlankRunner(env);
491 let config = SkipBlankRunner(config);
492 let resolved = usage_rs::config::resolve(
493 Self::SETTINGS_REGISTRY,
494 Layers::new().then(&cli).then(&env).then(&config),
495 )
496 .map_err(|e| anyhow!("{e}"))?;
497 // A typo must not silently become the default and let a regression
498 // through a gate the user thought they set — say so, then proceed with
499 // the value the remaining sources produce.
500 for warning in usage_rs::config::explain::warnings(&resolved) {
501 eprintln!("warning: {warning}");
502 }
503 let mut settings = Self::read(&resolved).map_err(|e| anyhow!("{e}"))?;
504 // `TAK_ENV_DENY=A,,B` never named an empty variable; the hand-written
505 // reader dropped blanks and call sites still rely on that.
506 settings.env_deny.retain(|name| !name.is_empty());
507 settings.env_allow.retain(|name| !name.is_empty());
508 Ok(settings)
509 }
510
511 /// Resolve against the real process environment and the `tak.toml` found
512 /// upward from the current directory.
513 pub fn from_process(cli: &CliLayer) -> Result<Self> {
514 Self::from_process_at(cli, None)
515 }
516
517 /// As [`Self::from_process`], reading `config` instead of searching for
518 /// `tak.toml` when one is given.
519 pub fn from_process_at(cli: &CliLayer, config: Option<&Path>) -> Result<Self> {
520 let config = match config {
521 Some(path) => TakConfigLayer::at(path),
522 None => TakConfigLayer::find(&std::env::current_dir()?),
523 }
524 .context("could not read settings")?;
525 Self::resolve(cli, &EnvLayer::from_process(), &config)
526 }
527
528 /// The value of a setting, by its registry key.
529 ///
530 /// Exists so display code cannot silently omit a setting: `SETTINGS_PROPS`
531 /// is generated, so a new entry appears in `tak settings` whether or not
532 /// anything can produce its value. A test asserts this returns `Some` for
533 /// every registry entry, which turns "added a setting, forgot the
534 /// accessor" into a build failure instead of a blank row.
535 pub fn display_value(&self, name: &str) -> Option<String> {
536 match name {
537 "env_allow" => Some(format!("{:?}", self.env_allow)),
538 "env_deny" => Some(format!("{:?}", self.env_deny)),
539 "credit" => Some(format!("{}", self.credit)),
540 "accept_trailers" => Some(format!("{}", self.accept_trailers)),
541 "allow_empty" => Some(format!("{}", self.allow_empty)),
542 "runner_class" => Some(if self.runner_class.is_empty() {
543 "(derived)".to_string()
544 } else {
545 self.runner_class.clone()
546 }),
547 "gate_pct" => Some(format!("{}", self.gate_pct)),
548 "gate_min_delta" => Some(format!("{}", self.gate_min_delta)),
549 _ => None,
550 }
551 }
552
553 /// Variables to remove from a benchmark subject: denied, less allowed.
554 ///
555 /// Allow subtracts from deny rather than sitting beside it, so opting one
556 /// variable back in does not mean restating the whole default list.
557 pub fn scrubbed_env(&self) -> impl Iterator<Item = &str> {
558 self.env_deny
559 .iter()
560 .filter(|name| !self.env_allow.contains(name))
561 .map(String::as_str)
562 }
563}
564
565#[cfg(test)]
566mod tests {
567 use super::*;
568
569 fn no_cli() -> CliLayer {
570 CliLayer::new(std::iter::empty::<(String, String)>())
571 }
572
573 fn no_env() -> EnvLayer {
574 EnvLayer::new(std::iter::empty::<(String, String)>())
575 }
576
577 fn env(vars: &[(&str, &str)]) -> EnvLayer {
578 EnvLayer::new(
579 vars.iter()
580 .map(|(k, v)| (k.to_string(), v.to_string()))
581 .collect::<Vec<_>>(),
582 )
583 }
584
585 #[test]
586 fn the_default_scrubs_forge_tokens() {
587 let s = Settings::default();
588 let scrubbed: Vec<_> = s.scrubbed_env().collect();
589 assert!(scrubbed.contains(&"GITHUB_TOKEN"));
590 assert!(scrubbed.contains(&"GH_TOKEN"));
591 }
592
593 #[test]
594 fn allow_subtracts_from_deny() {
595 let s = Settings {
596 env_deny: vec!["A".into(), "B".into()],
597 env_allow: vec!["B".into()],
598 ..Settings::default()
599 };
600 assert_eq!(s.scrubbed_env().collect::<Vec<_>>(), ["A"]);
601 }
602
603 /// Allowing something that is not denied is a no-op, not an error and not
604 /// an addition — this setting only ever removes entries from the deny list.
605 #[test]
606 fn allowing_an_undenied_variable_does_nothing() {
607 let s = Settings {
608 env_deny: vec!["A".into()],
609 env_allow: vec!["ZZZ".into()],
610 ..Settings::default()
611 };
612 assert_eq!(s.scrubbed_env().collect::<Vec<_>>(), ["A"]);
613 }
614
615 #[test]
616 fn cli_beats_env_beats_config() {
617 let cfg = TakConfigLayer::from_text("[env]\ndeny = [\"FROM_CONFIG\"]\n");
618 let with_env = env(&[("TAK_ENV_DENY", "FROM_ENV")]);
619
620 let from_config = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap();
621 assert_eq!(from_config.env_deny, ["FROM_CONFIG"]);
622
623 let from_env = Settings::resolve(&no_cli(), &with_env, &cfg).unwrap();
624 assert_eq!(from_env.env_deny, ["FROM_ENV"]);
625
626 let cli = no_cli().with_value("env_deny", Value::List(vec![Value::from("FROM_CLI")]));
627 let from_cli = Settings::resolve(&cli, &with_env, &cfg).unwrap();
628 assert_eq!(from_cli.env_deny, ["FROM_CLI"]);
629 }
630
631 #[test]
632 fn an_absent_source_defers_rather_than_clearing() {
633 let cfg = TakConfigLayer::from_text("[env]\ndeny = [\"FROM_CONFIG\"]\n");
634 // No CLI flag and no variable: the config value survives.
635 let s = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap();
636 assert_eq!(s.env_deny, ["FROM_CONFIG"]);
637 }
638
639 /// An exported-but-empty variable is a deliberate empty list. Falling
640 /// through to `tak.toml` here would make `TAK_ENV_DENY=` silently do the
641 /// opposite of what it looks like.
642 #[test]
643 fn an_empty_variable_means_an_empty_list() {
644 let cfg = TakConfigLayer::from_text("[env]\ndeny = [\"FROM_CONFIG\"]\n");
645 let s = Settings::resolve(&no_cli(), &env(&[("TAK_ENV_DENY", "")]), &cfg).unwrap();
646 assert!(s.env_deny.is_empty());
647 }
648
649 #[test]
650 fn a_variable_is_split_on_commas_and_trimmed() {
651 let with_env = env(&[("TAK_ENV_DENY", " A , B ,, C ")]);
652 let s = Settings::resolve(&no_cli(), &with_env, &TakConfigLayer::empty()).unwrap();
653 assert_eq!(s.env_deny, ["A", "B", "C"]);
654 }
655
656 /// A blank flag must defer, like a blank variable and a blank config key.
657 /// Otherwise `--runner ""` blocks every lower-precedence source and records
658 /// under an empty class, merging every machine into one series.
659 #[test]
660 fn a_blank_cli_runner_falls_through() {
661 let cfg = TakConfigLayer::from_text("[runner]\nclass = \"from-config\"\n");
662 let cli = no_cli().with("runner_class", " ");
663 let s = Settings::resolve(&cli, &no_env(), &cfg).unwrap();
664 assert_eq!(s.runner_class, "from-config");
665 }
666
667 /// The same for the environment: exported-but-empty means "derive it".
668 #[test]
669 fn a_blank_runner_variable_falls_through() {
670 let cfg = TakConfigLayer::from_text("[runner]\nclass = \"from-config\"\n");
671 let s = Settings::resolve(&no_cli(), &env(&[("TAK_RUNNER", "")]), &cfg).unwrap();
672 assert_eq!(s.runner_class, "from-config");
673 }
674
675 /// Keys in `tak.toml` that are not settings — `[bench]` above all — are
676 /// none of the resolver's business and must not produce warnings or
677 /// errors. The layer reads the registry's bindings, not the file's keys.
678 #[test]
679 fn non_setting_keys_are_not_looked_at() {
680 let cfg = TakConfigLayer::from_text(
681 "[bench.startup]\ncmd = \"./x --version\"\n[gate]\npct = 0.5\n",
682 );
683 let s = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap();
684 assert_eq!(s.gate_pct, 0.5);
685 }
686
687 /// `allow_empty` resolves like every other setting: `tak.toml` turns it on,
688 /// the environment overrides the file either way, and `--allow-empty` wins
689 /// over both. The flag can only say `true` — its absence says nothing — so
690 /// turning it off for one run is `TAK_ALLOW_EMPTY=0`, and a flag left off
691 /// must not undo the file.
692 #[test]
693 fn allow_empty_precedence() {
694 let on = TakConfigLayer::from_text("[gate]\nallow_empty = true\n");
695 let off = TakConfigLayer::from_text("[gate]\nallow_empty = false\n");
696 let resolve = |cli: &CliLayer, env: &EnvLayer, cfg: &TakConfigLayer| {
697 Settings::resolve(cli, env, cfg).unwrap().allow_empty
698 };
699 let flag = no_cli().with_value("allow_empty", Value::Bool(true));
700
701 assert!(!Settings::default().allow_empty, "off by default");
702 assert!(resolve(&no_cli(), &no_env(), &on));
703 assert!(!resolve(&no_cli(), &no_env(), &off));
704 assert!(!resolve(&no_cli(), &env(&[("TAK_ALLOW_EMPTY", "0")]), &on));
705 assert!(resolve(&no_cli(), &env(&[("TAK_ALLOW_EMPTY", "1")]), &off));
706 assert!(resolve(&flag, &env(&[("TAK_ALLOW_EMPTY", "0")]), &off));
707 }
708
709 /// A declared key holding the wrong TOML type is an error, not a guess.
710 /// The resolver's coercion would read `deny = "X"` as a one-item list;
711 /// tak's config file has always been stricter, because guessing here
712 /// changes what gets scrubbed from a subject's environment.
713 #[test]
714 fn a_wrongly_typed_config_key_is_an_error() {
715 let cfg = TakConfigLayer::from_text("[env]\ndeny = \"not a list\"\n");
716 let err = Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap_err();
717 assert!(format!("{err:#}").contains("env.deny"), "{err:#}");
718 }
719
720 /// The drift guard, half one: every declared environment variable actually
721 /// changes the resolved settings. A sentinel that differs from every
722 /// default and parses as every declared type — a list sees `["12345"]`, a
723 /// float sees `12345`; booleans are tried both ways, since defaults differ
724 /// and one of the two must move it.
725 #[test]
726 fn every_declared_env_var_is_honoured() {
727 for meta in Settings::SETTINGS_PROPS {
728 for var in meta.envs {
729 let sentinels: &[&str] = if meta.ty == Ty::Bool {
730 &["false", "true"]
731 } else {
732 &["12345"]
733 };
734 let moved = sentinels.iter().any(|sentinel| {
735 let with_env = env(&[(var, sentinel)]);
736 Settings::resolve(&no_cli(), &with_env, &TakConfigLayer::empty()).unwrap()
737 != Settings::default()
738 });
739 assert!(
740 moved,
741 "`{}` declares {var} but setting it changes nothing",
742 meta.key
743 );
744 }
745 }
746 }
747
748 /// TOML literals for sentinels of this registry type. Booleans get both
749 /// values: defaults differ, and one of the two always moves the setting.
750 fn config_sentinels(ty: &Ty) -> Vec<String> {
751 match ty {
752 Ty::List(_) => vec!["[\"SENTINEL\"]".to_string()],
753 Ty::Float => vec!["12345.0".to_string()],
754 Ty::Bool => vec!["false".to_string(), "true".to_string()],
755 Ty::Uint => vec!["12345".to_string()],
756 Ty::String => vec!["\"SENTINEL\"".to_string()],
757 other => panic!(
758 "the drift check has no sentinel for type `{}`",
759 other.name()
760 ),
761 }
762 }
763
764 /// The drift guard, half two: every declared `tak.toml` key reaches its
765 /// field. A dotted registry key is valid TOML on its own, so this builds
766 /// the smallest config that sets exactly that key and checks it lands.
767 #[test]
768 fn every_declared_config_key_is_honoured() {
769 let kind = config_source();
770 for meta in Settings::SETTINGS_PROPS {
771 for (source, key) in meta.bindings {
772 if *source != kind.name() {
773 continue;
774 }
775 let moved = config_sentinels(&meta.ty).iter().any(|sentinel| {
776 let cfg = TakConfigLayer::from_text(&format!("{key} = {sentinel}\n"));
777 Settings::resolve(&no_cli(), &no_env(), &cfg).unwrap() != Settings::default()
778 });
779 assert!(
780 moved,
781 "`{}` declares config key `{key}` but setting it changes nothing",
782 meta.key
783 );
784 }
785 }
786 }
787
788 /// Display code reads values by registry key, and `SETTINGS_PROPS` is
789 /// generated, so a new setting shows up in `tak settings` whether or not
790 /// its value can be produced. This is what stops that being a blank row.
791 #[test]
792 fn every_setting_has_an_accessor() {
793 let s = Settings::default();
794 for meta in Settings::SETTINGS_PROPS {
795 assert!(
796 s.display_value(meta.key).is_some(),
797 "`{}` has no accessor in Settings::display_value",
798 meta.key
799 );
800 }
801 }
802
803 /// Every setting must be reachable somehow, or it is documentation for a
804 /// feature that does not exist.
805 #[test]
806 fn every_setting_declares_a_source() {
807 for meta in Settings::SETTINGS_PROPS {
808 assert!(
809 !meta.cli.is_empty() || !meta.envs.is_empty() || !meta.bindings.is_empty(),
810 "`{}` has no sources",
811 meta.key
812 );
813 }
814 }
815}