Skip to main content

targeted_mutation/
config.rs

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