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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! Pattern matching for ignore rules with config integration
use crate::error::ConfigError;
use crate::fs_utils::GlobMatcher;
use std::borrow::Cow;
use std::collections::HashSet;
use std::fmt;
use std::path::Path;
/// Default binary file extensions to ignore.
///
/// Single source of truth — used by [`IgnorePatterns::default_extensions`]
/// and by property tests to avoid the defaults and test expectations
/// drifting apart.
const DEFAULT_IGNORE_EXTENSIONS: &[&str] = &[
"png", "jpg", "jpeg", "gif", "bmp", "pdf", "zip", "tar", "gz", "xz", "bz2", "exe", "dll", "so",
"bin", "iso", "img", "mp3", "mp4", "avi", "mkv", "mov", "wmv", "flv", "swf", "webm",
];
/// Default directory names to ignore.
///
/// Single source of truth — see [`DEFAULT_IGNORE_EXTENSIONS`] for rationale.
const DEFAULT_IGNORE_DIRECTORIES: &[&str] = &[".git", "__pycache__", ".venv", "node_modules"];
/// Default specific filenames to ignore.
///
/// Single source of truth — see [`DEFAULT_IGNORE_EXTENSIONS`] for rationale.
const DEFAULT_IGNORE_FILES: &[&str] = &[".terraform.lock.hcl"];
/// Discriminant for the kind of simple (non-glob) ignore pattern being
/// validated.
///
/// Used by [`IgnorePatterns::validate_simple_pattern`] so the compiler
/// can enforce exhaustive handling when a new variant is added.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PatternKind {
/// File extension (e.g. `"png"`). Must be lowercase, no leading dot.
Extension,
/// Directory name (e.g. `"build"`). No path separators.
Directory,
/// Filename (e.g. `"secret.key"`). No path separators.
Filename,
}
impl fmt::Display for PatternKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Extension => f.write_str("extension"),
Self::Directory => f.write_str("directory"),
Self::Filename => f.write_str("filename"),
}
}
}
/// Container for all ignore patterns
#[derive(Debug, Clone)]
pub struct IgnorePatterns {
/// File extensions that should be ignored (e.g., "png", "jpg")
extensions: HashSet<String>,
/// Directory names that should be ignored (e.g., ".git", "__pycache__")
directories: HashSet<String>,
/// Specific filenames that should be ignored (e.g., ".terraform.lock.hcl")
files: HashSet<String>,
/// Glob patterns for complex matching (e.g., "src/**/*.rs")
globs: GlobMatcher,
}
impl Default for IgnorePatterns {
fn default() -> Self {
Self {
extensions: Self::default_extensions(),
directories: Self::default_directories(),
files: Self::default_files(),
globs: GlobMatcher::empty(),
}
}
}
impl IgnorePatterns {
/// Create patterns from config values, validating and merging with defaults.
///
/// All simple pattern validation (empty strings, glob metacharacters,
/// path separators, leading dots on extensions) is performed here,
/// making this the single gate through which user-supplied patterns
/// must pass. Callers do not need to pre-validate.
///
/// Merges user-provided extensions, directories, and filenames with
/// the built-in defaults. Glob patterns are purely user-supplied
/// (there are no default globs).
///
/// # Arguments
///
/// * `extensions` - Additional extensions to ignore (merged with defaults)
/// * `directories` - Additional directories to ignore (merged with defaults)
/// * `files` - Additional filenames to ignore (merged with defaults)
/// * `globs` - List of glob patterns to ignore (no defaults; user-only)
///
/// # Errors
///
/// Returns [`ConfigError::InvalidPattern`] if any pattern fails validation
/// or any glob pattern fails to compile.
pub(crate) fn from_config(
extensions: &[String],
directories: &[String],
files: &[String],
globs: &[String],
) -> Result<Self, ConfigError> {
let validated_extensions =
Self::validate_simple_patterns(extensions, PatternKind::Extension)?;
let validated_directories =
Self::validate_simple_patterns(directories, PatternKind::Directory)?;
let validated_files = Self::validate_simple_patterns(files, PatternKind::Filename)?;
let mut patterns = Self::default();
// Merge user patterns into the default sets
patterns.extensions.extend(validated_extensions);
patterns.directories.extend(validated_directories);
patterns.files.extend(validated_files);
// Compile user globs — fail loudly so the user can fix their config.
// There are no default globs; an empty slice leaves GlobMatcher::empty().
if !globs.is_empty() {
patterns.globs = GlobMatcher::new(globs).map_err(|e| ConfigError::InvalidPattern {
pattern: globs.join(", "),
pattern_type: "glob".to_string(),
help: format!("Failed to compile glob patterns: {e}"),
})?;
}
Ok(patterns)
}
/// Validate simple (non-glob) ignore patterns.
///
/// The `kind` discriminant controls which additional checks apply
/// (e.g. extensions reject leading dots and are lowercased, while
/// directory/filename patterns are stored as-is). Because
/// `PatternKind` is an enum the compiler will force us to handle
/// any new variant we add in the future.
///
/// Path separators are rejected for **all** kinds — none of these
/// simple patterns are meant to express hierarchical paths. Use
/// glob patterns (`ignore_globs`) for path-based matching.
fn validate_simple_patterns(
patterns: &[String],
kind: PatternKind,
) -> Result<Vec<String>, ConfigError> {
let mut validated = Vec::with_capacity(patterns.len());
for pattern in patterns {
// Reject empty patterns — they would silently match files
// without extensions or produce meaningless HashSet entries
if pattern.is_empty() {
return Err(ConfigError::InvalidPattern {
pattern: String::new(),
pattern_type: kind.to_string(),
help: format!("{kind} patterns must not be empty"),
});
}
// Check for glob metacharacters
if pattern.contains(&['*', '?', '[', ']'][..]) {
return Err(ConfigError::InvalidPattern {
pattern: pattern.clone(),
pattern_type: kind.to_string(),
help:
"Patterns cannot contain glob metacharacters (*, ?, [, ]) in this version"
.to_string(),
});
}
// Reject path separators for all simple pattern kinds.
// Extensions, directory names, and filenames are all
// single-component — use ignore_globs for path matching.
if pattern.chars().any(std::path::is_separator) {
return Err(ConfigError::InvalidPattern {
pattern: pattern.clone(),
pattern_type: kind.to_string(),
help: format!(
"{kind} patterns cannot contain path separators; \
use ignore_globs for path-based patterns"
),
});
}
match kind {
PatternKind::Extension => {
if pattern.starts_with('.') {
return Err(ConfigError::InvalidPattern {
pattern: pattern.clone(),
pattern_type: kind.to_string(),
help: "Extensions should not include the leading dot".to_string(),
});
}
validated.push(pattern.to_lowercase());
}
PatternKind::Directory | PatternKind::Filename => {
validated.push(pattern.clone());
}
}
}
Ok(validated)
}
/// Returns the default set of binary file extensions to ignore
fn default_extensions() -> HashSet<String> {
DEFAULT_IGNORE_EXTENSIONS
.iter()
.map(std::string::ToString::to_string)
.collect()
}
/// Returns the default set of directories to ignore
fn default_directories() -> HashSet<String> {
DEFAULT_IGNORE_DIRECTORIES
.iter()
.map(std::string::ToString::to_string)
.collect()
}
/// Returns the default set of specific files to ignore
fn default_files() -> HashSet<String> {
DEFAULT_IGNORE_FILES
.iter()
.map(std::string::ToString::to_string)
.collect()
}
/// Check if a file extension should be ignored
///
/// # Performance
///
/// Uses `Cow` to avoid allocation when the extension is already lowercase
/// (which is the common case).
#[must_use]
pub fn should_ignore_extension(&self, ext: &str) -> bool {
// Optimization: Avoid allocation if the extension contains no uppercase characters
let ext_lower = if ext.chars().any(char::is_uppercase) {
Cow::Owned(ext.to_lowercase())
} else {
Cow::Borrowed(ext)
};
self.extensions.contains(ext_lower.as_ref())
}
/// Check if a directory should be ignored
#[must_use]
pub fn should_ignore_directory(&self, name: &str) -> bool {
self.directories.contains(name)
}
/// Check if a specific file should be ignored
#[must_use]
pub fn should_ignore_file(&self, name: &str) -> bool {
self.files.contains(name)
}
/// Check if a path matches any configured glob pattern
#[must_use]
pub fn should_ignore_glob(&self, path: &Path) -> bool {
self.globs.is_match(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn test_from_config_with_custom_patterns() {
let patterns = IgnorePatterns::from_config(
&["custom".to_string()],
&["build".to_string()],
&["secret.key".to_string()],
&["*.log".to_string()],
)
.unwrap();
assert!(patterns.should_ignore_extension("custom"));
assert!(patterns.should_ignore_directory("build"));
assert!(patterns.should_ignore_file("secret.key"));
assert!(patterns.should_ignore_extension("png")); // defaults still present
assert!(patterns.should_ignore_glob(Path::new("app.log")));
}
#[test]
fn test_from_config_rejects_invalid_glob() {
let result = IgnorePatterns::from_config(&[], &[], &[], &["[invalid".to_string()]);
assert!(result.is_err());
}
#[test]
fn test_from_config_rejects_empty_extension() {
let result = IgnorePatterns::from_config(&[String::new()], &[], &[], &[]);
assert!(matches!(
result.unwrap_err(),
ConfigError::InvalidPattern { .. }
));
}
#[test]
fn test_from_config_rejects_empty_directory() {
let result = IgnorePatterns::from_config(&[], &[String::new()], &[], &[]);
assert!(matches!(
result.unwrap_err(),
ConfigError::InvalidPattern { .. }
));
}
#[test]
fn test_from_config_rejects_empty_file() {
let result = IgnorePatterns::from_config(&[], &[], &[String::new()], &[]);
assert!(matches!(
result.unwrap_err(),
ConfigError::InvalidPattern { .. }
));
}
#[test]
fn test_from_config_rejects_extension_with_leading_dot() {
let result = IgnorePatterns::from_config(&[".png".to_string()], &[], &[], &[]);
assert!(matches!(
result.unwrap_err(),
ConfigError::InvalidPattern { .. }
));
}
#[test]
fn test_from_config_rejects_path_separator_in_extension() {
let result = IgnorePatterns::from_config(&["foo/bar".to_string()], &[], &[], &[]);
assert!(matches!(
result.unwrap_err(),
ConfigError::InvalidPattern { .. }
));
}
#[test]
fn test_from_config_rejects_glob_metachar_in_directory() {
let result = IgnorePatterns::from_config(&[], &["build*".to_string()], &[], &[]);
assert!(matches!(
result.unwrap_err(),
ConfigError::InvalidPattern { .. }
));
}
fn arb_case_variation(s: &'static str) -> impl Strategy<Value = String> {
proptest::collection::vec(proptest::bool::ANY, s.len()).prop_map(move |bits| {
s.chars()
.zip(bits)
.map(|(c, upper)| {
if upper {
c.to_uppercase().to_string()
} else {
c.to_lowercase().to_string()
}
})
.collect()
})
}
proptest! {
/// `should_ignore_extension` must never panic, regardless of input.
#[test]
fn test_extension_matching_never_panics(s in "\\PC{0,10}") {
let patterns = IgnorePatterns::default();
let _ = patterns.should_ignore_extension(&s);
}
/// `should_ignore_directory` must never panic, regardless of input.
#[test]
fn test_directory_matching_never_panics(s in "\\PC{0,64}") {
let patterns = IgnorePatterns::default();
let _ = patterns.should_ignore_directory(&s);
}
/// `should_ignore_file` must never panic, regardless of input.
#[test]
fn test_file_matching_never_panics(s in "\\PC{0,64}") {
let patterns = IgnorePatterns::default();
let _ = patterns.should_ignore_file(&s);
}
/// Every default extension is ignored regardless of casing.
#[test]
fn test_known_extensions_always_ignored_any_case(
ext_idx in 0..DEFAULT_IGNORE_EXTENSIONS.len(),
) {
let ext = DEFAULT_IGNORE_EXTENSIONS[ext_idx];
let patterns = IgnorePatterns::default();
// Lowercase
prop_assert!(patterns.should_ignore_extension(ext));
// Uppercase
prop_assert!(patterns.should_ignore_extension(&ext.to_uppercase()));
}
/// Case-insensitivity holds for arbitrary mixed-case variations.
#[test]
fn test_extension_case_insensitive_arbitrary(
variation in prop::sample::select(DEFAULT_IGNORE_EXTENSIONS.to_vec())
.prop_flat_map(arb_case_variation)
) {
let patterns = IgnorePatterns::default();
prop_assert!(
patterns.should_ignore_extension(&variation),
"expected {:?} to be ignored", variation
);
}
/// User-added extensions are case-insensitively matched for
/// arbitrary mixed-case queries.
#[test]
fn test_user_extension_case_insensitive_arbitrary(
ext in "[a-z]{2,8}",
query_upper_bits in proptest::collection::vec(proptest::bool::ANY, 2..=8),
) {
// from_config receives raw extensions; validation lowercases them
let patterns = IgnorePatterns::from_config(
std::slice::from_ref(&ext),
&[],
&[],
&[],
).unwrap();
// Build an arbitrary-case variation of the same extension
let query: String = ext.chars()
.zip(query_upper_bits.iter().cycle())
.map(|(c, &upper)| {
if upper {
c.to_uppercase().to_string()
} else {
c.to_lowercase().to_string()
}
})
.collect();
prop_assert!(
patterns.should_ignore_extension(&query),
"user extension {ext:?} should match query {query:?}"
);
}
/// Every default directory is matched exactly.
#[test]
fn test_default_directories_always_matched(
dir_idx in 0..DEFAULT_IGNORE_DIRECTORIES.len(),
) {
let dir = DEFAULT_IGNORE_DIRECTORIES[dir_idx];
let patterns = IgnorePatterns::default();
prop_assert!(patterns.should_ignore_directory(dir));
}
/// Every default file is matched exactly.
#[test]
fn test_default_files_always_matched(
file_idx in 0..DEFAULT_IGNORE_FILES.len(),
) {
let file = DEFAULT_IGNORE_FILES[file_idx];
let patterns = IgnorePatterns::default();
prop_assert!(patterns.should_ignore_file(file));
}
/// Strings that are not in the default sets must not be matched.
/// We generate ASCII alphanumeric strings that cannot collide
/// with any default.
#[test]
fn test_non_default_extension_not_ignored(
ext in "[a-z]{4,8}"
) {
// Filter out any accidental collisions with the default set
prop_assume!(!DEFAULT_IGNORE_EXTENSIONS.contains(&ext.as_str()));
let patterns = IgnorePatterns::default();
prop_assert!(!patterns.should_ignore_extension(&ext));
}
/// Strings not in the default directory set must not be matched.
#[test]
fn test_non_default_directory_not_ignored(
name in "[a-z]{5,12}"
) {
prop_assume!(!DEFAULT_IGNORE_DIRECTORIES.contains(&name.as_str()));
let patterns = IgnorePatterns::default();
prop_assert!(!patterns.should_ignore_directory(&name));
}
/// Strings not in the default file set must not be matched.
#[test]
fn test_non_default_file_not_ignored(
name in "[a-z]{5,12}\\.[a-z]{1,4}"
) {
prop_assume!(!DEFAULT_IGNORE_FILES.contains(&name.as_str()));
let patterns = IgnorePatterns::default();
prop_assert!(!patterns.should_ignore_file(&name));
}
/// Custom patterns added via `from_config` are always present
/// alongside defaults — i.e., defaults are never lost by merging.
#[test]
fn test_from_config_preserves_defaults(
ext in "[a-z]{4,8}",
dir in "[a-z]{5,12}",
file in "[a-z]{5,12}\\.[a-z]{1,4}",
) {
prop_assume!(!DEFAULT_IGNORE_EXTENSIONS.contains(&ext.as_str()));
prop_assume!(!DEFAULT_IGNORE_DIRECTORIES.contains(&dir.as_str()));
prop_assume!(!DEFAULT_IGNORE_FILES.contains(&file.as_str()));
let patterns = IgnorePatterns::from_config(
std::slice::from_ref(&ext),
std::slice::from_ref(&dir),
std::slice::from_ref(&file),
&[],
).unwrap();
// User patterns present
prop_assert!(patterns.should_ignore_extension(&ext));
prop_assert!(patterns.should_ignore_directory(&dir));
prop_assert!(patterns.should_ignore_file(&file));
// Defaults still present (spot-check first entry from each)
prop_assert!(patterns.should_ignore_extension(DEFAULT_IGNORE_EXTENSIONS[0]));
prop_assert!(patterns.should_ignore_directory(DEFAULT_IGNORE_DIRECTORIES[0]));
prop_assert!(patterns.should_ignore_file(DEFAULT_IGNORE_FILES[0]));
}
/// Empty strings are rejected for all simple pattern kinds
/// when going through `from_config`.
#[test]
fn test_empty_pattern_rejected_for_all_kinds(
kind in prop::sample::select(vec![0u8, 1, 2])
) {
let empty = [String::new()];
let result = match kind {
0 => IgnorePatterns::from_config(&empty, &[], &[], &[]),
1 => IgnorePatterns::from_config(&[], &empty, &[], &[]),
_ => IgnorePatterns::from_config(&[], &[], &empty, &[]),
};
let err = result.expect_err("empty pattern must be rejected");
prop_assert!(
matches!(err, ConfigError::InvalidPattern { .. }),
"unexpected error variant: {err:?}"
);
}
/// Patterns containing glob metacharacters are always rejected for
/// all simple pattern kinds through `from_config`.
#[test]
fn test_glob_metachar_rejected_for_all_kinds(
kind in prop::sample::select(vec![0u8, 1, 2]),
metachar in prop::sample::select(vec!['*', '?', '[', ']']),
prefix in "[a-z]{0,4}",
suffix in "[a-z]{0,4}",
) {
let pattern = vec![format!("{prefix}{metachar}{suffix}")];
let result = match kind {
0 => IgnorePatterns::from_config(&pattern, &[], &[], &[]),
1 => IgnorePatterns::from_config(&[], &pattern, &[], &[]),
_ => IgnorePatterns::from_config(&[], &[], &pattern, &[]),
};
let err = result.expect_err("glob metachar must be rejected");
prop_assert!(
matches!(err, ConfigError::InvalidPattern { .. }),
"unexpected error variant: {err:?}"
);
}
/// Patterns containing path separators are always rejected for all
/// simple pattern kinds through `from_config`.
#[test]
fn test_path_separator_rejected_for_all_kinds(
kind in prop::sample::select(vec![0u8, 1, 2]),
prefix in "[a-z]{1,4}",
suffix in "[a-z]{1,4}",
) {
let pattern = vec![format!("{prefix}/{suffix}")];
let result = match kind {
0 => IgnorePatterns::from_config(&pattern, &[], &[], &[]),
1 => IgnorePatterns::from_config(&[], &pattern, &[], &[]),
_ => IgnorePatterns::from_config(&[], &[], &pattern, &[]),
};
let err = result.expect_err("path separator must be rejected");
prop_assert!(
matches!(err, ConfigError::InvalidPattern { .. }),
"unexpected error variant: {err:?}"
);
}
/// Extensions with a leading dot are rejected; without are accepted
/// and lowercased — validated through `from_config`.
#[test]
fn test_extension_leading_dot_rejected(ext in "[a-zA-Z]{1,6}") {
// With leading dot → rejected
let dotted = vec![format!(".{ext}")];
let err = IgnorePatterns::from_config(&dotted, &[], &[], &[])
.expect_err("leading dot must be rejected");
prop_assert!(
matches!(err, ConfigError::InvalidPattern { .. }),
"unexpected error variant: {err:?}"
);
// Without leading dot → accepted and lowercased
let bare = vec![ext.clone()];
let patterns = IgnorePatterns::from_config(&bare, &[], &[], &[])
.expect("bare extension must validate");
prop_assert!(
patterns.should_ignore_extension(&ext),
"extension {ext:?} should be ignored after validation"
);
}
/// Valid simple patterns (no metacharacters, no path separators,
/// non-empty) always succeed for directory and filename kinds
/// through `from_config`.
#[test]
fn test_valid_simple_patterns_accepted(
kind in prop::sample::select(vec![1u8, 2]),
name in "[a-zA-Z0-9._-]{1,20}",
) {
let pattern = vec![name.clone()];
let result = match kind {
1 => IgnorePatterns::from_config(&[], &pattern, &[], &[]),
_ => IgnorePatterns::from_config(&[], &[], &pattern, &[]),
};
prop_assert!(result.is_ok(), "valid pattern {name:?} must be accepted");
}
}
}