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).with_context(|| {
444                format!(
445                    "parsing [package.{name}] in {source} (cargo-tmt v{})",
446                    env!("CARGO_PKG_VERSION")
447                )
448            })?;
449            if settings.format.is_some() {
450                bail!(
451                    "{source} [package.{name}]: `format` is only supported at the top level of tmt.toml"
452                );
453            }
454            if settings.show_unreached.is_some() {
455                bail!(
456                    "{source} [package.{name}]: `show_unreached` is only supported at the top level of tmt.toml"
457                );
458            }
459            settings.validate_layer(&format!("{source} [package.{name}]"))?;
460            package.insert(name.to_owned(), settings);
461        }
462    }
463
464    let defaults: Settings = toml_edit::de::from_document(doc).with_context(|| {
465        format!(
466            "parsing top-level settings in {source} (cargo-tmt v{})",
467            env!("CARGO_PKG_VERSION")
468        )
469    })?;
470    defaults.validate_layer(source)?;
471
472    Ok(ConfigFile { defaults, package })
473}
474
475fn is_disallowed_bidi(ch: char) -> bool {
476    matches!(
477        ch,
478        '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
479    )
480}
481
482fn validate_text_characters(text: &str, source: &str) -> Result<()> {
483    for ch in text.chars() {
484        if ch == '\0' {
485            bail!("{source}: config file must not contain NUL bytes");
486        }
487        if (ch.is_control() && !matches!(ch, '\n' | '\r' | '\t')) || is_disallowed_bidi(ch) {
488            bail!(
489                "{source}: config file contains disallowed control character U+{:04X}",
490                ch as u32
491            );
492        }
493    }
494    Ok(())
495}
496
497fn validate_decoded_string(value: &str, context: &str) -> Result<()> {
498    for ch in value.chars() {
499        if ch == '\0' {
500            bail!("{context}: value must be without control characters (found NUL byte)");
501        }
502        if ch.is_control() || is_disallowed_bidi(ch) {
503            bail!(
504                "{context}: value must be without control characters (found U+{:04X})",
505                ch as u32
506            );
507        }
508    }
509    Ok(())
510}
511
512fn validate_decoded_path(path: &Path, context: &str) -> Result<()> {
513    if let Some(text) = path.to_str() {
514        validate_decoded_string(text, context)?;
515    }
516    Ok(())
517}
518
519impl ConfigFile {
520    fn resolve_paths(&mut self, base_dir: &Path) {
521        self.defaults.resolve_paths(base_dir);
522        for pkg in self.package.values_mut() {
523            pkg.resolve_paths(base_dir);
524        }
525    }
526}
527
528impl Settings {
529    fn resolve_paths(&mut self, base_dir: &Path) {
530        if let Some(baseline) = &mut self.baseline
531            && baseline.is_relative()
532        {
533            *baseline = base_dir.join(&*baseline);
534        }
535        if let Some(work_dir) = &mut self.work_dir
536            && work_dir.is_relative()
537        {
538            *work_dir = base_dir.join(&*work_dir);
539        }
540    }
541
542    fn validate_decoded_strings(&self, context: &str) -> Result<()> {
543        for (field, list) in [
544            ("exclude_file", self.exclude_file.as_deref()),
545            ("error", self.error.as_deref()),
546            ("also_test", self.also_test.as_deref()),
547            ("test", self.test.as_deref()),
548            ("test_target", self.test_target.as_deref()),
549            ("test_filter", self.test_filter.as_deref()),
550            ("include_test", self.include_test.as_deref()),
551            ("exclude_test", self.exclude_test.as_deref()),
552            ("features", self.features.as_deref()),
553            ("copy_output_fixture", self.copy_output_fixture.as_deref()),
554            ("stage_external", self.stage_external.as_deref()),
555        ] {
556            if let Some(items) = list {
557                for item in items {
558                    validate_decoded_string(item, &format!("{context}: `{field}`"))?;
559                }
560            }
561        }
562        if let Some(profile) = &self.nextest_profile {
563            validate_decoded_string(profile, &format!("{context}: `nextest_profile`"))?;
564        }
565        for (field, path) in [
566            ("test_wrapper", self.test_wrapper.as_deref()),
567            ("baseline", self.baseline.as_deref()),
568            ("work_dir", self.work_dir.as_deref()),
569        ] {
570            if let Some(p) = path {
571                validate_decoded_path(p, &format!("{context}: `{field}`"))?;
572            }
573        }
574        for (field, paths) in [
575            ("copy_fixture", self.copy_fixture.as_deref()),
576            ("copy_fixture_exclude", self.copy_fixture_exclude.as_deref()),
577        ] {
578            if let Some(items) = paths {
579                for p in items {
580                    validate_decoded_path(p, &format!("{context}: `{field}`"))?;
581                }
582            }
583        }
584        Ok(())
585    }
586
587    /// Validates a single configuration layer (value ranges, syntax, and intra-layer conflicts).
588    pub fn validate_layer(&self, context: &str) -> Result<()> {
589        self.validate_decoded_strings(context)?;
590        if let Some(patterns) = &self.exclude_file {
591            for pattern in patterns {
592                if pattern.trim().is_empty() {
593                    bail!("{context}: `exclude_file` pattern must not be empty");
594                }
595                if pattern.len() > 4096 {
596                    bail!("{context}: `exclude_file` pattern exceeds 4096 bytes");
597                }
598            }
599        }
600        if self.jobs == Some(0) {
601            bail!("{context}: `jobs` must be at least 1");
602        }
603        if self.baseline_jobs == Some(0) {
604            bail!("{context}: `baseline_jobs` must be at least 1");
605        }
606        if self.baseline_timeout == Some(0) {
607            bail!("{context}: `baseline_timeout` must be at least 1");
608        }
609        if self.timeout == Some(0) {
610            bail!("{context}: `timeout` must be at least 1");
611        }
612        if let Some(opt) = self.opt_level
613            && opt > 3
614        {
615            bail!("{context}: `opt_level` must be between 0 and 3 (got {opt})");
616        }
617        if let Some(fixtures) = &self.copy_output_fixture {
618            for spec in fixtures {
619                Fixture::from_str(spec).with_context(|| {
620                    format!("{context}: invalid `copy_output_fixture` entry `{spec}`")
621                })?;
622            }
623        }
624        if let Some(externals) = &self.stage_external {
625            for spec in externals {
626                StageExternal::from_str(spec).with_context(|| {
627                    format!("{context}: invalid `stage_external` entry `{spec}`")
628                })?;
629            }
630        }
631        if self.rebuild == Some(true) && self.source_only == Some(true) {
632            bail!("{context}: `rebuild` and `source_only` cannot both be true");
633        }
634        if self.source_only == Some(true) && self.audit.is_some() {
635            bail!("{context}: `source_only` cannot be combined with `audit`");
636        }
637        if self.source_only == Some(true) && self.verify == Some(false) {
638            bail!("{context}: `source_only` cannot be combined with `verify = false`");
639        }
640        if self.audit.is_some() && self.verify == Some(false) {
641            bail!("{context}: `audit` cannot be combined with `verify = false`");
642        }
643        if self.all_features == Some(true)
644            && (self.features.as_ref().is_some_and(|f| !f.is_empty())
645                || self.no_default_features == Some(true))
646        {
647            bail!(
648                "{context}: `all_features` cannot be combined with `features` or `no_default_features`"
649            );
650        }
651        if self.test_tool == Some(TestTool::Cargo) && self.nextest_profile.is_some() {
652            bail!("{context}: `nextest_profile` requires `test_tool = \"nextest\"`");
653        }
654        Ok(())
655    }
656
657    /// Overlays `upper` on top of `self`. Upper values replace lower values, and explicit
658    /// mode switches in `upper` clear mutually exclusive lower-layer settings.
659    pub fn overlay(&self, upper: &Settings) -> Settings {
660        let mut out = Settings {
661            exclude_file: upper
662                .exclude_file
663                .clone()
664                .or_else(|| self.exclude_file.clone()),
665            rebuild: upper.rebuild.or(self.rebuild),
666            source_only: upper.source_only.or(self.source_only),
667            error: upper.error.clone().or_else(|| self.error.clone()),
668            literal_operators: upper.literal_operators.or(self.literal_operators),
669            verify: upper.verify.or(self.verify),
670            effects: upper.effects.or(self.effects),
671            audit: upper.audit.or(self.audit),
672            also_test: upper.also_test.clone().or_else(|| self.also_test.clone()),
673            dependents: upper.dependents.or(self.dependents),
674            test_workspace: upper.test_workspace.or(self.test_workspace),
675            doc: upper.doc.or(self.doc),
676            test_tool: upper.test_tool.or(self.test_tool),
677            nextest_profile: upper
678                .nextest_profile
679                .clone()
680                .or_else(|| self.nextest_profile.clone()),
681            isolate_tests: upper.isolate_tests.or(self.isolate_tests),
682            lib: upper.lib.or(self.lib),
683            bins: upper.bins.or(self.bins),
684            test: upper.test.clone().or_else(|| self.test.clone()),
685            test_target: upper
686                .test_target
687                .clone()
688                .or_else(|| self.test_target.clone()),
689            test_filter: upper
690                .test_filter
691                .clone()
692                .or_else(|| self.test_filter.clone()),
693            include_test: upper
694                .include_test
695                .clone()
696                .or_else(|| self.include_test.clone()),
697            exclude_test: upper
698                .exclude_test
699                .clone()
700                .or_else(|| self.exclude_test.clone()),
701            include_ignored: upper.include_ignored.or(self.include_ignored),
702            test_wrapper: upper
703                .test_wrapper
704                .clone()
705                .or_else(|| self.test_wrapper.clone()),
706            wrapper_grace: upper.wrapper_grace.or(self.wrapper_grace),
707            format: upper.format.or(self.format),
708            show_unreached: upper.show_unreached.or(self.show_unreached),
709            quiet: upper.quiet.or(self.quiet),
710            baseline: upper.baseline.clone().or_else(|| self.baseline.clone()),
711            jobs: upper.jobs.or(self.jobs),
712            baseline_jobs: upper.baseline_jobs.or(self.baseline_jobs),
713            baseline_timeout: upper.baseline_timeout.or(self.baseline_timeout),
714            timeout: upper.timeout.or(self.timeout),
715            timeout_recheck: upper.timeout_recheck.or(self.timeout_recheck),
716            checkpoint: upper.checkpoint.or(self.checkpoint),
717            opt_level: upper.opt_level.or(self.opt_level),
718            features: upper.features.clone().or_else(|| self.features.clone()),
719            all_features: upper.all_features.or(self.all_features),
720            no_default_features: upper.no_default_features.or(self.no_default_features),
721            locked: upper.locked.or(self.locked),
722            work_dir: upper.work_dir.clone().or_else(|| self.work_dir.clone()),
723            all_files: upper.all_files.or(self.all_files),
724            git_index: upper.git_index.or(self.git_index),
725            copy_fixture: upper
726                .copy_fixture
727                .clone()
728                .or_else(|| self.copy_fixture.clone()),
729            copy_fixture_exclude: upper
730                .copy_fixture_exclude
731                .clone()
732                .or_else(|| self.copy_fixture_exclude.clone()),
733            copy_output_fixture: upper
734                .copy_output_fixture
735                .clone()
736                .or_else(|| self.copy_output_fixture.clone()),
737            stage_external: upper
738                .stage_external
739                .clone()
740                .or_else(|| self.stage_external.clone()),
741        };
742
743        // Resolve cross-layer mutually exclusive overrides so upper layer wins cleanly.
744        if upper.source_only == Some(true) {
745            if upper.rebuild.is_none() {
746                out.rebuild = Some(false);
747            }
748            if upper.audit.is_none() {
749                out.audit = None;
750            }
751            if upper.verify.is_none() {
752                out.verify = Some(true);
753            }
754        }
755        if upper.rebuild == Some(true) && upper.source_only.is_none() {
756            out.source_only = Some(false);
757        }
758        if upper.audit.is_some() {
759            if upper.verify.is_none() {
760                out.verify = Some(true);
761            }
762            if upper.source_only.is_none() {
763                out.source_only = Some(false);
764            }
765        }
766        if upper.verify == Some(false) {
767            if upper.audit.is_none() {
768                out.audit = None;
769            }
770            if upper.source_only.is_none() {
771                out.source_only = Some(false);
772            }
773        }
774        if out.source_only == Some(false) && upper.literal_operators.is_none() {
775            out.literal_operators = Some(false);
776        }
777        if upper.all_features == Some(true) {
778            if upper.features.is_none() {
779                out.features = None;
780            }
781            if upper.no_default_features.is_none() {
782                out.no_default_features = Some(false);
783            }
784        }
785        if (upper.features.as_ref().is_some_and(|f| !f.is_empty())
786            || upper.no_default_features == Some(true))
787            && upper.all_features.is_none()
788        {
789            out.all_features = Some(false);
790        }
791        if upper.test_tool == Some(TestTool::Cargo) && upper.nextest_profile.is_none() {
792            out.nextest_profile = None;
793        }
794        if upper.copy_fixture.as_ref().is_some_and(Vec::is_empty)
795            && upper.copy_fixture_exclude.is_none()
796        {
797            out.copy_fixture_exclude = None;
798        }
799
800        out
801    }
802
803    /// Validates the final merged settings after all layers have been combined.
804    pub fn validate_effective(&self, context: &str) -> Result<()> {
805        self.validate_layer(context)?;
806
807        let source_only = self.source_only.unwrap_or(false);
808        let literal_operators = self.literal_operators.unwrap_or(false);
809        let test_tool = self.test_tool.unwrap_or_default();
810
811        if literal_operators && !source_only {
812            bail!("{context}: `literal_operators` requires `source_only = true`");
813        }
814        if self.nextest_profile.is_some() && test_tool != TestTool::Nextest {
815            bail!("{context}: `nextest_profile` requires `test_tool = \"nextest\"`");
816        }
817        if self.wrapper_grace.is_some() && self.test_wrapper.is_none() {
818            bail!("{context}: `wrapper_grace` requires `test_wrapper`");
819        }
820        if self
821            .copy_fixture_exclude
822            .as_ref()
823            .is_some_and(|e| !e.is_empty())
824            && self.copy_fixture.as_ref().is_none_or(Vec::is_empty)
825        {
826            bail!("{context}: `copy_fixture_exclude` requires `copy_fixture`");
827        }
828        Ok(())
829    }
830
831    /// Parses `copy_output_fixture` strings into validated `Fixture` values.
832    pub fn parsed_output_fixtures(&self) -> Result<Vec<Fixture>> {
833        self.copy_output_fixture
834            .as_deref()
835            .unwrap_or(&[])
836            .iter()
837            .map(|s| Fixture::from_str(s))
838            .collect()
839    }
840
841    /// Parses `stage_external` strings into validated `StageExternal` values.
842    pub fn parsed_stage_external(&self) -> Result<Vec<StageExternal>> {
843        self.stage_external
844            .as_deref()
845            .unwrap_or(&[])
846            .iter()
847            .map(|s| StageExternal::from_str(s))
848            .collect()
849    }
850}
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855    use std::sync::atomic::{AtomicU64, Ordering};
856
857    fn temp_dir(label: &str) -> PathBuf {
858        static COUNTER: AtomicU64 = AtomicU64::new(0);
859        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
860        let dir = std::env::temp_dir().join(format!(
861            "tmt-config-test-{}-{}-{label}",
862            std::process::id(),
863            id
864        ));
865        let _ = fs::remove_dir_all(&dir);
866        fs::create_dir_all(&dir).unwrap();
867        dir
868    }
869
870    fn write(path: &Path, content: &str) {
871        if let Some(parent) = path.parent() {
872            fs::create_dir_all(parent).unwrap();
873        }
874        fs::write(path, content).unwrap();
875    }
876
877    #[test]
878    fn config_file_pict_table() {
879        let table = include_str!("../tests/data/config-file.pict.tsv");
880        let mut lines = table.lines();
881        let _header = lines.next().expect("header");
882
883        for (idx, line) in lines.filter(|l| !l.trim().is_empty()).enumerate() {
884            let cols: Vec<&str> = line.split('\t').collect();
885            assert_eq!(cols.len(), 5, "row {idx}: {line}");
886            let (source, pkg_override, cli_override, path_base, validity) =
887                (cols[0], cols[1], cols[2], cols[3], cols[4]);
888
889            let root = temp_dir(&format!("pict-{idx}"));
890            let pkg_dir = if source == "auto_workspace_parent" {
891                write(
892                    &root.join("Cargo.toml"),
893                    "[workspace]\nmembers = [\"crates/alpha\"]\n",
894                );
895                let member = root.join("crates/alpha");
896                write(
897                    &member.join("Cargo.toml"),
898                    "[package]\nname = \"alpha\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
899                );
900                member
901            } else {
902                write(
903                    &root.join("Cargo.toml"),
904                    "[package]\nname = \"alpha\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
905                );
906                root.clone()
907            };
908
909            let abs_baseline = root.join("abs-baseline.json");
910            let mut body = String::new();
911            match validity {
912                "valid" => {
913                    body.push_str("jobs = 4\n");
914                    body.push_str("rebuild = true\n");
915                    body.push_str("exclude_test = [\"top_skip\"]\n");
916                    match path_base {
917                        "relative" => body.push_str("baseline = \"base/rel.json\"\n"),
918                        "absolute" => {
919                            let escaped = abs_baseline.display().to_string().replace('\\', "\\\\");
920                            body.push_str(&format!("baseline = \"{escaped}\"\n"));
921                        }
922                        "absent" => {}
923                        other => panic!("unexpected PathBase: {other}"),
924                    }
925                    match pkg_override {
926                        "matching" => {
927                            body.push_str(
928                                "\n[package.alpha]\njobs = 2\nexclude_test = [\"pkg_skip\"]\n",
929                            );
930                        }
931                        "other_only" => {
932                            body.push_str(
933                                "\n[package.beta]\njobs = 8\nexclude_test = [\"beta_skip\"]\n",
934                            );
935                        }
936                        "none" => {}
937                        other => panic!("unexpected PackageOverride: {other}"),
938                    }
939                }
940                "unknown_key" => body.push_str("no_such_option = true\n"),
941                "invalid_value" => body.push_str("jobs = 0\n"),
942                "duplicate_candidates" => {
943                    body.push_str("jobs = 2\n");
944                }
945                "missing_explicit" => {}
946                other => panic!("unexpected Validity: {other}"),
947            }
948
949            let explicit_path = root.join("custom/explicit.toml");
950            let mut explicit_arg: Option<PathBuf> = None;
951            let mut no_config = false;
952
953            match source {
954                "none" => {}
955                "disabled" => {
956                    write(&root.join("tmt.toml"), "jobs = 9\n");
957                    no_config = true;
958                }
959                "auto_root" | "auto_workspace_parent" => {
960                    write(&root.join("tmt.toml"), &body);
961                    if validity == "duplicate_candidates" {
962                        write(&root.join(".config/tmt.toml"), "jobs = 3\n");
963                    }
964                }
965                "auto_dot_config" => {
966                    write(&root.join(".config/tmt.toml"), &body);
967                    if validity == "duplicate_candidates" {
968                        write(&root.join(".cargo/tmt.toml"), "jobs = 3\n");
969                    }
970                }
971                "auto_dot_cargo" => {
972                    write(&root.join(".cargo/tmt.toml"), &body);
973                    if validity == "duplicate_candidates" {
974                        write(&root.join("tmt.toml"), "jobs = 3\n");
975                    }
976                }
977                "explicit" => {
978                    if validity != "missing_explicit" {
979                        write(&explicit_path, &body);
980                    }
981                    explicit_arg = Some(explicit_path.clone());
982                }
983                other => panic!("unexpected ConfigSource: {other}"),
984            }
985
986            let loaded = load_for_dir(&pkg_dir, explicit_arg.as_deref(), no_config);
987            if validity != "valid" {
988                assert!(
989                    loaded.is_err(),
990                    "expected error for row {idx} ({line}), got {loaded:?}"
991                );
992                let _ = fs::remove_dir_all(&root);
993                continue;
994            }
995            let loaded = loaded.unwrap_or_else(|e| panic!("row {idx} ({line}) failed: {e:#}"));
996            if matches!(source, "none" | "disabled") {
997                assert!(loaded.is_none(), "row {idx}: expected no config");
998                let _ = fs::remove_dir_all(&root);
999                continue;
1000            }
1001            let loaded = loaded.unwrap_or_else(|| panic!("row {idx}: expected config to load"));
1002
1003            let mut cli = Settings::default();
1004            match cli_override {
1005                "none" => {}
1006                "scalar" => cli.jobs = Some(1),
1007                "array" => cli.exclude_test = Some(vec!["cli_skip".into()]),
1008                "conflicting_mode" => cli.source_only = Some(true),
1009                other => panic!("unexpected CliOverride: {other}"),
1010            }
1011
1012            let effective = loaded
1013                .resolve(Some("alpha"), &cli)
1014                .unwrap_or_else(|e| panic!("row {idx} ({line}) resolve failed: {e:#}"));
1015
1016            let expected_jobs = match (cli_override, pkg_override) {
1017                ("scalar", _) => Some(1),
1018                (_, "matching") => Some(2),
1019                _ => Some(4),
1020            };
1021            assert_eq!(effective.jobs, expected_jobs, "row {idx}: {line}");
1022
1023            let expected_exclude = match (cli_override, pkg_override) {
1024                ("array", _) => Some(vec!["cli_skip".into()]),
1025                (_, "matching") => Some(vec!["pkg_skip".into()]),
1026                _ => Some(vec!["top_skip".into()]),
1027            };
1028            assert_eq!(
1029                effective.exclude_test, expected_exclude,
1030                "row {idx}: {line}"
1031            );
1032
1033            if cli_override == "conflicting_mode" {
1034                assert_eq!(effective.source_only, Some(true), "row {idx}");
1035                assert_eq!(effective.rebuild, Some(false), "row {idx}");
1036            } else {
1037                assert_eq!(effective.rebuild, Some(true), "row {idx}");
1038            }
1039
1040            let expected_base = if source == "explicit" {
1041                root.join("custom")
1042            } else {
1043                fs::canonicalize(&root).unwrap()
1044            };
1045            match path_base {
1046                "absent" => assert_eq!(effective.baseline, None, "row {idx}"),
1047                "relative" => assert_eq!(
1048                    effective.baseline,
1049                    Some(expected_base.join("base/rel.json")),
1050                    "row {idx}: {line}"
1051                ),
1052                "absolute" => assert_eq!(effective.baseline, Some(abs_baseline), "row {idx}"),
1053                _ => unreachable!(),
1054            }
1055
1056            let _ = fs::remove_dir_all(&root);
1057        }
1058    }
1059
1060    #[test]
1061    fn discovery_stops_at_workspace_and_git_boundaries() {
1062        let outer = temp_dir("boundary");
1063        write(&outer.join("tmt.toml"), "jobs = 9\n");
1064
1065        // Case 1: inner crate declares its own `[workspace]`, so outer tmt.toml must not leak.
1066        let isolated_ws = outer.join("isolated-ws");
1067        write(
1068            &isolated_ws.join("Cargo.toml"),
1069            "[workspace]\n[package]\nname = \"iso\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1070        );
1071        assert!(discover(&isolated_ws).unwrap().is_none());
1072
1073        // Case 2: inner repo has `.git`, so outer tmt.toml must not leak.
1074        let inner_git = outer.join("inner-git");
1075        fs::create_dir_all(inner_git.join(".git")).unwrap();
1076        write(
1077            &inner_git.join("Cargo.toml"),
1078            "[package]\nname = \"gitpkg\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1079        );
1080        assert!(discover(&inner_git).unwrap().is_none());
1081
1082        // Case 3: nested member inside a workspace without its own tmt.toml stops at workspace root
1083        // and picks up the workspace root's `.config/tmt.toml`, resolving package-level paths.
1084        let ws = outer.join("ws");
1085        write(&ws.join("Cargo.toml"), "[workspace]\nmembers = [\"a\"]\n");
1086        write(
1087            &ws.join(".config/tmt.toml"),
1088            "opt_level = 3\n\n[package.a]\nwork_dir = \"custom-work\"\nbaseline = \"a-base.json\"\n",
1089        );
1090        let member = ws.join("a");
1091        write(
1092            &member.join("Cargo.toml"),
1093            "[package]\nname = \"a\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1094        );
1095        let loaded = discover(&member).unwrap().expect("workspace config");
1096        let ws_canon = fs::canonicalize(&ws).unwrap();
1097        assert_eq!(loaded.file.defaults.opt_level, Some(3));
1098        assert_eq!(loaded.base_dir, ws_canon);
1099        let eff = loaded.resolve(Some("a"), &Settings::default()).unwrap();
1100        assert_eq!(eff.work_dir, Some(ws_canon.join("custom-work")));
1101        assert_eq!(eff.baseline, Some(ws_canon.join("a-base.json")));
1102
1103        let _ = fs::remove_dir_all(&outer);
1104    }
1105
1106    #[test]
1107    fn size_limit_non_file_and_symlink_boundary_are_enforced() {
1108        let dir = temp_dir("io-limits");
1109
1110        // Exact 1 MiB file succeeds; 1 MiB + 1 byte fails.
1111        let exact = dir.join("exact.toml");
1112        let pad_exact = "#".repeat(MAX_CONFIG_BYTES as usize);
1113        write(&exact, &pad_exact);
1114        assert!(load_explicit(&exact).is_ok());
1115
1116        let over = dir.join("over.toml");
1117        let pad_over = "#".repeat(MAX_CONFIG_BYTES as usize + 1);
1118        write(&over, &pad_over);
1119        assert!(load_explicit(&over).is_err());
1120
1121        // Passing a directory as `--config` fails.
1122        let subdir = dir.join("subdir");
1123        fs::create_dir_all(&subdir).unwrap();
1124        assert!(load_explicit(&subdir).is_err());
1125
1126        // Auto-discovery rejects a symlink resolving outside the discovered directory
1127        // (both direct file symlink and `.config` directory symlink), and FIFOs never block.
1128        #[cfg(unix)]
1129        {
1130            use std::os::unix::fs::symlink;
1131            let outside = temp_dir("outside-symlink");
1132            let secret_cfg = outside.join("outside.toml");
1133            write(&secret_cfg, "jobs = 2\n");
1134            let proj = dir.join("proj");
1135            fs::create_dir_all(&proj).unwrap();
1136            symlink(&secret_cfg, proj.join("tmt.toml")).unwrap();
1137            assert!(discover(&proj).is_err());
1138            // Explicit `--config` is allowed when the user names it directly.
1139            assert!(load_explicit(&proj.join("tmt.toml")).is_ok());
1140
1141            // `.config` itself symlinked outside the project must also be rejected.
1142            let proj2 = dir.join("proj2");
1143            fs::create_dir_all(&proj2).unwrap();
1144            let outside_cfg_dir = outside.join("cfgdir");
1145            write(&outside_cfg_dir.join("tmt.toml"), "jobs = 2\n");
1146            symlink(&outside_cfg_dir, proj2.join(".config")).unwrap();
1147            assert!(discover(&proj2).is_err());
1148
1149            // FIFO config fails immediately without blocking (both auto-discovered and explicit).
1150            let fifo_proj = dir.join("fifo-proj");
1151            fs::create_dir_all(&fifo_proj).unwrap();
1152            let fifo_path = fifo_proj.join("tmt.toml");
1153            let status = std::process::Command::new("mkfifo")
1154                .arg(&fifo_path)
1155                .status()
1156                .expect("mkfifo");
1157            assert!(status.success());
1158            assert!(discover(&fifo_proj).is_err());
1159            assert!(load_explicit(&fifo_path).is_err());
1160
1161            let _ = fs::remove_dir_all(&outside);
1162        }
1163
1164        let _ = fs::remove_dir_all(&dir);
1165    }
1166
1167    #[test]
1168    fn parse_rejects_dangerous_chars_escaped_controls_and_invalid_values() {
1169        assert!(parse_config("jobs = 1\0\n", "test").is_err());
1170        assert!(parse_config("jobs = 1\x07\n", "test").is_err());
1171        assert!(parse_config("# \u{202E}bidi\njobs = 1\n", "test").is_err());
1172        assert!(parse_config("# \u{061C}alm\njobs = 1\n", "test").is_err());
1173
1174        // Exact limit succeeds; 1 byte over fails.
1175        assert!(parse_config(&"#".repeat(MAX_CONFIG_BYTES as usize), "test").is_ok());
1176        assert!(parse_config(&"#".repeat(MAX_CONFIG_BYTES as usize + 1), "test").is_err());
1177
1178        // Valid boundary values succeed.
1179        let ok = parse_config(
1180            "opt_level = 3\njobs = 1\nbaseline_jobs = 1\nbaseline_timeout = 1\ntimeout = 1\n",
1181            "test",
1182        )
1183        .unwrap();
1184        assert_eq!(ok.defaults.opt_level, Some(3));
1185        assert_eq!(ok.defaults.baseline_timeout, Some(1));
1186
1187        for bad in [
1188            "jobs = 0\n",
1189            "baseline_jobs = 0\n",
1190            "baseline_timeout = 0\n",
1191            "timeout = 0\n",
1192            "opt_level = 4\n",
1193            "unknown_field = 1\n",
1194            "rebuild = true\nsource_only = true\n",
1195            "source_only = true\naudit = 2\n",
1196            "source_only = true\nverify = false\n",
1197            "audit = 2\nverify = false\n",
1198            "all_features = true\nfeatures = [\"a\"]\n",
1199            "all_features = true\nno_default_features = true\n",
1200            "test_tool = \"cargo\"\nnextest_profile = \"ci\"\n",
1201            "copy_output_fixture = [\"missing_equals\"]\n",
1202            "stage_external = [\"not_parent_relative\"]\n",
1203            "package = \"not_a_table\"\n",
1204            "[package]\nfoo = 123\n",
1205            "[package.foo]\nunknown = true\n",
1206            "[package.foo]\njobs = 0\n",
1207            "[package.foo]\nformat = \"json\"\n",
1208            "[package.foo]\nshow_unreached = true\n",
1209            // TOML-escaped control / NUL / BiDi characters in values and package keys.
1210            "exclude_test = [\"bad\\u0000name\"]\n",
1211            "nextest_profile = \"ci\\u001b[31m\"\n",
1212            "baseline = \"foo\\u202Ebar.json\"\n",
1213            "baseline = \"foo\\u061cbar.json\"\n",
1214            "[package.\"bad\\u0000pkg\"]\njobs = 1\n",
1215        ] {
1216            assert!(
1217                parse_config(bad, "test").is_err(),
1218                "expected parse_config error for:\n{bad}"
1219            );
1220        }
1221    }
1222
1223    #[test]
1224    fn overlay_and_effective_validation_cover_all_mode_switches_and_requirements() {
1225        let base = parse_config(
1226            r#"
1227            all_features = true
1228            test_tool = "nextest"
1229            nextest_profile = "ci"
1230            source_only = true
1231            literal_operators = true
1232            exclude_test = ["slow_a", "slow_b"]
1233            copy_fixture = ["data"]
1234            copy_fixture_exclude = ["data/tmp"]
1235            test_wrapper = "scripts/wrap.sh"
1236            wrapper_grace = 5
1237            "#,
1238            "tmt.toml",
1239        )
1240        .unwrap()
1241        .defaults;
1242        // Base itself is valid as effective settings.
1243        base.validate_effective("base").unwrap();
1244
1245        // Explicit `source_only = false` clears inherited `literal_operators`.
1246        let disable_source = Settings {
1247            source_only: Some(false),
1248            ..Settings::default()
1249        };
1250        let disabled = base.overlay(&disable_source);
1251        assert_eq!(disabled.source_only, Some(false));
1252        assert_eq!(disabled.literal_operators, Some(false));
1253        disabled.validate_effective("disabled").unwrap();
1254
1255        // Switching to `audit` clears `source_only` and inherited `literal_operators`.
1256        let audit_cli = Settings {
1257            audit: Some(3),
1258            ..Settings::default()
1259        };
1260        let audited = base.overlay(&audit_cli);
1261        assert_eq!(audited.source_only, Some(false));
1262        assert_eq!(audited.literal_operators, Some(false));
1263        audited.validate_effective("audited").unwrap();
1264
1265        // CLI switches features, test_tool, rebuild, and clears arrays.
1266        let cli = Settings {
1267            features: Some(vec!["minimal".into()]),
1268            test_tool: Some(TestTool::Cargo),
1269            rebuild: Some(true),
1270            exclude_test: Some(vec![]),
1271            copy_fixture: Some(vec![]),
1272            ..Settings::default()
1273        };
1274        let merged = base.overlay(&cli);
1275        merged.validate_effective("merged").unwrap();
1276        assert_eq!(merged.all_features, Some(false));
1277        assert_eq!(merged.features, Some(vec!["minimal".into()]));
1278        assert_eq!(merged.test_tool, Some(TestTool::Cargo));
1279        assert_eq!(merged.nextest_profile, None);
1280        assert_eq!(merged.rebuild, Some(true));
1281        assert_eq!(merged.source_only, Some(false));
1282        assert_eq!(merged.literal_operators, Some(false));
1283        assert_eq!(merged.exclude_test, Some(vec![]));
1284        assert_eq!(merged.copy_fixture, Some(vec![]));
1285        assert_eq!(merged.copy_fixture_exclude, None);
1286
1287        // Effective validation catches missing prerequisites.
1288        assert!(
1289            Settings {
1290                literal_operators: Some(true),
1291                ..Settings::default()
1292            }
1293            .validate_effective("lit")
1294            .is_err()
1295        );
1296        assert!(
1297            Settings {
1298                nextest_profile: Some("ci".into()),
1299                ..Settings::default()
1300            }
1301            .validate_effective("nextest")
1302            .is_err()
1303        );
1304        assert!(
1305            Settings {
1306                wrapper_grace: Some(5),
1307                ..Settings::default()
1308            }
1309            .validate_effective("grace")
1310            .is_err()
1311        );
1312        assert!(
1313            Settings {
1314                copy_fixture_exclude: Some(vec![PathBuf::from("a")]),
1315                ..Settings::default()
1316            }
1317            .validate_effective("exclude")
1318            .is_err()
1319        );
1320
1321        // LoadedConfig::resolve rejects merged settings that fail effective validation.
1322        let loaded = LoadedConfig {
1323            path: PathBuf::from("tmt.toml"),
1324            base_dir: PathBuf::from("."),
1325            file: parse_config("jobs = 2\n", "tmt.toml").unwrap(),
1326        };
1327        assert!(
1328            loaded
1329                .resolve(
1330                    None,
1331                    &Settings {
1332                        wrapper_grace: Some(3),
1333                        ..Settings::default()
1334                    }
1335                )
1336                .is_err()
1337        );
1338    }
1339
1340    #[test]
1341    fn detect_package_name_reads_manifest_and_single_member_virtual_workspace() {
1342        let dir = temp_dir("pkg-name");
1343        write(
1344            &dir.join("Cargo.toml"),
1345            "[package]\nname = \"my-crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1346        );
1347        assert_eq!(detect_package_name(&dir).as_deref(), Some("my-crate"));
1348
1349        let virt_empty = temp_dir("virt-ws-empty");
1350        write(
1351            &virt_empty.join("Cargo.toml"),
1352            "[workspace]\nmembers = []\n",
1353        );
1354        assert_eq!(detect_package_name(&virt_empty), None);
1355
1356        let virt_single = temp_dir("virt-ws-single");
1357        write(
1358            &virt_single.join("Cargo.toml"),
1359            "[workspace]\nmembers = [\"crates/only\"]\n",
1360        );
1361        write(
1362            &virt_single.join("crates/only/Cargo.toml"),
1363            "[package]\nname = \"only-crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1364        );
1365        assert_eq!(
1366            detect_package_name(&virt_single).as_deref(),
1367            Some("only-crate")
1368        );
1369
1370        let _ = fs::remove_dir_all(&dir);
1371        let _ = fs::remove_dir_all(&virt_empty);
1372        let _ = fs::remove_dir_all(&virt_single);
1373    }
1374
1375    #[test]
1376    fn exclude_file_config_parses_overlays_and_rejects_invalid_values() {
1377        let cfg = parse_config(
1378            r#"
1379exclude_file = ["src/generated.rs", "src/fixtures/**"]
1380
1381[package.demo]
1382exclude_file = ["src/sample.rs"]
1383
1384[package.cleared]
1385exclude_file = []
1386"#,
1387            "tmt.toml",
1388        )
1389        .unwrap();
1390        let loaded = LoadedConfig {
1391            path: PathBuf::from("tmt.toml"),
1392            base_dir: PathBuf::from("."),
1393            file: cfg,
1394        };
1395        let top = loaded.resolve(None, &Settings::default()).unwrap();
1396        assert_eq!(
1397            top.exclude_file,
1398            Some(vec!["src/generated.rs".into(), "src/fixtures/**".into()])
1399        );
1400        let demo = loaded.resolve(Some("demo"), &Settings::default()).unwrap();
1401        assert_eq!(demo.exclude_file, Some(vec!["src/sample.rs".into()]));
1402        let cleared = loaded
1403            .resolve(Some("cleared"), &Settings::default())
1404            .unwrap();
1405        assert_eq!(cleared.exclude_file, Some(vec![]));
1406        let cli_override = loaded
1407            .resolve(
1408                Some("demo"),
1409                &Settings {
1410                    exclude_file: Some(vec!["src/cli.rs".into()]),
1411                    ..Settings::default()
1412                },
1413            )
1414            .unwrap();
1415        assert_eq!(cli_override.exclude_file, Some(vec!["src/cli.rs".into()]));
1416
1417        // Empty or control-character patterns are rejected.
1418        assert!(parse_config("exclude_file = [\"\"]\n", "tmt.toml").is_err());
1419        assert!(parse_config("exclude_file = [\"   \"]\n", "tmt.toml").is_err());
1420        assert!(parse_config("exclude_file = [\"src/\\u0000.rs\"]\n", "tmt.toml").is_err());
1421    }
1422}