litnik 0.2.0

An embedded Lit and FileCheck runner for compiler test suites.
Documentation
//! Suite configuration and its builder API.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// Configuration shared by all tests in one Lit suite.
///
/// Create this value with [`LitConfig::new()`]. Builder methods replace scalar
/// settings and add values to collection settings. The configuration inherits
/// the process environment when it is created. Relative roots and tool paths
/// are anchored to the process working directory when each method is called.
#[derive(Debug, Clone)]
pub struct LitConfig {
    pub(crate) name: String,
    pub(crate) root: PathBuf,
    pub(crate) tools: HashMap<String, RegisteredTool>,
    pub(crate) suffixes: HashSet<String>,
    pub(crate) exclusions: HashSet<String>,
    pub(crate) substitutions: Vec<(String, String)>,
    pub(crate) environment: HashMap<String, String>,
    pub(crate) available_features: HashSet<String>,
    pub(crate) pipefail: bool,
    pub(crate) recursive_expansion_limit: Option<usize>,
    pub(crate) limit_to_features: HashSet<String>,
    pub(crate) max_individual_test_time_seconds: Option<u64>,
    pub(crate) no_execute: bool,
    pub(crate) normalize_slashes: bool,
    pub(crate) test_source_root: Option<PathBuf>,
    pub(crate) test_exec_root: Option<PathBuf>,
    pub(crate) default_substitutions: Vec<(String, String)>,
    pub(crate) test_retry_attempts: usize,
}

#[derive(Debug, Clone)]
pub(crate) struct RegisteredTool {
    path: PathBuf,
    #[cfg(test)]
    utf8: Option<String>,
}

impl LitConfig {
    /// Creates configuration for tests below `root`.
    ///
    /// The initial environment contains every Unicode variable from the current
    /// process. Tests inherit this snapshot unless [`Self::env()`] replaces a
    /// value. A relative root is anchored when this method is called.
    ///
    /// # Panics
    ///
    /// Panics if `root` is relative and the process working directory is not
    /// available.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        let root = anchor_path(root.into());

