const META: [char; 7] = ['*', '?', '[', ']', '{', '}', '\\'];
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Tail {
Any,
EndsWith(Vec<String>),
Contains(Vec<String>),
}
impl Tail {
pub(super) fn of(glob: &str) -> Self {
match glob.strip_suffix("/**") {
Some(dir) if !dir.is_empty() => endings(dir).map_or(Self::Any, Self::Contains),
_ => endings(glob).map_or(Self::Any, Self::EndsWith),
}
}
pub(super) fn may_match(&self, candidate: &str, case_insensitive: bool) -> bool {
if !candidate.is_ascii() || candidate.contains('\\') {
return true;
}
let eq = |a: &[u8], b: &[u8]| {
if case_insensitive {
a.eq_ignore_ascii_case(b)
} else {
a == b
}
};
let text = candidate.as_bytes();
match self {
Self::Any => true,
Self::EndsWith(ends) => ends.iter().any(|end| {
let end = end.as_bytes();
text.len() >= end.len() && eq(&text[text.len() - end.len()..], end)
}),
Self::Contains(parts) => parts.iter().any(|part| {
let part = part.as_bytes();
text.windows(part.len()).any(|w| eq(w, part))
}),
}
}
}
fn endings(glob: &str) -> Option<Vec<String>> {
let Some(body) = glob.strip_suffix('}') else {
return ending(glob).map(|e| vec![e]);
};
if glob.contains(['[', '\\']) {
return None;
}
let open = body.rfind('{')?;
let alternatives = &body[open + 1..];
if alternatives.contains('}') {
return None;
}
alternatives.split(',').map(ending).collect()
}
fn ending(glob: &str) -> Option<String> {
let literal = glob.rfind(META).map_or(glob, |at| &glob[at + 1..]);
let ascii = literal
.rfind(|c: char| !c.is_ascii())
.map_or(literal, |at| {
let width = literal[at..].chars().next().map_or(1, char::len_utf8);
&literal[at + width..]
});
let end = ascii.trim_start_matches('/');
(!end.is_empty()).then(|| end.to_owned())
}
#[cfg(test)]
mod tests;