Skip to main content

notify/
filter.rs

1//! Ignoring paths, see [`Config::with_ignored`](crate::Config::with_ignored)
2
3use std::{fmt, fs::FileType, path::Path, sync::Arc};
4use walkdir::WalkDir;
5
6/// The type of a path passed to an [`IgnoreFilter`].
7#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
8pub enum EntryKind {
9    /// The path is a directory.
10    Dir,
11
12    /// The path is anything but a directory.
13    File,
14
15    /// The watcher cannot tell, for example because the path does not exist.
16    Unknown,
17}
18
19impl From<FileType> for EntryKind {
20    fn from(file_type: FileType) -> Self {
21        if file_type.is_dir() {
22            EntryKind::Dir
23        } else {
24            EntryKind::File
25        }
26    }
27}
28
29type Ignored = dyn Fn(&Path, EntryKind) -> bool + Send + Sync;
30
31/// The ignore filter of a watcher, see [`Config::with_ignored`](crate::Config::with_ignored).
32///
33/// The default filter ignores nothing. Clones share the same filter function.
34#[derive(Clone, Default)]
35pub struct IgnoreFilter(Option<Arc<Ignored>>);
36
37impl IgnoreFilter {
38    /// Creates a filter that ignores the paths for which `ignored` returns `true`.
39    pub fn new(ignored: impl Fn(&Path, EntryKind) -> bool + Send + Sync + 'static) -> Self {
40        Self(Some(Arc::new(ignored)))
41    }
42
43    /// Returns whether the filter ignores `path`.
44    #[must_use]
45    pub fn is_ignored(&self, path: &Path, kind: EntryKind) -> bool {
46        self.0.as_ref().is_some_and(|ignored| ignored(path, kind))
47    }
48
49    /// Like [`IgnoreFilter::is_ignored`], but looks up the kind of `path` in the file system.
50    #[must_use]
51    pub fn is_path_ignored(&self, path: &Path) -> bool {
52        // no need to look up the kind if nothing is ignored
53        self.0.is_some() && {
54            let kind = path
55                .metadata()
56                .map_or(EntryKind::Unknown, |metadata| metadata.file_type().into());
57            self.is_ignored(path, kind)
58        }
59    }
60
61    /// Walks a directory tree, skipping ignored entries and everything inside them.
62    ///
63    /// The root of the walk is not filtered, the caller has already checked it.
64    pub(crate) fn walk(
65        &self,
66        walk_dir: WalkDir,
67    ) -> impl Iterator<Item = walkdir::Result<walkdir::DirEntry>> + use<> {
68        let filter = self.clone();
69        walk_dir.into_iter().filter_entry(move |entry| {
70            entry.depth() == 0 || !filter.is_ignored(entry.path(), entry.file_type().into())
71        })
72    }
73}
74
75impl fmt::Debug for IgnoreFilter {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.write_str(match self.0 {
78            Some(_) => "IgnoreFilter(Some(..))",
79            None => "IgnoreFilter(None)",
80        })
81    }
82}
83
84#[cfg(all(test, not(target_family = "wasm")))]
85mod tests {
86    use super::*;
87    use crate::test::testdir;
88    use std::{
89        fs,
90        path::PathBuf,
91        sync::{Arc, Mutex},
92    };
93
94    #[test]
95    fn default_filter_ignores_nothing() {
96        let filter = IgnoreFilter::default();
97        assert!(!filter.is_ignored(Path::new("/p/node_modules"), EntryKind::Dir));
98        assert!(!filter.is_path_ignored(Path::new("/p/node_modules/a.js")));
99    }
100
101    #[test]
102    fn is_path_ignored_looks_up_the_kind() {
103        let tmpdir = testdir();
104        let root = tmpdir.path();
105        fs::create_dir(root.join("dir")).expect("create dir");
106        fs::write(root.join("file"), "").expect("write");
107
108        let asked = Arc::new(Mutex::new(Vec::new()));
109        let filter = IgnoreFilter::new({
110            let asked = Arc::clone(&asked);
111            move |path, kind| {
112                asked.lock().unwrap().push((path.to_path_buf(), kind));
113                true
114            }
115        });
116        assert!(filter.is_path_ignored(&root.join("dir")));
117        assert!(filter.is_path_ignored(&root.join("file")));
118        assert!(filter.is_path_ignored(&root.join("missing")));
119
120        assert_eq!(
121            *asked.lock().unwrap(),
122            [
123                (root.join("dir"), EntryKind::Dir),
124                (root.join("file"), EntryKind::File),
125                (root.join("missing"), EntryKind::Unknown),
126            ]
127        );
128    }
129
130    #[test]
131    fn walk_does_not_descend_into_ignored_directories() {
132        let tmpdir = testdir();
133        let root = tmpdir.path();
134        fs::create_dir_all(root.join("node_modules/pkg")).expect("create dir");
135        fs::write(root.join("node_modules/pkg/index.js"), "").expect("write");
136        fs::create_dir(root.join("src")).expect("create dir");
137        fs::write(root.join("src/index.js"), "").expect("write");
138
139        let asked = Arc::new(Mutex::new(Vec::new()));
140        let filter = IgnoreFilter::new({
141            let asked = Arc::clone(&asked);
142            move |path, _| {
143                asked.lock().unwrap().push(path.to_path_buf());
144                path.file_name().is_some_and(|name| name == "node_modules")
145            }
146        });
147
148        let mut walked: Vec<PathBuf> = filter
149            .walk(WalkDir::new(root))
150            .map(|entry| entry.expect("walk").into_path())
151            .collect();
152        walked.sort();
153        assert_eq!(
154            walked,
155            [
156                root.to_path_buf(),
157                root.join("src"),
158                root.join("src/index.js")
159            ]
160        );
161
162        // the root is not filtered, and the entries of an ignored directory are never seen
163        let mut asked = std::mem::take(&mut *asked.lock().unwrap());
164        asked.sort();
165        assert_eq!(
166            asked,
167            [
168                root.join("node_modules"),
169                root.join("src"),
170                root.join("src/index.js")
171            ]
172        );
173    }
174}
175
176/// The observable behavior must be the same on every backend, so these tests run against the
177/// recommended watcher of the platform.
178#[cfg(all(test, not(target_family = "wasm")))]
179mod watcher_tests {
180    use crate::{RecommendedWatcher, RecursiveMode, TargetMode, WatchMode, Watcher, test::*};
181    use std::{fs, path::Path};
182
183    fn watcher() -> (TestWatcher<RecommendedWatcher>, Receiver) {
184        ignoring_channel()
185    }
186
187    /// Returns the paths of all events, which must never contain an ignored path.
188    fn event_paths(rx: &mut Receiver, root: &Path) -> Vec<std::path::PathBuf> {
189        let paths: Vec<_> = rx.iter().flat_map(|event| event.paths).collect();
190        for path in &paths {
191            let below_root = path.strip_prefix(root).unwrap_or(path);
192            assert!(
193                !is_ignored(below_root),
194                "ignored path was reported: {}",
195                path.display()
196            );
197        }
198        paths
199    }
200    #[test]
201    fn ignored_paths_are_not_reported() {
202        let tmpdir = testdir();
203        let root = tmpdir.path();
204        fs::create_dir_all(root.join("node_modules/pkg")).expect("create dir");
205        fs::create_dir(root.join("src")).expect("create dir");
206        fs::create_dir(root.join("lib")).expect("create dir");
207
208        let (mut watcher, mut rx) = watcher();
209        watcher.watch_recursively(root);
210
211        // existing ignored directory
212        fs::write(root.join("node_modules/pkg/index.js"), "").expect("write");
213        // ignored directory created while watching
214        fs::create_dir(root.join("src/node_modules")).expect("create dir");
215        fs::write(root.join("src/node_modules/index.js"), "").expect("write");
216        // ignored file
217        fs::write(root.join("src/debug.log"), "").expect("write");
218        fs::remove_file(root.join("src/debug.log")).expect("remove");
219        fs::remove_dir_all(root.join("src/node_modules")).expect("remove dir");
220
221        // kqueue re-registers a directory when a sub directory comes or goes and may miss other
222        // events in it meanwhile, so use a different directory
223        fs::write(root.join("lib/index.js"), "").expect("write");
224
225        let paths = event_paths(&mut rx, root);
226        assert!(paths.contains(&root.join("lib/index.js")), "{paths:#?}");
227    }
228
229    #[test]
230    fn rename_to_an_ignored_path_only_reports_the_other_path() {
231        let tmpdir = testdir();
232        let root = tmpdir.path();
233        fs::write(root.join("a.js"), "").expect("write");
234        fs::write(root.join("b.log"), "").expect("write");
235
236        let (mut watcher, mut rx) = watcher();
237        watcher.watch_recursively(root);
238
239        fs::rename(root.join("a.js"), root.join("a.log")).expect("rename");
240        fs::rename(root.join("b.log"), root.join("b.js")).expect("rename");
241
242        let paths = event_paths(&mut rx, root);
243        assert!(paths.contains(&root.join("a.js")), "{paths:#?}");
244        assert!(paths.contains(&root.join("b.js")), "{paths:#?}");
245    }
246
247    #[test]
248    fn watching_an_ignored_path_does_nothing() {
249        let tmpdir = testdir();
250        let root = tmpdir.path();
251        let pkg = root.join("node_modules/pkg");
252        fs::create_dir_all(&pkg).expect("create dir");
253        fs::write(root.join("debug.log"), "").expect("write");
254
255        let (mut watcher, mut rx) = watcher();
256        watcher.watch_recursively(root);
257        watcher.watch_recursively(root.join("node_modules"));
258        watcher.watch_recursively(&pkg);
259        watcher.watch_nonrecursively(root.join("debug.log"));
260        let no_track = WatchMode {
261            recursive_mode: RecursiveMode::NonRecursive,
262            target_mode: TargetMode::NoTrack,
263        };
264        watcher.watch(root.join("node_modules/missing"), no_track);
265
266        fs::write(pkg.join("index.js"), "").expect("write");
267        fs::write(root.join("debug.log"), "123").expect("write");
268        fs::write(root.join("index.js"), "").expect("write");
269
270        let paths = event_paths(&mut rx, root);
271        assert!(paths.contains(&root.join("index.js")), "{paths:#?}");
272
273        watcher.watcher.unwatch(&pkg).expect("unwatch");
274        watcher
275            .watcher
276            .unwatch(&root.join("debug.log"))
277            .expect("unwatch");
278    }
279}