        Self {
            name: "litnik".into(),
            root,
            tools: HashMap::new(),
            suffixes: HashSet::new(),
            exclusions: HashSet::new(),
            substitutions: Vec::new(),
            environment: std::env::vars().collect(),
            available_features: HashSet::new(),
            pipefail: true,
            recursive_expansion_limit: None,
            limit_to_features: HashSet::new(),
            max_individual_test_time_seconds: None,
            no_execute: false,
            normalize_slashes: false,
            test_source_root: None,
            test_exec_root: None,
            default_substitutions: Vec::new(),
            test_retry_attempts: 0,
        }
    }

    /// Replaces the name shown before each test path.
    pub fn suite_name(mut self, value: impl Into<String>) -> Self {
        self.name = value.into();
        self
    }

    /// Registers an executable for a command name used in `RUN:` directives.
    ///
    /// Registration replaces an earlier path for the same name. The runner
    /// invokes the path directly and does not require it to be on `PATH`. A
    /// relative path is anchored when this method is called.
    ///
    /// # Panics
    ///
    /// Panics if `path` is relative and the process working directory is not
    /// available.
    pub fn tool(mut self, name: impl Into<String>, path: impl Into<PathBuf>) -> Self {
        let name = name.into();
        let path = anchor_path(path.into());
        #[cfg(test)]
        let utf8 = path.to_str().map(ToOwned::to_owned);
        self.tools.insert(
            name,
            RegisteredTool {
                path,
                #[cfg(test)]
                utf8,
            },
        );
        self
    }

    /// Adds one test-file suffix.
    ///
    /// A missing leading dot is added. An empty suffix is ignored.
    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
        let suffix = suffix.into();
        if !suffix.is_empty() {
            self.suffixes.insert(if suffix.starts_with('.') {
                suffix
            } else {
                format!(".{suffix}")
            });
        }
        self
    }

    /// Adds test-file suffixes.
    ///
    /// This method applies the same normalization as [`Self::suffix()`] to each
    /// value.
    pub fn suffixes<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for value in values {
            self = self.suffix(value);
        }
        self
    }

    /// Excludes a file or directory whose base name equals `value`.
    pub fn exclude(mut self, value: impl Into<String>) -> Self {
        self.exclusions.insert(value.into());
        self
    }

    /// Adds excluded file or directory base names.
    pub fn excludes<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.exclusions.extend(values.into_iter().map(Into::into));
        self
    }

    /// Adds a regular-expression substitution for `RUN:` directives.
    ///
    /// Substitutions run in insertion order before Lit's built-in substitutions.
    /// The replacement is inserted as literal text; `$` has no special meaning.
    pub fn substitution(mut self, pattern: impl Into<String>, value: impl Into<String>) -> Self {
        self.substitutions.push((pattern.into(), value.into()));
        self
    }

    /// Adds regular-expression substitutions in iteration order.
    pub fn substitutions<I, K, V>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.substitutions
            .extend(values.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    /// Adds a default substitution before Lit's built-in substitutions.
    ///
    /// Use [`Self::substitution()`] for suite-specific substitutions. This
    /// method exists for integrations that assemble a base configuration.
    pub fn default_substitution(
        mut self,
        pattern: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        self.default_substitutions
            .push((pattern.into(), value.into()));
        self
    }

    /// Adds default substitutions in iteration order.
    pub fn default_substitutions<I, K, V>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.default_substitutions
            .extend(values.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    /// Makes one feature available to boolean test directives.
    pub fn feature(mut self, value: impl Into<String>) -> Self {
        self.available_features.insert(value.into());
        self
    }

    /// Makes each supplied feature available to boolean test directives.
    pub fn features<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.available_features
            .extend(values.into_iter().map(Into::into));
        self
    }

    /// Replaces one environment variable in the test environment snapshot.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.environment.insert(key.into(), value.into());
        self
    }

    /// Replaces the source root used for discovery and `%s` paths.
    ///
    /// A relative root is anchored when this method is called.
    ///
    /// # Panics
    ///
    /// Panics if the root is relative and the process working directory is not
    /// available.
    pub fn source_root(mut self, value: impl Into<PathBuf>) -> Self {
        self.test_source_root = Some(anchor_path(value.into()));
        self
    }

    /// Replaces the root used for test working directories and temporary files.
    ///
    /// The directory is created when a test runs. The source tree is used when
    /// no execution root is set. A relative root is anchored when this method
    /// is called.
    ///
    /// # Panics
    ///
    /// Panics if the root is relative and the process working directory is not
    /// available.
    pub fn exec_root(mut self, value: impl Into<PathBuf>) -> Self {
        self.test_exec_root = Some(anchor_path(value.into()));
        self
    }

    /// Sets the maximum number of recursive substitution passes.
    ///
    /// `None` applies one pass. `Some(limit)` requires expansion to stabilize
    /// within `limit` additional passes.
    pub fn recursive_expansion_limit(mut self, value: Option<usize>) -> Self {
        self.recursive_expansion_limit = value;
        self
    }

    /// Sets the time limit for one test attempt, in seconds.
    ///
    /// A value of zero disables the limit. The runner stops child processes at
    /// the limit. It cannot preempt an embedded command while it runs.
    pub fn max_individual_test_time(mut self, secs: u64) -> Self {
        self.max_individual_test_time_seconds = (secs != 0).then_some(secs);
        self
    }

    /// Selects validation without command execution.
    ///
    /// The runner still reads the test, parses directives, applies
    /// substitutions, and evaluates feature conditions.
    pub fn no_execute(mut self, value: bool) -> Self {
        self.no_execute = value;
        self
    }

    /// Controls whether a failed pipeline stage fails the complete pipeline.
    pub fn with_pipefail(mut self, value: bool) -> Self {
        self.pipefail = value;
        self
    }

    /// Controls slash normalization in path substitutions.
    pub fn normalize_slashes(mut self, value: bool) -> Self {
        self.normalize_slashes = value;
        self
    }

    /// Restricts execution to tests that require at least one listed feature.
    pub fn limit_to_features<I, S>(mut self, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.limit_to_features = values.into_iter().map(Into::into).collect();
        self
    }

    /// Sets the number of retries after an initial failed attempt.
    ///
    /// A test-level `ALLOW_RETRIES:` directive replaces this value.
    pub fn test_retry_attempts(mut self, attempts: usize) -> Self {
        self.test_retry_attempts = attempts;
        self
    }

    #[cfg(test)]
    pub(crate) fn tool_path(&self, name: &str) -> Option<&String> {
        self.tools.get(name)?.utf8.as_ref()
    }

    /// Returns the registered executable for `name`.
    pub fn registered_tool(&self, name: &str) -> Option<&Path> {
        self.tools.get(name).map(|tool| tool.path.as_path())
    }

    pub(crate) fn to_test_config(&self) -> crate::test::TestConfig {
        crate::test::TestConfig {
            name: self.name.clone(),
            suffixes: self.suffixes.clone(),
            exclusions: self.exclusions.clone(),
            substitutions: self.substitutions.clone(),
            default_substitutions: self.default_substitutions.clone(),
            available_features: self.available_features.clone(),
            normalize_slashes: self.normalize_slashes,
            pipefail: self.pipefail,
            recursive_expansion_limit: self.recursive_expansion_limit,
            limit_to_features: self.limit_to_features.clone(),
            max_individual_test_time: self
                .max_individual_test_time_seconds
                .map(std::time::Duration::from_secs),
            environment: self.environment.clone(),
            test_retry_attempts: self.test_retry_attempts,
            tools: self
                .tools
                .iter()
                .map(|(name, tool)| (name.clone(), tool.path.clone()))
                .collect(),
        }
    }

    #[cfg(test)]
    pub(crate) fn use_external_shell(self, _value: bool) -> Self {
        self
    }
}

pub(crate) fn anchor_path(path: PathBuf) -> PathBuf {
    if path.is_absolute() {
        path
    } else {
        std::env::current_dir()
            .expect("cannot anchor a relative path without a process working directory")
            .join(path)
    }
}

impl Default for LitConfig {
    fn default() -> Self {
        Self::new(".")
    }
}

#[cfg(test)]
mod tests {
    use super::LitConfig;

    #[test]
    fn builder_roundtrip() {
        let cfg = LitConfig::new("/tmp/root")
            .suite_name("x")
            .suffix(".mlir")
            .exclude("Inputs")
            .tool("clang", "/bin/clang")
            .feature("linux");
        assert_eq!(cfg.name, "x");
        assert!(cfg.suffixes.contains(".mlir"));
        assert!(cfg.exclusions.contains("Inputs"));
        assert_eq!(cfg.tool_path("clang"), Some(&"/bin/clang".to_string()));
        assert!(cfg.available_features.contains("linux"));
    }
}