use super::{ExplicitPaths, MatchSpec, RelPath};
use crate::cli::RuleKind;
use crate::safety::SafetyPreset;
use globset::{Glob, GlobMatcher};
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use std::collections::HashMap;
use std::io;
use std::path::Path;
use std::sync::RwLock;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Selection {
Include,
Exclude,
PruneDir,
}
struct CompiledRule {
kind: RuleKind,
pattern: String,
matcher: GlobMatcher,
}
pub struct MatcherEngine {
rules: Vec<CompiledRule>,
respect_gitignore: bool,
root_gitignore: Option<Gitignore>,
nested_gitignores: RwLock<HashMap<String, Gitignore>>,
safety_preset: Option<SafetyPreset>,
has_includes: bool,
explicit: Option<ExplicitPaths>,
}
impl MatcherEngine {
pub fn compile(spec: &MatchSpec, root: &Path) -> io::Result<Self> {
let rules = spec
.rules
.iter()
.map(|r| {
let glob = Glob::new(&r.pattern).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Invalid glob pattern '{}': {}", r.pattern, e),
)
})?;
Ok(CompiledRule {
kind: r.kind,
pattern: r.pattern.clone(),
matcher: glob.compile_matcher(),
})
})
.collect::<io::Result<Vec<_>>>()?;
let root_gitignore = if spec.respect_gitignore {
build_root_gitignore(root)?
} else {
None
};
let safety_preset = if spec.use_safety_preset {
Some(SafetyPreset::new())
} else {
None
};
Ok(Self {
has_includes: spec.explicit_paths.is_some()
|| rules.iter().any(|r| r.kind == RuleKind::Include),
rules,
respect_gitignore: spec.respect_gitignore,
root_gitignore,
nested_gitignores: RwLock::new(HashMap::new()),
safety_preset,
explicit: spec.explicit_paths.clone(),
})
}
pub fn select_file(&self, rel_path: &RelPath) -> Selection {
let path_str = rel_path.as_match_str();
let path_ref = path_str.as_ref();
let mut last: Option<RuleKind> = match &self.explicit {
Some(e) if e.covers(path_ref) => Some(RuleKind::Include),
_ => None,
};
for rule in &self.rules {
if rule.matcher.is_match(path_ref) {
last = Some(rule.kind);
}
}
if let Some(kind) = last {
return match kind {
RuleKind::Include => Selection::Include,
RuleKind::Exclude => Selection::Exclude,
};
}
if self.has_includes {
return Selection::Exclude;
}
if self.matches_gitignore(&path_str, rel_path, false) {
return Selection::Exclude;
}
if let Some(ref safety) = self.safety_preset {
if safety.matches(path_ref) {
return Selection::Exclude;
}
}
Selection::Include
}
pub fn select_dir(&self, rel_path: &RelPath) -> Selection {
let path_str = rel_path.as_match_str();
let path_ref = path_str.as_ref();
if path_ref == ".git" || path_ref.starts_with(".git/") {
return Selection::PruneDir;
}
let mut last_explicit: Option<RuleKind> = match &self.explicit {
Some(e) if e.covers(path_ref) || e.is_ancestor(path_ref) => Some(RuleKind::Include),
_ => None,
};
for rule in &self.rules {
let applies = match rule.kind {
RuleKind::Include => path_specific_include_targets_dir(&rule.pattern, path_ref),
RuleKind::Exclude => {
rule.matcher.is_match(path_ref)
|| rule.matcher.is_match(format!("{}/", path_ref))
}
};
if applies {
last_explicit = Some(rule.kind);
}
}
if let Some(kind) = last_explicit {
return match kind {
RuleKind::Include => Selection::Include,
RuleKind::Exclude => Selection::PruneDir,
};
}
if self.matches_gitignore(&path_str, rel_path, true) {
return Selection::PruneDir;
}
if let Some(ref safety) = self.safety_preset {
if safety.matches(path_ref) || safety.matches(&format!("{}/", path_ref)) {
return Selection::PruneDir;
}
}
let any_include_relates = self.rules.iter().any(|r| {
r.kind == RuleKind::Include && include_rule_relates_to_dir(&r.pattern, path_ref)
});
if any_include_relates {
return Selection::Include;
}
if self.has_includes {
return Selection::PruneDir;
}
Selection::Include
}
pub fn load_nested_gitignore(&self, dir_rel: &RelPath, dir: &Path) -> io::Result<()> {
if !self.respect_gitignore {
return Ok(());
}
let gi_path = dir.join(".gitignore");
if !gi_path.exists() {
return Ok(());
}
let scope = dir_rel.as_match_str().into_owned();
let mut builder = GitignoreBuilder::new(dir);
builder.add(&gi_path);
let gi = builder.build().map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Failed to build gitignore for {}: {}", scope, e),
)
})?;
self.nested_gitignores
.write()
.unwrap_or_else(|e| e.into_inner())
.insert(scope, gi);
Ok(())
}
fn matches_gitignore(&self, path_str: &str, rel_path: &RelPath, is_dir: bool) -> bool {
if let Some(ref gitignore) = self.root_gitignore {
if gitignore
.matched(rel_path.to_path_buf(), is_dir)
.is_ignore()
{
return true;
}
}
let nested = self
.nested_gitignores
.read()
.unwrap_or_else(|e| e.into_inner());
if nested.is_empty() {
return false;
}
for (i, _) in path_str.match_indices('/') {
if let Some(gitignore) = nested.get(&path_str[..i]) {
if gitignore
.matched(Path::new(&path_str[i + 1..]), is_dir)
.is_ignore()
{
return true;
}
}
}
false
}
}
fn path_specific_include_targets_dir(pattern: &str, dir_path: &str) -> bool {
if pattern.starts_with("**/") || pattern == "**" {
return false;
}
brace_expand(pattern)
.iter()
.any(|p| static_prefix_relates(p, dir_path))
}
fn include_rule_relates_to_dir(pattern: &str, dir_path: &str) -> bool {
if pattern.starts_with("**/") || pattern == "**" {
return true;
}
brace_expand(pattern)
.iter()
.any(|p| static_prefix_relates(p, dir_path))
}
fn static_prefix_relates(pattern: &str, dir_path: &str) -> bool {
let static_prefix = match pattern.find(['*', '?', '[']) {
Some(idx) => &pattern[..idx],
None => pattern,
};
let static_prefix = static_prefix.trim_end_matches('/');
if static_prefix.is_empty() {
return false;
}
if static_prefix == dir_path || static_prefix.starts_with(&format!("{}/", dir_path)) {
return true;
}
if format!("{}/", dir_path).starts_with(&format!("{}/", static_prefix)) {
return true;
}
false
}
fn brace_expand(pattern: &str) -> Vec<String> {
let bytes = pattern.as_bytes();
let n = bytes.len();
let i = match bytes.iter().position(|&b| b == b'{') {
Some(p) => p,
None => return vec![pattern.to_string()],
};
let mut depth = 1i32;
let mut j = i + 1;
while j < n {
match bytes[j] {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
j += 1;
}
if depth != 0 {
return vec![pattern.to_string()];
}
let prefix = &pattern[..i];
let inside = &pattern[i + 1..j];
let suffix = &pattern[j + 1..];
let mut results = Vec::new();
for alt in split_top_level_commas(inside) {
let combined = format!("{}{}{}", prefix, alt, suffix);
results.extend(brace_expand(&combined));
}
results
}
fn split_top_level_commas(s: &str) -> Vec<&str> {
let bytes = s.as_bytes();
let mut depth = 0i32;
let mut start = 0;
let mut out = Vec::new();
for (i, &b) in bytes.iter().enumerate() {
match b {
b'{' => depth += 1,
b'}' => depth -= 1,
b',' if depth == 0 => {
out.push(&s[start..i]);
start = i + 1;
}
_ => {}
}
}
out.push(&s[start..]);
out
}
fn build_root_gitignore(root: &Path) -> io::Result<Option<Gitignore>> {
let mut root_builder = GitignoreBuilder::new(root);
let mut has_root_patterns = false;
let mut current = root;
loop {
let gi = current.join(".gitignore");
if gi.exists() {
root_builder.add(gi);
has_root_patterns = true;
}
match current.parent() {
Some(parent) => current = parent,
None => break,
}
}
let git_info_exclude = root.join(".git/info/exclude");
if git_info_exclude.exists() {
root_builder.add(git_info_exclude);
has_root_patterns = true;
}
if let Some(home) = dirs::home_dir() {
let xdg = home.join(".config/git/ignore");
let legacy = home.join(".gitignore");
if xdg.exists() {
root_builder.add(xdg);
has_root_patterns = true;
} else if legacy.exists() {
root_builder.add(legacy);
has_root_patterns = true;
}
}
if !has_root_patterns {
return Ok(None);
}
let gi = root_builder.build().map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Failed to build root gitignore: {}", e),
)
})?;
Ok(Some(gi))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::FilterRule;
use tempfile::TempDir;
fn engine(spec: MatchSpec) -> MatcherEngine {
let t = TempDir::new().unwrap();
MatcherEngine::compile(&spec, t.path()).unwrap()
}
fn rule(kind: RuleKind, pattern: &str) -> FilterRule {
FilterRule {
kind,
pattern: pattern.to_string(),
}
}
#[test]
fn last_wins_include_alone() {
let spec = MatchSpec::new().with_include_glob(vec!["**/*.rs".into()]);
let e = engine(spec);
assert_eq!(
e.select_file(&RelPath::from_relative("src/main.rs")),
Selection::Include
);
assert_eq!(
e.select_file(&RelPath::from_relative("README.md")),
Selection::Exclude
);
}
#[test]
fn last_wins_exclude_after_path_include_narrows_subtree() {
let spec = MatchSpec::new().with_rules(vec![
rule(RuleKind::Include, "projects/alpha/**"),
rule(RuleKind::Exclude, "build"),
]);
let e = engine(spec);
assert_eq!(
e.select_file(&RelPath::from_relative("projects/alpha/index.ts")),
Selection::Include
);
assert_eq!(
e.select_file(&RelPath::from_relative("projects/alpha/build/out.js")),
Selection::Exclude,
"exclude after include must narrow"
);
assert_eq!(
e.select_dir(&RelPath::from_relative("projects/alpha/build")),
Selection::PruneDir
);
}
#[test]
fn last_wins_include_after_exclude_carves_out() {
let spec = MatchSpec::new().with_rules(vec![
rule(RuleKind::Exclude, "vendor"),
rule(RuleKind::Include, "vendor/**/*.py"),
]);
let e = engine(spec);
assert_eq!(
e.select_file(&RelPath::from_relative("vendor/lib1/code.py")),
Selection::Include
);
assert_eq!(
e.select_file(&RelPath::from_relative("vendor/lib1/README.md")),
Selection::Exclude
);
assert_eq!(
e.select_dir(&RelPath::from_relative("vendor")),
Selection::Include,
"must descend into vendor to find .py"
);
}
#[test]
fn double_star_no_slash_is_fixed() {
let spec = MatchSpec::new().with_rules(vec![
rule(RuleKind::Include, "projects/alpha/**"),
rule(RuleKind::Exclude, "**.generated.json"),
]);
let e = engine(spec);
assert_eq!(
e.select_file(&RelPath::from_relative("projects/alpha/index.ts")),
Selection::Include
);
assert_eq!(
e.select_file(&RelPath::from_relative(
"projects/alpha/data.generated.json"
)),
Selection::Exclude
);
}
#[test]
fn directory_with_no_relevant_include_is_pruned() {
let spec = MatchSpec::new().with_include_glob(vec!["projects/alpha/**".into()]);
let e = engine(spec);
assert_eq!(
e.select_dir(&RelPath::from_relative("projects/beta")),
Selection::PruneDir
);
assert_eq!(
e.select_dir(&RelPath::from_relative("projects/alpha")),
Selection::Include
);
assert_eq!(
e.select_dir(&RelPath::from_relative("projects")),
Selection::Include
);
}
#[test]
fn git_dir_always_pruned() {
let e = engine(MatchSpec::new());
assert_eq!(
e.select_dir(&RelPath::from_relative(".git")),
Selection::PruneDir
);
}
#[test]
fn bare_exclude_anywhere() {
let spec = MatchSpec::new().with_exclude_glob(vec!["archived".into()]);
let e = engine(spec);
assert_eq!(
e.select_file(&RelPath::from_relative("projects/archived/old.ts")),
Selection::Exclude
);
assert_eq!(
e.select_dir(&RelPath::from_relative("projects/archived")),
Selection::PruneDir
);
}
#[test]
fn nested_gitignore_scoped() {
let temp = TempDir::new().unwrap();
let root = temp.path();
std::fs::create_dir_all(root.join("a/b/c")).unwrap();
std::fs::write(root.join("a/b/c/.gitignore"), "*.tmp\n").unwrap();
let e = MatcherEngine::compile(&MatchSpec::new().with_gitignore(true), root).unwrap();
assert_eq!(
e.select_file(&RelPath::from_relative("a/b/c/remove.tmp")),
Selection::Include
);
for dir in ["a", "a/b", "a/b/c"] {
e.load_nested_gitignore(&RelPath::from_relative(dir), &root.join(dir))
.unwrap();
}
assert_eq!(
e.select_file(&RelPath::from_relative("a/b/keep.tmp")),
Selection::Include
);
assert_eq!(
e.select_file(&RelPath::from_relative("a/b/c/remove.tmp")),
Selection::Exclude
);
assert_eq!(
e.select_file(&RelPath::from_relative("a/b/c/d/remove.tmp")),
Selection::Exclude
);
assert_eq!(
e.select_file(&RelPath::from_relative("a/b/cc/keep.tmp")),
Selection::Include
);
}
#[test]
fn nested_gitignore_not_loaded_when_disabled() {
let temp = TempDir::new().unwrap();
let root = temp.path();
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("sub/.gitignore"), "*.tmp\n").unwrap();
let e = MatcherEngine::compile(&MatchSpec::new().with_gitignore(false), root).unwrap();
e.load_nested_gitignore(&RelPath::from_relative("sub"), &root.join("sub"))
.unwrap();
assert_eq!(
e.select_file(&RelPath::from_relative("sub/x.tmp")),
Selection::Include
);
}
}