kaish-glob 0.4.0

Glob matching and async file walking with gitignore support
Documentation
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Gitignore-style pattern matching.
//!
//! Implements gitignore semantics for filtering files during walks.

use std::path::Path;

use crate::WalkerFs;
use crate::glob::glob_match;

/// Maximum size for .gitignore files (1 MiB). Files larger than this are
/// rejected to prevent accidental memory exhaustion from corrupt/adversarial
/// gitignore files.
const MAX_GITIGNORE_SIZE: usize = 1_048_576;

/// A compiled ignore rule from a gitignore file.
#[derive(Debug, Clone)]
struct IgnoreRule {
    /// The pattern to match.
    pattern: String,
    /// True if this rule negates (starts with !).
    negated: bool,
    /// True if this rule only matches directories (ends with /).
    dir_only: bool,
    /// True if this pattern is anchored (contains / not at end).
    anchored: bool,
}

impl IgnoreRule {
    fn parse(line: &str) -> Option<Self> {
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with('#') {
            return None;
        }

        let mut pattern = line.to_string();
        let mut negated = false;
        let mut dir_only = false;

        // Check for negation
        if let Some(stripped) = pattern.strip_prefix('!') {
            negated = true;
            pattern = stripped.to_string();
        }

        // Check for directory-only pattern
        if let Some(stripped) = pattern.strip_suffix('/') {
            dir_only = true;
            pattern = stripped.to_string();
        }

        // Check if anchored (contains / that's not at the end)
        let anchored = pattern.contains('/');

        // Remove leading /
        if let Some(stripped) = pattern.strip_prefix('/') {
            pattern = stripped.to_string();
        }

        Some(IgnoreRule {
            pattern,
            negated,
            dir_only,
            anchored,
        })
    }

    fn matches(&self, path: &Path, is_dir: bool) -> bool {
        // Dir-only rules only match directories
        if self.dir_only && !is_dir {
            return false;
        }

        let path_str = path.to_string_lossy();

        if self.anchored {
            // Anchored patterns match from the root
            self.glob_match_path(&path_str)
        } else {
            // Non-anchored patterns can match anywhere
            // Try matching the full path
            if self.glob_match_path(&path_str) {
                return true;
            }

            // Try matching just the filename
            if let Some(name) = path.file_name() {
                let name_str = name.to_string_lossy();
                if glob_match(&self.pattern, &name_str) {
                    return true;
                }
            }

            false
        }
    }

    fn glob_match_path(&self, path: &str) -> bool {
        // Handle ** in patterns by converting to a match that works
        if self.pattern.contains("**") {
            self.match_with_globstar(path)
        } else {
            glob_match(&self.pattern, path)
        }
    }

    fn match_with_globstar(&self, path: &str) -> bool {
        // Split pattern by **
        let parts: Vec<&str> = self.pattern.split("**").collect();

        if parts.len() == 2 {
            let prefix = parts[0].trim_end_matches('/');
            let suffix = parts[1].trim_start_matches('/');

            // Check prefix
            let remaining = if prefix.is_empty() {
                path
            } else if let Some(rest) = path.strip_prefix(prefix) {
                rest.trim_start_matches('/')
            } else {
                return false;
            };

            // Check suffix
            if suffix.is_empty() {
                return true;
            }

            // Try matching suffix against any tail of the path
            for (i, _) in remaining.char_indices() {
                let tail = &remaining[i..];
                if glob_match(suffix, tail) {
                    return true;
                }
            }

            // Also try matching just the suffix
            glob_match(suffix, remaining)
        } else {
            // Complex pattern with multiple **. Replacing ** with * is safe here
            // because glob_match's * already crosses / boundaries (unlike POSIX
            // path-aware globbing). This flattens O(n^k) multi-globstar into a
            // single wildcard pass while preserving match semantics.
            glob_match(&self.pattern.replace("**", "*"), path)
        }
    }
}

/// Filter for gitignore-style patterns.
#[derive(Debug, Clone, Default)]
pub struct IgnoreFilter {
    rules: Vec<IgnoreRule>,
}

