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 out.source_only == Some(false) && upper.literal_operators.is_none() {
767            out.literal_operators = Some(false);
768        }
769        if upper.verify == Some(false) && upper.audit.is_none() {
770            out.audit = None;
771        }
772        if upper.all_features == Some(true) {
773            if upper.features.is_none() {
774                out.features = None;
775            }
776            if upper.no_default_features.is_none() {
777                out.no_default_features = Some(false);
778            }
779        }
780        if (upper.features.as_ref().is_some_and(|f| !f.is_empty())
781            || upper.no_default_features == Some(true))
782            && upper.all_features.is_none()
783        {
784            out.all_features = Some(false);
785        }
786        if upper.test_tool == Some(TestTool::Cargo) && upper.nextest_profile.is_none() {
787            out.nextest_profile = None;
788        }
789        if upper.copy_fixture.as_ref().is_some_and(Vec::is_empty)
790            && upper.copy_fixture_exclude.is_none()
791        {
792            out.copy_fixture_exclude = None;
793        }
794
795        out
796    }
797
798    /// Validates the final merged settings after all layers have been combined.
799    pub fn validate_effective(&self, context: &str) -> Result<()> {
800        self.validate_layer(context)?;
801
802        let source_only = self.source_only.unwrap_or(false);
803        let literal_operators = self.literal_operators.unwrap_or(false);
804        let test_tool = self.test_tool.unwrap_or_default();
805
806        if literal_operators && !source_only {
807            bail!("{context}: `literal_operators` requires `source_only = true`");
808        }
809        if self.nextest_profile.is_some() && test_tool != TestTool::Nextest {
810            bail!("{context}: `nextest_profile` requires `test_tool = \"nextest\"`");
811        }
812        if self.wrapper_grace.is_some() && self.test_wrapper.is_none() {
813            bail!("{context}: `wrapper_grace` requires `test_wrapper`");
814        }
815        if self
816            .copy_fixture_exclude
817            .as_ref()
818            .is_some_and(|e| !e.is_empty())
819            && self.copy_fixture.as_ref().is_none_or(Vec::is_empty)
820        {
821            bail!("{context}: `copy_fixture_exclude` requires `copy_fixture`");
822        }
823        Ok(())
824    }
825
826    /// Parses `copy_output_fixture` strings into validated `Fixture` values.
827    pub fn parsed_output_fixtures(&self) -> Result<Vec<Fixture>> {
828        self.copy_output_fixture
829            .as_deref()
830            .unwrap_or(&[])
831            .iter()
832            .map(|s| Fixture::from_str(s))
833            .collect()
834    }
835
836    /// Parses `stage_external` strings into validated `StageExternal` values.
837    pub fn parsed_stage_external(&self) -> Result<Vec<StageExternal>> {
838        self.stage_external
839            .as_deref()
840            .unwrap_or(&[])
841            .iter()
842            .map(|s| StageExternal::from_str(s))
843            .collect()
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    use super::*;
850    use std::sync::atomic::{AtomicU64, Ordering};
851
852    fn temp_dir(label: &str) -> PathBuf {
853        static COUNTER: AtomicU64 = AtomicU64::new(0);
854        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
855        let dir = std::env::temp_dir().join(format!(
856            "tmt-config-test-{}-{}-{label}",
857            std::process::id(),
858            id
859        ));
860        let _ = fs::remove_dir_all(&dir);
861        fs::create_dir_all(&dir).unwrap();
862        dir
863    }
864
865    fn write(path: &Path, content: &str) {
866        if let Some(parent) = path.parent() {
867            fs::create_dir_all(parent).unwrap();
868        }
869        fs::write(path, content).unwrap();
870    }
871
872    #[test]
873    fn config_file_pict_table() {
874        let table = include_str!("../tests/data/config-file.pict.tsv");
875        let mut lines = table.lines();
876        let _header = lines.next().expect("header");
877
878        for (idx, line) in lines.filter(|l| !l.trim().is_empty()).enumerate() {
879            let cols: Vec<&str> = line.split('\t').collect();
880            assert_eq!(cols.len(), 5, "row {idx}: {line}");
881            let (source, pkg_override, cli_override, path_base, validity) =
882                (cols[0], cols[1], cols[2], cols[3], cols[4]);
883
884            let root = temp_dir(&format!("pict-{idx}"));
885            let pkg_dir = if source == "auto_workspace_parent" {
886                write(
887                    &root.join("Cargo.toml"),
888                    "[workspace]\nmembers = [\"crates/alpha\"]\n",
889                );
890                let member = root.join("crates/alpha");
891                write(
892                    &member.join("Cargo.toml"),
893                    "[package]\nname = \"alpha\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
894                );
895                member
896            } else {
897                write(
898                    &root.join("Cargo.toml"),
899                    "[package]\nname = \"alpha\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
900                );
901                root.clone()
902            };
903
904            let abs_baseline = root.join("abs-baseline.json");
905            let mut body = String::new();
906            match validity {
907                "valid" => {
908                    body.push_str("jobs = 4\n");
909                    body.push_str("rebuild = true\n");
910                    body.push_str("exclude_test = [\"top_skip\"]\n");
911                    match path_base {
912                        "relative" => body.push_str("baseline = \"base/rel.json\"\n"),
913                        "absolute" => {
914                            let escaped = abs_baseline.display().to_string().replace('\\', "\\\\");
915                            body.push_str(&format!("baseline = \"{escaped}\"\n"));
916                        }
917                        "absent" => {}
918                        other => panic!("unexpected PathBase: {other}"),
919                    }
920                    match pkg_override {
921                        "matching" => {
922                            body.push_str(
923                                "\n[package.alpha]\njobs = 2\nexclude_test = [\"pkg_skip\"]\n",
924                            );
925                        }
926                        "other_only" => {
927                            body.push_str(
928                                "\n[package.beta]\njobs = 8\nexclude_test = [\"beta_skip\"]\n",
929                            );
930                        }
931                        "none" => {}
932                        other => panic!("unexpected PackageOverride: {other}"),
933                    }
934                }
935                "unknown_key" => body.push_str("no_such_option = true\n"),
936                "invalid_value" => body.push_str("jobs = 0\n"),
937                "duplicate_candidates" => {
938                    body.push_str("jobs = 2\n");
939                }
940                "missing_explicit" => {}
941                other => panic!("unexpected Validity: {other}"),
942            }
943
944            let explicit_path = root.join("custom/explicit.toml");
945            let mut explicit_arg: Option<PathBuf> = None;
946            let mut no_config = false;
947
948            match source {
949                "none" => {}
950                "disabled" => {
951                    write(&root.join("tmt.toml"), "jobs = 9\n");
952                    no_config = true;
953                }
954                "auto_root" | "auto_workspace_parent" => {
955                    write(&root.join("tmt.toml"), &body);
956                    if validity == "duplicate_candidates" {
957                        write(&root.join(".config/tmt.toml"), "jobs = 3\n");
958                    }
959                }
960                "auto_dot_config" => {
961                    write(&root.join(".config/tmt.toml"), &body);
962                    if validity == "duplicate_candidates" {
963                        write(&root.join(".cargo/tmt.toml"), "jobs = 3\n");
964                    }
965                }
966                "auto_dot_cargo" => {
967                    write(&root.join(".cargo/tmt.toml"), &body);
968                    if validity == "duplicate_candidates" {
969                        write(&root.join("tmt.toml"), "jobs = 3\n");
970                    }
971                }
972                "explicit" => {
973                    if validity != "missing_explicit" {
974                        write(&explicit_path, &body);
975                    }
976                    explicit_arg = Some(explicit_path.clone());
977                }
978                other => panic!("unexpected ConfigSource: {other}"),
979            }
980
981            let loaded = load_for_dir(&pkg_dir, explicit_arg.as_deref(), no_config);
982            if validity != "valid" {
983                assert!(
984                    loaded.is_err(),
985                    "expected error for row {idx} ({line}), got {loaded:?}"
986                );
987                let _ = fs::remove_dir_all(&root);
988                continue;
989            }
990            let loaded = loaded.unwrap_or_else(|e| panic!("row {idx} ({line}) failed: {e:#}"));
991            if matches!(source, "none" | "disabled") {
992                assert!(loaded.is_none(), "row {idx}: expected no config");
993                let _ = fs::remove_dir_all(&root);
994                continue;
995            }
996            let loaded = loaded.unwrap_or_else(|| panic!("row {idx}: expected config to load"));
997
998            let mut cli = Settings::default();
999            match cli_override {
1000                "none" => {}
1001                "scalar" => cli.jobs = Some(1),
1002                "array" => cli.exclude_test = Some(vec!["cli_skip".into()]),
1003                "conflicting_mode" => cli.source_only = Some(true),
1004                other => panic!("unexpected CliOverride: {other}"),
1005            }
1006
1007            let effective = loaded
1008                .resolve(Some("alpha"), &cli)
1009                .unwrap_or_else(|e| panic!("row {idx} ({line}) resolve failed: {e:#}"));
1010
1011            let expected_jobs = match (cli_override, pkg_override) {
1012                ("scalar", _) => Some(1),
1013                (_, "matching") => Some(2),
1014                _ => Some(4),
1015            };
1016            assert_eq!(effective.jobs, expected_jobs, "row {idx}: {line}");
1017
1018            let expected_exclude = match (cli_override, pkg_override) {
1019                ("array", _) => Some(vec!["cli_skip".into()]),
1020                (_, "matching") => Some(vec!["pkg_skip".into()]),
1021                _ => Some(vec!["top_skip".into()]),
1022            };
1023            assert_eq!(
1024                effective.exclude_test, expected_exclude,
1025                "row {idx}: {line}"
1026            );
1027
1028            if cli_override == "conflicting_mode" {
1029                assert_eq!(effective.source_only, Some(true), "row {idx}");
1030                assert_eq!(effective.rebuild, Some(false), "row {idx}");
1031            } else {
1032                assert_eq!(effective.rebuild, Some(true), "row {idx}");
1033            }
1034
1035            let expected_base = if source == "explicit" {
1036                root.join("custom")
1037            } else {
1038                fs::canonicalize(&root).unwrap()
1039            };
1040            match path_base {
1041                "absent" => assert_eq!(effective.baseline, None, "row {idx}"),
1042                "relative" => assert_eq!(
1043                    effective.baseline,
1044                    Some(expected_base.join("base/rel.json")),
1045                    "row {idx}: {line}"
1046                ),
1047                "absolute" => assert_eq!(effective.baseline, Some(abs_baseline), "row {idx}"),
1048                _ => unreachable!(),
1049            }
1050
1051            let _ = fs::remove_dir_all(&root);
1052        }
1053    }
1054
1055    #[test]
1056    fn discovery_stops_at_workspace_and_git_boundaries() {
1057        let outer = temp_dir("boundary");
1058        write(&outer.join("tmt.toml"), "jobs = 9\n");
1059
1060        // Case 1: inner crate declares its own `[workspace]`, so outer tmt.toml must not leak.
1061        let isolated_ws = outer.join("isolated-ws");
1062        write(
1063            &isolated_ws.join("Cargo.toml"),
1064            "[workspace]\n[package]\nname = \"iso\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1065        );
1066        assert!(discover(&isolated_ws).unwrap().is_none());
1067
1068        // Case 2: inner repo has `.git`, so outer tmt.toml must not leak.
1069        let inner_git = outer.join("inner-git");
1070        fs::create_dir_all(inner_git.join(".git")).unwrap();
1071        write(
1072            &inner_git.join("Cargo.toml"),
1073            "[package]\nname = \"gitpkg\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1074        );
1075        assert!(discover(&inner_git).unwrap().is_none());
1076
1077        // Case 3: nested member inside a workspace without its own tmt.toml stops at workspace root
1078        // and picks up the workspace root's `.config/tmt.toml`, resolving package-level paths.
1079        let ws = outer.join("ws");
1080        write(&ws.join("Cargo.toml"), "[workspace]\nmembers = [\"a\"]\n");
1081        write(
1082            &ws.join(".config/tmt.toml"),
1083            "opt_level = 3\n\n[package.a]\nwork_dir = \"custom-work\"\nbaseline = \"a-base.json\"\n",
1084        );
1085        let member = ws.join("a");
1086        write(
1087            &member.join("Cargo.toml"),
1088            "[package]\nname = \"a\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1089        );
1090        let loaded = discover(&member).unwrap().expect("workspace config");
1091        let ws_canon = fs::canonicalize(&ws).unwrap();
1092        assert_eq!(loaded.file.defaults.opt_level, Some(3));
1093        assert_eq!(loaded.base_dir, ws_canon);
1094        let eff = loaded.resolve(Some("a"), &Settings::default()).unwrap();
1095        assert_eq!(eff.work_dir, Some(ws_canon.join("custom-work")));
1096        assert_eq!(eff.baseline, Some(ws_canon.join("a-base.json")));
1097
1098        let _ = fs::remove_dir_all(&outer);
1099    }
1100
1101    #[test]
1102    fn size_limit_non_file_and_symlink_boundary_are_enforced() {
1103        let dir = temp_dir("io-limits");
1104
1105        // Exact 1 MiB file succeeds; 1 MiB + 1 byte fails.
1106        let exact = dir.join("exact.toml");
1107        let pad_exact = "#".repeat(MAX_CONFIG_BYTES as usize);
1108        write(&exact, &pad_exact);
1109        assert!(load_explicit(&exact).is_ok());
1110
1111        let over = dir.join("over.toml");
1112        let pad_over = "#".repeat(MAX_CONFIG_BYTES as usize + 1);
1113        write(&over, &pad_over);
1114        assert!(load_explicit(&over).is_err());
1115
1116        // Passing a directory as `--config` fails.
1117        let subdir = dir.join("subdir");
1118        fs::create_dir_all(&subdir).unwrap();
1119        assert!(load_explicit(&subdir).is_err());
1120
1121        // Auto-discovery rejects a symlink resolving outside the discovered directory
1122        // (both direct file symlink and `.config` directory symlink), and FIFOs never block.
1123        #[cfg(unix)]
1124        {
1125            use std::os::unix::fs::symlink;
1126            let outside = temp_dir("outside-symlink");
1127            let secret_cfg = outside.join("outside.toml");
1128            write(&secret_cfg, "jobs = 2\n");
1129            let proj = dir.join("proj");
1130            fs::create_dir_all(&proj).unwrap();
1131            symlink(&secret_cfg, proj.join("tmt.toml")).unwrap();
1132            assert!(discover(&proj).is_err());
1133            // Explicit `--config` is allowed when the user names it directly.
1134            assert!(load_explicit(&proj.join("tmt.toml")).is_ok());
1135
1136            // `.config` itself symlinked outside the project must also be rejected.
1137            let proj2 = dir.join("proj2");
1138            fs::create_dir_all(&proj2).unwrap();
1139            let outside_cfg_dir = outside.join("cfgdir");
1140            write(&outside_cfg_dir.join("tmt.toml"), "jobs = 2\n");
1141            symlink(&outside_cfg_dir, proj2.join(".config")).unwrap();
1142            assert!(discover(&proj2).is_err());
1143
1144            // FIFO config fails immediately without blocking (both auto-discovered and explicit).
1145            let fifo_proj = dir.join("fifo-proj");
1146            fs::create_dir_all(&fifo_proj).unwrap();
1147            let fifo_path = fifo_proj.join("tmt.toml");
1148            let status = std::process::Command::new("mkfifo")
1149                .arg(&fifo_path)
1150                .status()
1151                .expect("mkfifo");
1152            assert!(status.success());
1153            assert!(discover(&fifo_proj).is_err());
1154            assert!(load_explicit(&fifo_path).is_err());
1155
1156            let _ = fs::remove_dir_all(&outside);
1157        }
1158
1159        let _ = fs::remove_dir_all(&dir);
1160    }
1161
1162    #[test]
1163    fn parse_rejects_dangerous_chars_escaped_controls_and_invalid_values() {
1164        assert!(parse_config("jobs = 1\0\n", "test").is_err());
1165        assert!(parse_config("jobs = 1\x07\n", "test").is_err());
1166        assert!(parse_config("# \u{202E}bidi\njobs = 1\n", "test").is_err());
1167        assert!(parse_config("# \u{061C}alm\njobs = 1\n", "test").is_err());
1168
1169        // Exact limit succeeds; 1 byte over fails.
1170        assert!(parse_config(&"#".repeat(MAX_CONFIG_BYTES as usize), "test").is_ok());
1171        assert!(parse_config(&"#".repeat(MAX_CONFIG_BYTES as usize + 1), "test").is_err());
1172
1173        // Valid boundary values succeed.
1174        let ok = parse_config(
1175            "opt_level = 3\njobs = 1\nbaseline_jobs = 1\nbaseline_timeout = 1\ntimeout = 1\n",
1176            "test",
1177        )
1178        .unwrap();
1179        assert_eq!(ok.defaults.opt_level, Some(3));
1180        assert_eq!(ok.defaults.baseline_timeout, Some(1));
1181
1182        for bad in [
1183            "jobs = 0\n",
1184            "baseline_jobs = 0\n",
1185            "baseline_timeout = 0\n",
1186            "timeout = 0\n",
1187            "opt_level = 4\n",
1188            "unknown_field = 1\n",
1189            "rebuild = true\nsource_only = true\n",
1190            "source_only = true\naudit = 2\n",
1191            "source_only = true\nverify = false\n",
1192            "audit = 2\nverify = false\n",
1193            "all_features = true\nfeatures = [\"a\"]\n",
1194            "all_features = true\nno_default_features = true\n",
1195            "test_tool = \"cargo\"\nnextest_profile = \"ci\"\n",
1196            "copy_output_fixture = [\"missing_equals\"]\n",
1197            "stage_external = [\"not_parent_relative\"]\n",
1198            "package = \"not_a_table\"\n",
1199            "[package]\nfoo = 123\n",
1200            "[package.foo]\nunknown = true\n",
1201            "[package.foo]\njobs = 0\n",
1202            "[package.foo]\nformat = \"json\"\n",
1203            "[package.foo]\nshow_unreached = true\n",
1204            // TOML-escaped control / NUL / BiDi characters in values and package keys.
1205            "exclude_test = [\"bad\\u0000name\"]\n",
1206            "nextest_profile = \"ci\\u001b[31m\"\n",
1207            "baseline = \"foo\\u202Ebar.json\"\n",
1208            "baseline = \"foo\\u061cbar.json\"\n",
1209            "[package.\"bad\\u0000pkg\"]\njobs = 1\n",
1210        ] {
1211            assert!(
1212                parse_config(bad, "test").is_err(),
1213                "expected parse_config error for:\n{bad}"
1214            );
1215        }
1216    }
1217
1218    #[test]
1219    fn overlay_and_effective_validation_cover_all_mode_switches_and_requirements() {
1220        let base = parse_config(
1221            r#"
1222            all_features = true
1223            test_tool = "nextest"
1224            nextest_profile = "ci"
1225            source_only = true
1226            literal_operators = true
1227            exclude_test = ["slow_a", "slow_b"]
1228            copy_fixture = ["data"]
1229            copy_fixture_exclude = ["data/tmp"]
1230            test_wrapper = "scripts/wrap.sh"
1231            wrapper_grace = 5
1232            "#,
1233            "tmt.toml",
1234        )
1235        .unwrap()
1236        .defaults;
1237        // Base itself is valid as effective settings.
1238        base.validate_effective("base").unwrap();
1239
1240        // Explicit `source_only = false` clears inherited `literal_operators`.
1241        let disable_source = Settings {
1242            source_only: Some(false),
1243            ..Settings::default()
1244        };
1245        let disabled = base.overlay(&disable_source);
1246        assert_eq!(disabled.source_only, Some(false));
1247        assert_eq!(disabled.literal_operators, Some(false));
1248        disabled.validate_effective("disabled").unwrap();
1249
1250        // Switching to `audit` clears `source_only` and inherited `literal_operators`.
1251        let audit_cli = Settings {
1252            audit: Some(3),
1253            ..Settings::default()
1254        };
1255        let audited = base.overlay(&audit_cli);
1256        assert_eq!(audited.source_only, Some(false));
1257        assert_eq!(audited.literal_operators, Some(false));
1258        audited.validate_effective("audited").unwrap();
1259
1260        // CLI switches features, test_tool, rebuild, and clears arrays.
1261        let cli = Settings {
1262            features: Some(vec!["minimal".into()]),
1263            test_tool: Some(TestTool::Cargo),
1264            rebuild: Some(true),
1265            exclude_test: Some(vec![]),
1266            copy_fixture: Some(vec![]),
1267            ..Settings::default()
1268        };
1269        let merged = base.overlay(&cli);
1270        merged.validate_effective("merged").unwrap();
1271        assert_eq!(merged.all_features, Some(false));
1272        assert_eq!(merged.features, Some(vec!["minimal".into()]));
1273        assert_eq!(merged.test_tool, Some(TestTool::Cargo));
1274        assert_eq!(merged.nextest_profile, None);
1275        assert_eq!(merged.rebuild, Some(true));
1276        assert_eq!(merged.source_only, Some(false));
1277        assert_eq!(merged.literal_operators, Some(false));
1278        assert_eq!(merged.exclude_test, Some(vec![]));
1279        assert_eq!(merged.copy_fixture, Some(vec![]));
1280        assert_eq!(merged.copy_fixture_exclude, None);
1281
1282        // Effective validation catches missing prerequisites.
1283        assert!(
1284            Settings {
1285                literal_operators: Some(true),
1286                ..Settings::default()
1287            }
1288            .validate_effective("lit")
1289            .is_err()
1290        );
1291        assert!(
1292            Settings {
1293                nextest_profile: Some("ci".into()),
1294                ..Settings::default()
1295            }
1296            .validate_effective("nextest")
1297            .is_err()
1298        );
1299        assert!(
1300            Settings {
1301                wrapper_grace: Some(5),
1302                ..Settings::default()
1303            }
1304            .validate_effective("grace")
1305            .is_err()
1306        );
1307        assert!(
1308            Settings {
1309                copy_fixture_exclude: Some(vec![PathBuf::from("a")]),
1310                ..Settings::default()
1311            }
1312            .validate_effective("exclude")
1313            .is_err()
1314        );
1315
1316        // LoadedConfig::resolve rejects merged settings that fail effective validation.
1317        let loaded = LoadedConfig {
1318            path: PathBuf::from("tmt.toml"),
1319            base_dir: PathBuf::from("."),
1320            file: parse_config("jobs = 2\n", "tmt.toml").unwrap(),
1321        };
1322        assert!(
1323            loaded
1324                .resolve(
1325                    None,
1326                    &Settings {
1327                        wrapper_grace: Some(3),
1328                        ..Settings::default()
1329                    }
1330                )
1331                .is_err()
1332        );
1333    }
1334
1335    #[test]
1336    fn detect_package_name_reads_manifest_and_single_member_virtual_workspace() {
1337        let dir = temp_dir("pkg-name");
1338        write(
1339            &dir.join("Cargo.toml"),
1340            "[package]\nname = \"my-crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1341        );
1342        assert_eq!(detect_package_name(&dir).as_deref(), Some("my-crate"));
1343
1344        let virt_empty = temp_dir("virt-ws-empty");
1345        write(
1346            &virt_empty.join("Cargo.toml"),
1347            "[workspace]\nmembers = []\n",
1348        );
1349        assert_eq!(detect_package_name(&virt_empty), None);
1350
1351        let virt_single = temp_dir("virt-ws-single");
1352        write(
1353            &virt_single.join("Cargo.toml"),
1354            "[workspace]\nmembers = [\"crates/only\"]\n",
1355        );
1356        write(
1357            &virt_single.join("crates/only/Cargo.toml"),
1358            "[package]\nname = \"only-crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
1359        );
1360        assert_eq!(
1361            detect_package_name(&virt_single).as_deref(),
1362            Some("only-crate")
1363        );
1364
1365        let _ = fs::remove_dir_all(&dir);
1366        let _ = fs::remove_dir_all(&virt_empty);
1367        let _ = fs::remove_dir_all(&virt_single);
1368    }
1369
1370    #[test]
1371    fn exclude_file_config_parses_overlays_and_rejects_invalid_values() {
1372        let cfg = parse_config(
1373            r#"
1374exclude_file = ["src/generated.rs", "src/fixtures/**"]
1375
1376[package.demo]
1377exclude_file = ["src/sample.rs"]
1378
1379[package.cleared]
1380exclude_file = []
1381"#,
1382            "tmt.toml",
1383        )
1384        .unwrap();
1385        let loaded = LoadedConfig {
1386            path: PathBuf::from("tmt.toml"),
1387            base_dir: PathBuf::from("."),
1388            file: cfg,
1389        };
1390        let top = loaded.resolve(None, &Settings::default()).unwrap();
1391        assert_eq!(
1392            top.exclude_file,
1393            Some(vec!["src/generated.rs".into(), "src/fixtures/**".into()])
1394        );
1395        let demo = loaded.resolve(Some("demo"), &Settings::default()).unwrap();
1396        assert_eq!(demo.exclude_file, Some(vec!["src/sample.rs".into()]));
1397        let cleared = loaded
1398            .resolve(Some("cleared"), &Settings::default())
1399            .unwrap();
1400        assert_eq!(cleared.exclude_file, Some(vec![]));
1401        let cli_override = loaded
1402            .resolve(
1403                Some("demo"),
1404                &Settings {
1405                    exclude_file: Some(vec!["src/cli.rs".into()]),
1406                    ..Settings::default()
1407                },
1408            )
1409            .unwrap();
1410        assert_eq!(cli_override.exclude_file, Some(vec!["src/cli.rs".into()]));
1411
1412        // Empty or control-character patterns are rejected.
1413        assert!(parse_config("exclude_file = [\"\"]\n", "tmt.toml").is_err());
1414        assert!(parse_config("exclude_file = [\"   \"]\n", "tmt.toml").is_err());
1415        assert!(parse_config("exclude_file = [\"src/\\u0000.rs\"]\n", "tmt.toml").is_err());
1416    }
1417}