1use std::collections::BTreeMap;
5use std::fs::{self, File, OpenOptions};
6use std::io::Read;
7use std::path::{Path, PathBuf};
8use std::str::FromStr;
9
10use anyhow::{Context, Result, bail};
11use serde::Deserialize;
12
13use crate::driver::StageExternal;
14use crate::output_fixture::Fixture;
15
16pub const MAX_CONFIG_BYTES: u64 = 1024 * 1024;
18
19pub const CONFIG_CANDIDATES: &[&str] = &["tmt.toml", ".config/tmt.toml", ".cargo/tmt.toml"];
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum OutputFormat {
25 #[default]
26 Text,
27 Json,
28 Jsonl,
29 Sarif,
30}
31
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
33#[serde(rename_all = "kebab-case")]
34pub enum TimeoutRecheck {
35 #[default]
36 Serial,
37 None,
38}
39
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
41#[serde(rename_all = "kebab-case")]
42pub enum TestTool {
43 #[default]
44 Cargo,
45 Nextest,
46}
47
48#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct Settings {
53 pub rebuild: Option<bool>,
55 pub source_only: Option<bool>,
56 pub error: Option<Vec<String>>,
57 pub literal_operators: Option<bool>,
58 pub verify: Option<bool>,
59 pub effects: Option<bool>,
60 pub audit: Option<usize>,
61
62 pub also_test: Option<Vec<String>>,
64 pub dependents: Option<bool>,
65 pub test_workspace: Option<bool>,
66 pub doc: Option<bool>,
67 pub test_tool: Option<TestTool>,
68 pub nextest_profile: Option<String>,
69 pub isolate_tests: Option<bool>,
70 pub lib: Option<bool>,
71 pub bins: Option<bool>,
72 pub test: Option<Vec<String>>,
73 pub test_target: Option<Vec<String>>,
74 pub test_filter: Option<Vec<String>>,
75 pub include_test: Option<Vec<String>>,
76 pub exclude_test: Option<Vec<String>>,
77 pub include_ignored: Option<bool>,
78 pub test_wrapper: Option<PathBuf>,
79 pub wrapper_grace: Option<u64>,
80
81 pub format: Option<OutputFormat>,
83 pub show_unreached: Option<bool>,
84 pub quiet: Option<bool>,
85 pub baseline: Option<PathBuf>,
86
87 pub jobs: Option<u32>,
89 pub baseline_jobs: Option<u32>,
90 pub timeout: Option<u64>,
91 pub timeout_recheck: Option<TimeoutRecheck>,
92 pub checkpoint: Option<bool>,
93 pub opt_level: Option<u8>,
94 pub features: Option<Vec<String>>,
95 pub all_features: Option<bool>,
96 pub no_default_features: Option<bool>,
97 pub locked: Option<bool>,
98
99 pub work_dir: Option<PathBuf>,
101 pub all_files: Option<bool>,
102 pub git_index: Option<bool>,
103 pub copy_fixture: Option<Vec<PathBuf>>,
104 pub copy_fixture_exclude: Option<Vec<PathBuf>>,
105 pub copy_output_fixture: Option<Vec<String>>,
106 pub stage_external: Option<Vec<String>>,
107}
108
109#[derive(Clone, Debug, Default, PartialEq, Eq)]
111pub struct ConfigFile {
112 pub defaults: Settings,
113 pub package: BTreeMap<String, Settings>,
114}
115
116#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct LoadedConfig {
119 pub path: PathBuf,
120 pub base_dir: PathBuf,
121 pub file: ConfigFile,
122}
123
124impl LoadedConfig {
125 pub fn resolve(&self, package: Option<&str>, cli: &Settings) -> Result<Settings> {
128 let mut combined = self.file.defaults.clone();
129 if let Some(pkg) = package
130 && let Some(pkg_settings) = self.file.package.get(pkg)
131 {
132 combined = combined.overlay(pkg_settings);
133 }
134 let merged = combined.overlay(cli);
135 merged.validate_effective(&format!(
136 "effective configuration (from {})",
137 self.path.display()
138 ))?;
139 Ok(merged)
140 }
141
142 pub fn resolve_workspace_base(&self, cli: &Settings) -> Result<Settings> {
146 let merged = self.file.defaults.overlay(cli);
147 merged.validate_layer(&format!(
148 "workspace configuration (from {})",
149 self.path.display()
150 ))?;
151 Ok(merged)
152 }
153}
154
155pub fn resolve_without_config(cli: &Settings) -> Result<Settings> {
157 cli.validate_effective("CLI options")?;
158 Ok(cli.clone())
159}
160
161pub fn resolve_workspace_base_without_config(cli: &Settings) -> Result<Settings> {
163 cli.validate_layer("CLI options")?;
164 Ok(cli.clone())
165}
166
167pub fn load_for_dir(
169 dir: &Path,
170 explicit: Option<&Path>,
171 no_config: bool,
172) -> Result<Option<LoadedConfig>> {
173 if no_config {
174 return Ok(None);
175 }
176 if let Some(path) = explicit {
177 return load_explicit(path).map(Some);
178 }
179 discover(dir)
180}
181
182pub fn load_explicit(path: &Path) -> Result<LoadedConfig> {
184 let base_dir = path
185 .parent()
186 .filter(|p| !p.as_os_str().is_empty())
187 .unwrap_or_else(|| Path::new("."))
188 .to_path_buf();
189 load_from_path(path, base_dir, None)
190}
191
192pub fn discover(dir: &Path) -> Result<Option<LoadedConfig>> {
195 if !dir.exists() {
196 return Ok(None);
197 }
198 let start = fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
199 let start_dir = if start.is_file() {
200 match start.parent() {
201 Some(parent) => parent.to_path_buf(),
202 None => return Ok(None),
203 }
204 } else {
205 start
206 };
207
208 let mut current: Option<&Path> = Some(start_dir.as_path());
209 while let Some(dir) = current {
210 let mut found = Vec::new();
211 for rel in CONFIG_CANDIDATES {
212 let candidate = dir.join(rel);
213 if candidate
214 .try_exists()
215 .with_context(|| format!("checking {}", candidate.display()))?
216 {
217 found.push(candidate);
218 }
219 }
220 if found.len() > 1 {
221 let names = found
222 .iter()
223 .map(|p| p.display().to_string())
224 .collect::<Vec<_>>()
225 .join(", ");
226 bail!(
227 "multiple tmt config files found in {}: {names} (keep only one or pass --config)",
228 dir.display()
229 );
230 }
231 if let Some(path) = found.into_iter().next() {
232 let canonical_dir = fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
233 return load_from_path(&path, canonical_dir.clone(), Some(&canonical_dir)).map(Some);
234 }
235 if is_workspace_manifest(&dir.join("Cargo.toml")) || dir.join(".git").exists() {
236 break;
237 }
238 current = dir.parent();
239 }
240 Ok(None)
241}
242
243pub fn detect_package_name(dir: &Path) -> Option<String> {
246 let manifest = dir.join("Cargo.toml");
247 let text = fs::read_to_string(&manifest).ok()?;
248 let doc: toml_edit::DocumentMut = text.parse().ok()?;
249 if let Some(name) = doc
250 .get("package")
251 .and_then(|p| p.get("name"))
252 .and_then(|n| n.as_str())
253 {
254 return Some(name.to_owned());
255 }
256 let members = doc
258 .get("workspace")
259 .and_then(|w| w.get("members"))
260 .and_then(|m| m.as_array())?;
261 if members.len() == 1
262 && let Some(member_rel) = members.get(0).and_then(|v| v.as_str())
263 && !member_rel.contains(['*', '?', '['])
264 {
265 let member_manifest = dir.join(member_rel).join("Cargo.toml");
266 let member_text = fs::read_to_string(member_manifest).ok()?;
267 let member_doc: toml_edit::DocumentMut = member_text.parse().ok()?;
268 return member_doc
269 .get("package")?
270 .get("name")?
271 .as_str()
272 .map(ToOwned::to_owned);
273 }
274 None
275}
276
277fn is_workspace_manifest(manifest: &Path) -> bool {
278 let Ok(text) = fs::read_to_string(manifest) else {
279 return false;
280 };
281 let Ok(doc) = text.parse::<toml_edit::DocumentMut>() else {
282 return false;
283 };
284 doc.get("workspace").is_some_and(toml_edit::Item::is_table)
285}
286
287fn open_regular_config(path: &Path, reject_symlink: bool) -> Result<File> {
288 let mut options = OpenOptions::new();
289 options.read(true);
290 #[cfg(unix)]
291 {
292 use std::os::unix::fs::OpenOptionsExt;
293 #[cfg(any(
294 target_os = "macos",
295 target_os = "ios",
296 target_os = "freebsd",
297 target_os = "netbsd",
298 target_os = "openbsd",
299 target_os = "dragonfly"
300 ))]
301 const O_NONBLOCK: i32 = 0x0004;
302 #[cfg(any(
303 target_os = "macos",
304 target_os = "ios",
305 target_os = "freebsd",
306 target_os = "netbsd",
307 target_os = "openbsd",
308 target_os = "dragonfly"
309 ))]
310 const O_NOFOLLOW: i32 = 0x0100;
311
312 #[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86")))]
313 const O_NONBLOCK: i32 = 0o4000;
314 #[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86")))]
315 const O_NOFOLLOW: i32 = 0o400000;
316
317 #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
318 const O_NONBLOCK: i32 = 0o4000;
319 #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
320 const O_NOFOLLOW: i32 = 0o100000;
321
322 #[cfg(not(any(
323 target_os = "macos",
324 target_os = "ios",
325 target_os = "freebsd",
326 target_os = "netbsd",
327 target_os = "openbsd",
328 target_os = "dragonfly",
329 all(
330 target_os = "linux",
331 any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64")
332 )
333 )))]
334 const O_NONBLOCK: i32 = 0;
335 #[cfg(not(any(
336 target_os = "macos",
337 target_os = "ios",
338 target_os = "freebsd",
339 target_os = "netbsd",
340 target_os = "openbsd",
341 target_os = "dragonfly",
342 all(
343 target_os = "linux",
344 any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64")
345 )
346 )))]
347 const O_NOFOLLOW: i32 = 0;
348
349 let flags = if reject_symlink {
350 O_NONBLOCK | O_NOFOLLOW
351 } else {
352 O_NONBLOCK
353 };
354 if flags != 0 {
355 options.custom_flags(flags);
356 }
357 }
358 let file = options
359 .open(path)
360 .with_context(|| format!("reading config file {}", path.display()))?;
361 let metadata = file
362 .metadata()
363 .with_context(|| format!("inspecting config file {}", path.display()))?;
364 if !metadata.is_file() {
365 bail!("config path is not a regular file: {}", path.display());
366 }
367 Ok(file)
368}
369
370fn load_from_path(
371 path: &Path,
372 base_dir: PathBuf,
373 confined_to: Option<&Path>,
374) -> Result<LoadedConfig> {
375 let open_target = if let Some(boundary) = confined_to {
376 let resolved = fs::canonicalize(path)
377 .with_context(|| format!("resolving config file {}", path.display()))?;
378 if !resolved.starts_with(boundary) {
379 bail!(
380 "auto-discovered config file {} resolves outside {} (pass --config explicitly to allow)",
381 path.display(),
382 boundary.display()
383 );
384 }
385 resolved
386 } else {
387 path.to_path_buf()
388 };
389 let file_handle = open_regular_config(&open_target, confined_to.is_some())?;
390 let mut text = String::new();
391 file_handle
392 .take(MAX_CONFIG_BYTES + 1)
393 .read_to_string(&mut text)
394 .with_context(|| format!("reading config file {}", path.display()))?;
395 let text_len = text.len() as u64;
396 if text_len > MAX_CONFIG_BYTES {
397 bail!(
398 "config file {} exceeds maximum size of {} bytes",
399 path.display(),
400 MAX_CONFIG_BYTES
401 );
402 }
403 let mut file = parse_config(&text, &path.display().to_string())?;
404 file.resolve_paths(&base_dir);
405 Ok(LoadedConfig {
406 path: path.to_path_buf(),
407 base_dir,
408 file,
409 })
410}
411
412pub fn parse_config(text: &str, source: &str) -> Result<ConfigFile> {
414 let text_len = text.len() as u64;
415 if text_len > MAX_CONFIG_BYTES {
416 bail!("config {source} exceeds maximum size of {MAX_CONFIG_BYTES} bytes");
417 }
418 validate_text_characters(text, source)?;
419
420 let mut doc: toml_edit::DocumentMut = text
421 .parse()
422 .with_context(|| format!("parsing TOML in {source}"))?;
423
424 let mut package = BTreeMap::new();
425 if let Some(pkg_item) = doc.remove("package") {
426 let Some(pkg_table) = pkg_item.as_table_like() else {
427 bail!("{source}: `package` must be a table of per-package settings");
428 };
429 for (name, value) in pkg_table.iter() {
430 if name.trim().is_empty() {
431 bail!("{source}: `[package]` entry name must not be empty");
432 }
433 validate_decoded_string(name, &format!("{source}: `[package]` key"))?;
434 let Some(sub_table) = value.as_table_like() else {
435 bail!("{source}: `[package.{name}]` must be a table");
436 };
437 let mut sub_doc = toml_edit::DocumentMut::new();
438 for (k, v) in sub_table.iter() {
439 sub_doc.insert(k, v.clone());
440 }
441 let settings: Settings = toml_edit::de::from_document(sub_doc)
442 .with_context(|| format!("parsing [package.{name}] in {source}"))?;
443 if settings.format.is_some() {
444 bail!(
445 "{source} [package.{name}]: `format` is only supported at the top level of tmt.toml"
446 );
447 }
448 if settings.show_unreached.is_some() {
449 bail!(
450 "{source} [package.{name}]: `show_unreached` is only supported at the top level of tmt.toml"
451 );
452 }
453 settings.validate_layer(&format!("{source} [package.{name}]"))?;
454 package.insert(name.to_owned(), settings);
455 }
456 }
457
458 let defaults: Settings = toml_edit::de::from_document(doc)
459 .with_context(|| format!("parsing top-level settings in {source}"))?;
460 defaults.validate_layer(source)?;
461
462 Ok(ConfigFile { defaults, package })
463}
464
465fn is_disallowed_bidi(ch: char) -> bool {
466 matches!(
467 ch,
468 '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
469 )
470}
471
472fn validate_text_characters(text: &str, source: &str) -> Result<()> {
473 for ch in text.chars() {
474 if ch == '\0' {
475 bail!("{source}: config file must not contain NUL bytes");
476 }
477 if (ch.is_control() && !matches!(ch, '\n' | '\r' | '\t')) || is_disallowed_bidi(ch) {
478 bail!(
479 "{source}: config file contains disallowed control character U+{:04X}",
480 ch as u32
481 );
482 }
483 }
484 Ok(())
485}
486
487fn validate_decoded_string(value: &str, context: &str) -> Result<()> {
488 for ch in value.chars() {
489 if ch == '\0' {
490 bail!("{context}: value must be without control characters (found NUL byte)");
491 }
492 if ch.is_control() || is_disallowed_bidi(ch) {
493 bail!(
494 "{context}: value must be without control characters (found U+{:04X})",
495 ch as u32
496 );
497 }
498 }
499 Ok(())
500}
501
502fn validate_decoded_path(path: &Path, context: &str) -> Result<()> {
503 if let Some(text) = path.to_str() {
504 validate_decoded_string(text, context)?;
505 }
506 Ok(())
507}
508
509impl ConfigFile {
510 fn resolve_paths(&mut self, base_dir: &Path) {
511 self.defaults.resolve_paths(base_dir);
512 for pkg in self.package.values_mut() {
513 pkg.resolve_paths(base_dir);
514 }
515 }
516}
517
518impl Settings {
519 fn resolve_paths(&mut self, base_dir: &Path) {
520 if let Some(baseline) = &mut self.baseline
521 && baseline.is_relative()
522 {
523 *baseline = base_dir.join(&*baseline);
524 }
525 if let Some(work_dir) = &mut self.work_dir
526 && work_dir.is_relative()
527 {
528 *work_dir = base_dir.join(&*work_dir);
529 }
530 }
531
532 fn validate_decoded_strings(&self, context: &str) -> Result<()> {
533 for (field, list) in [
534 ("error", self.error.as_deref()),
535 ("also_test", self.also_test.as_deref()),
536 ("test", self.test.as_deref()),
537 ("test_target", self.test_target.as_deref()),
538 ("test_filter", self.test_filter.as_deref()),
539 ("include_test", self.include_test.as_deref()),
540 ("exclude_test", self.exclude_test.as_deref()),
541 ("features", self.features.as_deref()),
542 ("copy_output_fixture", self.copy_output_fixture.as_deref()),
543 ("stage_external", self.stage_external.as_deref()),
544 ] {
545 if let Some(items) = list {
546 for item in items {
547 validate_decoded_string(item, &format!("{context}: `{field}`"))?;
548 }
549 }
550 }
551 if let Some(profile) = &self.nextest_profile {
552 validate_decoded_string(profile, &format!("{context}: `nextest_profile`"))?;
553 }
554 for (field, path) in [
555 ("test_wrapper", self.test_wrapper.as_deref()),
556 ("baseline", self.baseline.as_deref()),
557 ("work_dir", self.work_dir.as_deref()),
558 ] {
559 if let Some(p) = path {
560 validate_decoded_path(p, &format!("{context}: `{field}`"))?;
561 }
562 }
563 for (field, paths) in [
564 ("copy_fixture", self.copy_fixture.as_deref()),
565 ("copy_fixture_exclude", self.copy_fixture_exclude.as_deref()),
566 ] {
567 if let Some(items) = paths {
568 for p in items {
569 validate_decoded_path(p, &format!("{context}: `{field}`"))?;
570 }
571 }
572 }
573 Ok(())
574 }
575
576 pub fn validate_layer(&self, context: &str) -> Result<()> {
578 self.validate_decoded_strings(context)?;
579 if self.jobs == Some(0) {
580 bail!("{context}: `jobs` must be at least 1");
581 }
582 if self.baseline_jobs == Some(0) {
583 bail!("{context}: `baseline_jobs` must be at least 1");
584 }
585 if self.timeout == Some(0) {
586 bail!("{context}: `timeout` must be at least 1");
587 }
588 if let Some(opt) = self.opt_level
589 && opt > 3
590 {
591 bail!("{context}: `opt_level` must be between 0 and 3 (got {opt})");
592 }
593 if let Some(fixtures) = &self.copy_output_fixture {
594 for spec in fixtures {
595 Fixture::from_str(spec).with_context(|| {
596 format!("{context}: invalid `copy_output_fixture` entry `{spec}`")
597 })?;
598 }
599 }
600 if let Some(externals) = &self.stage_external {
601 for spec in externals {
602 StageExternal::from_str(spec).with_context(|| {
603 format!("{context}: invalid `stage_external` entry `{spec}`")
604 })?;
605 }
606 }
607 if self.rebuild == Some(true) && self.source_only == Some(true) {
608 bail!("{context}: `rebuild` and `source_only` cannot both be true");
609 }
610 if self.source_only == Some(true) && self.audit.is_some() {
611 bail!("{context}: `source_only` cannot be combined with `audit`");
612 }
613 if self.source_only == Some(true) && self.verify == Some(false) {
614 bail!("{context}: `source_only` cannot be combined with `verify = false`");
615 }
616 if self.audit.is_some() && self.verify == Some(false) {
617 bail!("{context}: `audit` cannot be combined with `verify = false`");
618 }
619 if self.all_features == Some(true)
620 && (self.features.as_ref().is_some_and(|f| !f.is_empty())
621 || self.no_default_features == Some(true))
622 {
623 bail!(
624 "{context}: `all_features` cannot be combined with `features` or `no_default_features`"
625 );
626 }
627 if self.test_tool == Some(TestTool::Cargo) && self.nextest_profile.is_some() {
628 bail!("{context}: `nextest_profile` requires `test_tool = \"nextest\"`");
629 }
630 Ok(())
631 }
632
633 pub fn overlay(&self, upper: &Settings) -> Settings {
636 let mut out = Settings {
637 rebuild: upper.rebuild.or(self.rebuild),
638 source_only: upper.source_only.or(self.source_only),
639 error: upper.error.clone().or_else(|| self.error.clone()),
640 literal_operators: upper.literal_operators.or(self.literal_operators),
641 verify: upper.verify.or(self.verify),
642 effects: upper.effects.or(self.effects),
643 audit: upper.audit.or(self.audit),
644 also_test: upper.also_test.clone().or_else(|| self.also_test.clone()),
645 dependents: upper.dependents.or(self.dependents),
646 test_workspace: upper.test_workspace.or(self.test_workspace),
647 doc: upper.doc.or(self.doc),
648 test_tool: upper.test_tool.or(self.test_tool),
649 nextest_profile: upper
650 .nextest_profile
651 .clone()
652 .or_else(|| self.nextest_profile.clone()),
653 isolate_tests: upper.isolate_tests.or(self.isolate_tests),
654 lib: upper.lib.or(self.lib),
655 bins: upper.bins.or(self.bins),
656 test: upper.test.clone().or_else(|| self.test.clone()),
657 test_target: upper
658 .test_target
659 .clone()
660 .or_else(|| self.test_target.clone()),
661 test_filter: upper
662 .test_filter
663 .clone()
664 .or_else(|| self.test_filter.clone()),
665 include_test: upper
666 .include_test
667 .clone()
668 .or_else(|| self.include_test.clone()),
669 exclude_test: upper
670 .exclude_test
671 .clone()
672 .or_else(|| self.exclude_test.clone()),
673 include_ignored: upper.include_ignored.or(self.include_ignored),
674 test_wrapper: upper
675 .test_wrapper
676 .clone()
677 .or_else(|| self.test_wrapper.clone()),
678 wrapper_grace: upper.wrapper_grace.or(self.wrapper_grace),
679 format: upper.format.or(self.format),
680 show_unreached: upper.show_unreached.or(self.show_unreached),
681 quiet: upper.quiet.or(self.quiet),
682 baseline: upper.baseline.clone().or_else(|| self.baseline.clone()),
683 jobs: upper.jobs.or(self.jobs),
684 baseline_jobs: upper.baseline_jobs.or(self.baseline_jobs),
685 timeout: upper.timeout.or(self.timeout),
686 timeout_recheck: upper.timeout_recheck.or(self.timeout_recheck),
687 checkpoint: upper.checkpoint.or(self.checkpoint),
688 opt_level: upper.opt_level.or(self.opt_level),
689 features: upper.features.clone().or_else(|| self.features.clone()),
690 all_features: upper.all_features.or(self.all_features),
691 no_default_features: upper.no_default_features.or(self.no_default_features),
692 locked: upper.locked.or(self.locked),
693 work_dir: upper.work_dir.clone().or_else(|| self.work_dir.clone()),
694 all_files: upper.all_files.or(self.all_files),
695 git_index: upper.git_index.or(self.git_index),
696 copy_fixture: upper
697 .copy_fixture
698 .clone()
699 .or_else(|| self.copy_fixture.clone()),
700 copy_fixture_exclude: upper
701 .copy_fixture_exclude
702 .clone()
703 .or_else(|| self.copy_fixture_exclude.clone()),
704 copy_output_fixture: upper
705 .copy_output_fixture
706 .clone()
707 .or_else(|| self.copy_output_fixture.clone()),
708 stage_external: upper
709 .stage_external
710 .clone()
711 .or_else(|| self.stage_external.clone()),
712 };
713
714 if upper.source_only == Some(true) {
716 if upper.rebuild.is_none() {
717 out.rebuild = Some(false);
718 }
719 if upper.audit.is_none() {
720 out.audit = None;
721 }
722 if upper.verify.is_none() {
723 out.verify = Some(true);
724 }
725 }
726 if upper.rebuild == Some(true) && upper.source_only.is_none() {
727 out.source_only = Some(false);
728 }
729 if upper.audit.is_some() {
730 if upper.verify.is_none() {
731 out.verify = Some(true);
732 }
733 if upper.source_only.is_none() {
734 out.source_only = Some(false);
735 }
736 }
737 if out.source_only == Some(false) && upper.literal_operators.is_none() {
738 out.literal_operators = Some(false);
739 }
740 if upper.verify == Some(false) && upper.audit.is_none() {
741 out.audit = None;
742 }
743 if upper.all_features == Some(true) {
744 if upper.features.is_none() {
745 out.features = None;
746 }
747 if upper.no_default_features.is_none() {
748 out.no_default_features = Some(false);
749 }
750 }
751 if (upper.features.as_ref().is_some_and(|f| !f.is_empty())
752 || upper.no_default_features == Some(true))
753 && upper.all_features.is_none()
754 {
755 out.all_features = Some(false);
756 }
757 if upper.test_tool == Some(TestTool::Cargo) && upper.nextest_profile.is_none() {
758 out.nextest_profile = None;
759 }
760 if upper.copy_fixture.as_ref().is_some_and(Vec::is_empty)
761 && upper.copy_fixture_exclude.is_none()
762 {
763 out.copy_fixture_exclude = None;
764 }
765
766 out
767 }
768
769 pub fn validate_effective(&self, context: &str) -> Result<()> {
771 self.validate_layer(context)?;
772
773 let source_only = self.source_only.unwrap_or(false);
774 let literal_operators = self.literal_operators.unwrap_or(false);
775 let test_tool = self.test_tool.unwrap_or_default();
776
777 if literal_operators && !source_only {
778 bail!("{context}: `literal_operators` requires `source_only = true`");
779 }
780 if self.nextest_profile.is_some() && test_tool != TestTool::Nextest {
781 bail!("{context}: `nextest_profile` requires `test_tool = \"nextest\"`");
782 }
783 if self.wrapper_grace.is_some() && self.test_wrapper.is_none() {
784 bail!("{context}: `wrapper_grace` requires `test_wrapper`");
785 }
786 if self
787 .copy_fixture_exclude
788 .as_ref()
789 .is_some_and(|e| !e.is_empty())
790 && self.copy_fixture.as_ref().is_none_or(Vec::is_empty)
791 {
792 bail!("{context}: `copy_fixture_exclude` requires `copy_fixture`");
793 }
794 Ok(())
795 }
796
797 pub fn parsed_output_fixtures(&self) -> Result<Vec<Fixture>> {
799 self.copy_output_fixture
800 .as_deref()
801 .unwrap_or(&[])
802 .iter()
803 .map(|s| Fixture::from_str(s))
804 .collect()
805 }
806
807 pub fn parsed_stage_external(&self) -> Result<Vec<StageExternal>> {
809 self.stage_external
810 .as_deref()
811 .unwrap_or(&[])
812 .iter()
813 .map(|s| StageExternal::from_str(s))
814 .collect()
815 }
816}
817
818#[cfg(test)]
819mod tests {
820 use super::*;
821 use std::sync::atomic::{AtomicU64, Ordering};
822
823 fn temp_dir(label: &str) -> PathBuf {
824 static COUNTER: AtomicU64 = AtomicU64::new(0);
825 let id = COUNTER.fetch_add(1, Ordering::Relaxed);
826 let dir = std::env::temp_dir().join(format!(
827 "tmt-config-test-{}-{}-{label}",
828 std::process::id(),
829 id
830 ));
831 let _ = fs::remove_dir_all(&dir);
832 fs::create_dir_all(&dir).unwrap();
833 dir
834 }
835
836 fn write(path: &Path, content: &str) {
837 if let Some(parent) = path.parent() {
838 fs::create_dir_all(parent).unwrap();
839 }
840 fs::write(path, content).unwrap();
841 }
842
843 #[test]
844 fn config_file_pict_table() {
845 let table = include_str!("../tests/data/config-file.pict.tsv");
846 let mut lines = table.lines();
847 let _header = lines.next().expect("header");
848
849 for (idx, line) in lines.filter(|l| !l.trim().is_empty()).enumerate() {
850 let cols: Vec<&str> = line.split('\t').collect();
851 assert_eq!(cols.len(), 5, "row {idx}: {line}");
852 let (source, pkg_override, cli_override, path_base, validity) =
853 (cols[0], cols[1], cols[2], cols[3], cols[4]);
854
855 let root = temp_dir(&format!("pict-{idx}"));
856 let pkg_dir = if source == "auto_workspace_parent" {
857 write(
858 &root.join("Cargo.toml"),
859 "[workspace]\nmembers = [\"crates/alpha\"]\n",
860 );
861 let member = root.join("crates/alpha");
862 write(
863 &member.join("Cargo.toml"),
864 "[package]\nname = \"alpha\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
865 );
866 member
867 } else {
868 write(
869 &root.join("Cargo.toml"),
870 "[package]\nname = \"alpha\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
871 );
872 root.clone()
873 };
874
875 let abs_baseline = root.join("abs-baseline.json");
876 let mut body = String::new();
877 match validity {
878 "valid" => {
879 body.push_str("jobs = 4\n");
880 body.push_str("rebuild = true\n");
881 body.push_str("exclude_test = [\"top_skip\"]\n");
882 match path_base {
883 "relative" => body.push_str("baseline = \"base/rel.json\"\n"),
884 "absolute" => {
885 let escaped = abs_baseline.display().to_string().replace('\\', "\\\\");
886 body.push_str(&format!("baseline = \"{escaped}\"\n"));
887 }
888 "absent" => {}
889 other => panic!("unexpected PathBase: {other}"),
890 }
891 match pkg_override {
892 "matching" => {
893 body.push_str(
894 "\n[package.alpha]\njobs = 2\nexclude_test = [\"pkg_skip\"]\n",
895 );
896 }
897 "other_only" => {
898 body.push_str(
899 "\n[package.beta]\njobs = 8\nexclude_test = [\"beta_skip\"]\n",
900 );
901 }
902 "none" => {}
903 other => panic!("unexpected PackageOverride: {other}"),
904 }
905 }
906 "unknown_key" => body.push_str("no_such_option = true\n"),
907 "invalid_value" => body.push_str("jobs = 0\n"),
908 "duplicate_candidates" => {
909 body.push_str("jobs = 2\n");
910 }
911 "missing_explicit" => {}
912 other => panic!("unexpected Validity: {other}"),
913 }
914
915 let explicit_path = root.join("custom/explicit.toml");
916 let mut explicit_arg: Option<PathBuf> = None;
917 let mut no_config = false;
918
919 match source {
920 "none" => {}
921 "disabled" => {
922 write(&root.join("tmt.toml"), "jobs = 9\n");
923 no_config = true;
924 }
925 "auto_root" | "auto_workspace_parent" => {
926 write(&root.join("tmt.toml"), &body);
927 if validity == "duplicate_candidates" {
928 write(&root.join(".config/tmt.toml"), "jobs = 3\n");
929 }
930 }
931 "auto_dot_config" => {
932 write(&root.join(".config/tmt.toml"), &body);
933 if validity == "duplicate_candidates" {
934 write(&root.join(".cargo/tmt.toml"), "jobs = 3\n");
935 }
936 }
937 "auto_dot_cargo" => {
938 write(&root.join(".cargo/tmt.toml"), &body);
939 if validity == "duplicate_candidates" {
940 write(&root.join("tmt.toml"), "jobs = 3\n");
941 }
942 }
943 "explicit" => {
944 if validity != "missing_explicit" {
945 write(&explicit_path, &body);
946 }
947 explicit_arg = Some(explicit_path.clone());
948 }
949 other => panic!("unexpected ConfigSource: {other}"),
950 }
951
952 let loaded = load_for_dir(&pkg_dir, explicit_arg.as_deref(), no_config);
953 if validity != "valid" {
954 assert!(
955 loaded.is_err(),
956 "expected error for row {idx} ({line}), got {loaded:?}"
957 );
958 let _ = fs::remove_dir_all(&root);
959 continue;
960 }
961 let loaded = loaded.unwrap_or_else(|e| panic!("row {idx} ({line}) failed: {e:#}"));
962 if matches!(source, "none" | "disabled") {
963 assert!(loaded.is_none(), "row {idx}: expected no config");
964 let _ = fs::remove_dir_all(&root);
965 continue;
966 }
967 let loaded = loaded.unwrap_or_else(|| panic!("row {idx}: expected config to load"));
968
969 let mut cli = Settings::default();
970 match cli_override {
971 "none" => {}
972 "scalar" => cli.jobs = Some(1),
973 "array" => cli.exclude_test = Some(vec!["cli_skip".into()]),
974 "conflicting_mode" => cli.source_only = Some(true),
975 other => panic!("unexpected CliOverride: {other}"),
976 }
977
978 let effective = loaded
979 .resolve(Some("alpha"), &cli)
980 .unwrap_or_else(|e| panic!("row {idx} ({line}) resolve failed: {e:#}"));
981
982 let expected_jobs = match (cli_override, pkg_override) {
983 ("scalar", _) => Some(1),
984 (_, "matching") => Some(2),
985 _ => Some(4),
986 };
987 assert_eq!(effective.jobs, expected_jobs, "row {idx}: {line}");
988
989 let expected_exclude = match (cli_override, pkg_override) {
990 ("array", _) => Some(vec!["cli_skip".into()]),
991 (_, "matching") => Some(vec!["pkg_skip".into()]),
992 _ => Some(vec!["top_skip".into()]),
993 };
994 assert_eq!(
995 effective.exclude_test, expected_exclude,
996 "row {idx}: {line}"
997 );
998
999 if cli_override == "conflicting_mode" {
1000 assert_eq!(effective.source_only, Some(true), "row {idx}");
1001 assert_eq!(effective.rebuild, Some(false), "row {idx}");
1002 } else {
1003 assert_eq!(effective.rebuild, Some(true), "row {idx}");
1004 }
1005
1006 let expected_base = if source == "explicit" {
1007 root.join("custom")
1008 } else {
1009 fs::canonicalize(&root).unwrap()
1010 };
1011 match path_base {
1012 "absent" => assert_eq!(effective.baseline, None, "row {idx}"),
1013 "relative" => assert_eq!(
1014 effective.baseline,
1015 Some(expected_base.join("base/rel.json")),
1016 "row {idx}: {line}"
1017 ),
1018 "absolute" => assert_eq!(effective.baseline, Some(abs_baseline), "row {idx}"),
1019 _ => unreachable!(),
1020 }
1021
1022 let _ = fs::remove_dir_all(&root);
1023 }
1024 }
1025
1026 #[test]
1027 fn discovery_stops_at_workspace_and_git_boundaries() {
1028 let outer = temp_dir("boundary");
1029 write(&outer.join("tmt.toml"), "jobs = 9\n");
1030
1031 let isolated_ws = outer.join("isolated-ws");
1033 write(
1034 &isolated_ws.join("Cargo.toml"),
1035 "[workspace]\n[package]\nname = \"iso\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1036 );
1037 assert!(discover(&isolated_ws).unwrap().is_none());
1038
1039 let inner_git = outer.join("inner-git");
1041 fs::create_dir_all(inner_git.join(".git")).unwrap();
1042 write(
1043 &inner_git.join("Cargo.toml"),
1044 "[package]\nname = \"gitpkg\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1045 );
1046 assert!(discover(&inner_git).unwrap().is_none());
1047
1048 let ws = outer.join("ws");
1051 write(&ws.join("Cargo.toml"), "[workspace]\nmembers = [\"a\"]\n");
1052 write(
1053 &ws.join(".config/tmt.toml"),
1054 "opt_level = 3\n\n[package.a]\nwork_dir = \"custom-work\"\nbaseline = \"a-base.json\"\n",
1055 );
1056 let member = ws.join("a");
1057 write(
1058 &member.join("Cargo.toml"),
1059 "[package]\nname = \"a\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1060 );
1061 let loaded = discover(&member).unwrap().expect("workspace config");
1062 let ws_canon = fs::canonicalize(&ws).unwrap();
1063 assert_eq!(loaded.file.defaults.opt_level, Some(3));
1064 assert_eq!(loaded.base_dir, ws_canon);
1065 let eff = loaded.resolve(Some("a"), &Settings::default()).unwrap();
1066 assert_eq!(eff.work_dir, Some(ws_canon.join("custom-work")));
1067 assert_eq!(eff.baseline, Some(ws_canon.join("a-base.json")));
1068
1069 let _ = fs::remove_dir_all(&outer);
1070 }
1071
1072 #[test]
1073 fn size_limit_non_file_and_symlink_boundary_are_enforced() {
1074 let dir = temp_dir("io-limits");
1075
1076 let exact = dir.join("exact.toml");
1078 let pad_exact = "#".repeat(MAX_CONFIG_BYTES as usize);
1079 write(&exact, &pad_exact);
1080 assert!(load_explicit(&exact).is_ok());
1081
1082 let over = dir.join("over.toml");
1083 let pad_over = "#".repeat(MAX_CONFIG_BYTES as usize + 1);
1084 write(&over, &pad_over);
1085 assert!(load_explicit(&over).is_err());
1086
1087 let subdir = dir.join("subdir");
1089 fs::create_dir_all(&subdir).unwrap();
1090 assert!(load_explicit(&subdir).is_err());
1091
1092 #[cfg(unix)]
1095 {
1096 use std::os::unix::fs::symlink;
1097 let outside = temp_dir("outside-symlink");
1098 let secret_cfg = outside.join("outside.toml");
1099 write(&secret_cfg, "jobs = 2\n");
1100 let proj = dir.join("proj");
1101 fs::create_dir_all(&proj).unwrap();
1102 symlink(&secret_cfg, proj.join("tmt.toml")).unwrap();
1103 assert!(discover(&proj).is_err());
1104 assert!(load_explicit(&proj.join("tmt.toml")).is_ok());
1106
1107 let proj2 = dir.join("proj2");
1109 fs::create_dir_all(&proj2).unwrap();
1110 let outside_cfg_dir = outside.join("cfgdir");
1111 write(&outside_cfg_dir.join("tmt.toml"), "jobs = 2\n");
1112 symlink(&outside_cfg_dir, proj2.join(".config")).unwrap();
1113 assert!(discover(&proj2).is_err());
1114
1115 let fifo_proj = dir.join("fifo-proj");
1117 fs::create_dir_all(&fifo_proj).unwrap();
1118 let fifo_path = fifo_proj.join("tmt.toml");
1119 let status = std::process::Command::new("mkfifo")
1120 .arg(&fifo_path)
1121 .status()
1122 .expect("mkfifo");
1123 assert!(status.success());
1124 assert!(discover(&fifo_proj).is_err());
1125 assert!(load_explicit(&fifo_path).is_err());
1126
1127 let _ = fs::remove_dir_all(&outside);
1128 }
1129
1130 let _ = fs::remove_dir_all(&dir);
1131 }
1132
1133 #[test]
1134 fn parse_rejects_dangerous_chars_escaped_controls_and_invalid_values() {
1135 assert!(parse_config("jobs = 1\0\n", "test").is_err());
1136 assert!(parse_config("jobs = 1\x07\n", "test").is_err());
1137 assert!(parse_config("# \u{202E}bidi\njobs = 1\n", "test").is_err());
1138 assert!(parse_config("# \u{061C}alm\njobs = 1\n", "test").is_err());
1139
1140 assert!(parse_config(&"#".repeat(MAX_CONFIG_BYTES as usize), "test").is_ok());
1142 assert!(parse_config(&"#".repeat(MAX_CONFIG_BYTES as usize + 1), "test").is_err());
1143
1144 let ok = parse_config(
1146 "opt_level = 3\njobs = 1\nbaseline_jobs = 1\ntimeout = 1\n",
1147 "test",
1148 )
1149 .unwrap();
1150 assert_eq!(ok.defaults.opt_level, Some(3));
1151
1152 for bad in [
1153 "jobs = 0\n",
1154 "baseline_jobs = 0\n",
1155 "timeout = 0\n",
1156 "opt_level = 4\n",
1157 "unknown_field = 1\n",
1158 "rebuild = true\nsource_only = true\n",
1159 "source_only = true\naudit = 2\n",
1160 "source_only = true\nverify = false\n",
1161 "audit = 2\nverify = false\n",
1162 "all_features = true\nfeatures = [\"a\"]\n",
1163 "all_features = true\nno_default_features = true\n",
1164 "test_tool = \"cargo\"\nnextest_profile = \"ci\"\n",
1165 "copy_output_fixture = [\"missing_equals\"]\n",
1166 "stage_external = [\"not_parent_relative\"]\n",
1167 "package = \"not_a_table\"\n",
1168 "[package]\nfoo = 123\n",
1169 "[package.foo]\nunknown = true\n",
1170 "[package.foo]\njobs = 0\n",
1171 "[package.foo]\nformat = \"json\"\n",
1172 "[package.foo]\nshow_unreached = true\n",
1173 "exclude_test = [\"bad\\u0000name\"]\n",
1175 "nextest_profile = \"ci\\u001b[31m\"\n",
1176 "baseline = \"foo\\u202Ebar.json\"\n",
1177 "baseline = \"foo\\u061cbar.json\"\n",
1178 "[package.\"bad\\u0000pkg\"]\njobs = 1\n",
1179 ] {
1180 assert!(
1181 parse_config(bad, "test").is_err(),
1182 "expected parse_config error for:\n{bad}"
1183 );
1184 }
1185 }
1186
1187 #[test]
1188 fn overlay_and_effective_validation_cover_all_mode_switches_and_requirements() {
1189 let base = parse_config(
1190 r#"
1191 all_features = true
1192 test_tool = "nextest"
1193 nextest_profile = "ci"
1194 source_only = true
1195 literal_operators = true
1196 exclude_test = ["slow_a", "slow_b"]
1197 copy_fixture = ["data"]
1198 copy_fixture_exclude = ["data/tmp"]
1199 test_wrapper = "scripts/wrap.sh"
1200 wrapper_grace = 5
1201 "#,
1202 "tmt.toml",
1203 )
1204 .unwrap()
1205 .defaults;
1206 base.validate_effective("base").unwrap();
1208
1209 let disable_source = Settings {
1211 source_only: Some(false),
1212 ..Settings::default()
1213 };
1214 let disabled = base.overlay(&disable_source);
1215 assert_eq!(disabled.source_only, Some(false));
1216 assert_eq!(disabled.literal_operators, Some(false));
1217 disabled.validate_effective("disabled").unwrap();
1218
1219 let audit_cli = Settings {
1221 audit: Some(3),
1222 ..Settings::default()
1223 };
1224 let audited = base.overlay(&audit_cli);
1225 assert_eq!(audited.source_only, Some(false));
1226 assert_eq!(audited.literal_operators, Some(false));
1227 audited.validate_effective("audited").unwrap();
1228
1229 let cli = Settings {
1231 features: Some(vec!["minimal".into()]),
1232 test_tool: Some(TestTool::Cargo),
1233 rebuild: Some(true),
1234 exclude_test: Some(vec![]),
1235 copy_fixture: Some(vec![]),
1236 ..Settings::default()
1237 };
1238 let merged = base.overlay(&cli);
1239 merged.validate_effective("merged").unwrap();
1240 assert_eq!(merged.all_features, Some(false));
1241 assert_eq!(merged.features, Some(vec!["minimal".into()]));
1242 assert_eq!(merged.test_tool, Some(TestTool::Cargo));
1243 assert_eq!(merged.nextest_profile, None);
1244 assert_eq!(merged.rebuild, Some(true));
1245 assert_eq!(merged.source_only, Some(false));
1246 assert_eq!(merged.literal_operators, Some(false));
1247 assert_eq!(merged.exclude_test, Some(vec![]));
1248 assert_eq!(merged.copy_fixture, Some(vec![]));
1249 assert_eq!(merged.copy_fixture_exclude, None);
1250
1251 assert!(
1253 Settings {
1254 literal_operators: Some(true),
1255 ..Settings::default()
1256 }
1257 .validate_effective("lit")
1258 .is_err()
1259 );
1260 assert!(
1261 Settings {
1262 nextest_profile: Some("ci".into()),
1263 ..Settings::default()
1264 }
1265 .validate_effective("nextest")
1266 .is_err()
1267 );
1268 assert!(
1269 Settings {
1270 wrapper_grace: Some(5),
1271 ..Settings::default()
1272 }
1273 .validate_effective("grace")
1274 .is_err()
1275 );
1276 assert!(
1277 Settings {
1278 copy_fixture_exclude: Some(vec![PathBuf::from("a")]),
1279 ..Settings::default()
1280 }
1281 .validate_effective("exclude")
1282 .is_err()
1283 );
1284
1285 let loaded = LoadedConfig {
1287 path: PathBuf::from("tmt.toml"),
1288 base_dir: PathBuf::from("."),
1289 file: parse_config("jobs = 2\n", "tmt.toml").unwrap(),
1290 };
1291 assert!(
1292 loaded
1293 .resolve(
1294 None,
1295 &Settings {
1296 wrapper_grace: Some(3),
1297 ..Settings::default()
1298 }
1299 )
1300 .is_err()
1301 );
1302 }
1303
1304 #[test]
1305 fn detect_package_name_reads_manifest_and_single_member_virtual_workspace() {
1306 let dir = temp_dir("pkg-name");
1307 write(
1308 &dir.join("Cargo.toml"),
1309 "[package]\nname = \"my-crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1310 );
1311 assert_eq!(detect_package_name(&dir).as_deref(), Some("my-crate"));
1312
1313 let virt_empty = temp_dir("virt-ws-empty");
1314 write(
1315 &virt_empty.join("Cargo.toml"),
1316 "[workspace]\nmembers = []\n",
1317 );
1318 assert_eq!(detect_package_name(&virt_empty), None);
1319
1320 let virt_single = temp_dir("virt-ws-single");
1321 write(
1322 &virt_single.join("Cargo.toml"),
1323 "[workspace]\nmembers = [\"crates/only\"]\n",
1324 );
1325 write(
1326 &virt_single.join("crates/only/Cargo.toml"),
1327 "[package]\nname = \"only-crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1328 );
1329 assert_eq!(
1330 detect_package_name(&virt_single).as_deref(),
1331 Some("only-crate")
1332 );
1333
1334 let _ = fs::remove_dir_all(&dir);
1335 let _ = fs::remove_dir_all(&virt_empty);
1336 let _ = fs::remove_dir_all(&virt_single);
1337 }
1338}