infiniloom-engine 0.6.3

High-performance repository context engine for LLMs - AST parsing, token counting, and secret detection
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Centralized file filtering logic
//!
//! This module provides unified pattern matching and filtering functionality
//! used across all commands (pack, diff, scan, map, chunk, index).
//!
//! # Key Features
//!
//! - **Glob pattern support**: `*.rs`, `src/**/*.ts`, `**/*.test.js`
//! - **Substring matching**: `node_modules`, `dist`, `target`
//! - **Path component matching**: Match against directory names
//! - **Generic API**: Works with any collection type
//!
//! # Usage Example
//!
//! ```no_run
//! use infiniloom_engine::filtering::{apply_exclude_patterns, apply_include_patterns};
//! use infiniloom_engine::types::RepoFile;
//!
//! let mut files: Vec<RepoFile> = vec![/* ... */];
//! let exclude = vec!["node_modules".to_string(), "*.min.js".to_string()];
//! let include = vec!["src/**/*.rs".to_string()];
//!
//! // Apply filters
//! apply_exclude_patterns(&mut files, &exclude, |f| &f.relative_path);
//! apply_include_patterns(&mut files, &include, |f| &f.relative_path);
//! ```

use glob::Pattern;
use std::collections::HashMap;
use std::sync::OnceLock;

/// Compiled pattern cache to avoid recompilation
static PATTERN_CACHE: OnceLock<std::sync::Mutex<HashMap<String, Option<Pattern>>>> =
    OnceLock::new();

/// Get or create the pattern cache
fn get_pattern_cache() -> &'static std::sync::Mutex<HashMap<String, Option<Pattern>>> {
    PATTERN_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}

/// Compile a glob pattern with caching
///
/// Returns `None` if the pattern is invalid.
fn compile_pattern(pattern: &str) -> Option<Pattern> {
    let cache = get_pattern_cache();
    let mut cache_guard = cache.lock().unwrap();

    if let Some(cached) = cache_guard.get(pattern) {
        return cached.clone();
    }

    let compiled = Pattern::new(pattern).ok();
    cache_guard.insert(pattern.to_owned(), compiled.clone());
    compiled
}

/// Check if a path matches an exclude pattern
///
/// Exclude patterns support:
/// - Glob patterns: `*.min.js`, `src/**/*.test.ts`
/// - Path component matches: `tests`, `vendor`, `node_modules` (matches directory names)
/// - Prefix matches: `target` matches `target/debug/file.rs`
///
/// Note: Pattern "target" will match "target/file.rs" and "src/target/file.rs"
/// but NOT "src/target.rs" (where target is part of a filename).
///
/// # Arguments
///
/// * `path` - File path to check
/// * `pattern` - Exclude pattern
///
/// # Returns
///
/// Returns `true` if the path should be excluded.
///
/// # Examples
///
/// ```no_run
/// use infiniloom_engine::filtering::matches_exclude_pattern;
///
/// assert!(matches_exclude_pattern("src/tests/foo.rs", "tests"));
/// assert!(matches_exclude_pattern("node_modules/lib.js", "node_modules"));
/// assert!(matches_exclude_pattern("dist/bundle.min.js", "*.min.js"));
/// ```
pub fn matches_exclude_pattern(path: &str, pattern: &str) -> bool {
    // Empty pattern should not match anything
    if pattern.is_empty() {
        return false;
    }

    // Try as glob pattern first if contains wildcard
    if pattern.contains('*') {
        if let Some(glob) = compile_pattern(pattern) {
            if glob.matches(path) {
                return true;
            }
        }
    }

    // Path component match (e.g., "tests" matches "src/tests/foo.rs")
    // This handles directory names like "node_modules", "target", "dist"
    if path.split('/').any(|part| part == pattern) {
        return true;
    }

    // Prefix match (e.g., "src/" matches "src/foo.rs")
    if path.starts_with(pattern) {
        return true;
    }

    false
}

