use log::debug;
use parking_lot::RwLock;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct GitIgnoreMatcher {
repo_root: PathBuf,
matcher: Arc<RwLock<Option<ignore::gitignore::Gitignore>>>,
}
impl GitIgnoreMatcher {
pub fn new(repo_path: &Path) -> Self {
Self {
repo_root: repo_path.to_path_buf(),
matcher: Arc::new(RwLock::new(None)),
}
}
pub fn should_exclude(&self, file_path: &str) -> bool {
debug!("GitIgnoreMatcher checking: {}", file_path);
let mut matcher_guard = self.matcher.write();
if matcher_guard.is_none() {
let mut builder = ignore::gitignore::GitignoreBuilder::new(&self.repo_root);
self.add_gitignore_files(&mut builder);
match builder.build() {
Ok(gitignore) => {
*matcher_guard = Some(gitignore);
debug!("Loaded gitignore matcher with all .gitignore files");
}
Err(e) => {
debug!("Failed to build gitignore matcher: {}", e);
}
}
}
if let Some(ref gitignore) = *matcher_guard {
let full_path = self.repo_root.join(file_path);
let relative_path = full_path
.strip_prefix(&self.repo_root)
.unwrap_or_else(|_| Path::new(file_path));
let mut result = gitignore.matched(relative_path, false).is_ignore();
if !result && file_path.contains('/') {
let parts: Vec<&str> = file_path.split('/').collect();
for i in 1..=parts.len() {
let dir_path = parts[..i].join("/");
let dir_full = self.repo_root.join(&dir_path);
let dir_relative = dir_full
.strip_prefix(&self.repo_root)
.unwrap_or_else(|_| Path::new(&dir_path));
if gitignore.matched(dir_relative, true).is_ignore() {
result = true;
break;
}
}
}
result
} else {
false
}
}
fn add_gitignore_files(&self, builder: &mut ignore::gitignore::GitignoreBuilder) {
self.add_gitignore_from_dir(builder, &self.repo_root);
}
#[allow(clippy::only_used_in_recursion)]
fn add_gitignore_from_dir(
&self,
builder: &mut ignore::gitignore::GitignoreBuilder,
dir: &Path,
) {
let gitignore_path = dir.join(".gitignore");
if gitignore_path.exists() {
debug!("Adding .gitignore from: {}", gitignore_path.display());
if let Some(e) = builder.add(&gitignore_path) {
debug!(
"Failed to add .gitignore {}: {}",
gitignore_path.display(),
e
);
}
}
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
if let Ok(file_type) = entry.file_type()
&& file_type.is_dir()
{
let subdir = entry.path();
if !subdir.ends_with(".git") {
self.add_gitignore_from_dir(builder, &subdir);
}
}
}
}
}
}