Skip to main content

notify/
inotify.rs

1//! Watcher implementation for the inotify Linux API
2//!
3//! The inotify API provides a mechanism for monitoring filesystem events.  Inotify can be used to
4//! monitor individual files, or to monitor directories.  When a directory is monitored, inotify
5//! will return events for the directory itself, and for files inside the directory.
6
7use super::event::*;
8use super::{Config, Error, ErrorKind, EventHandler, RecursiveMode, Result, WatchMode, Watcher};
9use crate::bimap::BiHashMap;
10use crate::filter::{EntryKind, IgnoreFilter};
11use crate::{BoundSender, Receiver, Sender, TargetMode, bounded, unbounded};
12use inotify as inotify_sys;
13use inotify_sys::{EventMask, Inotify, WatchDescriptor, WatchMask};
14use rustc_hash::FxBuildHasher;
15use std::collections::HashMap;
16#[cfg(test)]
17use std::collections::HashSet;
18use std::env;
19use std::fs::metadata;
20use std::os::unix::fs::MetadataExt;
21use std::os::unix::io::AsRawFd;
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::thread;
25use walkdir::WalkDir;
26
27const INOTIFY: mio::Token = mio::Token(0);
28const MESSAGE: mio::Token = mio::Token(1);
29
30// The EventLoop will set up a mio::Poll and use it to wait for the following:
31//
32// -  messages telling it what to do
33//
34// -  events telling it that something has happened on one of the watched files.
35
36struct EventLoop {
37    running: bool,
38    poll: mio::Poll,
39    event_loop_waker: Arc<mio::Waker>,
40    event_loop_tx: Sender<EventLoopMsg>,
41    event_loop_rx: Receiver<EventLoopMsg>,
42    inotify: Option<Inotify>,
43    event_handler: Box<dyn EventHandler>,
44    watches: HashMap<PathBuf, WatchMode, FxBuildHasher>,
45    watch_handles: BiHashMap<
46        WatchDescriptor,
47        PathBuf,
48        (/* watch_self */ bool, /* is_dir */ bool),
49        FxBuildHasher,
50    >,
51    rename_event: Option<Event>,
52    follow_links: bool,
53    ignore_filter: IgnoreFilter,
54}
55
56/// Watcher implementation based on inotify
57#[derive(Debug)]
58pub struct INotifyWatcher {
59    channel: Sender<EventLoopMsg>,
60    waker: Arc<mio::Waker>,
61}
62
63enum EventLoopMsg {
64    AddWatch(PathBuf, WatchMode, Sender<Result<()>>),
65    RemoveWatch(PathBuf, Sender<Result<()>>),
66    Shutdown,
67    Configure(Config, BoundSender<Result<bool>>),
68    #[cfg(test)]
69    GetWatchHandles(BoundSender<HashSet<PathBuf>>),
70}
71
72#[inline]
73fn add_watch_by_event(
74    path: &PathBuf,
75    is_file_without_hardlinks: bool,
76    watches: &HashMap<PathBuf, WatchMode, FxBuildHasher>,
77    add_watches: &mut Vec<(PathBuf, bool, bool)>,
78) {
79    if let Some(watch_mode) = watches.get(path) {
80        add_watches.push((
81            path.to_owned(),
82            watch_mode.recursive_mode.is_recursive(),
83            is_file_without_hardlinks,
84        ));
85        return;
86    }
87
88    let Some(parent) = path.parent() else {
89        return;
90    };
91    if let Some(watch_mode) = watches.get(parent) {
92        add_watches.push((
93            path.to_owned(),
94            watch_mode.recursive_mode.is_recursive(),
95            is_file_without_hardlinks,
96        ));
97        return;
98    }
99
100    for ancestor in parent.ancestors().skip(1) {
101        if let Some(watch_mode) = watches.get(ancestor)
102            && watch_mode.recursive_mode == RecursiveMode::Recursive
103        {
104            add_watches.push((path.to_owned(), true, is_file_without_hardlinks));
105            return;
106        }
107    }
108}
109
110#[inline]
111fn remove_watch_by_event(
112    path: &PathBuf,
113    watch_handles: &BiHashMap<WatchDescriptor, PathBuf, (bool, bool), FxBuildHasher>,
114    remove_watches: &mut Vec<PathBuf>,
115) {
116    if watch_handles.contains_right(path) {
117        remove_watches.push(path.to_owned());
118    }
119}
120
121impl EventLoop {
122    pub fn new(
123        inotify: Inotify,
124        event_handler: Box<dyn EventHandler>,
125        follow_links: bool,
126        ignore_filter: IgnoreFilter,
127    ) -> Result<Self> {
128        let (event_loop_tx, event_loop_rx) = unbounded::<EventLoopMsg>();
129        let poll = mio::Poll::new()?;
130
131        let event_loop_waker = Arc::new(mio::Waker::new(poll.registry(), MESSAGE)?);
132
133        let inotify_fd = inotify.as_raw_fd();
134        let mut evented_inotify = mio::unix::SourceFd(&inotify_fd);
135        poll.registry()
136            .register(&mut evented_inotify, INOTIFY, mio::Interest::READABLE)?;
137
138        let event_loop = EventLoop {
139            running: true,
140            poll,
141            event_loop_waker,
142            event_loop_tx,
143            event_loop_rx,
144            inotify: Some(inotify),
145            event_handler,
146            watches: HashMap::default(),
147            watch_handles: BiHashMap::default(),
148            rename_event: None,
149            follow_links,
150            ignore_filter,
151        };
152        Ok(event_loop)
153    }
154
155    // Run the event loop.
156    pub fn run(self) {
157        let result = thread::Builder::new()
158            .name("notify-rs inotify loop".to_string())
159            .spawn(|| self.event_loop_thread());
160        if let Err(e) = result {
161            tracing::error!(?e, "failed to start inotify event loop thread");
162        }
163    }
164
165    fn event_loop_thread(mut self) {
166        let mut events = mio::Events::with_capacity(16);
167        loop {
168            // Wait for something to happen.
169            match self.poll.poll(&mut events, None) {
170                Err(ref e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {
171                    // System call was interrupted, we will retry
172                    // TODO: Not covered by tests (to reproduce likely need to setup signal handlers)
173                }
174                Err(e) => panic!("poll failed: {e}"),
175                Ok(()) => {}
176            }
177
178            // Process whatever happened.
179            for event in &events {
180                self.handle_event(event);
181            }
182
183            // Stop, if we're done.
184            if !self.running {
185                break;
186            }
187        }
188    }
189
190    // Handle a single event.
191    fn handle_event(&mut self, event: &mio::event::Event) {
192        match event.token() {
193            MESSAGE => {
194                // The channel is readable - handle messages.
195                self.handle_messages();
196            }
197            INOTIFY => {
198                // inotify has something to tell us.
199                self.handle_inotify();
200            }
201            _ => unreachable!(),
202        }
203    }
204
205    fn handle_messages(&mut self) {
206        while let Ok(msg) = self.event_loop_rx.try_recv() {
207            match msg {
208                EventLoopMsg::AddWatch(path, watch_mode, tx) => {
209                    let result = tx.send(self.add_watch(path, watch_mode));
210                    if let Err(e) = result {
211                        tracing::error!(?e, "failed to send AddWatch result");
212                    }
213                }
214                EventLoopMsg::RemoveWatch(path, tx) => {
215                    let result = tx.send(self.remove_watch(path));
216                    if let Err(e) = result {
217                        tracing::error!(?e, "failed to send RemoveWatch result");
218                    }
219                }
220                EventLoopMsg::Shutdown => {
221                    let result = self.remove_all_watches();
222                    if let Err(e) = result {
223                        tracing::error!(?e, "failed to remove all watches on shutdown");
224                    }
225                    if let Some(inotify) = self.inotify.take() {
226                        let result = inotify.close();
227                        if let Err(e) = result {
228                            tracing::error!(?e, "failed to close inotify instance on shutdown");
229                        }
230                    }
231                    self.running = false;
232                    break;
233                }
234                EventLoopMsg::Configure(config, tx) => {
235                    Self::configure_raw_mode(config, &tx);
236                }
237                #[cfg(test)]
238                EventLoopMsg::GetWatchHandles(tx) => {
239                    let handles: HashSet<PathBuf> = self
240                        .watch_handles
241                        .iter()
242                        .map(|(_, path, _)| path.clone())
243                        .collect();
244                    tx.send(handles).unwrap();
245                }
246            }
247        }
248    }
249
250    fn configure_raw_mode(_config: Config, tx: &BoundSender<Result<bool>>) {
251        tx.send(Ok(false))
252            .expect("configuration channel disconnected");
253    }
254
255    fn is_watched_path(watches: &HashMap<PathBuf, WatchMode, FxBuildHasher>, path: &Path) -> bool {
256        if watches.contains_key(path) {
257            return true;
258        }
259
260        let Some(parent) = path.parent() else {
261            return false;
262        };
263        if watches.contains_key(parent) {
264            return true;
265        }
266
267        parent.ancestors().skip(1).any(|ancestor| {
268            watches
269                .get(ancestor)
270                .is_some_and(|watch_mode| watch_mode.recursive_mode == RecursiveMode::Recursive)
271        })
272    }
273
274    #[expect(clippy::too_many_lines)]
275    fn handle_inotify(&mut self) {
276        let mut add_watches = Vec::new();
277        let mut remove_watches = Vec::new();
278        let mut remove_watches_no_syscall = Vec::new();
279
280        if let Some(ref mut inotify) = self.inotify {
281            let mut buffer = [0; 1024];
282            // Read all buffers available.
283            loop {
284                match inotify.read_events(&mut buffer) {
285                    Ok(events) => {
286                        let mut num_events = 0;
287                        for event in events {
288                            tracing::trace!(?event, "inotify event received");
289
290                            num_events += 1;
291                            if event.mask.contains(EventMask::Q_OVERFLOW) {
292                                let ev = Ok(Event::new(EventKind::Other).set_flag(Flag::Rescan));
293                                self.event_handler.handle_event(ev);
294                            }
295
296                            let path = match event.name {
297                                Some(name) => self
298                                    .watch_handles
299                                    .get_by_left(&event.wd)
300                                    .map(|(root, _)| root.join(name)),
301                                None => self
302                                    .watch_handles
303                                    .get_by_left(&event.wd)
304                                    .map(|(root, _)| root.clone()),
305                            };
306
307                            let Some(path) = path else {
308                                tracing::debug!(?event, "inotify event with unknown descriptor");
309                                continue;
310                            };
311
312                            // drop events of ignored entries; a watched directory itself is
313                            // never ignored
314                            let kind = if event.mask.contains(EventMask::ISDIR) {
315                                EntryKind::Dir
316                            } else {
317                                EntryKind::File
318                            };
319                            if event.name.is_some() && self.ignore_filter.is_ignored(&path, kind) {
320                                continue;
321                            }
322
323                            let mut evs = Vec::new();
324
325                            if event.mask.contains(EventMask::MOVED_FROM) {
326                                remove_watch_by_event(
327                                    &path,
328                                    &self.watch_handles,
329                                    &mut remove_watches,
330                                );
331
332                                let event = Event::new(EventKind::Modify(ModifyKind::Name(
333                                    RenameMode::From,
334                                )))
335                                .add_path(path.clone())
336                                .set_tracker(event.cookie as usize);
337
338                                self.rename_event = Some(event.clone());
339
340                                if Self::is_watched_path(&self.watches, &path) {
341                                    evs.push(event);
342                                }
343                            } else if event.mask.contains(EventMask::MOVED_TO) {
344                                if Self::is_watched_path(&self.watches, &path) {
345                                    evs.push(
346                                        Event::new(EventKind::Modify(ModifyKind::Name(
347                                            RenameMode::To,
348                                        )))
349                                        .set_tracker(event.cookie as usize)
350                                        .add_path(path.clone()),
351                                    );
352
353                                    let trackers_match =
354                                        self.rename_event.as_ref().and_then(|e| e.tracker())
355                                            == Some(event.cookie as usize);
356
357                                    if trackers_match {
358                                        let rename_event = self.rename_event.take().unwrap(); // unwrap is safe because `rename_event` must be set at this point
359                                        let from_path = rename_event.paths.first();
360                                        if from_path.is_none_or(|from_path| {
361                                            Self::is_watched_path(&self.watches, from_path)
362                                        }) {
363                                            evs.push(
364                                                Event::new(EventKind::Modify(ModifyKind::Name(
365                                                    RenameMode::Both,
366                                                )))
367                                                .set_tracker(event.cookie as usize)
368                                                .add_some_path(from_path.cloned())
369                                                .add_path(path.clone()),
370                                            );
371                                        }
372                                    }
373                                }
374
375                                let is_file_without_hardlinks = !event
376                                    .mask
377                                    .contains(EventMask::ISDIR)
378                                    && metadata(&path).is_ok_and(|m| m.is_file_without_hardlinks());
379                                add_watch_by_event(
380                                    &path,
381                                    is_file_without_hardlinks,
382                                    &self.watches,
383                                    &mut add_watches,
384                                );
385                            }
386                            if event.mask.contains(EventMask::MOVE_SELF) {
387                                remove_watch_by_event(
388                                    &path,
389                                    &self.watch_handles,
390                                    &mut remove_watches,
391                                );
392                                if Self::is_watched_path(&self.watches, &path) {
393                                    evs.push(
394                                        Event::new(EventKind::Modify(ModifyKind::Name(
395                                            RenameMode::From,
396                                        )))
397                                        .add_path(path.clone()),
398                                    );
399                                    // TODO stat the path and get to new path
400                                    // - emit To and Both events
401                                    // - change prefix for further events
402                                }
403                            }
404                            if event.mask.contains(EventMask::CREATE) {
405                                let is_dir = event.mask.contains(EventMask::ISDIR);
406                                if Self::is_watched_path(&self.watches, &path) {
407                                    evs.push(
408                                        Event::new(EventKind::Create(if is_dir {
409                                            CreateKind::Folder
410                                        } else {
411                                            CreateKind::File
412                                        }))
413                                        .add_path(path.clone()),
414                                    );
415                                }
416                                let is_file_without_hardlinks = !is_dir
417                                    && metadata(&path).is_ok_and(|m| m.is_file_without_hardlinks());
418                                add_watch_by_event(
419                                    &path,
420                                    is_file_without_hardlinks,
421                                    &self.watches,
422                                    &mut add_watches,
423                                );
424                            }
425                            if event.mask.contains(EventMask::DELETE) {
426                                if Self::is_watched_path(&self.watches, &path) {
427                                    evs.push(
428                                        Event::new(EventKind::Remove(
429                                            if event.mask.contains(EventMask::ISDIR) {
430                                                RemoveKind::Folder
431                                            } else {
432                                                RemoveKind::File
433                                            },
434                                        ))
435                                        .add_path(path.clone()),
436                                    );
437                                }
438                                remove_watch_by_event(
439                                    &path,
440                                    &self.watch_handles,
441                                    &mut remove_watches,
442                                );
443                            }
444                            if event.mask.contains(EventMask::DELETE_SELF) {
445                                let remove_kind = match self.watch_handles.get_by_right(&path) {
446                                    Some((_, (_, true))) => RemoveKind::Folder,
447                                    Some((_, (_, false))) => RemoveKind::File,
448                                    None => RemoveKind::Other,
449                                };
450                                if Self::is_watched_path(&self.watches, &path) {
451                                    evs.push(
452                                        Event::new(EventKind::Remove(remove_kind))
453                                            .add_path(path.clone()),
454                                    );
455                                }
456                                remove_watch_by_event(
457                                    &path,
458                                    &self.watch_handles,
459                                    &mut remove_watches,
460                                );
461                            }
462                            if event.mask.contains(EventMask::UNMOUNT) {
463                                if Self::is_watched_path(&self.watches, &path) {
464                                    evs.push(
465                                        Event::new(EventKind::Remove(RemoveKind::Other))
466                                            .add_path(path.clone()),
467                                    );
468                                }
469                                // The kernel has already removed this watch descriptor and will
470                                // emit IGNORED; clean up internal state without inotify_rm_watch.
471                                // ref. https://www.man7.org/linux/man-pages/man7/inotify.7.html
472                                remove_watch_by_event(
473                                    &path,
474                                    &self.watch_handles,
475                                    &mut remove_watches_no_syscall,
476                                );
477                            }
478                            if event.mask.contains(EventMask::MODIFY)
479                                && Self::is_watched_path(&self.watches, &path)
480                            {
481                                evs.push(
482                                    Event::new(EventKind::Modify(ModifyKind::Data(
483                                        DataChange::Any,
484                                    )))
485                                    .add_path(path.clone()),
486                                );
487                            }
488                            if event.mask.contains(EventMask::CLOSE_WRITE)
489                                && Self::is_watched_path(&self.watches, &path)
490                            {
491                                evs.push(
492                                    Event::new(EventKind::Access(AccessKind::Close(
493                                        AccessMode::Write,
494                                    )))
495                                    .add_path(path.clone()),
496                                );
497                            }
498                            if event.mask.contains(EventMask::CLOSE_NOWRITE)
499                                && Self::is_watched_path(&self.watches, &path)
500                            {
501                                evs.push(
502                                    Event::new(EventKind::Access(AccessKind::Close(
503                                        AccessMode::Read,
504                                    )))
505                                    .add_path(path.clone()),
506                                );
507                            }
508                            if event.mask.contains(EventMask::ATTRIB)
509                                && Self::is_watched_path(&self.watches, &path)
510                            {
511                                evs.push(
512                                    Event::new(EventKind::Modify(ModifyKind::Metadata(
513                                        MetadataKind::Any,
514                                    )))
515                                    .add_path(path.clone()),
516                                );
517                            }
518                            if event.mask.contains(EventMask::OPEN)
519                                && Self::is_watched_path(&self.watches, &path)
520                            {
521                                evs.push(
522                                    Event::new(EventKind::Access(AccessKind::Open(
523                                        AccessMode::Any,
524                                    )))
525                                    .add_path(path.clone()),
526                                );
527                            }
528
529                            for ev in evs {
530                                self.event_handler.handle_event(Ok(ev));
531                            }
532                        }
533
534                        // All events read. Break out.
535                        if num_events == 0 {
536                            break;
537                        }
538                    }
539                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
540                        // No events read. Break out.
541                        break;
542                    }
543                    Err(e) => {
544                        self.event_handler.handle_event(Err(Error::io(e)));
545                    }
546                }
547            }
548        }
549
550        tracing::trace!(
551            ?add_watches,
552            ?remove_watches,
553            "processing inotify watch changes"
554        );
555
556        for path in remove_watches_no_syscall {
557            if self
558                .watches
559                .get(&path)
560                .is_some_and(|watch_mode| watch_mode.target_mode == TargetMode::NoTrack)
561            {
562                self.watches.remove(&path);
563            }
564            self.remove_maybe_recursive_watch(&path, true, true).ok();
565        }
566
567        for path in remove_watches {
568            if self
569                .watches
570                .get(&path)
571                .is_some_and(|watch_mode| watch_mode.target_mode == TargetMode::NoTrack)
572            {
573                self.watches.remove(&path);
574            }
575            self.remove_maybe_recursive_watch(&path, true, false).ok();
576        }
577
578        for (path, is_recursive, is_file_without_hardlinks) in add_watches {
579            if let Err(add_watch_error) =
580                self.add_maybe_recursive_watch(path, is_recursive, is_file_without_hardlinks, false)
581            {
582                // The handler should be notified if we have reached the limit.
583                // Otherwise, the user might expect that a recursive watch
584                // is continuing to work correctly, but it's not.
585                if let ErrorKind::MaxFilesWatch = add_watch_error.kind {
586                    self.event_handler.handle_event(Err(add_watch_error));
587
588                    // After that kind of a error we should stop adding watches,
589                    // because the limit has already reached and all next calls
590                    // will return us only the same error.
591                    break;
592                }
593            }
594        }
595    }
596
597    #[tracing::instrument(level = "trace", skip(self))]
598    fn add_watch(&mut self, path: PathBuf, watch_mode: WatchMode) -> Result<()> {
599        // an ignored path is not watched
600        if self.ignore_filter.is_path_ignored(&path) {
601            return Ok(());
602        }
603
604        if let Some(existing) = self.watches.get(&path) {
605            let need_upgrade_to_recursive = match existing.recursive_mode {
606                RecursiveMode::Recursive => false,
607                RecursiveMode::NonRecursive => {
608                    watch_mode.recursive_mode == RecursiveMode::Recursive
609                }
610            };
611            let need_to_watch_parent_newly = match existing.target_mode {
612                TargetMode::TrackPath => false,
613                TargetMode::NoTrack => watch_mode.target_mode == TargetMode::TrackPath,
614            };
615            tracing::trace!(
616                ?need_upgrade_to_recursive,
617                ?need_to_watch_parent_newly,
618                "upgrading existing watch for path: {}",
619                path.display()
620            );
621            if need_to_watch_parent_newly && let Some(parent) = path.parent() {
622                self.add_single_watch(parent.to_path_buf(), false, false)?;
623            }
624            if need_upgrade_to_recursive && metadata(&path).map_err(Error::io)?.is_dir() {
625                self.add_maybe_recursive_watch(path.clone(), true, false, true)?;
626            }
627            self.watches
628                .get_mut(&path)
629                .unwrap()
630                .upgrade_with(watch_mode);
631            return Ok(());
632        }
633
634        if watch_mode.target_mode == TargetMode::TrackPath
635            && let Some(parent) = path.parent()
636        {
637            self.add_single_watch(parent.to_path_buf(), false, false)?;
638        }
639
640        let meta = match metadata(&path).map_err(Error::io_watch) {
641            Ok(metadata) => metadata,
642            Err(err) => {
643                if watch_mode.target_mode == TargetMode::TrackPath
644                    && matches!(err.kind, ErrorKind::PathNotFound)
645                {
646                    self.watches.insert(path, watch_mode);
647                    return Ok(());
648                }
649                return Err(err);
650            }
651        };
652
653        self.add_maybe_recursive_watch(
654            path.clone(),
655            // If the watch is not recursive, or if we determine (by stat'ing the path to get its
656            // metadata) that the watched path is not a directory, add a single path watch.
657            watch_mode.recursive_mode.is_recursive() && meta.is_dir(),
658            meta.is_file_without_hardlinks(),
659            watch_mode.target_mode != TargetMode::TrackPath, // parent is watched, so no need to watch self
660        )?;
661
662        self.watches.insert(path, watch_mode);
663
664        Ok(())
665    }
666
667    #[tracing::instrument(level = "trace", skip(self))]
668    fn add_maybe_recursive_watch(
669        &mut self,
670        path: PathBuf,
671        is_recursive: bool,
672        is_file_without_hardlinks: bool,
673        mut watch_self: bool,
674    ) -> Result<()> {
675        if is_recursive {
676            for entry in self
677                .ignore_filter
678                .walk(WalkDir::new(&path).follow_links(self.follow_links))
679                .filter_map(filter_dir)
680            {
681                self.add_single_watch(entry.into_path(), false, watch_self)?;
682                watch_self = false;
683            }
684        } else {
685            self.add_single_watch(path, is_file_without_hardlinks, watch_self)?;
686        }
687        Ok(())
688    }
689
690    #[tracing::instrument(level = "trace", skip(self))]
691    fn add_single_watch(
692        &mut self,
693        path: PathBuf,
694        is_file_without_hardlinks: bool,
695        watch_self: bool,
696    ) -> Result<()> {
697        if let Some((_, &(old_watch_self, _))) = self.watch_handles.get_by_right(&path)
698            // if upgrade to watch self is not needed
699            && (old_watch_self || !watch_self)
700        {
701            tracing::trace!(
702                "watch handle already exists and no need to upgrade: {}",
703                path.display()
704            );
705            return Ok(());
706        }
707
708        if is_file_without_hardlinks
709            && let Some(parent) = path.parent()
710            && self.watch_handles.get_by_right(parent).is_some()
711        {
712            tracing::trace!(
713                "parent dir watch handle already exists and is a file without hardlinks: {}",
714                path.display()
715            );
716            return Ok(());
717        }
718
719        let mut watchmask = WatchMask::ATTRIB
720            | WatchMask::CREATE
721            | WatchMask::OPEN
722            | WatchMask::DELETE
723            | WatchMask::CLOSE_WRITE
724            | WatchMask::MODIFY
725            | WatchMask::MOVED_FROM
726            | WatchMask::MOVED_TO;
727        if watch_self {
728            watchmask.insert(WatchMask::DELETE_SELF);
729            watchmask.insert(WatchMask::MOVE_SELF);
730        }
731
732        if let Some(ref mut inotify) = self.inotify {
733            tracing::trace!("adding inotify watch: {}", path.display());
734
735            match inotify.watches().add(&path, watchmask) {
736                Err(e) => {
737                    Err(if e.raw_os_error() == Some(libc::ENOSPC) {
738                        // do not report inotify limits as "no more space" on linux #266
739                        Error::new(ErrorKind::MaxFilesWatch)
740                    } else if e.kind() == std::io::ErrorKind::NotFound {
741                        Error::new(ErrorKind::PathNotFound)
742                    } else {
743                        Error::io(e)
744                    }
745                    .add_path(path))
746                }
747                Ok(w) => {
748                    watchmask.remove(WatchMask::MASK_ADD);
749                    let is_dir = metadata(&path).map_err(Error::io)?.is_dir();
750                    self.watch_handles.insert(w, path, (watch_self, is_dir));
751                    Ok(())
752                }
753            }
754        } else {
755            Ok(())
756        }
757    }
758
759    #[tracing::instrument(level = "trace", skip(self))]
760    fn remove_watch(&mut self, path: PathBuf) -> Result<()> {
761        match self.watches.remove(&path) {
762            // an ignored path is never watched, so unwatching it is not an error
763            None if self.ignore_filter.is_path_ignored(&path) => {}
764            None => return Err(Error::watch_not_found().add_path(path)),
765            Some(watch_mode) => {
766                self.remove_maybe_recursive_watch(
767                    &path,
768                    watch_mode.recursive_mode.is_recursive(),
769                    false,
770                )?;
771            }
772        }
773        Ok(())
774    }
775
776    #[tracing::instrument(level = "trace", skip(self))]
777    fn remove_maybe_recursive_watch(
778        &mut self,
779        path: &Path,
780        is_recursive: bool,
781        without_os_call: bool,
782    ) -> Result<()> {
783        let Some(ref mut inotify) = self.inotify else {
784            return Ok(());
785        };
786        let mut inotify_watches = inotify.watches();
787
788        if let Some((handle, _)) = self.watch_handles.remove_by_right(path) {
789            tracing::trace!("removing inotify watch: {}", path.display());
790
791            if !without_os_call {
792                inotify_watches
793                    .remove(handle)
794                    .map_err(|e| Error::io(e).add_path(path.to_path_buf()))?;
795            }
796        }
797
798        if is_recursive {
799            let mut remove_list = Vec::new();
800            for (w, p, _) in &self.watch_handles {
801                if p.starts_with(path) {
802                    if !without_os_call {
803                        inotify_watches
804                            .remove(w.clone())
805                            .map_err(|e| Error::io(e).add_path(p.into()))?;
806                    }
807                    remove_list.push(w.clone());
808                }
809            }
810            for w in remove_list {
811                self.watch_handles.remove_by_left(&w);
812            }
813        }
814        Ok(())
815    }
816
817    fn remove_all_watches(&mut self) -> Result<()> {
818        if let Some(ref mut inotify) = self.inotify {
819            let mut inotify_watches = inotify.watches();
820            for (w, p, _) in &self.watch_handles {
821                inotify_watches
822                    .remove(w.clone())
823                    .map_err(|e| Error::io(e).add_path(p.into()))?;
824            }
825            self.watch_handles.clear();
826            self.watches.clear();
827        }
828        Ok(())
829    }
830}
831
832/// return `DirEntry` when it is a directory
833fn filter_dir(e: walkdir::Result<walkdir::DirEntry>) -> Option<walkdir::DirEntry> {
834    if let Ok(e) = e
835        && e.file_type().is_dir()
836    {
837        return Some(e);
838    }
839    None
840}
841
842impl INotifyWatcher {
843    fn from_event_handler(
844        event_handler: Box<dyn EventHandler>,
845        follow_links: bool,
846        ignore_filter: IgnoreFilter,
847    ) -> Result<Self> {
848        let inotify = Inotify::init()?;
849        let event_loop = EventLoop::new(inotify, event_handler, follow_links, ignore_filter)?;
850        let channel = event_loop.event_loop_tx.clone();
851        let waker = Arc::clone(&event_loop.event_loop_waker);
852        event_loop.run();
853        Ok(INotifyWatcher { channel, waker })
854    }
855
856    fn watch_inner(&self, path: &Path, watch_mode: WatchMode) -> Result<()> {
857        let pb = if path.is_absolute() {
858            path.to_owned()
859        } else {
860            let p = env::current_dir().map_err(Error::io)?;
861            p.join(path)
862        };
863        let (tx, rx) = unbounded();
864        let msg = EventLoopMsg::AddWatch(pb, watch_mode, tx);
865
866        // we expect the event loop to live and reply => unwraps must not panic
867        self.channel.send(msg).unwrap();
868        self.waker.wake().unwrap();
869        rx.recv().unwrap()
870    }
871
872    fn unwatch_inner(&self, path: &Path) -> Result<()> {
873        let pb = if path.is_absolute() {
874            path.to_owned()
875        } else {
876            let p = env::current_dir().map_err(Error::io)?;
877            p.join(path)
878        };
879        let (tx, rx) = unbounded();
880        let msg = EventLoopMsg::RemoveWatch(pb, tx);
881
882        // we expect the event loop to live and reply => unwraps must not panic
883        self.channel.send(msg).unwrap();
884        self.waker.wake().unwrap();
885        rx.recv().unwrap()
886    }
887}
888
889impl Watcher for INotifyWatcher {
890    /// Create a new watcher.
891    #[tracing::instrument(level = "debug", skip(event_handler))]
892    fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> {
893        Self::from_event_handler(
894            Box::new(event_handler),
895            config.follow_symlinks(),
896            config.ignored().clone(),
897        )
898    }
899
900    #[tracing::instrument(level = "debug", skip(self))]
901    fn watch(&mut self, path: &Path, watch_mode: WatchMode) -> Result<()> {
902        self.watch_inner(path, watch_mode)
903    }
904
905    #[tracing::instrument(level = "debug", skip(self))]
906    fn unwatch(&mut self, path: &Path) -> Result<()> {
907        self.unwatch_inner(path)
908    }
909
910    #[tracing::instrument(level = "debug", skip(self))]
911    fn configure(&mut self, config: Config) -> Result<bool> {
912        let (tx, rx) = bounded(1);
913        self.channel.send(EventLoopMsg::Configure(config, tx))?;
914        self.waker.wake()?;
915        rx.recv()?
916    }
917
918    fn kind() -> crate::WatcherKind {
919        crate::WatcherKind::Inotify
920    }
921
922    #[cfg(test)]
923    fn get_watch_handles(&self) -> std::collections::HashSet<std::path::PathBuf> {
924        let (tx, rx) = bounded(1);
925        self.channel
926            .send(EventLoopMsg::GetWatchHandles(tx))
927            .unwrap();
928        self.waker.wake().unwrap();
929        rx.recv().unwrap()
930    }
931}
932
933impl Drop for INotifyWatcher {
934    fn drop(&mut self) {
935        // we expect the event loop to live => unwrap must not panic
936        self.channel.send(EventLoopMsg::Shutdown).unwrap();
937        self.waker.wake().unwrap();
938    }
939}
940
941trait MetadataNotifyExt {
942    fn is_file_without_hardlinks(&self) -> bool;
943}
944
945impl MetadataNotifyExt for std::fs::Metadata {
946    #[inline]
947    fn is_file_without_hardlinks(&self) -> bool {
948        self.is_file() && self.nlink() == 1
949    }
950}
951
952#[cfg(test)]
953mod tests {
954    use std::{
955        collections::HashSet,
956        path::{Path, PathBuf},
957        sync::{Arc, atomic::AtomicBool, mpsc},
958        thread::{self, available_parallelism},
959        time::Duration,
960    };
961
962    use super::{Config, Error, ErrorKind, Event, INotifyWatcher, Result, Watcher};
963
964    use crate::{
965        RecursiveMode, TargetMode,
966        config::WatchMode,
967        event::{EventKind, ModifyKind},
968        test::*,
969    };
970
971    fn watcher() -> (TestWatcher<INotifyWatcher>, Receiver) {
972        channel()
973    }
974
975    fn ignoring_watcher() -> (TestWatcher<INotifyWatcher>, Receiver) {
976        ignoring_channel()
977    }
978
979    #[test]
980    fn ignored_directory_is_not_watched() {
981        let tmpdir = testdir();
982        let root = tmpdir.path();
983        std::fs::create_dir_all(root.join("node_modules/pkg")).expect("create dir");
984        std::fs::create_dir(root.join("src")).expect("create dir");
985
986        let (mut watcher, _rx) = ignoring_watcher();
987        watcher.watch_recursively(root);
988
989        assert_eq!(
990            watcher.get_watch_handles_in(root),
991            HashSet::from([root.to_path_buf(), root.join("src")])
992        );
993    }
994
995    #[test]
996    fn ignored_directory_created_at_runtime_is_not_watched() {
997        let tmpdir = testdir();
998        let root = tmpdir.path();
999
1000        let (mut watcher, _rx) = ignoring_watcher();
1001        watcher.watch_recursively(root);
1002
1003        std::fs::create_dir(root.join("node_modules")).expect("create dir");
1004        // created last: once it is watched, the ignored directory has been handled
1005        std::fs::create_dir(root.join("src")).expect("create dir");
1006
1007        assert!(
1008            sleep_until(
1009                || watcher.get_watch_handles().contains(&root.join("src")),
1010                Duration::from_secs(5)
1011            ),
1012            "the new directory was never watched: {:#?}",
1013            watcher.get_watch_handles()
1014        );
1015        assert_eq!(
1016            watcher.get_watch_handles_in(root),
1017            HashSet::from([root.to_path_buf(), root.join("src")])
1018        );
1019    }
1020
1021    #[test]
1022    fn inotify_watcher_is_send_and_sync() {
1023        fn check<T: Send + Sync>() {}
1024        check::<INotifyWatcher>();
1025    }
1026
1027    #[test]
1028    fn native_error_type_on_missing_path() {
1029        let mut watcher = INotifyWatcher::new(|_| {}, Config::default()).unwrap();
1030
1031        let result = watcher.watch(
1032            &PathBuf::from("/some/non/existant/path"),
1033            WatchMode::non_recursive(),
1034        );
1035
1036        assert!(matches!(
1037            result,
1038            Err(Error {
1039                paths: _,
1040                kind: ErrorKind::PathNotFound
1041            })
1042        ));
1043    }
1044
1045    /// Runs manually.
1046    ///
1047    /// * Save actual value of the limit: `MAX_USER_WATCHES=$(sysctl -n fs.inotify.max_user_watches)`
1048    /// * Run the test.
1049    /// * Set the limit to 0: `sudo sysctl fs.inotify.max_user_watches=0` while test is running
1050    /// * Wait for the test to complete
1051    /// * Restore the limit `sudo sysctl fs.inotify.max_user_watches=$MAX_USER_WATCHES`
1052    #[test]
1053    #[ignore = "requires changing sysctl fs.inotify.max_user_watches while test is running"]
1054    fn recursive_watch_calls_handler_if_creating_a_file_raises_max_files_watch() {
1055        use std::time::Duration;
1056
1057        let tmpdir = tempfile::tempdir().unwrap();
1058        let (tx, rx) = std::sync::mpsc::channel();
1059        let (proc_changed_tx, proc_changed_rx) = std::sync::mpsc::channel();
1060        let proc_path = Path::new("/proc/sys/fs/inotify/max_user_watches");
1061        let mut watcher = INotifyWatcher::new(
1062            move |result: Result<Event>| match result {
1063                Ok(event) => {
1064                    if event.paths.first().is_some_and(|path| path == proc_path) {
1065                        proc_changed_tx.send(()).unwrap();
1066                    }
1067                }
1068                Err(e) => tx.send(e).unwrap(),
1069            },
1070            Config::default(),
1071        )
1072        .unwrap();
1073
1074        watcher
1075            .watch(tmpdir.path(), WatchMode::recursive())
1076            .unwrap();
1077        watcher
1078            .watch(proc_path, WatchMode::non_recursive())
1079            .unwrap();
1080
1081        // give the time to set the limit
1082        proc_changed_rx
1083            .recv_timeout(Duration::from_secs(30))
1084            .unwrap();
1085
1086        let child_dir = tmpdir.path().join("child");
1087        std::fs::create_dir(child_dir).unwrap();
1088
1089        let result = rx.recv_timeout(Duration::from_millis(500));
1090
1091        assert!(
1092            matches!(
1093                &result,
1094                Ok(Error {
1095                    kind: ErrorKind::MaxFilesWatch,
1096                    paths: _,
1097                })
1098            ),
1099            "expected {:?}, found: {:#?}",
1100            ErrorKind::MaxFilesWatch,
1101            result
1102        );
1103    }
1104
1105    /// https://github.com/notify-rs/notify/issues/678
1106    #[test]
1107    fn race_condition_on_unwatch_and_pending_events_with_deleted_descriptor() {
1108        let tmpdir = tempfile::tempdir().expect("tmpdir");
1109        let (tx, rx) = mpsc::channel();
1110        let mut inotify = INotifyWatcher::new(
1111            move |e: Result<Event>| {
1112                let e = match e {
1113                    Ok(e) if e.paths.is_empty() => e,
1114                    Ok(_) | Err(_) => return,
1115                };
1116                let _ = tx.send(e);
1117            },
1118            Config::default(),
1119        )
1120        .expect("inotify creation");
1121
1122        let dir_path = tmpdir.path();
1123        let file_path = dir_path.join("foo");
1124        std::fs::File::create(&file_path).unwrap();
1125
1126        let stop = Arc::new(AtomicBool::new(false));
1127
1128        let handles: Vec<_> = (0..available_parallelism().unwrap().get().max(4))
1129            .map(|_| {
1130                let file_path = file_path.clone();
1131                let stop = Arc::clone(&stop);
1132                thread::spawn(move || {
1133                    while !stop.load(std::sync::atomic::Ordering::Relaxed) {
1134                        let _ = std::fs::File::open(&file_path).unwrap();
1135                    }
1136                })
1137            })
1138            .collect();
1139
1140        let non_recursive = WatchMode::non_recursive();
1141        for _ in 0..(handles.len() * 4) {
1142            inotify.watch(dir_path, non_recursive).unwrap();
1143            inotify.unwatch(dir_path).unwrap();
1144        }
1145
1146        stop.store(true, std::sync::atomic::Ordering::Relaxed);
1147        for handle in handles {
1148            handle.join().ok().unwrap_or_default();
1149        }
1150
1151        drop(inotify);
1152
1153        let events: Vec<_> = rx.into_iter().map(|e| format!("{e:?}")).collect();
1154
1155        const LOG_LEN: usize = 10;
1156        let events_len = events.len();
1157        assert!(
1158            events.is_empty(),
1159            "expected no events without path, but got {events_len}. first 10: {:#?}",
1160            &events[..LOG_LEN.min(events_len)]
1161        );
1162    }
1163
1164    #[test]
1165    fn create_file() {
1166        let tmpdir = testdir();
1167        let (mut watcher, rx) = watcher();
1168        watcher.watch_recursively(&tmpdir);
1169
1170        let path = tmpdir.path().join("entry");
1171        std::fs::File::create_new(&path).expect("create");
1172
1173        rx.wait_ordered_exact([
1174            expected(tmpdir.path()).access_open_any().optional(),
1175            expected(&path).create_file(),
1176            expected(&path).access_open_any(),
1177            expected(&path).access_close_write(),
1178        ]);
1179        assert_eq!(
1180            watcher.get_watch_handles(),
1181            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1182        );
1183    }
1184
1185    #[test]
1186    fn create_self_file() {
1187        let tmpdir = testdir();
1188        let (mut watcher, rx) = watcher();
1189
1190        let path = tmpdir.path().join("entry");
1191
1192        watcher.watch_nonrecursively(&path);
1193
1194        std::fs::File::create_new(&path).expect("create");
1195
1196        rx.wait_ordered_exact([
1197            expected(&path).create_file(),
1198            expected(&path).access_open_any(),
1199            expected(&path).access_close_write(),
1200        ]);
1201        assert_eq!(
1202            watcher.get_watch_handles(),
1203            HashSet::from([tmpdir.to_path_buf()])
1204        );
1205    }
1206
1207    #[test]
1208    fn create_self_file_no_track() {
1209        let tmpdir = testdir();
1210        let (mut watcher, _) = watcher();
1211
1212        let path = tmpdir.path().join("entry");
1213
1214        let result = watcher.watcher.watch(
1215            &path,
1216            WatchMode {
1217                recursive_mode: RecursiveMode::NonRecursive,
1218                target_mode: TargetMode::NoTrack,
1219            },
1220        );
1221        assert!(matches!(
1222            result,
1223            Err(Error {
1224                paths: _,
1225                kind: ErrorKind::PathNotFound
1226            })
1227        ));
1228    }
1229
1230    #[test]
1231    #[ignore = "TODO: not implemented"]
1232    fn create_self_file_nested() {
1233        let tmpdir = testdir();
1234        let (mut watcher, rx) = watcher();
1235
1236        let path = tmpdir.path().join("entry/nested");
1237
1238        watcher.watch_nonrecursively(&path);
1239
1240        std::fs::create_dir_all(path.parent().unwrap()).expect("create");
1241        std::fs::File::create_new(&path).expect("create");
1242
1243        rx.wait_ordered_exact([
1244            expected(&path).create_file(),
1245            expected(&path).access_open_any(),
1246            expected(&path).access_close_write(),
1247        ]);
1248        assert_eq!(
1249            watcher.get_watch_handles(),
1250            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1251        );
1252    }
1253
1254    #[test]
1255    fn create_file_nested_in_recursive_watch() {
1256        let tmpdir = testdir();
1257        let (mut watcher, rx) = watcher();
1258
1259        let nested1_dir = tmpdir.path().join("nested1");
1260        let nested2_dir = nested1_dir.join("nested2");
1261        std::fs::create_dir_all(&nested2_dir).expect("create_dir");
1262
1263        watcher.watch_recursively(&tmpdir);
1264
1265        let path = nested2_dir.join("entry");
1266        std::fs::File::create_new(&path).expect("create");
1267
1268        rx.wait_ordered_exact([
1269            expected(tmpdir.path()).access_open_any().optional(),
1270            expected(&nested1_dir).access_open_any().optional(),
1271            expected(&nested2_dir).access_open_any().optional(),
1272            expected(&path).create_file(),
1273            expected(&path).access_open_any(),
1274            expected(&path).access_close_write(),
1275        ]);
1276        assert_eq!(
1277            watcher.get_watch_handles(),
1278            HashSet::from([
1279                tmpdir.parent_path_buf(),
1280                tmpdir.to_path_buf(),
1281                nested1_dir,
1282                nested2_dir
1283            ])
1284        );
1285    }
1286
1287    #[test]
1288    fn write_file() {
1289        let tmpdir = testdir();
1290        let (mut watcher, rx) = watcher();
1291
1292        let path = tmpdir.path().join("entry");
1293        std::fs::File::create_new(&path).expect("create");
1294
1295        watcher.watch_recursively(&tmpdir);
1296        std::fs::write(&path, b"123").expect("write");
1297
1298        rx.wait_ordered_exact([
1299            expected(tmpdir.path()).access_open_any().optional(),
1300            expected(&path).access_open_any(),
1301            expected(&path).modify_data_any().multiple(),
1302            expected(&path).access_close_write(),
1303        ])
1304        .ensure_no_tail();
1305        assert_eq!(
1306            watcher.get_watch_handles(),
1307            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1308        );
1309    }
1310
1311    #[test]
1312    fn chmod_file() {
1313        let tmpdir = testdir();
1314        let (mut watcher, rx) = watcher();
1315
1316        let path = tmpdir.path().join("entry");
1317        let file = std::fs::File::create_new(&path).expect("create");
1318        let mut permissions = file.metadata().expect("metadata").permissions();
1319        permissions.set_readonly(true);
1320
1321        watcher.watch_recursively(&tmpdir);
1322        file.set_permissions(permissions).expect("set_permissions");
1323
1324        rx.wait_ordered_exact([
1325            expected(tmpdir.path()).access_open_any().optional(),
1326            expected(&path).modify_meta_any(),
1327        ]);
1328        assert_eq!(
1329            watcher.get_watch_handles(),
1330            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1331        );
1332    }
1333
1334    #[test]
1335    fn rename_file() {
1336        let tmpdir = testdir();
1337        let (mut watcher, rx) = watcher();
1338
1339        let path = tmpdir.path().join("entry");
1340        std::fs::File::create_new(&path).expect("create");
1341
1342        watcher.watch_recursively(&tmpdir);
1343        let new_path = tmpdir.path().join("renamed");
1344
1345        std::fs::rename(&path, &new_path).expect("rename");
1346
1347        rx.wait_ordered_exact([
1348            expected(tmpdir.path()).access_open_any().optional(),
1349            expected(&path).rename_from(),
1350            expected(&new_path).rename_to(),
1351            expected([path, new_path]).rename_both(),
1352        ])
1353        .ensure_trackers_len(1)
1354        .ensure_no_tail();
1355        assert_eq!(
1356            watcher.get_watch_handles(),
1357            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1358        );
1359    }
1360
1361    #[test]
1362    fn rename_self_file() {
1363        let tmpdir = testdir();
1364        let (mut watcher, rx) = watcher();
1365
1366        let path = tmpdir.path().join("entry");
1367        std::fs::File::create_new(&path).expect("create");
1368
1369        watcher.watch_nonrecursively(&path);
1370        let new_path = tmpdir.path().join("renamed");
1371
1372        std::fs::rename(&path, &new_path).expect("rename");
1373
1374        rx.wait_ordered_exact([expected(&path).rename_from()])
1375            .ensure_no_tail();
1376        assert_eq!(
1377            watcher.get_watch_handles(),
1378            HashSet::from([tmpdir.to_path_buf()])
1379        );
1380
1381        std::fs::rename(&new_path, &path).expect("rename2");
1382
1383        rx.wait_ordered_exact([expected(&path).rename_to()])
1384            .ensure_no_tail();
1385        assert_eq!(
1386            watcher.get_watch_handles(),
1387            HashSet::from([tmpdir.to_path_buf()])
1388        );
1389    }
1390
1391    #[test]
1392    fn rename_self_file_no_track() {
1393        let tmpdir = testdir();
1394        let (mut watcher, rx) = watcher();
1395
1396        let path = tmpdir.path().join("entry");
1397        std::fs::File::create_new(&path).expect("create");
1398
1399        watcher.watch(
1400            &path,
1401            WatchMode {
1402                recursive_mode: RecursiveMode::NonRecursive,
1403                target_mode: TargetMode::NoTrack,
1404            },
1405        );
1406
1407        let new_path = tmpdir.path().join("renamed");
1408
1409        std::fs::rename(&path, &new_path).expect("rename");
1410
1411        rx.wait_ordered_exact([expected(&path).rename_from()])
1412            .ensure_no_tail();
1413        assert_eq!(watcher.get_watch_handles(), HashSet::from([]));
1414
1415        let result = watcher.watcher.watch(
1416            &path,
1417            WatchMode {
1418                recursive_mode: RecursiveMode::NonRecursive,
1419                target_mode: TargetMode::NoTrack,
1420            },
1421        );
1422        assert!(matches!(
1423            result,
1424            Err(Error {
1425                paths: _,
1426                kind: ErrorKind::PathNotFound
1427            })
1428        ));
1429    }
1430
1431    #[test]
1432    fn delete_file() {
1433        let tmpdir = testdir();
1434        let (mut watcher, rx) = watcher();
1435        let file = tmpdir.path().join("file");
1436        std::fs::write(&file, "").expect("write");
1437
1438        watcher.watch_nonrecursively(&tmpdir);
1439
1440        std::fs::remove_file(&file).expect("remove");
1441
1442        rx.wait_ordered_exact([
1443            expected(tmpdir.path()).access_open_any().optional(),
1444            expected(&file).remove_file(),
1445        ]);
1446        assert_eq!(
1447            watcher.get_watch_handles(),
1448            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1449        );
1450    }
1451
1452    #[test]
1453    fn delete_self_file() {
1454        let tmpdir = testdir();
1455        let (mut watcher, rx) = watcher();
1456        let file = tmpdir.path().join("file");
1457        std::fs::write(&file, "").expect("write");
1458
1459        watcher.watch_nonrecursively(&file);
1460
1461        std::fs::remove_file(&file).expect("remove");
1462
1463        rx.wait_ordered_exact([expected(&file).remove_file()]);
1464        assert_eq!(
1465            watcher.get_watch_handles(),
1466            HashSet::from([tmpdir.to_path_buf()])
1467        );
1468
1469        std::fs::write(&file, "").expect("write");
1470
1471        rx.wait_ordered_exact([expected(&file).create_file()]);
1472        assert_eq!(
1473            watcher.get_watch_handles(),
1474            HashSet::from([tmpdir.to_path_buf()])
1475        );
1476    }
1477
1478    #[test]
1479    fn delete_self_file_no_track() {
1480        let tmpdir = testdir();
1481        let (mut watcher, rx) = watcher();
1482        let file = tmpdir.path().join("file");
1483        std::fs::write(&file, "").expect("write");
1484
1485        watcher.watch(
1486            &file,
1487            WatchMode {
1488                recursive_mode: RecursiveMode::NonRecursive,
1489                target_mode: TargetMode::NoTrack,
1490            },
1491        );
1492
1493        std::fs::remove_file(&file).expect("remove");
1494
1495        rx.wait_ordered_exact([
1496            expected(&file).modify_meta_any(),
1497            expected(&file).remove_file(),
1498        ]);
1499        assert_eq!(watcher.get_watch_handles(), HashSet::from([]));
1500
1501        std::fs::write(&file, "").expect("write");
1502
1503        rx.ensure_empty_with_wait();
1504    }
1505
1506    #[test]
1507    fn create_write_overwrite() {
1508        let tmpdir = testdir();
1509        let (mut watcher, rx) = watcher();
1510        let overwritten_file = tmpdir.path().join("overwritten_file");
1511        let overwriting_file = tmpdir.path().join("overwriting_file");
1512        std::fs::write(&overwritten_file, "123").expect("write1");
1513
1514        watcher.watch_nonrecursively(&tmpdir);
1515
1516        std::fs::File::create(&overwriting_file).expect("create");
1517        std::fs::write(&overwriting_file, "321").expect("write2");
1518        std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");
1519
1520        rx.wait_ordered_exact([
1521            expected(tmpdir.path()).access_open_any().optional(),
1522            expected(&overwriting_file).create_file(),
1523            expected(&overwriting_file).access_open_any(),
1524            expected(&overwriting_file).access_close_write(),
1525            expected(&overwriting_file).access_open_any(),
1526            expected(&overwriting_file).modify_data_any().multiple(),
1527            expected(&overwriting_file).access_close_write().multiple(),
1528            expected(&overwriting_file).rename_from(),
1529            expected(&overwritten_file).rename_to(),
1530            expected([&overwriting_file, &overwritten_file]).rename_both(),
1531        ])
1532        .ensure_no_tail()
1533        .ensure_trackers_len(1);
1534        assert_eq!(
1535            watcher.get_watch_handles(),
1536            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1537        );
1538    }
1539
1540    #[test]
1541    fn create_self_write_overwrite() {
1542        let tmpdir = testdir();
1543        let (mut watcher, rx) = watcher();
1544        let overwritten_file = tmpdir.path().join("overwritten_file");
1545        let overwriting_file = tmpdir.path().join("overwriting_file");
1546        std::fs::write(&overwritten_file, "123").expect("write1");
1547
1548        watcher.watch_nonrecursively(&overwritten_file);
1549
1550        std::fs::File::create(&overwriting_file).expect("create");
1551        std::fs::write(&overwriting_file, "321").expect("write2");
1552        std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");
1553
1554        rx.wait_ordered_exact([expected(&overwritten_file).rename_to()])
1555            .ensure_no_tail()
1556            .ensure_trackers_len(1);
1557        assert_eq!(
1558            watcher.get_watch_handles(),
1559            HashSet::from([tmpdir.to_path_buf()])
1560        );
1561    }
1562
1563    fn assert_track_path_continues_after_recreating_file_in_nested_directory(
1564        upgrade_from_no_track: bool,
1565    ) {
1566        let tmpdir = testdir();
1567        let (mut watcher, mut rx) = watcher();
1568        let nested_dir = tmpdir.path().join("nested");
1569        let watched_file = nested_dir.join("watched");
1570        let moved_file = tmpdir.path().join("moved");
1571        std::fs::create_dir(&nested_dir).expect("create nested dir");
1572        std::fs::write(&watched_file, "initial").expect("write watched file");
1573
1574        watcher.watch_nonrecursively(&tmpdir);
1575        if upgrade_from_no_track {
1576            watcher.watch(
1577                &watched_file,
1578                WatchMode {
1579                    recursive_mode: RecursiveMode::NonRecursive,
1580                    target_mode: TargetMode::NoTrack,
1581                },
1582            );
1583        }
1584        watcher.watch_nonrecursively(&watched_file);
1585        let mut expected_handles = HashSet::from([
1586            tmpdir.parent_path_buf(),
1587            tmpdir.to_path_buf(),
1588            nested_dir.clone(),
1589        ]);
1590        if upgrade_from_no_track {
1591            expected_handles.insert(watched_file.clone());
1592        }
1593        assert_eq!(watcher.get_watch_handles(), expected_handles);
1594
1595        std::fs::rename(&watched_file, &moved_file).expect("move watched file");
1596        std::fs::copy(&moved_file, &watched_file).expect("recreate watched file");
1597        std::fs::remove_file(&moved_file).expect("remove moved file");
1598
1599        // Wait until the replacement events are drained before checking the next write.
1600        for _ in rx.iter() {}
1601
1602        std::fs::write(&watched_file, "updated").expect("update watched file");
1603        let received_change = rx.iter().any(|event| {
1604            event.paths.iter().any(|path| path == &watched_file)
1605                && matches!(
1606                    event.kind,
1607                    EventKind::Create(_) | EventKind::Modify(ModifyKind::Data(_))
1608                )
1609        });
1610
1611        assert!(
1612            received_change,
1613            "expected a change event after recreating the watched file"
1614        );
1615        assert_eq!(
1616            watcher.get_watch_handles(),
1617            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf(), nested_dir,])
1618        );
1619    }
1620
1621    #[test]
1622    fn track_path_continues_after_recreating_file_in_nested_directory() {
1623        assert_track_path_continues_after_recreating_file_in_nested_directory(false);
1624    }
1625
1626    #[test]
1627    fn track_path_upgrade_continues_after_recreating_file_in_nested_directory() {
1628        assert_track_path_continues_after_recreating_file_in_nested_directory(true);
1629    }
1630
1631    #[test]
1632    fn create_self_write_overwrite_no_track() {
1633        let tmpdir = testdir();
1634        let (mut watcher, rx) = watcher();
1635        let overwritten_file = tmpdir.path().join("overwritten_file");
1636        let overwriting_file = tmpdir.path().join("overwriting_file");
1637        std::fs::write(&overwritten_file, "123").expect("write1");
1638
1639        watcher.watch(
1640            &overwritten_file,
1641            WatchMode {
1642                recursive_mode: RecursiveMode::NonRecursive,
1643                target_mode: TargetMode::NoTrack,
1644            },
1645        );
1646
1647        std::fs::File::create(&overwriting_file).expect("create");
1648        std::fs::write(&overwriting_file, "321").expect("write2");
1649        std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");
1650
1651        rx.wait_ordered_exact([
1652            expected(&overwritten_file).modify_meta_any(),
1653            expected(&overwritten_file).remove_file(),
1654        ])
1655        .ensure_no_tail()
1656        .ensure_trackers_len(0);
1657        assert_eq!(watcher.get_watch_handles(), HashSet::from([]));
1658    }
1659
1660    #[test]
1661    fn create_dir() {
1662        let tmpdir = testdir();
1663        let (mut watcher, rx) = watcher();
1664        watcher.watch_recursively(&tmpdir);
1665
1666        let path = tmpdir.path().join("entry");
1667        std::fs::create_dir(&path).expect("create");
1668
1669        rx.wait_ordered_exact([
1670            expected(tmpdir.path()).access_open_any().optional(),
1671            expected(&path).create_folder(),
1672        ]);
1673        assert_eq!(
1674            watcher.get_watch_handles(),
1675            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf(), path])
1676        );
1677    }
1678
1679    #[test]
1680    fn chmod_dir() {
1681        let tmpdir = testdir();
1682        let (mut watcher, rx) = watcher();
1683
1684        let path = tmpdir.path().join("entry");
1685        std::fs::create_dir(&path).expect("create_dir");
1686        let mut permissions = std::fs::metadata(&path).expect("metadata").permissions();
1687        permissions.set_readonly(true);
1688
1689        watcher.watch_recursively(&tmpdir);
1690        std::fs::set_permissions(&path, permissions).expect("set_permissions");
1691
1692        rx.wait_ordered_exact([
1693            expected(tmpdir.path()).access_open_any().optional(),
1694            expected(&path).access_open_any().optional(),
1695            expected(&path).modify_meta_any(),
1696            expected(&path).modify_meta_any(),
1697        ])
1698        .ensure_no_tail();
1699        assert_eq!(
1700            watcher.get_watch_handles(),
1701            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf(), path])
1702        );
1703    }
1704
1705    #[test]
1706    fn rename_dir() {
1707        let tmpdir = testdir();
1708        let (mut watcher, rx) = watcher();
1709
1710        let path = tmpdir.path().join("entry");
1711        let new_path = tmpdir.path().join("new_path");
1712        std::fs::create_dir(&path).expect("create_dir");
1713
1714        watcher.watch_recursively(&tmpdir);
1715
1716        std::fs::rename(&path, &new_path).expect("rename");
1717
1718        rx.wait_ordered_exact([
1719            expected(tmpdir.path()).access_open_any().optional(),
1720            expected(&path).access_open_any().optional(),
1721            expected(&path).rename_from(),
1722            expected(&new_path).rename_to(),
1723            expected([&path, &new_path]).rename_both(),
1724        ])
1725        .ensure_trackers_len(1);
1726        assert_eq!(
1727            watcher.get_watch_handles(),
1728            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf(), new_path])
1729        );
1730    }
1731
1732    #[test]
1733    fn delete_dir() {
1734        let tmpdir = testdir();
1735        let (mut watcher, rx) = watcher();
1736
1737        let path = tmpdir.path().join("entry");
1738        std::fs::create_dir(&path).expect("create_dir");
1739
1740        watcher.watch_recursively(&tmpdir);
1741        std::fs::remove_dir(&path).expect("remove");
1742
1743        rx.wait_ordered_exact([
1744            expected(tmpdir.path()).access_open_any().optional(),
1745            expected(&path).access_open_any().optional(),
1746            expected(&path).remove_folder(),
1747        ])
1748        .ensure_no_tail();
1749        assert_eq!(
1750            watcher.get_watch_handles(),
1751            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1752        );
1753    }
1754
1755    #[test]
1756    fn delete_self_dir() {
1757        let tmpdir = testdir();
1758        let (mut watcher, rx) = watcher();
1759
1760        let path = tmpdir.path().join("entry");
1761        std::fs::create_dir(&path).expect("create_dir");
1762
1763        watcher.watch_recursively(&path);
1764        std::fs::remove_dir(&path).expect("remove");
1765
1766        rx.wait_ordered_exact([
1767            expected(&path).access_open_any().optional(),
1768            expected(&path).remove_folder(),
1769            expected(&path).access_open_any().optional(),
1770        ])
1771        .ensure_no_tail();
1772        assert_eq!(
1773            watcher.get_watch_handles(),
1774            HashSet::from([tmpdir.to_path_buf()])
1775        );
1776
1777        std::fs::create_dir(&path).expect("create_dir2");
1778
1779        rx.wait_ordered_exact([
1780            expected(&path).access_open_any().optional(),
1781            expected(&path).create_folder(),
1782            expected(&path).access_open_any().optional(),
1783        ])
1784        .ensure_no_tail();
1785        assert_eq!(
1786            watcher.get_watch_handles(),
1787            HashSet::from([tmpdir.to_path_buf(), path.clone()])
1788        );
1789    }
1790
1791    #[test]
1792    fn delete_self_dir_no_track() {
1793        let tmpdir = testdir();
1794        let (mut watcher, rx) = watcher();
1795
1796        let path = tmpdir.path().join("entry");
1797        std::fs::create_dir(&path).expect("create_dir");
1798
1799        watcher
1800            .watcher
1801            .watch(
1802                &path,
1803                WatchMode {
1804                    recursive_mode: RecursiveMode::Recursive,
1805                    target_mode: TargetMode::NoTrack,
1806                },
1807            )
1808            .expect("watch");
1809        std::fs::remove_dir(&path).expect("remove");
1810
1811        rx.wait_ordered_exact([expected(&path).remove_folder()])
1812            .ensure_no_tail();
1813        assert_eq!(watcher.get_watch_handles(), HashSet::from([]));
1814
1815        std::fs::create_dir(&path).expect("create_dir2");
1816
1817        rx.ensure_empty_with_wait();
1818    }
1819
1820    #[test]
1821    fn rename_dir_twice() {
1822        let tmpdir = testdir();
1823        let (mut watcher, rx) = watcher();
1824
1825        let path = tmpdir.path().join("entry");
1826        let new_path = tmpdir.path().join("new_path");
1827        let new_path2 = tmpdir.path().join("new_path2");
1828        std::fs::create_dir(&path).expect("create_dir");
1829
1830        watcher.watch_recursively(&tmpdir);
1831        std::fs::rename(&path, &new_path).expect("rename");
1832        std::fs::rename(&new_path, &new_path2).expect("rename2");
1833
1834        rx.wait_ordered_exact([
1835            expected(tmpdir.path()).access_open_any().optional(),
1836            expected(&path).access_open_any().optional(),
1837            expected(&path).rename_from(),
1838            expected(&new_path).rename_to(),
1839            expected([&path, &new_path]).rename_both(),
1840            expected(&new_path).access_open_any().optional(),
1841            expected(&new_path).rename_from(),
1842            expected(&new_path2).rename_to(),
1843            expected([&new_path, &new_path2]).rename_both(),
1844        ])
1845        .ensure_trackers_len(2);
1846        assert_eq!(
1847            watcher.get_watch_handles(),
1848            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf(), new_path2])
1849        );
1850    }
1851
1852    #[test]
1853    fn move_out_of_watched_dir() {
1854        let tmpdir = testdir();
1855        let subdir = tmpdir.path().join("subdir");
1856        let (mut watcher, rx) = watcher();
1857
1858        let path = subdir.join("entry");
1859        std::fs::create_dir_all(&subdir).expect("create_dir_all");
1860        std::fs::File::create_new(&path).expect("create");
1861
1862        watcher.watch_recursively(&subdir);
1863        let new_path = tmpdir.path().join("entry");
1864
1865        std::fs::rename(&path, &new_path).expect("rename");
1866
1867        rx.wait_ordered_exact([
1868            expected(&subdir).access_open_any(),
1869            expected(&path).rename_from(),
1870        ])
1871        .ensure_trackers_len(1)
1872        .ensure_no_tail();
1873        assert_eq!(
1874            watcher.get_watch_handles(),
1875            HashSet::from([tmpdir.to_path_buf(), subdir])
1876        );
1877    }
1878
1879    #[test]
1880    fn create_write_write_rename_write_remove() {
1881        let tmpdir = testdir();
1882        let (mut watcher, rx) = watcher();
1883
1884        let file1 = tmpdir.path().join("entry");
1885        let file2 = tmpdir.path().join("entry2");
1886        std::fs::File::create_new(&file2).expect("create file2");
1887        let new_path = tmpdir.path().join("renamed");
1888
1889        watcher.watch_recursively(&tmpdir);
1890        std::fs::write(&file1, "123").expect("write 1");
1891        std::fs::write(&file2, "321").expect("write 2");
1892        std::fs::rename(&file1, &new_path).expect("rename");
1893        std::fs::write(&new_path, b"1").expect("write 3");
1894        std::fs::remove_file(&new_path).expect("remove");
1895
1896        rx.wait_ordered_exact([
1897            expected(tmpdir.path()).access_open_any().optional(),
1898            expected(&file1).create_file(),
1899            expected(&file1).access_open_any(),
1900            expected(&file1).modify_data_any().multiple(),
1901            expected(&file1).access_close_write(),
1902            expected(&file2).access_open_any(),
1903            expected(&file2).modify_data_any().multiple(),
1904            expected(&file2).access_close_write(),
1905            expected(&file1).access_open_any().optional(),
1906            expected(&file1).rename_from(),
1907            expected(&new_path).rename_to(),
1908            expected([&file1, &new_path]).rename_both(),
1909            expected(&new_path).access_open_any(),
1910            expected(&new_path).modify_data_any().multiple(),
1911            expected(&new_path).access_close_write(),
1912            expected(&new_path).remove_file(),
1913        ]);
1914        assert_eq!(
1915            watcher.get_watch_handles(),
1916            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1917        );
1918    }
1919
1920    #[test]
1921    fn rename_twice() {
1922        let tmpdir = testdir();
1923        let (mut watcher, rx) = watcher();
1924
1925        let path = tmpdir.path().join("entry");
1926        std::fs::File::create_new(&path).expect("create");
1927
1928        watcher.watch_recursively(&tmpdir);
1929        let new_path1 = tmpdir.path().join("renamed1");
1930        let new_path2 = tmpdir.path().join("renamed2");
1931
1932        std::fs::rename(&path, &new_path1).expect("rename1");
1933        std::fs::rename(&new_path1, &new_path2).expect("rename2");
1934
1935        rx.wait_ordered_exact([
1936            expected(tmpdir.path()).access_open_any().optional(),
1937            expected(&path).access_open_any().optional(),
1938            expected(&path).rename_from(),
1939            expected(&new_path1).rename_to(),
1940            expected([&path, &new_path1]).rename_both(),
1941            expected(&new_path1).access_open_any().optional(),
1942            expected(&new_path1).rename_from(),
1943            expected(&new_path2).rename_to(),
1944            expected([&new_path1, &new_path2]).rename_both(),
1945        ])
1946        .ensure_no_tail()
1947        .ensure_trackers_len(2);
1948        assert_eq!(
1949            watcher.get_watch_handles(),
1950            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1951        );
1952    }
1953
1954    #[test]
1955    fn set_file_mtime() {
1956        let tmpdir = testdir();
1957        let (mut watcher, rx) = watcher();
1958
1959        let path = tmpdir.path().join("entry");
1960        let file = std::fs::File::create_new(&path).expect("create");
1961
1962        watcher.watch_recursively(&tmpdir);
1963
1964        file.set_modified(
1965            std::time::SystemTime::now()
1966                .checked_sub(Duration::from_secs(60 * 60))
1967                .expect("time"),
1968        )
1969        .expect("set_time");
1970
1971        rx.wait_ordered_exact([
1972            expected(tmpdir.path()).access_open_any().optional(),
1973            expected(&path).modify_data_any(),
1974        ])
1975        .ensure_no_tail();
1976        assert_eq!(
1977            watcher.get_watch_handles(),
1978            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf()])
1979        );
1980    }
1981
1982    #[test]
1983    fn write_file_non_recursive_watch() {
1984        let tmpdir = testdir();
1985        let (mut watcher, rx) = watcher();
1986
1987        let path = tmpdir.path().join("entry");
1988        std::fs::File::create_new(&path).expect("create");
1989
1990        watcher.watch_nonrecursively(&path);
1991
1992        std::fs::write(&path, b"123").expect("write");
1993
1994        rx.wait_ordered_exact([
1995            expected(&path).access_open_any(),
1996            expected(&path).modify_data_any().multiple(),
1997            expected(&path).access_close_write(),
1998        ])
1999        .ensure_no_tail();
2000        assert_eq!(
2001            watcher.get_watch_handles(),
2002            HashSet::from([tmpdir.to_path_buf()])
2003        );
2004    }
2005
2006    #[test]
2007    fn watch_recursively_then_unwatch_child_stops_events_from_child() {
2008        let tmpdir = testdir();
2009        let (mut watcher, rx) = watcher();
2010
2011        let subdir = tmpdir.path().join("subdir");
2012        let file = subdir.join("file");
2013        std::fs::create_dir(&subdir).expect("create");
2014
2015        watcher.watch_recursively(&tmpdir);
2016
2017        std::fs::File::create(&file).expect("create");
2018
2019        rx.wait_ordered_exact([
2020            expected(tmpdir.path()).access_open_any().optional(),
2021            expected(&subdir).access_open_any().optional(),
2022            expected(&file).create_file(),
2023            expected(&file).access_open_any(),
2024            expected(&file).access_close_write(),
2025        ])
2026        .ensure_no_tail();
2027        assert_eq!(
2028            watcher.get_watch_handles(),
2029            HashSet::from([tmpdir.parent_path_buf(), tmpdir.to_path_buf(), subdir])
2030        );
2031
2032        // TODO: https://github.com/rolldown/notify/issues/8
2033        // watcher.watcher.unwatch(&subdir).expect("unwatch");
2034
2035        // std::fs::write(&file, b"123").expect("write");
2036
2037        // std::fs::remove_dir_all(&subdir).expect("remove_dir_all");
2038
2039        // rx.wait_ordered_exact([
2040        //     expected(&subdir).access_open_any().optional(),
2041        //     expected(&subdir).remove_folder(),
2042        // ])
2043        // .ensure_no_tail();
2044    }
2045
2046    #[test]
2047    fn write_to_a_hardlink_pointed_to_the_watched_file_triggers_an_event() {
2048        let tmpdir = testdir();
2049        let (mut watcher, rx) = watcher();
2050
2051        let subdir = tmpdir.path().join("subdir");
2052        let subdir2 = tmpdir.path().join("subdir2");
2053        let file = subdir.join("file");
2054        let hardlink = subdir2.join("hardlink");
2055
2056        std::fs::create_dir(&subdir).expect("create");
2057        std::fs::create_dir(&subdir2).expect("create2");
2058        std::fs::write(&file, "").expect("file");
2059        std::fs::hard_link(&file, &hardlink).expect("hardlink");
2060
2061        watcher.watch_nonrecursively(&file);
2062
2063        std::fs::write(&hardlink, "123123").expect("write to the hard link");
2064
2065        rx.wait_ordered_exact([
2066            expected(&file).access_open_any(),
2067            expected(&file).modify_data_any().multiple(),
2068            expected(&file).access_close_write(),
2069        ]);
2070        assert_eq!(watcher.get_watch_handles(), HashSet::from([subdir, file]));
2071    }
2072
2073    #[test]
2074    fn write_to_a_hardlink_pointed_to_the_watched_file_triggers_an_event_even_if_the_parent_is_watched()
2075     {
2076        let tmpdir = testdir();
2077        let (mut watcher, rx) = watcher();
2078
2079        let subdir1 = tmpdir.path().join("subdir1");
2080        let subdir2 = subdir1.join("subdir2");
2081        let file = subdir2.join("file");
2082        let hardlink = tmpdir.path().join("hardlink");
2083
2084        std::fs::create_dir_all(&subdir2).expect("create");
2085        std::fs::write(&file, "").expect("file");
2086        std::fs::hard_link(&file, &hardlink).expect("hardlink");
2087
2088        watcher.watch_nonrecursively(&subdir2);
2089        watcher.watch_nonrecursively(&file);
2090
2091        std::fs::write(&hardlink, "123123").expect("write to the hard link");
2092
2093        rx.wait_ordered_exact([
2094            expected(&subdir2).access_open_any().optional(),
2095            expected(&file).access_open_any(),
2096            expected(&file).modify_data_any().multiple(),
2097            expected(&file).access_close_write(),
2098        ]);
2099        assert_eq!(
2100            watcher.get_watch_handles(),
2101            HashSet::from([subdir1, subdir2, file])
2102        );
2103    }
2104
2105    #[test]
2106    fn write_to_a_hardlink_pointed_to_the_file_in_the_watched_dir_doesnt_trigger_an_event() {
2107        let tmpdir = testdir();
2108        let (mut watcher, rx) = watcher();
2109
2110        let subdir = tmpdir.path().join("subdir");
2111        let subdir2 = tmpdir.path().join("subdir2");
2112        let file = subdir.join("file");
2113        let hardlink = subdir2.join("hardlink");
2114
2115        std::fs::create_dir(&subdir).expect("create");
2116        std::fs::create_dir(&subdir2).expect("create");
2117        std::fs::write(&file, "").expect("file");
2118        std::fs::hard_link(&file, &hardlink).expect("hardlink");
2119
2120        watcher.watch_nonrecursively(&subdir);
2121
2122        std::fs::write(&hardlink, "123123").expect("write to the hard link");
2123
2124        rx.wait_ordered_exact([expected(&subdir).access_open_any().optional()])
2125            .ensure_no_tail();
2126        assert_eq!(
2127            watcher.get_watch_handles(),
2128            HashSet::from([tmpdir.to_path_buf(), subdir])
2129        );
2130    }
2131
2132    #[test]
2133    #[ignore = "see https://github.com/notify-rs/notify/issues/727"]
2134    fn recursive_creation() {
2135        let tmpdir = testdir();
2136        let nested1 = tmpdir.path().join("1");
2137        let nested2 = tmpdir.path().join("1/2");
2138        let nested3 = tmpdir.path().join("1/2/3");
2139        let nested4 = tmpdir.path().join("1/2/3/4");
2140        let nested5 = tmpdir.path().join("1/2/3/4/5");
2141        let nested6 = tmpdir.path().join("1/2/3/4/5/6");
2142        let nested7 = tmpdir.path().join("1/2/3/4/5/6/7");
2143        let nested8 = tmpdir.path().join("1/2/3/4/5/6/7/8");
2144        let nested9 = tmpdir.path().join("1/2/3/4/5/6/7/8/9");
2145
2146        let (mut watcher, rx) = watcher();
2147
2148        watcher.watch_recursively(&tmpdir);
2149
2150        std::fs::create_dir_all(&nested9).expect("create_dir_all");
2151        rx.wait_ordered([
2152            expected(&nested1).create_folder(),
2153            expected(&nested2).create_folder(),
2154            expected(&nested3).create_folder(),
2155            expected(&nested4).create_folder(),
2156            expected(&nested5).create_folder(),
2157            expected(&nested6).create_folder(),
2158            expected(&nested7).create_folder(),
2159            expected(&nested8).create_folder(),
2160            expected(&nested9).create_folder(),
2161        ]);
2162        assert_eq!(
2163            watcher.get_watch_handles(),
2164            HashSet::from([
2165                tmpdir.to_path_buf(),
2166                nested1,
2167                nested2,
2168                nested3,
2169                nested4,
2170                nested5,
2171                nested6,
2172                nested7,
2173                nested8,
2174                nested9
2175            ])
2176        );
2177    }
2178
2179    #[test]
2180    fn upgrade_to_recursive() {
2181        let tmpdir = testdir();
2182        let (mut watcher, rx) = watcher();
2183
2184        let path = tmpdir.path().join("upgrade");
2185        let deep = tmpdir.path().join("upgrade/deep");
2186        let file = tmpdir.path().join("upgrade/deep/file");
2187        std::fs::create_dir_all(&deep).expect("create_dir");
2188
2189        watcher.watch_nonrecursively(&path);
2190        std::fs::File::create_new(&file).expect("create");
2191        std::fs::remove_file(&file).expect("delete");
2192
2193        rx.ensure_empty_with_wait();
2194
2195        watcher.watch_recursively(&path);
2196        std::fs::File::create_new(&file).expect("create");
2197
2198        rx.wait_ordered([
2199            expected(&file).create_file(),
2200            expected(&file).access_open_any(),
2201            expected(&file).access_close_write(),
2202        ])
2203        .ensure_no_tail();
2204        assert_eq!(
2205            watcher.get_watch_handles(),
2206            HashSet::from([tmpdir.to_path_buf(), path, deep])
2207        );
2208    }
2209}