use super::*;
#[derive(Clone, Debug, Default)]
pub struct PathFilter {
include: Option<GlobSet>,
include_dirs: Option<GlobSet>,
exclude: Option<GlobSet>,
}
pub(super) fn compile_glob(pat: &str) -> Option<Glob> {
if let Some(anchored) = pat.strip_prefix('/') {
return globset::GlobBuilder::new(anchored)
.literal_separator(true)
.build()
.ok();
}
let expanded = if let Some(anchored) = pat.strip_prefix("./") {
anchored.to_string()
} else if pat.contains('/') {
pat.to_string()
} else {
format!("**/{pat}")
};
Glob::new(&expanded).ok()
}
pub fn invalid_globs(raw: &str) -> Vec<&str> {
split_globs(raw)
.filter(|p| compile_glob(p).is_none())
.collect()
}
pub(super) fn build_glob_set(raw: &str, fail_closed: bool) -> Option<GlobSet> {
build_glob_set_of(raw, fail_closed, |_| true)
}
pub(super) fn build_glob_set_of(
raw: &str,
fail_closed: bool,
keep: impl Fn(&str) -> bool,
) -> Option<GlobSet> {
let mut builder = GlobSetBuilder::new();
let mut any = false;
let mut typed = false;
for pat in split_globs(raw).filter(|p| keep(p)) {
typed = true;
if let Some(g) = compile_glob(pat) {
builder.add(g);
any = true;
}
}
if !any && !(typed && fail_closed) {
return None;
}
builder.build().ok()
}
pub(super) fn names_a_folder(pat: &str) -> bool {
let last = pat.trim_end_matches('/').rsplit('/').next().unwrap_or(pat);
!last.is_empty() && !last.contains(['*', '?', '[', '{'])
}
pub(super) fn matches_self_or_parent(set: &GlobSet, rel: &Path) -> bool {
rel.ancestors()
.any(|p| !p.as_os_str().is_empty() && set.is_match(p))
}
impl PathFilter {
pub fn new(include: &str, exclude: &str) -> Self {
Self {
include: build_glob_set(include, true),
include_dirs: build_glob_set_of(include, false, names_a_folder),
exclude: build_glob_set(exclude, false),
}
}
pub fn is_empty(&self) -> bool {
self.include.is_none() && self.exclude.is_none()
}
pub fn allows(&self, root: &Path, path: &Path) -> bool {
let inside = path.strip_prefix(root).ok();
let rel = inside.unwrap_or(path);
if let Some(inc) = &self.include
&& !inc.is_match(rel)
&& !inside.is_some_and(|rel| {
self.include_dirs
.as_ref()
.is_some_and(|dirs| matches_self_or_parent(dirs, rel))
})
{
return false;
}
if let Some(exc) = &self.exclude
&& matches_self_or_parent(exc, rel)
{
return false;
}
true
}
pub fn excludes(&self, root: &Path, path: &Path) -> bool {
let rel = path.strip_prefix(root).unwrap_or(path);
self.exclude
.as_ref()
.is_some_and(|exc| matches_self_or_parent(exc, rel))
}
pub fn excluding(globs: &[String]) -> Self {
Self::new("", &globs.join(", "))
}
}