impl IgnoreFilter {
    /// Create an empty ignore filter.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a filter with default ignores for common build artifacts.
    pub fn with_defaults() -> Self {
        let mut filter = Self::new();

        // Always ignore .git
        filter.add_rule(".git");

        // Common build/dependency directories
        filter.add_rule("node_modules");
        filter.add_rule("target"); // Rust
        filter.add_rule("__pycache__");
        filter.add_rule(".venv");
        filter.add_rule("venv");
        filter.add_rule("dist");
        filter.add_rule("build");
        filter.add_rule(".next"); // Next.js

        filter
    }

    /// Load patterns from a gitignore file via `WalkerFs`.
    ///
    /// Rejects files larger than 1 MiB to prevent memory exhaustion.
    pub async fn from_gitignore(
        path: &Path,
        fs: &impl WalkerFs,
    ) -> Result<Self, crate::WalkerError> {
        let content = fs.read_file(path).await?;
        if content.len() > MAX_GITIGNORE_SIZE {
            return Err(crate::WalkerError::Io(format!(
                "{}: gitignore too large ({} bytes, max {})",
                path.display(),
                content.len(),
                MAX_GITIGNORE_SIZE,
            )));
        }
        let text = String::from_utf8_lossy(&content);

        let mut filter = Self::new();
        for line in text.lines() {
            if let Some(rule) = IgnoreRule::parse(line) {
                filter.rules.push(rule);
            }
        }

        Ok(filter)
    }

    /// Add a rule from a pattern string.
    pub fn add_rule(&mut self, pattern: &str) {
        if let Some(rule) = IgnoreRule::parse(pattern) {
            self.rules.push(rule);
        }
    }

    /// Check if a path should be ignored.
    ///
    /// Returns true if the path matches any non-negated rule
    /// and doesn't match a later negated rule.
    pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
        let mut ignored = false;

        for rule in &self.rules {
            if rule.matches(path, is_dir) {
                ignored = !rule.negated;
            }
        }

