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