use std::fs;
use std::path::Path;
use crate::config::LitConfig;
use crate::test::{Test, TestConfig};
pub fn discover_tests(root: &Path, cfg: &LitConfig) -> Vec<Test> {
let test_cfg = cfg.to_test_config();
let source_root = cfg
.test_source_root
.clone()
.unwrap_or_else(|| root.to_path_buf());
let exec_root = cfg
.test_exec_root
.clone()
.unwrap_or_else(|| root.to_path_buf());
let mut out = Vec::new();
visit_dir(&source_root, &source_root, &exec_root, &test_cfg, &mut out);
out
}
fn visit_dir(
root: &Path,
source_root: &Path,
current_exec_root: &Path,
cfg: &TestConfig,
out: &mut Vec<Test>,
) {
let entries = match fs::read_dir(root) {
Ok(entries) => entries,
Err(_) => return,
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if cfg.is_excluded_name(&name) {
continue;
}
let path = entry.path();
let rel = match path.strip_prefix(source_root) {
Ok(v) => v.to_path_buf(),
Err(_) => continue,
};
if path.is_dir() {
if name == "Output" {
continue;
}
let sub_exec = current_exec_root.join(&name);
visit_dir(&path, source_root, &sub_exec, cfg, out);
continue;
}
let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
continue;
};
if cfg.suffixes.is_empty() {
continue;
}
if !cfg.suffixes.contains(&format!(".{ext}")) {
continue;
}
if rel
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with('.'))
{
continue;
}
out.push(Test::new(
cfg.name.clone(),
source_root.to_path_buf(),
current_exec_root.to_path_buf(),
rel,
cfg.clone(),
));
}
}
#[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")));
}
}