/// Check if a path matches an include pattern
///
/// Include patterns support:
/// - Glob patterns: `*.rs`, `src/**/*.ts`, `**/*.test.js`
/// - Substring matches: `src`, `lib`
/// - Suffix matches: `.rs`, `.ts`
///
/// # Arguments
///
/// * `path` - File path to check
/// * `pattern` - Include pattern
///
/// # Returns
///
/// Returns `true` if the path should be included.
///
/// # Examples
///
/// ```no_run
/// use infiniloom_engine::filtering::matches_include_pattern;
///
/// assert!(matches_include_pattern("src/main.rs", "*.rs"));
/// assert!(matches_include_pattern("src/lib.rs", "src"));
/// assert!(matches_include_pattern("foo.test.ts", "*.test.ts"));
/// ```
pub fn matches_include_pattern(path: &str, pattern: &str) -> bool {
    // Empty pattern should not match anything
    if pattern.is_empty() {
        return false;
    }

    // Try as glob pattern first if contains wildcard
    if pattern.contains('*') {
        if let Some(glob) = compile_pattern(pattern) {
            return glob.matches(path);
        }
    }

    // Substring match or suffix match
    path.contains(pattern) || path.ends_with(pattern)
}

/// Apply exclude patterns to a collection
///
/// Removes items whose paths match any exclude pattern.
/// Uses a generic `get_path` function to extract the path from each item.
///
/// # Arguments
///
/// * `items` - Mutable reference to collection to filter
/// * `patterns` - List of exclude patterns
/// * `get_path` - Function to extract path from an item
///
/// # Type Parameters
///
/// * `T` - Type of items in the collection
/// * `F` - Type of the path extraction function
///
/// # Examples
///
/// ```no_run
/// use infiniloom_engine::filtering::apply_exclude_patterns;
/// use infiniloom_engine::types::RepoFile;
///
/// let mut files: Vec<RepoFile> = vec![/* ... */];
/// let exclude = vec!["node_modules".to_string(), "*.min.js".to_string()];
///
/// apply_exclude_patterns(&mut files, &exclude, |f| &f.relative_path);
/// ```
pub fn apply_exclude_patterns<T, F>(items: &mut Vec<T>, patterns: &[String], get_path: F)
where
    F: Fn(&T) -> &str,
{
    if patterns.is_empty() {
        return;
    }

    items.retain(|item| {
        let path = get_path(item);
        !patterns
            .iter()
            .any(|pattern| matches_exclude_pattern(path, pattern))
    });
}

/// Apply include patterns to a collection
///
/// Keeps only items whose paths match at least one include pattern.
/// Uses a generic `get_path` function to extract the path from each item.
///
/// # Arguments
///
/// * `items` - Mutable reference to collection to filter
/// * `patterns` - List of include patterns
/// * `get_path` - Function to extract path from an item
///
/// # Type Parameters
///
/// * `T` - Type of items in the collection
/// * `F` - Type of the path extraction function
///
/// # Examples
///
/// ```no_run
/// use infiniloom_engine::filtering::apply_include_patterns;
/// use infiniloom_engine::types::RepoFile;
///
/// let mut files: Vec<RepoFile> = vec![/* ... */];
/// let include = vec!["*.rs".to_string(), "*.ts".to_string()];
///
/// apply_include_patterns(&mut files, &include, |f| &f.relative_path);
/// ```
pub fn apply_include_patterns<T, F>(items: &mut Vec<T>, patterns: &[String], get_path: F)
where
    F: Fn(&T) -> &str,
{
    if patterns.is_empty() {
        return;
    }

    items.retain(|item| {
        let path = get_path(item);
        patterns
            .iter()
            .any(|pattern| matches_include_pattern(path, pattern))
    });
}

