litnik 0.2.1

An embedded Lit and FileCheck runner for compiler test suites.
Documentation
//! Recursive, deterministic discovery of integrated shell tests.
//!
//! Discovery selects non-directory entries by the suffixes in [`LitConfig`]. It
//! does not read or validate directives; [`crate::formats::run_shtest()`] does
//! that when each [`Test`] runs.

use std::error::Error;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use crate::config::LitConfig;
use crate::test::{Test, TestConfig};

/// A filesystem error that prevents a complete discovery scan.
#[derive(Debug)]
pub enum DiscoveryError {
    /// The scan could not open a directory.
    ReadDirectory {
        /// The directory that could not be opened.
        path: PathBuf,
        /// The underlying filesystem error.
        source: io::Error,
    },
    /// The scan could not read one entry from an open directory.
    ReadEntry {
        /// The directory that contains the unreadable entry.
        path: PathBuf,
        /// The underlying filesystem error.
        source: io::Error,
    },
}

impl fmt::Display for DiscoveryError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ReadDirectory { path, source } => {
                write!(
                    formatter,
                    "cannot read test directory '{}': {source}",
                    path.display()
                )
            }
            Self::ReadEntry { path, source } => {
                write!(
                    formatter,
                    "cannot read an entry in test directory '{}': {source}",
                    path.display()
                )
            }
        }
    }
}

impl Error for DiscoveryError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::ReadDirectory { source, .. } | Self::ReadEntry { source, .. } => Some(source),
        }
    }
}

/// Discovers all matching test files below `root`.
///
/// The scan is recursive and returns tests in stable path order. File names
/// must match a configured suffix. Entries named `Inputs`, `Output`, `.git`, or
/// `.svn`, explicit [`LitConfig::exclude()`] names, and hidden files are omitted.
/// A successful scan with no matching files returns an empty vector.
///
/// # Panics
///
/// Panics when the scan cannot read a directory or directory entry. Also
/// panics if `root` is relative and the process working directory is not
/// available. Use [`try_discover_tests()`] to handle filesystem errors.
pub fn discover_tests(root: &Path, config: &LitConfig) -> Vec<Test> {
    try_discover_tests(root, config).unwrap_or_else(|error| panic!("{error}"))
}

/// Discovers all matching test files and reports incomplete filesystem scans.
///
/// The configured source root replaces `root` when one is set. The configured
/// execution root determines each [`Test::exec_path()`] but does not change
/// which files are scanned. A successful scan with no matching files returns
/// an empty vector.
///
/// # Errors
///
/// Returns [`DiscoveryError`] when the scan cannot read the source root, an
/// included directory, or an entry in either.
///
/// # Panics
///
/// Panics if `root` is relative, no source-root override is set, and the process
/// working directory is not available.
pub fn try_discover_tests(root: &Path, config: &LitConfig) -> Result<Vec<Test>, DiscoveryError> {
    let test_config = config.to_test_config();
    let source_root = config
        .test_source_root
        .clone()
        .unwrap_or_else(|| crate::config::anchor_path(root.to_path_buf()));
    let exec_root = config
        .test_exec_root
        .clone()
        .unwrap_or_else(|| source_root.clone());
    let mut tests = Vec::new();
    visit_dir(
        &source_root,
        &source_root,
        &exec_root,
        &test_config,
        &mut tests,
    )?;
    Ok(tests)
}

fn visit_dir(
    directory: &Path,
    source_root: &Path,
    exec_root: &Path,
    config: &TestConfig,
    tests: &mut Vec<Test>,
) -> Result<(), DiscoveryError> {
    let entries = fs::read_dir(directory).map_err(|source| DiscoveryError::ReadDirectory {
        path: directory.to_path_buf(),
        source,
    })?;
    let mut entries = entries
        .map(|entry| {
            entry.map_err(|source| DiscoveryError::ReadEntry {
                path: directory.to_path_buf(),
                source,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    entries.sort_by_key(fs::DirEntry::file_name);

    for entry in entries {
        let name = entry.file_name();
        let name_text = name.to_string_lossy();
        if config.is_excluded_name(&name_text) || name_text == "Output" {
            continue;
        }

        let path = entry.path();
        if path.is_dir() {
            visit_dir(&path, source_root, exec_root, config, tests)?;
            continue;
        }
        if name_text.starts_with('.')
            || config.suffixes.is_empty()
            || !config
                .suffixes
                .iter()
                .any(|suffix| name_text.ends_with(suffix))
        {
            continue;
        }

        let relative_path = path
            .strip_prefix(source_root)
            .expect("directory traversal remains below the source root")
            .to_path_buf();
        tests.push(Test::new(
            config.name.clone(),
            source_root.to_path_buf(),
            exec_root.to_path_buf(),
            relative_path,
            config.clone(),
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self, File};
    use tempfile::tempdir;

    use crate::config::LitConfig;

    #[test]
    fn discovers_tests_by_suffix() {
        let root = tempdir().unwrap();
        let root = root.path();
        fs::create_dir(root.join("sub")).unwrap();
        fs::create_dir(root.join("Inputs")).unwrap();
        fs::create_dir(root.join(".git")).unwrap();
        File::create(root.join("a.mlir")).unwrap();
        File::create(root.join("b.txt")).unwrap();
        File::create(root.join("sub").join("c.mlir")).unwrap();

        let cfg = LitConfig::new(root).suffix(".mlir").exclude("Outputs");
        let tests = discover_tests(root, &cfg);
        let names: Vec<_> = tests
            .into_iter()
            .map(|t| t.relative_path.to_string_lossy().to_string())
            .collect();
        assert!(names.contains(&"a.mlir".into()));
        assert!(names.contains(&"sub/c.mlir".into()));
        assert!(!names.iter().any(|n| n.contains("Inputs")));
        assert!(!names.iter().any(|n| n.contains("b.txt")));
    }
}