1use globset::{GlobBuilder, GlobMatcher};
16
17#[derive(Debug, Clone)]
19struct Pattern {
20 negated: bool,
22 dir_only: bool,
24 matcher: GlobMatcher,
25}
26
27#[derive(Debug, Clone)]
29struct Layer {
30 scope: String,
32 prefix: String,
36 patterns: Vec<Pattern>,
37}
38
39const SYSTEM_IGNORE_PATTERNS: &str = "\
41._*
42.str.*
43.lock
44.DS_Store
45Thumbs.db
46desktop.ini
47.git
48.gitignore
49.gitattributes
50.gitmodules
51.gitkeep
52.github
53.hg
54.hgignore
55.svn
56.jj
57";
58
59fn parse_patterns(text: &str) -> Vec<Pattern> {
61 let mut out = Vec::new();
62 for raw in text.lines() {
63 let line = raw.trim_end_matches([' ', '\t']);
65 if line.is_empty() || line.starts_with('#') {
66 continue;
67 }
68 let line = if line.starts_with("\\#") || line.starts_with("\\!") {
70 &line[1..]
71 } else {
72 line
73 };
74 let (negated, line) = match line.strip_prefix('!') {
75 Some(rest) => (true, rest),
76 None => (false, line),
77 };
78 let (dir_only, line) = match line.strip_suffix('/') {
80 Some(rest) => (true, rest),
81 None => (false, line),
82 };
83 if line.is_empty() {
84 continue;
85 }
86 let anchored = line.contains('/');
88 let line = line.strip_prefix('/').unwrap_or(line);
89 if line.is_empty() {
90 continue;
91 }
92 let glob = if anchored {
93 line.to_string()
94 } else {
95 format!("**/{line}")
96 };
97 if let Ok(m) = GlobBuilder::new(&glob)
98 .literal_separator(true)
99 .case_insensitive(false)
100 .build()
101 {
102 out.push(Pattern {
103 negated,
104 dir_only,
105 matcher: m.compile_matcher(),
106 });
107 }
108 }
109 out
110}
111
112#[derive(Debug, Clone, Default)]
114pub struct IgnoreSet {
115 layers: Vec<Layer>,
117}
118
119impl IgnoreSet {
120 pub fn push_layer(&mut self, scope: &str, text: &str) {
123 self.layers.push(Layer {
124 scope: scope.trim_matches('/').to_string(),
125 prefix: String::new(),
126 patterns: parse_patterns(text),
127 });
128 }
129
130 pub fn push_outer(&mut self, prefix: &str, text: &str) {
134 self.layers.push(Layer {
135 scope: String::new(),
136 prefix: prefix.trim_matches('/').to_string(),
137 patterns: parse_patterns(text),
138 });
139 }
140
141 pub fn push_system_layer(&mut self) {
146 self.push_layer("", SYSTEM_IGNORE_PATTERNS);
147 }
148
149 pub fn is_empty(&self) -> bool {
151 self.layers.iter().all(|l| l.patterns.is_empty())
152 }
153
154 pub fn is_ignored(&self, rel: &str, is_dir: bool) -> bool {
156 let mut ignored = false;
157 for layer in &self.layers {
158 let sub: String = if !layer.prefix.is_empty() {
161 format!("{}/{}", layer.prefix, rel)
162 } else if layer.scope.is_empty() {
163 rel.to_string()
164 } else {
165 let scope = format!("{}/", layer.scope);
166 match rel.strip_prefix(scope.as_str()) {
167 Some(s) if !s.is_empty() => s.to_string(),
168 _ => continue,
169 }
170 };
171 let mut decided: Option<bool> = None;
173 for p in &layer.patterns {
174 if p.dir_only && !is_dir {
175 continue;
176 }
177 if p.matcher.is_match(&sub) {
178 decided = Some(!p.negated);
179 }
180 }
181 if let Some(d) = decided {
182 ignored = d;
183 }
184 }
185 ignored
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 fn set(layers: &[(&str, &str)]) -> IgnoreSet {
194 let mut s = IgnoreSet::default();
195 for (scope, text) in layers {
196 s.push_layer(scope, text);
197 }
198 s
199 }
200
201 #[test]
202 fn basename_matches_any_depth() {
203 let s = set(&[("", "*.log\nbuild\n")]);
204 assert!(s.is_ignored("a.log", false));
205 assert!(s.is_ignored("x/y/a.log", false));
206 assert!(s.is_ignored("build", true));
207 assert!(s.is_ignored("x/build", true));
208 assert!(!s.is_ignored("builder", true));
209 }
210
211 #[test]
212 fn anchored_and_dir_only() {
213 let s = set(&[("", "logs/\n/foo\nsub/bar.txt\n")]);
214 assert!(s.is_ignored("logs", true));
215 assert!(s.is_ignored("a/logs", true));
216 assert!(!s.is_ignored("logs", false)); assert!(s.is_ignored("foo", false));
218 assert!(!s.is_ignored("x/foo", false)); assert!(s.is_ignored("sub/bar.txt", false));
220 assert!(!s.is_ignored("other/bar.txt", false));
221 }
222
223 #[test]
224 fn last_match_and_negation() {
225 let s = set(&[("", "*.log\n!keep.log\n")]);
226 assert!(s.is_ignored("a.log", false));
227 assert!(!s.is_ignored("keep.log", false));
228 }
229
230 #[test]
231 fn inner_layer_overrides_outer() {
232 let s = set(&[("", "*.tmp\n"), ("", "!final.tmp\n")]);
234 assert!(s.is_ignored("a.tmp", false));
235 assert!(!s.is_ignored("final.tmp", false));
236 }
237
238 #[test]
239 fn scope_limits_layer() {
240 let s = set(&[("a/b", "cache\n")]);
242 assert!(s.is_ignored("a/b/cache", true));
243 assert!(!s.is_ignored("a/cache", true));
244 assert!(!s.is_ignored("cache", true));
245 }
246
247 #[test]
248 fn comments_and_escapes() {
249 let s = set(&[("", "# 注释\n\\#hash.txt\n")]);
250 assert!(!s.is_ignored("hash.txt", false));
251 assert!(s.is_ignored("#hash.txt", false));
252 }
253
254 #[test]
255 fn system_layer_is_innermost_and_unresurrectable() {
256 let mut s = IgnoreSet::default();
257 s.push_layer("", "!.str.cache\n!.str.toml\n!.str.schema\n");
259 s.push_system_layer();
260 assert!(s.is_ignored(".str.toml", false));
261 assert!(s.is_ignored(".str.schema", true));
262 assert!(s.is_ignored(".str.cache", true));
263 assert!(s.is_ignored("a/.str.cache", true));
264 assert!(s.is_ignored(".DS_Store", false));
265 assert!(s.is_ignored(".git", true));
266 assert!(s.is_ignored("x/.lock", false));
267 assert!(!s.is_ignored("data.json", false));
269 }
270
271 #[test]
272 fn outer_layer_anchoring() {
273 let mut s = IgnoreSet::default();
274 s.push_outer("bundles/x.str", "/target\n*.log\n");
276 assert!(!s.is_ignored("target", true));
278 assert!(s.is_ignored("a/b/c.log", false));
280 let mut s2 = IgnoreSet::default();
282 s2.push_outer("bundles/x.str", "/bundles/x.str/foo\n");
283 assert!(s2.is_ignored("foo", false));
284 }
285}