use std::collections::HashSet;
use globset::GlobBuilder;
use globset::GlobSetBuilder;
use crate::recipe::{Recipe, RecipeMeta};
pub struct SelectionConfig<'a> {
pub harness_root: &'a str,
pub repo_marker: &'a str,
pub smoke: &'a [&'a str],
}
pub fn changed_files_from_file(path: &str) -> std::io::Result<Vec<String>> {
let contents = std::fs::read_to_string(path)?;
Ok(contents
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect())
}
pub trait Selectable {
fn name(&self) -> &str;
fn ci_paths(&self) -> &[String];
}
impl Selectable for RecipeMeta {
fn name(&self) -> &str {
&self.name
}
fn ci_paths(&self) -> &[String] {
&self.ci_paths
}
}
impl Selectable for Recipe {
fn name(&self) -> &str {
self.meta.name()
}
fn ci_paths(&self) -> &[String] {
self.meta.ci_paths()
}
}
impl Selectable for (String, Vec<String>) {
fn name(&self) -> &str {
&self.0
}
fn ci_paths(&self) -> &[String] {
&self.1
}
}
pub fn select<'a, R: Selectable>(
recipes: &'a [R],
changed_files: &[String],
config: &SelectionConfig<'_>,
) -> Vec<&'a R> {
let mut chosen: HashSet<&str> = config
.smoke
.iter()
.filter(|name| recipes.iter().any(|r| r.name() == **name))
.copied()
.collect();
let paths: Vec<String> = changed_files
.iter()
.map(|p| normalize_path(p, config.repo_marker))
.collect();
let touches_harness = paths.iter().any(|p| p.starts_with(config.harness_root));
if !touches_harness {
for r in recipes {
if matches_any_path(r.ci_paths(), &paths, config.repo_marker) {
chosen.insert(r.name());
}
}
}
recipes
.iter()
.filter(|r| chosen.contains(r.name()))
.collect()
}
pub fn select_names<R: Selectable>(
recipes: &[R],
changed_files: &[String],
config: &SelectionConfig<'_>,
) -> Vec<String> {
select(recipes, changed_files, config)
.into_iter()
.map(|r| r.name().to_string())
.collect()
}
fn normalize_path(path: &str, repo_marker: &str) -> String {
let mut normalized = path.trim().replace('\\', "/");
while let Some(rest) = normalized.strip_prefix("./") {
normalized = rest.to_string();
}
if let Some(idx) = normalized.find(repo_marker) {
normalized = normalized[idx + repo_marker.len()..].to_string();
}
normalized.trim_end_matches('/').to_string()
}
fn matches_any_path(patterns: &[String], paths: &[String], repo_marker: &str) -> bool {
if patterns.is_empty() || paths.is_empty() {
return false;
}
let mut builder = GlobSetBuilder::new();
let mut any = false;
for pattern in patterns {
if let Ok(glob) = GlobBuilder::new(&normalize_path(pattern, repo_marker))
.literal_separator(false)
.build()
{
builder.add(glob);
any = true;
}
}
if !any {
return false;
}
match builder.build() {
Ok(set) => paths.iter().any(|p| set.is_match(p)),
Err(_) => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn recipe(name: &str, paths: &[&str]) -> Recipe {
serde_json::from_value(serde_json::json!({
"name": name,
"ci_paths": paths,
"steps": [],
"command": {"argv": ["true"]},
}))
.expect("valid recipe")
}
fn all() -> Vec<Recipe> {
vec![
recipe("smoke", &[]),
recipe("payments", &["src/payments/**"]),
recipe("search", &["src/search/**/*.rs"]),
]
}
fn cfg() -> SelectionConfig<'static> {
SelectionConfig {
harness_root: "verify/",
repo_marker: "/repo/",
smoke: &["smoke"],
}
}
fn names(changed: &[&str]) -> Vec<String> {
let owned: Vec<String> = changed.iter().map(|s| s.to_string()).collect();
select_names(&all(), &owned, &cfg())
}
#[test]
fn smoke_runs_even_when_nothing_matches() {
assert_eq!(names(&["docs/readme.md"]), vec!["smoke".to_string()]);
}
#[test]
fn a_matching_path_adds_its_recipe() {
assert_eq!(
names(&["src/payments/api.rs"]),
vec!["smoke".to_string(), "payments".to_string()]
);
}
#[test]
fn a_harness_change_suppresses_every_other_match() {
assert_eq!(
names(&["src/payments/api.rs", "verify/runner.rs"]),
vec!["smoke".to_string()]
);
}
#[test]
fn absolute_paths_are_made_repo_relative() {
assert_eq!(
names(&["/home/someone/repo/src/search/index.rs"]),
vec!["smoke".to_string(), "search".to_string()]
);
}
#[test]
fn windows_separators_and_dot_prefixes_normalise() {
assert_eq!(
names(&[".\\src\\payments\\api.rs"]),
vec!["smoke".to_string(), "payments".to_string()]
);
}
#[test]
fn a_star_crosses_directory_separators() {
assert_eq!(
names(&["src/search/backend/index/mod.rs"]),
vec!["smoke".to_string(), "search".to_string()]
);
}
#[test]
fn a_broken_glob_does_not_stop_the_others() {
let recipes = vec![
recipe("smoke", &[]),
recipe("broken", &["["]),
recipe("payments", &["src/payments/**"]),
];
let changed = vec!["src/payments/api.rs".to_string()];
let got = select_names(&recipes, &changed, &cfg());
assert!(got.contains(&"payments".to_string()), "{got:?}");
}
#[test]
fn a_smoke_name_that_does_not_exist_is_ignored() {
let config = SelectionConfig {
harness_root: "verify/",
repo_marker: "/repo/",
smoke: &["smoke", "nonexistent"],
};
let changed = vec!["docs/readme.md".to_string()];
assert_eq!(
select_names(&all(), &changed, &config),
vec!["smoke".to_string()]
);
}
#[test]
fn selection_preserves_the_input_order() {
let changed = vec![
"src/search/index.rs".to_string(),
"src/payments/api.rs".to_string(),
];
assert_eq!(
select_names(&all(), &changed, &cfg()),
vec![
"smoke".to_string(),
"payments".to_string(),
"search".to_string()
]
);
}
#[test]
fn an_empty_changeset_still_runs_smoke() {
assert_eq!(select_names(&all(), &[], &cfg()), vec!["smoke".to_string()]);
}
struct ImperativeRecipe {
name: String,
ci_paths: Vec<String>,
}
impl Selectable for ImperativeRecipe {
fn name(&self) -> &str {
&self.name
}
fn ci_paths(&self) -> &[String] {
&self.ci_paths
}
}
#[test]
fn a_foreign_recipe_type_can_be_selected() {
let recipes = vec![
ImperativeRecipe {
name: "smoke".into(),
ci_paths: vec![],
},
ImperativeRecipe {
name: "payments".into(),
ci_paths: vec!["src/payments/**".into()],
},
ImperativeRecipe {
name: "search".into(),
ci_paths: vec!["src/search/**".into()],
},
];
let changed = vec!["src/payments/api.rs".to_string()];
assert_eq!(
select_names(&recipes, &changed, &cfg()),
vec!["smoke".to_string(), "payments".to_string()]
);
}
#[test]
fn a_name_and_paths_pair_is_selectable_without_a_trait_impl() {
let recipes = vec![
("smoke".to_string(), Vec::<String>::new()),
("payments".to_string(), vec!["src/payments/**".to_string()]),
];
let changed = vec!["src/payments/api.rs".to_string()];
assert_eq!(
select_names(&recipes, &changed, &cfg()),
vec!["smoke".to_string(), "payments".to_string()]
);
}
#[test]
fn a_harness_change_suppresses_matches_for_a_foreign_type_too() {
let recipes = vec![
ImperativeRecipe {
name: "smoke".into(),
ci_paths: vec![],
},
ImperativeRecipe {
name: "payments".into(),
ci_paths: vec!["src/payments/**".into()],
},
];
let changed = vec![
"verify/runner.rs".to_string(),
"src/payments/api.rs".to_string(),
];
assert_eq!(
select_names(&recipes, &changed, &cfg()),
vec!["smoke".to_string()]
);
}
}