-
Notifications
You must be signed in to change notification settings - Fork 791
Expand file tree
/
Copy pathpattern_matcher.rs
More file actions
339 lines (309 loc) · 13.1 KB
/
pattern_matcher.rs
File metadata and controls
339 lines (309 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use anyhow::Result;
use globset::{Glob, GlobSet, GlobSetBuilder};
/// Builds a GlobSet from a vector of pattern strings
fn build_glob_set(patterns: Vec<String>) -> Result<GlobSet> {
let mut builder = GlobSetBuilder::new();
for pattern in patterns {
builder.add(Glob::new(pattern.as_str())?);
}
Ok(builder.build()?)
}
/// Splits a list of patterns into regular exclusion patterns and negation (``!``-prefixed)
/// patterns. Returns the compiled GlobSets together with the raw negation strings so that
/// callers can do prefix-based path ancestry checks without unpacking compiled globs.
fn split_excluded_patterns(
patterns: Option<Vec<String>>,
) -> Result<(Option<GlobSet>, Option<GlobSet>, Vec<String>)> {
let Some(pats) = patterns else {
return Ok((None, None, Vec::new()));
};
let mut regular: Vec<String> = Vec::new();
let mut negation: Vec<String> = Vec::new();
for p in pats {
if let Some(stripped) = p.strip_prefix('!') {
negation.push(stripped.to_string());
} else {
regular.push(p);
}
}
let regular_set = if regular.is_empty() {
None
} else {
Some(build_glob_set(regular)?)
};
let negation_raw = negation.clone();
let negation_set = if negation.is_empty() {
None
} else {
Some(build_glob_set(negation)?)
};
Ok((regular_set, negation_set, negation_raw))
}
/// Pattern matcher that handles include and exclude patterns for files.
///
/// Supports gitignore-style ``!``-prefixed negation in ``excluded_patterns``: a pattern
/// beginning with ``!`` un-excludes paths that would otherwise be excluded. For example,
/// combining ``"**/.*"`` with ``"!**/.github/**"`` excludes all dot-entries *except*
/// anything inside ``.github/``.
#[derive(Debug)]
pub struct PatternMatcher {
/// Patterns matching full path of files to be included.
included_glob_set: Option<GlobSet>,
/// Regular (non-negated) exclusion patterns.
excluded_glob_set: Option<GlobSet>,
/// Negation patterns compiled into a GlobSet (``!``-prefixed in the original list,
/// stored without the ``!``). A path that matches one of these is *not* excluded
/// even if it matches the regular exclusion patterns.
negation_excluded_glob_set: Option<GlobSet>,
/// Raw (uncompiled) negation pattern strings, kept so that ``is_dir_included`` can
/// detect directories that lie on the path to a negation-exempt file even when the
/// directory itself would otherwise be pruned (e.g. ``!dir1/dir2/dir3/a.yml``
/// combined with ``dir1/**``).
negation_patterns_raw: Vec<String>,
}
impl PatternMatcher {
/// Create a new PatternMatcher from optional include and exclude pattern vectors.
///
/// Patterns in `excluded_patterns` that start with ``!`` are treated as negations:
/// they un-exclude any path that would otherwise be excluded by the preceding patterns.
pub fn new(
included_patterns: Option<Vec<String>>,
excluded_patterns: Option<Vec<String>>,
) -> Result<Self> {
let included_glob_set = included_patterns.map(build_glob_set).transpose()?;
let (excluded_glob_set, negation_excluded_glob_set, negation_patterns_raw) =
split_excluded_patterns(excluded_patterns)?;
Ok(Self {
included_glob_set,
excluded_glob_set,
negation_excluded_glob_set,
negation_patterns_raw,
})
}
/// Check if a path is excluded after applying both exclusion and negation patterns.
pub fn is_excluded(&self, path: &str) -> bool {
if !self
.excluded_glob_set
.as_ref()
.is_some_and(|gs| gs.is_match(path))
{
return false;
}
// The path matches an exclusion pattern; a negation pattern can un-exclude it.
!self
.negation_excluded_glob_set
.as_ref()
.is_some_and(|gs| gs.is_match(path))
}
/// Check if a directory should be traversed based on the exclude/negation patterns.
///
/// A directory is included unless it matches an exclusion pattern *and* no negation
/// pattern applies to it or to any file that could live inside it.
///
/// Two complementary checks are used so that both glob-style and exact-path negations
/// work correctly:
///
/// 1. **GlobSet probe** — matches ``<dir>/__probe__`` against the compiled negation
/// GlobSet. Catches wildcard negations such as ``!**/.github/**`` that use ``**``
/// to span multiple directory levels.
///
/// 2. **Raw-prefix check** — scans the raw (uncompiled) negation strings and returns
/// ``true`` if any of them starts with ``<dir>/``. Catches exact-path negations
/// such as ``!dir1/dir2/dir3/a.yml`` where the probe alone would not help because
/// the pattern contains no wildcards relative to the directory.
pub fn is_dir_included(&self, path: &str) -> bool {
if !self
.excluded_glob_set
.as_ref()
.is_some_and(|gs| gs.is_match(path))
{
return true;
}
// Directory matches an exclusion pattern. Check whether a negation pattern
// could apply to the directory itself or to any descendant.
if let Some(neg_gs) = &self.negation_excluded_glob_set {
if neg_gs.is_match(path) {
return true;
}
// Probe one level inside: catches glob negations like `**/.github/**`.
let probe = format!("{}/__probe__", path);
if neg_gs.is_match(probe.as_str()) {
return true;
}
}
// Raw-prefix check: catches exact-path negations like `!dir1/dir2/dir3/a.yml`
// where the parent directories would otherwise be pruned by the exclusion but
// need to be traversed to reach the negation-exempt file.
let dir_prefix = format!("{}/", path);
if self
.negation_patterns_raw
.iter()
.any(|p| p.starts_with(&dir_prefix))
{
return true;
}
false
}
/// Check if a file should be included based on both include and exclude patterns.
pub fn is_file_included(&self, path: &str) -> bool {
self.included_glob_set
.as_ref()
.is_none_or(|glob_set| glob_set.is_match(path))
&& !self.is_excluded(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pattern_matcher_no_patterns() {
let matcher = PatternMatcher::new(None, None).unwrap();
assert!(matcher.is_file_included("test.txt"));
assert!(matcher.is_file_included("path/to/file.rs"));
assert!(!matcher.is_excluded("anything"));
}
#[test]
fn test_pattern_matcher_include_only() {
let matcher =
PatternMatcher::new(Some(vec!["*.txt".to_string(), "*.rs".to_string()]), None).unwrap();
assert!(matcher.is_file_included("test.txt"));
assert!(matcher.is_file_included("main.rs"));
assert!(!matcher.is_file_included("image.png"));
}
#[test]
fn test_pattern_matcher_exclude_only() {
let matcher =
PatternMatcher::new(None, Some(vec!["*.tmp".to_string(), "*.log".to_string()]))
.unwrap();
assert!(matcher.is_file_included("test.txt"));
assert!(!matcher.is_file_included("temp.tmp"));
assert!(!matcher.is_file_included("debug.log"));
}
#[test]
fn test_pattern_matcher_both_patterns() {
let matcher = PatternMatcher::new(
Some(vec!["*.txt".to_string()]),
Some(vec!["*temp*".to_string()]),
)
.unwrap();
assert!(matcher.is_file_included("test.txt"));
assert!(!matcher.is_file_included("temp.txt")); // excluded despite matching include
assert!(!matcher.is_file_included("main.rs")); // doesn't match include
}
#[test]
fn test_is_dir_included_no_patterns() {
let matcher = PatternMatcher::new(None, None).unwrap();
assert!(matcher.is_dir_included("any_dir"));
assert!(matcher.is_dir_included(".git"));
}
#[test]
fn test_is_dir_included_with_excluded() {
let matcher = PatternMatcher::new(None, Some(vec!["**/.*".to_string()])).unwrap();
assert!(!matcher.is_dir_included(".git"));
assert!(!matcher.is_dir_included("src/.hidden"));
assert!(matcher.is_dir_included("src"));
assert!(matcher.is_dir_included("node_modules"));
}
#[test]
fn test_recursive_include_patterns() {
let matcher = PatternMatcher::new(Some(vec!["**/*.py".to_string()]), None).unwrap();
assert!(matcher.is_file_included("main.py"));
assert!(matcher.is_file_included("src/main.py"));
assert!(matcher.is_file_included("a/b/c/main.py"));
assert!(!matcher.is_file_included("main.rs"));
}
// --- Negation (!) pattern tests ---
#[test]
fn test_negation_un_excludes_file() {
// Exclude all dot-files, but un-exclude .env.example
let matcher = PatternMatcher::new(
None,
Some(vec!["**/.env*".to_string(), "!**/.env.example".to_string()]),
)
.unwrap();
assert!(!matcher.is_file_included(".env"));
assert!(!matcher.is_file_included("config/.env.local"));
assert!(matcher.is_file_included(".env.example"));
assert!(matcher.is_file_included("config/.env.example"));
}
#[test]
fn test_negation_un_excludes_dotdir_files() {
// Exclude all dot-directories, but allow .github workflow files through.
let matcher = PatternMatcher::new(
None,
Some(vec!["**/.*".to_string(), "!**/.github/**".to_string()]),
)
.unwrap();
// Dot files/dirs that are NOT in .github remain excluded.
assert!(!matcher.is_file_included(".git/config"));
assert!(!matcher.is_file_included(".vscode/settings.json"));
// Files under .github are un-excluded.
assert!(matcher.is_file_included(".github/workflows/ci.yml"));
assert!(matcher.is_file_included("repo/.github/dependabot.yml"));
// Regular files are unaffected.
assert!(matcher.is_file_included("src/main.rs"));
}
#[test]
fn test_negation_dir_traversal() {
// Exclude all dot-directories, but un-exclude .github subtree.
let matcher = PatternMatcher::new(
None,
Some(vec!["**/.*".to_string(), "!**/.github/**".to_string()]),
)
.unwrap();
// .git should be pruned.
assert!(!matcher.is_dir_included(".git"));
assert!(!matcher.is_dir_included("src/.vscode"));
// .github must NOT be pruned so its contents can be reached.
assert!(matcher.is_dir_included(".github"));
assert!(matcher.is_dir_included("repo/.github"));
// Normal directories are always included.
assert!(matcher.is_dir_included("src"));
}
#[test]
fn test_negation_exact_path_deep_dir_traversal() {
// Exclude all of dir1, but un-exclude a specific deep file with an exact path.
// All ancestor directories of dir1/dir2/dir3/a.yml must be traversable.
let matcher = PatternMatcher::new(
None,
Some(vec![
"dir1/**".to_string(),
"!dir1/dir2/dir3/a.yml".to_string(),
]),
)
.unwrap();
// The negation-exempt file itself must be included.
assert!(matcher.is_file_included("dir1/dir2/dir3/a.yml"));
// Other files under dir1 remain excluded.
assert!(!matcher.is_file_included("dir1/other.txt"));
assert!(!matcher.is_file_included("dir1/dir2/other.txt"));
// Ancestor directories must be traversable to reach the exempt file.
assert!(matcher.is_dir_included("dir1"));
assert!(matcher.is_dir_included("dir1/dir2"));
assert!(matcher.is_dir_included("dir1/dir2/dir3"));
// Sibling directories that contain no negation-exempt files are still pruned.
assert!(!matcher.is_dir_included("dir1/other"));
}
#[test]
fn test_negation_only_no_regular_exclusion() {
// A negation without a corresponding exclusion is a no-op — nothing is excluded.
let matcher =
PatternMatcher::new(None, Some(vec!["!**/.github/**".to_string()])).unwrap();
assert!(matcher.is_file_included(".git/config"));
assert!(matcher.is_file_included(".github/workflows/ci.yml"));
assert!(matcher.is_file_included("src/main.rs"));
}
#[test]
fn test_negation_with_include_patterns() {
// Include only YAML files, exclude all dot-directories, but un-exclude .github.
let matcher = PatternMatcher::new(
Some(vec!["**/*.yml".to_string(), "**/*.yaml".to_string()]),
Some(vec!["**/.*".to_string(), "!**/.github/**".to_string()]),
)
.unwrap();
assert!(matcher.is_file_included(".github/workflows/ci.yml"));
assert!(!matcher.is_file_included(".github/workflows/ci.sh")); // not in included
assert!(!matcher.is_file_included(".git/config")); // excluded, not negated
assert!(matcher.is_file_included("src/config.yaml"));
}
}