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
//! Ignore pattern matching for file tree filtering
//!
//! This module provides functionality to filter files and directories based on:
//! - .gitignore patterns
//! - Custom glob patterns
//! - Hidden file detection
//!
//! Uses the `ignore` crate which provides robust .gitignore parsing
//! compatible with git's ignore rules.
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
/// Status of a file/directory with respect to ignore patterns
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IgnoreStatus {
/// File is visible and not ignored
Visible,
/// File is ignored by .gitignore
GitIgnored,
/// File is hidden (starts with .)
Hidden,
/// File is ignored by custom pattern
CustomIgnored,
}
/// Manages ignore patterns for file filtering
#[derive(Debug)]
pub struct IgnorePatterns {
/// Gitignore matchers per directory
/// Key: directory path, Value: gitignore rules for that directory
gitignores: Vec<(PathBuf, Gitignore)>,
/// Mtime of each loaded .gitignore at load time. Used to detect
/// external edits and deletions during the file-tree poll.
gitignore_mtimes: HashMap<PathBuf, SystemTime>,
/// Custom glob patterns to ignore
custom_patterns: Vec<String>,
/// Whether to show hidden files (starting with .)
show_hidden: bool,
/// Whether to show gitignored files
show_gitignored: bool,
/// Whether to show custom ignored files
show_custom_ignored: bool,
}
impl IgnorePatterns {
/// Create a new ignore pattern matcher
pub fn new() -> Self {
Self {
gitignores: Vec::new(),
gitignore_mtimes: HashMap::new(),
custom_patterns: Vec::new(),
show_hidden: false,
show_gitignored: false,
show_custom_ignored: false,
}
}
/// Install a gitignore for `dir` from already-read bytes.
///
/// I/O lives in the caller (the editor's filesystem authority), keeping
/// this module pure so it works uniformly over local and remote trees.
/// Pass `mtime` so the poll can later detect external changes.
pub fn load_gitignore_from_bytes(
&mut self,
dir: &Path,
contents: &[u8],
mtime: Option<SystemTime>,
) {
let mut builder = GitignoreBuilder::new(dir);
let source = dir.join(".gitignore");
for line in contents.split(|&b| b == b'\n') {
let line = std::str::from_utf8(line).unwrap_or("");
if let Err(e) = builder.add_line(Some(source.clone()), line) {
tracing::warn!("Malformed .gitignore line in {:?}: {}", source, e);
}
}
match builder.build() {
Ok(gitignore) => {
self.gitignores.retain(|(path, _)| path != dir);
self.gitignores.push((dir.to_path_buf(), gitignore));
if let Some(mtime) = mtime {
self.gitignore_mtimes.insert(dir.to_path_buf(), mtime);
} else {
self.gitignore_mtimes.remove(dir);
}
}
Err(e) => {
tracing::warn!("Failed to build .gitignore for {:?}: {}", dir, e);
}
}
}
/// Drop any loaded gitignore for `dir`.
pub fn remove_gitignore(&mut self, dir: &Path) {
self.gitignores.retain(|(d, _)| d != dir);
self.gitignore_mtimes.remove(dir);
}
/// Dirs for which a gitignore is currently loaded.
pub fn loaded_gitignore_dirs(&self) -> Vec<PathBuf> {
self.gitignores.iter().map(|(d, _)| d.clone()).collect()
}
/// Mtime recorded when the gitignore for `dir` was last loaded.
pub fn stored_gitignore_mtime(&self, dir: &Path) -> Option<SystemTime> {
self.gitignore_mtimes.get(dir).copied()
}
/// Add a custom glob pattern to ignore
///
/// Examples: "*.o", "target/", "node_modules/"
pub fn add_custom_pattern(&mut self, pattern: String) {
if !self.custom_patterns.contains(&pattern) {
self.custom_patterns.push(pattern);
}
}
/// Remove a custom pattern
pub fn remove_custom_pattern(&mut self, pattern: &str) {
self.custom_patterns.retain(|p| p != pattern);
}
/// Check if a path should be ignored
///
/// Each filter (hidden / custom / gitignored) is evaluated independently:
/// a file is hidden from the tree if *any* enabled filter matches it. This
/// way a file that is both hidden and gitignored still disappears when
/// gitignored files are hidden, even if hidden files are shown.
pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
if !self.show_hidden && is_hidden_name(path) {
return true;
}
if !self.show_custom_ignored && self.matches_custom_pattern(path) {
return true;
}
if !self.show_gitignored && self.matches_gitignore(path, is_dir) {
return true;
}
false
}
/// Get the ignore status of a path
///
/// This is useful for rendering (e.g., gray out ignored files)
pub fn get_status(&self, path: &Path, is_dir: bool) -> IgnoreStatus {
if is_hidden_name(path) {
return IgnoreStatus::Hidden;
}
// Check custom patterns
if self.matches_custom_pattern(path) {
return IgnoreStatus::CustomIgnored;
}
// Check gitignore
if self.matches_gitignore(path, is_dir) {
return IgnoreStatus::GitIgnored;
}
IgnoreStatus::Visible
}
/// Check if path matches any .gitignore rules
fn matches_gitignore(&self, path: &Path, is_dir: bool) -> bool {
// Find the most specific .gitignore (deepest directory)
// that could apply to this path
for (gitignore_dir, gitignore) in &self.gitignores {
// A .gitignore at dir X governs entries *inside* X, not X itself —
// otherwise a `*` pattern would hide the directory it lives in.
if path.starts_with(gitignore_dir) && path != gitignore_dir.as_path() {
let relative_path = path.strip_prefix(gitignore_dir).unwrap_or(path);
let matched = gitignore.matched(relative_path, is_dir);
if matched.is_ignore() {
return true;
}
}
}
false
}
/// Check if path matches any custom patterns
fn matches_custom_pattern(&self, path: &Path) -> bool {
let path_str = path.to_string_lossy();
for pattern in &self.custom_patterns {
// Simple pattern matching (could be improved with glob crate)
if pattern.ends_with('/') {
// Directory pattern
if path_str.contains(pattern.trim_end_matches('/')) {
return true;
}
} else if pattern.starts_with('*') {
// Extension pattern like "*.o"
let ext = pattern.trim_start_matches('*');
if path_str.ends_with(ext) {
return true;
}
} else {
// Exact match
if path_str.contains(pattern) {
return true;
}
}
}
false
}
/// Set whether to show hidden files
pub fn set_show_hidden(&mut self, show: bool) {
self.show_hidden = show;
}
/// Get whether hidden files are shown
pub fn show_hidden(&self) -> bool {
self.show_hidden
}
/// Set whether to show gitignored files
pub fn set_show_gitignored(&mut self, show: bool) {
self.show_gitignored = show;
}
/// Get whether gitignored files are shown
pub fn show_gitignored(&self) -> bool {
self.show_gitignored
}
/// Set whether to show custom ignored files
pub fn set_show_custom_ignored(&mut self, show: bool) {
self.show_custom_ignored = show;
}
/// Toggle showing gitignored files
pub fn toggle_show_gitignored(&mut self) {
self.show_gitignored = !self.show_gitignored;
}
/// Toggle showing hidden files
pub fn toggle_show_hidden(&mut self) {
self.show_hidden = !self.show_hidden;
}
/// Clear all gitignore rules
pub fn clear_gitignores(&mut self) {
self.gitignores.clear();
self.gitignore_mtimes.clear();
}
/// Clear all custom patterns
pub fn clear_custom_patterns(&mut self) {
self.custom_patterns.clear();
}
/// Get number of loaded .gitignore files
pub fn gitignore_count(&self) -> usize {
self.gitignores.len()
}
}
impl Default for IgnorePatterns {
fn default() -> Self {
Self::new()
}
}
fn is_hidden_name(path: &Path) -> bool {
path.file_name()
.and_then(|n| n.to_str())
.map(|n| n.starts_with('.') && n != "." && n != "..")
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hidden_file_detection() {
let patterns = IgnorePatterns::new();
assert_eq!(
patterns.get_status(Path::new("/foo/.hidden"), false),
IgnoreStatus::Hidden
);
assert_eq!(
patterns.get_status(Path::new("/foo/visible.txt"), false),
IgnoreStatus::Visible
);
// . and .. should not be considered hidden
assert_eq!(
patterns.get_status(Path::new("."), true),
IgnoreStatus::Visible
);
assert_eq!(
patterns.get_status(Path::new(".."), true),
IgnoreStatus::Visible
);
}
#[test]
fn test_custom_patterns() {
let mut patterns = IgnorePatterns::new();
patterns.add_custom_pattern("*.o".to_string());
patterns.add_custom_pattern("target/".to_string());
assert_eq!(
patterns.get_status(Path::new("/foo/main.o"), false),
IgnoreStatus::CustomIgnored
);
assert_eq!(
patterns.get_status(Path::new("/foo/target/debug"), true),
IgnoreStatus::CustomIgnored
);
assert_eq!(
patterns.get_status(Path::new("/foo/src/main.rs"), false),
IgnoreStatus::Visible
);
}
#[test]
fn test_gitignore_loading() {
let mut patterns = IgnorePatterns::new();
patterns.load_gitignore_from_bytes(
Path::new("/foo"),
b"*.log\nbuild/\n# Comment\n!important.log\n",
None,
);
assert_eq!(patterns.gitignore_count(), 1);
}
#[test]
fn test_show_hidden_toggle() {
let mut patterns = IgnorePatterns::new();
let hidden_path = Path::new("/foo/.hidden");
// Initially hidden files are not shown
assert!(!patterns.show_hidden());
assert!(patterns.is_ignored(hidden_path, false));
// Toggle to show hidden files
patterns.toggle_show_hidden();
assert!(patterns.show_hidden());
assert!(!patterns.is_ignored(hidden_path, false));
}
#[test]
fn test_show_gitignored_toggle() {
let mut patterns = IgnorePatterns::new();
assert!(!patterns.show_gitignored());
patterns.toggle_show_gitignored();
assert!(patterns.show_gitignored());
patterns.set_show_gitignored(false);
assert!(!patterns.show_gitignored());
}
#[test]
fn test_hidden_gitignored_respects_gitignore_filter() {
// Regression test for #1388: a file that is both hidden (starts with '.')
// and matched by .gitignore must stay hidden when `show_gitignored` is
// false, even if `show_hidden` is true. Hidden ≠ gitignored, and the
// user's choice to hide gitignored files should take precedence.
let root = Path::new("/repo");
let mut patterns = IgnorePatterns::new();
patterns.load_gitignore_from_bytes(root, b".DS_Store\n", None);
patterns.set_show_hidden(true);
patterns.set_show_gitignored(false);
let ds_store = root.join(".DS_Store");
assert!(
patterns.is_ignored(&ds_store, false),
".DS_Store is gitignored; should be hidden despite show_hidden=true"
);
// A hidden file NOT in .gitignore should still be shown.
let gitignore_file = root.join(".gitignore");
assert!(
!patterns.is_ignored(&gitignore_file, false),
".gitignore is hidden but not gitignored; should be visible \
when show_hidden=true"
);
// With show_hidden=false, the hidden filter hides .DS_Store on its own
// regardless of the gitignore filter state.
patterns.set_show_hidden(false);
patterns.set_show_gitignored(true);
assert!(
patterns.is_ignored(&ds_store, false),
"show_hidden=false still hides .DS_Store (hidden filter)"
);
// Both filters disabled → fully visible.
patterns.set_show_hidden(true);
patterns.set_show_gitignored(true);
assert!(!patterns.is_ignored(&ds_store, false));
}
#[test]
fn test_multiple_gitignores() {
let root = Path::new("/repo");
let sub = root.join("subdir");
let mut patterns = IgnorePatterns::new();
patterns.load_gitignore_from_bytes(root, b"*.tmp\n", None);
patterns.load_gitignore_from_bytes(&sub, b"*.bak\n", None);
assert_eq!(patterns.gitignore_count(), 2);
}
}