/// Compile patterns into glob::Pattern objects
///
/// Used by CLI commands that need pre-compiled patterns for repeated use.
///
/// # Arguments
///
/// * `patterns` - List of pattern strings
///
/// # Returns
///
/// Vector of successfully compiled glob patterns.
/// Invalid patterns are silently skipped.
///
/// # Examples
///
/// ```no_run
/// use infiniloom_engine::filtering::compile_patterns;
///
/// let patterns = vec!["*.rs".to_string(), "src/**/*.ts".to_string()];
/// let compiled = compile_patterns(&patterns);
/// assert_eq!(compiled.len(), 2);
/// ```
pub fn compile_patterns(patterns: &[String]) -> Vec<Pattern> {
    patterns.iter().filter_map(|p| compile_pattern(p)).collect()
}

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

    // =============================================================================
    // Exclude Pattern Tests
    // =============================================================================

    #[test]
    fn test_exclude_glob_patterns() {
        assert!(matches_exclude_pattern("foo.min.js", "*.min.js"));
        assert!(matches_exclude_pattern("dist/bundle.min.js", "*.min.js"));
        assert!(!matches_exclude_pattern("foo.js", "*.min.js"));
    }

    #[test]
    fn test_exclude_glob_recursive() {
        assert!(matches_exclude_pattern("src/tests/foo.rs", "**/tests/**"));
        assert!(matches_exclude_pattern("tests/unit/bar.rs", "**/tests/**"));
        assert!(!matches_exclude_pattern("src/main.rs", "**/tests/**"));
    }

    #[test]
    fn test_exclude_substring_match() {
        assert!(matches_exclude_pattern("node_modules/foo/bar.js", "node_modules"));
        assert!(matches_exclude_pattern("dist/bundle.js", "dist"));
        assert!(!matches_exclude_pattern("src/index.ts", "dist"));
    }

    #[test]
    fn test_exclude_prefix_match() {
        assert!(matches_exclude_pattern("target/debug/main", "target"));
        assert!(matches_exclude_pattern("vendor/lib.js", "vendor"));
        assert!(!matches_exclude_pattern("src/target.rs", "target"));
    }

    #[test]
    fn test_exclude_component_match() {
        assert!(matches_exclude_pattern("src/tests/foo.rs", "tests"));
        assert!(matches_exclude_pattern("lib/vendor/bar.js", "vendor"));
        assert!(!matches_exclude_pattern("src/main.rs", "tests"));
    }

    // =============================================================================
    // Include Pattern Tests
    // =============================================================================

    #[test]
    fn test_include_glob_patterns() {
        assert!(matches_include_pattern("foo.rs", "*.rs"));
        assert!(matches_include_pattern("src/main.rs", "*.rs"));
        assert!(!matches_include_pattern("foo.py", "*.rs"));
    }

    #[test]
    fn test_include_glob_recursive() {
        assert!(matches_include_pattern("src/foo/bar.rs", "src/**/*.rs"));
        assert!(matches_include_pattern("src/main.rs", "src/**/*.rs"));
        assert!(!matches_include_pattern("tests/foo.rs", "src/**/*.rs"));
    }

    #[test]
    fn test_include_substring_match() {
        assert!(matches_include_pattern("src/main.rs", "src"));
        assert!(matches_include_pattern("lib/index.ts", "lib"));
        assert!(!matches_include_pattern("tests/foo.rs", "src"));
    }

    #[test]
    fn test_include_suffix_match() {
        assert!(matches_include_pattern("foo.test.ts", ".test.ts"));
        assert!(matches_include_pattern("bar.spec.js", ".spec.js"));
        assert!(!matches_include_pattern("foo.ts", ".test.ts"));
    }

    // =============================================================================
    // Generic Filtering Tests
    // =============================================================================

    #[derive(Debug, Clone)]
    struct TestFile {
        path: String,
    }

    #[test]
    fn test_apply_exclude_patterns_empty() {
        let mut files = vec![
            TestFile { path: "src/main.rs".to_owned() },
            TestFile { path: "node_modules/lib.js".to_owned() },
        ];

        apply_exclude_patterns(&mut files, &[], |f| &f.path);
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_apply_exclude_patterns_basic() {
        let mut files = vec![
            TestFile { path: "src/main.rs".to_owned() },
            TestFile { path: "node_modules/lib.js".to_owned() },
            TestFile { path: "dist/bundle.js".to_owned() },
        ];

        let exclude = vec!["node_modules".to_owned(), "dist".to_owned()];
        apply_exclude_patterns(&mut files, &exclude, |f| &f.path);

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/main.rs");
    }

    #[test]
    fn test_apply_exclude_patterns_glob() {
        let mut files = vec![
            TestFile { path: "foo.js".to_owned() },
            TestFile { path: "foo.min.js".to_owned() },
            TestFile { path: "bar.js".to_owned() },
        ];

        let exclude = vec!["*.min.js".to_owned()];
        apply_exclude_patterns(&mut files, &exclude, |f| &f.path);

        assert_eq!(files.len(), 2);
        assert!(files.iter().all(|f| !f.path.contains(".min.")));
    }

    #[test]
    fn test_apply_include_patterns_empty() {
        let mut files = vec![
            TestFile { path: "src/main.rs".to_owned() },
            TestFile { path: "src/lib.py".to_owned() },
        ];

        apply_include_patterns(&mut files, &[], |f| &f.path);
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_apply_include_patterns_basic() {
        let mut files = vec![
            TestFile { path: "src/main.rs".to_owned() },
            TestFile { path: "src/lib.py".to_owned() },
            TestFile { path: "src/index.ts".to_owned() },
        ];

        let include = vec!["*.rs".to_owned(), "*.ts".to_owned()];
        apply_include_patterns(&mut files, &include, |f| &f.path);

        assert_eq!(files.len(), 2);
        assert!(files.iter().any(|f| f.path.ends_with(".rs")));
        assert!(files.iter().any(|f| f.path.ends_with(".ts")));
    }

    #[test]
    fn test_apply_include_patterns_substring() {
        let mut files = vec![
            TestFile { path: "src/main.rs".to_owned() },
            TestFile { path: "tests/test.rs".to_owned() },
            TestFile { path: "lib/index.ts".to_owned() },
        ];

        let include = vec!["src".to_owned()];
        apply_include_patterns(&mut files, &include, |f| &f.path);

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/main.rs");
    }

    #[test]
    fn test_compile_patterns() {
        let patterns = vec!["*.rs".to_owned(), "*.ts".to_owned(), "src/**/*.js".to_owned()];

        let compiled = compile_patterns(&patterns);
        assert_eq!(compiled.len(), 3);
    }

    #[test]
    fn test_compile_patterns_invalid() {
        let patterns = vec![
            "*.rs".to_owned(),
            "[invalid".to_owned(), // Invalid glob
            "*.ts".to_owned(),
        ];

        let compiled = compile_patterns(&patterns);
        assert_eq!(compiled.len(), 2); // Invalid pattern skipped
    }

    // =============================================================================
    // Integration Tests
    // =============================================================================

    #[test]
    fn test_exclude_then_include() {
        let mut files = vec![
            TestFile { path: "src/main.rs".to_owned() },
            TestFile { path: "src/lib.rs".to_owned() },
            TestFile { path: "src/main.test.rs".to_owned() },
            TestFile { path: "node_modules/lib.js".to_owned() },
        ];

        // First exclude test files and node_modules
        let exclude = vec!["node_modules".to_owned(), "*.test.rs".to_owned()];
        apply_exclude_patterns(&mut files, &exclude, |f| &f.path);
        assert_eq!(files.len(), 2);

        // Then include only Rust files
        let include = vec!["*.rs".to_owned()];
        apply_include_patterns(&mut files, &include, |f| &f.path);
        assert_eq!(files.len(), 2);
        assert!(files.iter().all(|f| f.path.ends_with(".rs")));
    }

    #[test]
    fn test_pattern_cache() {
        // First call compiles pattern
        let pattern1 = compile_pattern("*.rs");
        assert!(pattern1.is_some());

        // Second call uses cache
        let pattern2 = compile_pattern("*.rs");
        assert!(pattern2.is_some());

        // Patterns should be equal
        assert!(pattern1.unwrap().matches("foo.rs"));
        assert!(pattern2.unwrap().matches("foo.rs"));
    }
}