use globset::{GlobBuilder, GlobMatcher};
#[derive(Debug, Clone)]
struct Pattern {
negated: bool,
dir_only: bool,
matcher: GlobMatcher,
}
#[derive(Debug, Clone)]
struct Layer {
scope: String,
prefix: String,
patterns: Vec<Pattern>,
}
const SYSTEM_IGNORE_PATTERNS: &str = "\
._*
.lock
.DS_Store
Thumbs.db
desktop.ini
.git
.gitignore
.gitattributes
.gitmodules
.gitkeep
.github
.hg
.hgignore
.svn
.jj
";
fn parse_patterns(text: &str) -> Vec<Pattern> {
let mut out = Vec::new();
for raw in text.lines() {
let line = raw.trim_end_matches([' ', '\t']);
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = if line.starts_with("\\#") || line.starts_with("\\!") {
&line[1..]
} else {
line
};
let (negated, line) = match line.strip_prefix('!') {
Some(rest) => (true, rest),
None => (false, line),
};
let (dir_only, line) = match line.strip_suffix('/') {
Some(rest) => (true, rest),
None => (false, line),
};
if line.is_empty() {
continue;
}
let anchored = line.contains('/');
let line = line.strip_prefix('/').unwrap_or(line);
if line.is_empty() {
continue;
}
let glob = if anchored {
line.to_string()
} else {
format!("**/{line}")
};
if let Ok(m) = GlobBuilder::new(&glob)
.literal_separator(true)
.case_insensitive(false)
.build()
{
out.push(Pattern {
negated,
dir_only,
matcher: m.compile_matcher(),
});
}
}
out
}
#[derive(Debug, Clone, Default)]
pub struct IgnoreSet {
layers: Vec<Layer>,
}
impl IgnoreSet {
pub fn push_layer(&mut self, scope: &str, text: &str) {
self.layers.push(Layer {
scope: scope.trim_matches('/').to_string(),
prefix: String::new(),
patterns: parse_patterns(text),
});
}
pub fn push_outer(&mut self, prefix: &str, text: &str) {
self.layers.push(Layer {
scope: String::new(),
prefix: prefix.trim_matches('/').to_string(),
patterns: parse_patterns(text),
});
}
pub fn push_system_layer(&mut self) {
self.push_layer("", SYSTEM_IGNORE_PATTERNS);
}
pub fn is_empty(&self) -> bool {
self.layers.iter().all(|l| l.patterns.is_empty())
}
pub fn is_ignored(&self, rel: &str, is_dir: bool) -> bool {
let mut ignored = false;
for layer in &self.layers {
let sub: String = if !layer.prefix.is_empty() {
format!("{}/{}", layer.prefix, rel)
} else if layer.scope.is_empty() {
rel.to_string()
} else {
let scope = format!("{}/", layer.scope);
match rel.strip_prefix(scope.as_str()) {
Some(s) if !s.is_empty() => s.to_string(),
_ => continue,
}
};
let mut decided: Option<bool> = None;
for p in &layer.patterns {
if p.dir_only && !is_dir {
continue;
}
if p.matcher.is_match(&sub) {
decided = Some(!p.negated);
}
}
if let Some(d) = decided {
ignored = d;
}
}
ignored
}
}
#[cfg(test)]
mod tests {
use super::*;
fn set(layers: &[(&str, &str)]) -> IgnoreSet {
let mut s = IgnoreSet::default();
for (scope, text) in layers {
s.push_layer(scope, text);
}
s
}
#[test]
fn basename_matches_any_depth() {
let s = set(&[("", "*.log\nbuild\n")]);
assert!(s.is_ignored("a.log", false));
assert!(s.is_ignored("x/y/a.log", false));
assert!(s.is_ignored("build", true));
assert!(s.is_ignored("x/build", true));
assert!(!s.is_ignored("builder", true));
}
#[test]
fn anchored_and_dir_only() {
let s = set(&[("", "logs/\n/foo\nsub/bar.txt\n")]);
assert!(s.is_ignored("logs", true));
assert!(s.is_ignored("a/logs", true));
assert!(!s.is_ignored("logs", false)); assert!(s.is_ignored("foo", false));
assert!(!s.is_ignored("x/foo", false)); assert!(s.is_ignored("sub/bar.txt", false));
assert!(!s.is_ignored("other/bar.txt", false));
}
#[test]
fn last_match_and_negation() {
let s = set(&[("", "*.log\n!keep.log\n")]);
assert!(s.is_ignored("a.log", false));
assert!(!s.is_ignored("keep.log", false));
}
#[test]
fn inner_layer_overrides_outer() {
let s = set(&[("", "*.tmp\n"), ("", "!final.tmp\n")]);
assert!(s.is_ignored("a.tmp", false));
assert!(!s.is_ignored("final.tmp", false));
}
#[test]
fn scope_limits_layer() {
let s = set(&[("a/b", "cache\n")]);
assert!(s.is_ignored("a/b/cache", true));
assert!(!s.is_ignored("a/cache", true));
assert!(!s.is_ignored("cache", true));
}
#[test]
fn comments_and_escapes() {
let s = set(&[("", "# 注释\n\\#hash.txt\n")]);
assert!(!s.is_ignored("hash.txt", false));
assert!(s.is_ignored("#hash.txt", false));
}
#[test]
fn system_layer_is_innermost_and_unresurrectable() {
let mut s = IgnoreSet::default();
s.push_layer("", "!._cache\n!._meta\n!._schema\n");
s.push_system_layer();
assert!(s.is_ignored("._meta", false));
assert!(s.is_ignored("._schema", true));
assert!(s.is_ignored("._cache", true));
assert!(s.is_ignored("a/._cache", true));
assert!(s.is_ignored(".DS_Store", false));
assert!(s.is_ignored(".git", true));
assert!(s.is_ignored("x/.lock", false));
assert!(!s.is_ignored("data.json", false));
}
#[test]
fn outer_layer_anchoring() {
let mut s = IgnoreSet::default();
s.push_outer("bundles/x.str", "/target\n*.log\n");
assert!(!s.is_ignored("target", true));
assert!(s.is_ignored("a/b/c.log", false));
let mut s2 = IgnoreSet::default();
s2.push_outer("bundles/x.str", "/bundles/x.str/foo\n");
assert!(s2.is_ignored("foo", false));
}
}