        ignored
    }

    /// Check if a path component (single name) should be ignored.
    ///
    /// This is for quick filtering during directory traversal.
    pub fn is_name_ignored(&self, name: &str, is_dir: bool) -> bool {
        self.is_ignored(Path::new(name), is_dir)
    }

    /// Merge another filter's rules into this one.
    ///
    /// The other filter's rules are added after (and thus take precedence over)
    /// this filter's rules.
    pub fn merge(&mut self, other: &IgnoreFilter) {
        self.rules.extend(other.rules.iter().cloned());
    }

    /// Create a new filter by merging this filter with another.
    ///
    /// Returns a new filter with the combined rules (other's rules take precedence).
    pub fn merged_with(&self, other: &IgnoreFilter) -> IgnoreFilter {
        let mut merged = self.clone();
        merged.merge(other);
        merged
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_patterns() {
        let mut filter = IgnoreFilter::new();
        filter.add_rule("*.log");
        filter.add_rule("temp/");

        assert!(filter.is_ignored(Path::new("app.log"), false));
        assert!(filter.is_ignored(Path::new("debug.log"), false));
        assert!(!filter.is_ignored(Path::new("app.txt"), false));

        assert!(filter.is_ignored(Path::new("temp"), true));
        assert!(!filter.is_ignored(Path::new("temp"), false)); // dir-only
    }

    #[test]
    fn test_negation() {
        let mut filter = IgnoreFilter::new();
        filter.add_rule("*.log");
        filter.add_rule("!important.log");

        assert!(filter.is_ignored(Path::new("debug.log"), false));
        assert!(!filter.is_ignored(Path::new("important.log"), false));
    }

    #[test]
    fn test_anchored_patterns() {
        let mut filter = IgnoreFilter::new();
        filter.add_rule("/root.txt");
        filter.add_rule("anywhere.txt");

        assert!(filter.is_ignored(Path::new("root.txt"), false));
        assert!(!filter.is_ignored(Path::new("sub/root.txt"), false));

        assert!(filter.is_ignored(Path::new("anywhere.txt"), false));
        assert!(filter.is_ignored(Path::new("sub/anywhere.txt"), false));
    }

    #[test]
    fn test_directory_patterns() {
        let mut filter = IgnoreFilter::new();
        filter.add_rule("build/");

        assert!(filter.is_ignored(Path::new("build"), true));
        assert!(!filter.is_ignored(Path::new("build"), false)); // file named "build"
    }

    #[test]
    fn test_globstar() {
        let mut filter = IgnoreFilter::new();
        filter.add_rule("**/*.log");

        assert!(filter.is_ignored(Path::new("app.log"), false));
        assert!(filter.is_ignored(Path::new("logs/app.log"), false));
        assert!(filter.is_ignored(Path::new("var/logs/app.log"), false));
    }

    #[test]
    fn test_defaults() {
        let filter = IgnoreFilter::with_defaults();

        assert!(filter.is_ignored(Path::new(".git"), true));
        assert!(filter.is_ignored(Path::new("node_modules"), true));
        assert!(filter.is_ignored(Path::new("target"), true));
        assert!(filter.is_ignored(Path::new("__pycache__"), true));
    }

    #[test]
    fn test_comments_and_empty() {
        let mut filter = IgnoreFilter::new();
        filter.add_rule("# comment");
        filter.add_rule("");
        filter.add_rule("  ");
        filter.add_rule("valid.txt");

        assert_eq!(filter.rules.len(), 1);
        assert!(filter.is_ignored(Path::new("valid.txt"), false));
    }

    #[test]
    fn test_path_patterns() {
        let mut filter = IgnoreFilter::new();
        filter.add_rule("logs/*.log");

        assert!(filter.is_ignored(Path::new("logs/app.log"), false));
        assert!(!filter.is_ignored(Path::new("other/app.log"), false));
        assert!(!filter.is_ignored(Path::new("app.log"), false));
    }

    mod async_tests {
        use super::*;
        use crate::{WalkerDirEntry, WalkerError, WalkerFs};
        use std::collections::HashMap;
        use std::path::PathBuf;

        struct MemEntry;
        impl WalkerDirEntry for MemEntry {
            fn name(&self) -> &str { "" }
            fn is_dir(&self) -> bool { false }
            fn is_file(&self) -> bool { true }
            fn is_symlink(&self) -> bool { false }
        }

        /// Minimal FS for testing gitignore loading.
        struct SingleFileFs(HashMap<PathBuf, Vec<u8>>);

        #[async_trait::async_trait]
        impl WalkerFs for SingleFileFs {
            type DirEntry = MemEntry;
            async fn list_dir(&self, _: &Path) -> Result<Vec<MemEntry>, WalkerError> {
                Ok(vec![])
            }
            async fn read_file(&self, path: &Path) -> Result<Vec<u8>, WalkerError> {
                self.0.get(path)
                    .cloned()
                    .ok_or_else(|| WalkerError::NotFound(path.display().to_string()))
            }
            async fn is_dir(&self, _: &Path) -> bool { false }
            async fn exists(&self, path: &Path) -> bool { self.0.contains_key(path) }
        }

        #[tokio::test]
        async fn test_oversized_gitignore_rejected() {
            let oversized = vec![b'#'; super::MAX_GITIGNORE_SIZE + 1];
            let mut files = HashMap::new();
            files.insert(PathBuf::from("/.gitignore"), oversized);
            let fs = SingleFileFs(files);

            let result = IgnoreFilter::from_gitignore(Path::new("/.gitignore"), &fs).await;
            assert!(result.is_err());
            let err = result.unwrap_err().to_string();
            assert!(err.contains("too large"), "expected 'too large' in: {err}");
        }

        #[tokio::test]
        async fn test_normal_gitignore_accepted() {
            let content = b"*.log\n# comment\ntarget/\n".to_vec();
            let mut files = HashMap::new();
            files.insert(PathBuf::from("/.gitignore"), content);
            let fs = SingleFileFs(files);

            let filter = IgnoreFilter::from_gitignore(Path::new("/.gitignore"), &fs)
                .await
                .unwrap();
            assert!(filter.is_ignored(Path::new("app.log"), false));
            assert!(filter.is_ignored(Path::new("target"), true));
        }
    }
}