use crate::gitignore::GitIgnore;
enum Segment {
AnyDepth,
Name(String),
}
struct Pattern {
negate: bool,
dir_only: bool,
segments: Vec<Segment>,
}
fn strip_trailing_spaces(text: &str) -> &str {
let bytes = text.as_bytes();
let mut end = bytes.len();
while end > 0 && bytes[end - 1] == b' ' {
let mut backslashes = 0;
let mut index = end - 1;
while index > 0 && bytes[index - 1] == b'\\' {
backslashes += 1;
index -= 1;
}
if backslashes % 2 == 1 {
break;
}
end -= 1;
}
&text[..end]
}
impl Pattern {
fn compile(negate: bool, text: &str) -> Option<Self> {
let text = strip_trailing_spaces(text);
let (text, dir_only) = text.strip_suffix('/').map_or((text, false), |t| (t, true));
if text.is_empty() {
return None;
}
let anchored = text.contains('/');
let body = text.strip_prefix('/').unwrap_or(text);
if body.is_empty() {
return None;
}
let segments = if anchored {
body.split('/').map(Segment::parse).collect()
} else {
std::iter::once(Segment::AnyDepth)
.chain(std::iter::once(Segment::parse(body)))
.collect()
};
Some(Self {
negate,
dir_only,
segments,
})
}
fn matches(&self, path: &[&str]) -> bool {
match_segments(&self.segments, path)
}
}
impl Segment {
fn parse(text: &str) -> Self {
if text == "**" {
Self::AnyDepth
} else {
Self::Name(text.to_owned())
}
}
}
fn match_segments(pattern: &[Segment], path: &[&str]) -> bool {
match pattern.split_first() {
None => path.is_empty(),
Some((Segment::AnyDepth, rest)) => {
if rest.is_empty() {
return !path.is_empty();
}
(0..=path.len()).any(|skip| match_segments(rest, &path[skip..]))
}
Some((Segment::Name(name), rest)) => match path.split_first() {
Some((head, tail)) => matches_name(name, head) && match_segments(rest, tail),
None => false,
},
}
}
fn matches_name(pattern: &str, name: &str) -> bool {
let pattern: Vec<char> = pattern.chars().collect();
let name: Vec<char> = name.chars().collect();
match_here(&pattern, 0, &name, 0)
}
fn match_here(pattern: &[char], mut p: usize, name: &[char], mut n: usize) -> bool {
while p < pattern.len() {
match pattern[p] {
'*' => return (n..=name.len()).any(|skip| match_here(pattern, p + 1, name, skip)),
'?' if n < name.len() => {
p += 1;
n += 1;
}
'?' => return false,
'[' => {
let Some((matched, next)) = match_class(pattern, p, name.get(n).copied()) else {
return false;
};
if !matched {
return false;
}
p = next;
n += 1;
}
'\\' if p + 1 < pattern.len() => {
if name.get(n) != Some(&pattern[p + 1]) {
return false;
}
p += 2;
n += 1;
}
expected => {
if name.get(n) != Some(&expected) {
return false;
}
p += 1;
n += 1;
}
}
}
n == name.len()
}
fn match_class(pattern: &[char], start: usize, candidate: Option<char>) -> Option<(bool, usize)> {
let mut index = start + 1;
let negated = matches!(pattern.get(index), Some('!' | '^'));
if negated {
index += 1;
}
let mut found = false;
let mut first = true;
while index < pattern.len() {
if pattern[index] == ']' && !first {
return Some((found != negated, index + 1));
}
first = false;
let is_range = pattern.get(index + 1) == Some(&'-')
&& pattern.get(index + 2).is_some_and(|end| *end != ']');
if is_range {
if let Some(candidate) = candidate {
if pattern[index] <= candidate && candidate <= pattern[index + 2] {
found = true;
}
}
index += 3;
} else {
if candidate == Some(pattern[index]) {
found = true;
}
index += 1;
}
}
None
}
impl GitIgnore {
#[must_use]
pub fn is_ignored(&self, path: &str, is_dir: bool) -> bool {
let patterns: Vec<Pattern> = self
.lines()
.iter()
.filter_map(|line| line.pattern())
.filter_map(|(negate, text)| Pattern::compile(negate, text))
.collect();
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
for depth in 1..segments.len() {
if decide(&patterns, &segments[..depth], true) == Some(true) {
return true;
}
}
decide(&patterns, &segments, is_dir).unwrap_or(false)
}
}
fn decide(patterns: &[Pattern], path: &[&str], is_dir: bool) -> Option<bool> {
patterns
.iter()
.filter(|pattern| is_dir || !pattern.dir_only)
.filter(|pattern| pattern.matches(path))
.map(|pattern| !pattern.negate)
.next_back()
}