use crate::{
Config, Error, EventHandler, Receiver, RecursiveMode, Sender, Watcher,
paths::{WatchPath, absolute_path},
unbounded,
};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
thread,
time::Duration,
};
pub(crate) enum PollMessage {
Poll,
PollAndWait(Sender<crate::Result<()>>),
}
pub type ScanEvent = crate::Result<PathBuf>;
pub trait ScanEventHandler: Send + 'static {
fn handle_event(&mut self, event: ScanEvent);
}
impl<F> ScanEventHandler for F
where
F: FnMut(ScanEvent) + Send + 'static,
{
fn handle_event(&mut self, event: ScanEvent) {
(self)(event);
}
}
#[cfg(feature = "crossbeam-channel")]
impl ScanEventHandler for crossbeam_channel::Sender<ScanEvent> {
fn handle_event(&mut self, event: ScanEvent) {
let _ = self.send(event);
}
}
#[cfg(feature = "flume")]
impl ScanEventHandler for flume::Sender<ScanEvent> {
fn handle_event(&mut self, event: ScanEvent) {
let _ = self.send(event);
}
}
impl ScanEventHandler for std::sync::mpsc::Sender<ScanEvent> {
fn handle_event(&mut self, event: ScanEvent) {
let _ = self.send(event);
}
}
impl ScanEventHandler for () {
fn handle_event(&mut self, _event: ScanEvent) {}
}
use data::{DataBuilder, WatchData};
mod data {
use crate::{
EventHandler, RecursiveMode,
event::{CreateKind, DataChange, Event, EventKind, MetadataKind, ModifyKind, RemoveKind},
paths::{WatchPath, reported_path},
};
use notify_types::event::EventKindMask;
use std::{
cell::RefCell,
collections::HashMap,
fmt::{self, Debug},
fs::{self, File, FileType, Metadata},
io::{self, Read},
path::{Path, PathBuf},
time::Instant,
};
use walkdir::WalkDir;
use xxhash_rust::xxh3::Xxh3Default;
use super::ScanEventHandler;
const NANOS_PER_SECOND: i128 = 1_000_000_000;
fn system_time_to_nanos(time: std::time::SystemTime) -> i128 {
match time.duration_since(std::time::SystemTime::UNIX_EPOCH) {
Ok(d) => d.as_nanos() as i128,
Err(e) => -(e.duration().as_nanos() as i128),
}
}
pub(super) struct DataBuilder {
emitter: EventEmitter,
scan_emitter: Option<Box<RefCell<dyn ScanEventHandler>>>,
compare_contents: bool,
now: Instant,
}
impl DataBuilder {
pub(super) fn new<F, G>(
event_handler: F,
compare_content: bool,
scan_emitter: Option<G>,
event_kinds: EventKindMask,
) -> Self
where
F: EventHandler,
G: ScanEventHandler,
{
let scan_emitter = match scan_emitter {
None => None,
Some(v) => {
let intermediate: Box<RefCell<dyn ScanEventHandler>> =
Box::new(RefCell::new(v));
Some(intermediate)
}
};
Self {
emitter: EventEmitter::new(event_handler, event_kinds),
scan_emitter,
compare_contents: compare_content,
now: Instant::now(),
}
}
pub(super) fn update_timestamp(&mut self) {
self.now = Instant::now();
}
pub(super) fn build_watch_data(
&self,
root: WatchPath,
is_recursive: bool,
follow_symlinks: bool,
) -> crate::Result<WatchData> {
WatchData::new(self, root, is_recursive, follow_symlinks)
}
fn build_path_data(&self, meta_path: &MetaPath) -> PathData {
PathData::new(self, meta_path)
}
}
impl Debug for DataBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("DataBuilder")
.field("compare_contents", &self.compare_contents)
.field("now", &self.now)
.finish()
}
}
#[derive(Debug)]
pub(super) struct WatchData {
root: PathBuf,
requested_root: PathBuf,
user_data: Option<u64>,
is_recursive: bool,
follow_symlinks: bool,
all_path_data: HashMap<PathBuf, PathData>,
}
impl WatchData {
fn new(
data_builder: &DataBuilder,
root: WatchPath,
is_recursive: bool,
follow_symlinks: bool,
) -> crate::Result<Self> {
fs::metadata(&root.absolute)
.map_err(|e| crate::Error::io_watch(e).add_path(root.requested.clone()))?;
let all_path_data = Self::scan_all_path_data(
data_builder,
root.absolute.clone(),
root.requested.clone(),
root.user_data,
is_recursive,
follow_symlinks,
true,
)
.collect();
Ok(Self {
root: root.absolute,
requested_root: root.requested,
user_data: root.user_data,
is_recursive,
follow_symlinks,
all_path_data,
})
}
pub(super) fn rescan(&mut self, data_builder: &mut DataBuilder) {
for (path, new_path_data) in Self::scan_all_path_data(
data_builder,
self.root.clone(),
self.requested_root.clone(),
self.user_data,
self.is_recursive,
self.follow_symlinks,
false,
) {
let event_kind = if let Some(old_path_data) = self.all_path_data.get_mut(&path) {
let event_kind =
PathData::compare_to_kind(Some(&*old_path_data), Some(&new_path_data));
*old_path_data = new_path_data;
event_kind
} else {
let event_kind = PathData::compare_to_kind(None, Some(&new_path_data));
self.all_path_data.insert(path.clone(), new_path_data);
event_kind
};
if let Some(event_kind) = event_kind {
let mut event = Event::new(event_kind).add_path(reported_path(
&self.root,
&self.requested_root,
&path,
));
if let Some(user_data) = self.user_data {
event = event.set_user_data(user_data);
}
data_builder.emitter.emit_ok(event);
}
}
let mut disappeared_paths = Vec::new();
for (path, path_data) in self.all_path_data.iter() {
if path_data.last_check < data_builder.now {
disappeared_paths.push(path.clone());
}
}
for path in disappeared_paths {
let old_path_data = self.all_path_data.remove(&path);
if let Some(event_kind) = PathData::compare_to_kind(old_path_data.as_ref(), None) {
let mut event = Event::new(event_kind).add_path(reported_path(
&self.root,
&self.requested_root,
&path,
));
if let Some(user_data) = self.user_data {
event = event.set_user_data(user_data);
}
data_builder.emitter.emit_ok(event);
}
}
}
fn scan_all_path_data(
data_builder: &'_ DataBuilder,
root: PathBuf,
requested_root: PathBuf,
user_data: Option<u64>,
is_recursive: bool,
follow_symlinks: bool,
is_initial: bool,
) -> impl Iterator<Item = (PathBuf, PathData)> + '_ {
log::trace!("rescanning {root:?}");
WalkDir::new(root.clone())
.follow_links(follow_symlinks)
.max_depth(Self::dir_scan_depth(is_recursive))
.into_iter()
.filter_map(move |entry_res| match entry_res {
Ok(entry) => Some(entry),
Err(err) => {
log::warn!("walkdir error scanning {err:?}");
if let Some(io_error) = err.io_error() {
let new_io_error = io::Error::new(io_error.kind(), err.to_string());
data_builder
.emitter
.emit_io_err(new_io_error, err.path(), user_data);
} else {
let crate_err =
crate::Error::new(crate::ErrorKind::Generic(err.to_string()));
data_builder
.emitter
.emit(Err(crate_err.set_user_data_opt(user_data)));
}
None
}
})
.filter_map(move |entry| match entry.metadata() {
Ok(metadata) => {
let path = entry.into_path();
if is_initial {
if let Some(ref emitter) = data_builder.scan_emitter {
emitter.borrow_mut().handle_event(Ok(reported_path(
&root,
&requested_root,
&path,
)));
}
}
let meta_path = MetaPath::from_parts_unchecked(path, metadata);
let data_path = data_builder.build_path_data(&meta_path);
Some((meta_path.into_path(), data_path))
}
Err(e) => {
let path = entry.into_path();
data_builder.emitter.emit_io_err(e, Some(path), user_data);
None
}
})
}
fn dir_scan_depth(is_recursive: bool) -> usize {
if is_recursive { usize::MAX } else { 1 }
}
pub(super) fn recursive_mode(&self) -> RecursiveMode {
if self.is_recursive {
RecursiveMode::Recursive
} else {
RecursiveMode::NonRecursive
}
}
pub(super) fn requested_root(&self) -> &Path {
&self.requested_root
}
}
#[derive(Debug, Clone)]
struct PathData {
file_type: FileType,
mtime: i128,
size: Option<u64>,
hash: Option<u64>,
last_check: Instant,
}
impl PathData {
fn new(data_builder: &DataBuilder, meta_path: &MetaPath) -> PathData {
let metadata = meta_path.metadata();
let file_type = metadata.file_type();
let is_file = file_type.is_file();
let mut mtime = metadata.modified().map_or(0, system_time_to_nanos);
if file_type.is_dir() {
mtime = mtime / NANOS_PER_SECOND * NANOS_PER_SECOND;
}
PathData {
file_type,
mtime,
size: is_file.then_some(metadata.len()),
hash: if is_file && data_builder.compare_contents {
content_hash(meta_path.path()).ok()
} else {
None
},
last_check: data_builder.now,
}
}
fn compare_to_kind(old: Option<&PathData>, new: Option<&PathData>) -> Option<EventKind> {
match (old, new) {
(Some(old), Some(new)) => {
let same_contents = old.hash.zip(new.hash).map(|(old, new)| old == new);
if same_contents == Some(false) || new.size != old.size {
Some(EventKind::Modify(ModifyKind::Data(DataChange::Any)))
} else if new.mtime == old.mtime {
None
} else if new.size.is_some() && same_contents.is_none() {
Some(EventKind::Modify(ModifyKind::Data(DataChange::Any)))
} else {
Some(EventKind::Modify(ModifyKind::Metadata(
MetadataKind::WriteTime,
)))
}
}
(None, Some(new)) => Some(EventKind::Create(if new.file_type.is_dir() {
CreateKind::Folder
} else if new.file_type.is_file() {
CreateKind::File
} else {
CreateKind::Other
})),
(Some(old), None) => Some(EventKind::Remove(if old.file_type.is_dir() {
RemoveKind::Folder
} else if old.file_type.is_file() {
RemoveKind::File
} else {
RemoveKind::Other
})),
(None, None) => None,
}
}
}
pub(super) fn content_hash(path: &Path) -> io::Result<u64> {
let mut hasher = Xxh3Default::new();
let mut file = File::open(path)?;
let mut buf = [0u8; 8 * 1024];
loop {
let n = match file.read(&mut buf) {
Ok(0) => break,
Ok(len) => len,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
hasher.update(&buf[..n]);
}
Ok(hasher.digest())
}
#[derive(Debug)]
pub(super) struct MetaPath {
path: PathBuf,
metadata: Metadata,
}
impl MetaPath {
fn from_parts_unchecked(path: PathBuf, metadata: Metadata) -> Self {
Self { path, metadata }
}
fn path(&self) -> &Path {
&self.path
}
fn metadata(&self) -> &Metadata {
&self.metadata
}
fn into_path(self) -> PathBuf {
self.path
}
}
struct EventEmitter {
handler: Box<RefCell<dyn EventHandler>>,
event_kinds: EventKindMask,
}
impl EventEmitter {
fn new<F: EventHandler>(event_handler: F, event_kinds: EventKindMask) -> Self {
Self {
handler: Box::new(RefCell::new(event_handler)),
event_kinds,
}
}
fn emit(&self, event: crate::Result<Event>) {
self.handler.borrow_mut().handle_event(event);
}
fn emit_ok(&self, event: Event) {
if self.event_kinds.matches(&event.kind) {
self.emit(Ok(event))
}
}
fn emit_io_err<E, P>(&self, err: E, path: Option<P>, user_data: Option<u64>)
where
E: Into<io::Error>,
P: Into<PathBuf>,
{
let e = crate::Error::io(err.into()).set_user_data_opt(user_data);
if let Some(path) = path {
self.emit(Err(e.add_path(path.into())));
} else {
self.emit(Err(e));
}
}
}
#[cfg(test)]
mod tests {
use super::PathData;
use std::time::Instant;
#[test]
fn unavailable_hash_is_not_a_content_change() {
let file = tempfile::tempfile().expect("create file");
let file_type = file.metadata().expect("read metadata").file_type();
let path_data = |hash| PathData {
file_type,
mtime: 0,
size: Some(1),
hash,
last_check: Instant::now(),
};
for (old, new) in [(Some(1), None), (None, Some(1))] {
assert_eq!(
PathData::compare_to_kind(Some(&path_data(old)), Some(&path_data(new))),
None,
"old hash {old:?}, new hash {new:?}"
);
}
}
}
}
#[derive(Debug)]
pub struct PollWatcher {
watches: Arc<Mutex<HashMap<PathBuf, WatchData>>>,
data_builder: Arc<Mutex<DataBuilder>>,
want_to_stop: Arc<AtomicBool>,
message_channel: Sender<PollMessage>,
delay: Option<Duration>,
follow_sylinks: bool,
}
impl PollWatcher {
pub fn new<F: EventHandler>(event_handler: F, config: Config) -> crate::Result<PollWatcher> {
Self::with_opt::<_, ()>(event_handler, config, None)
}
pub fn poll(&self) -> crate::Result<()> {
self.message_channel
.send(PollMessage::Poll)
.map_err(|_| Error::generic("failed to send poll message"))?;
Ok(())
}
pub fn poll_blocking(&self) -> crate::Result<()> {
let (done_tx, done_rx) = std::sync::mpsc::channel();
self.message_channel
.send(PollMessage::PollAndWait(done_tx))
.map_err(|_| Error::generic("failed to send poll message"))?;
done_rx
.recv()
.map_err(|_| Error::generic("poll thread disconnected"))?
}
#[cfg(test)]
pub(crate) fn poll_sender(&self) -> Sender<PollMessage> {
self.message_channel.clone()
}
pub fn with_initial_scan<F: EventHandler, G: ScanEventHandler>(
event_handler: F,
config: Config,
scan_callback: G,
) -> crate::Result<PollWatcher> {
Self::with_opt(event_handler, config, Some(scan_callback))
}
fn with_opt<F: EventHandler, G: ScanEventHandler>(
event_handler: F,
config: Config,
scan_callback: Option<G>,
) -> crate::Result<PollWatcher> {
let data_builder = DataBuilder::new(
event_handler,
config.compare_contents(),
scan_callback,
config.event_kinds(),
);
let (tx, rx) = unbounded::<PollMessage>();
let poll_watcher = PollWatcher {
watches: Default::default(),
data_builder: Arc::new(Mutex::new(data_builder)),
want_to_stop: Arc::new(AtomicBool::new(false)),
delay: config.poll_interval(),
follow_sylinks: config.follow_symlinks(),
message_channel: tx,
};
poll_watcher.run(rx)?;
Ok(poll_watcher)
}
fn run(&self, rx: Receiver<PollMessage>) -> crate::Result<()> {
let watches = Arc::clone(&self.watches);
let data_builder = Arc::clone(&self.data_builder);
let want_to_stop = Arc::clone(&self.want_to_stop);
let delay = self.delay;
thread::Builder::new()
.name("notify-rs poll loop".to_string())
.spawn(move || {
let mut first_auto_scan = true;
loop {
if want_to_stop.load(Ordering::SeqCst) {
break;
}
let msg = match delay {
Some(_delay) if first_auto_scan => {
first_auto_scan = false;
None
}
Some(delay) => match rx.recv_timeout(delay) {
Ok(msg) => Some(msg),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => None,
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
},
None => match rx.recv() {
Ok(msg) => Some(msg),
Err(_) => break,
},
};
let scan_res = {
let mut watches = watches.lock().unwrap_or_else(|e| e.into_inner());
let mut data_builder =
data_builder.lock().unwrap_or_else(|e| e.into_inner());
data_builder.update_timestamp();
let vals = watches.values_mut();
for watch_data in vals {
watch_data.rescan(&mut data_builder);
}
Ok(())
};
if let Some(PollMessage::PollAndWait(done)) = msg {
let _ = done.send(scan_res);
}
}
})?;
Ok(())
}
fn watch_inner(&mut self, path: &Path, config: crate::WatchPathConfig) -> crate::Result<()> {
let watch_path = WatchPath::new(path, config.user_data())?;
let mut watches = self.watches.lock().unwrap_or_else(|e| e.into_inner());
let mut data_builder = self.data_builder.lock().unwrap_or_else(|e| e.into_inner());
data_builder.update_timestamp();
let watch_data = data_builder.build_watch_data(
watch_path.clone(),
config.recursive_mode().is_recursive(),
self.follow_sylinks,
)?;
watches.insert(watch_path.absolute, watch_data);
Ok(())
}
fn unwatch_inner(&mut self, path: &Path) -> crate::Result<()> {
let path = absolute_path(path)?;
self.watches
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&path)
.map(|_| ())
.ok_or_else(crate::Error::watch_not_found)
}
}
impl Watcher for PollWatcher {
fn new<F: EventHandler>(event_handler: F, config: Config) -> crate::Result<Self> {
Self::new(event_handler, config)
}
fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> crate::Result<()> {
self.watch_with(path, crate::WatchPathConfig::new(recursive_mode))
}
fn watch_with(&mut self, path: &Path, config: crate::WatchPathConfig) -> crate::Result<()> {
let user_data = config.user_data();
self.watch_inner(path, config)
.map_err(|err| err.set_user_data_opt(user_data))
}
fn unwatch(&mut self, path: &Path) -> crate::Result<()> {
self.unwatch_inner(path)
}
fn watched_paths(&self) -> crate::Result<Vec<crate::WatchedPath>> {
let watches = self.watches.lock().unwrap_or_else(|e| e.into_inner());
Ok(watches
.values()
.map(|watch| {
crate::WatchedPath::new(
watch.requested_root().to_path_buf(),
watch.recursive_mode(),
)
})
.collect())
}
fn kind() -> crate::WatcherKind {
crate::WatcherKind::PollWatcher
}
}
impl Drop for PollWatcher {
fn drop(&mut self) {
self.want_to_stop.store(true, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::PollWatcher;
use crate::{
Config, RecursiveMode, WatchedPath, Watcher,
event::{CreateKind, DataChange, Event, EventKind, MetadataKind, ModifyKind, RemoveKind},
test::*,
};
use notify_types::event::EventKindMask;
use std::{
fs,
path::Path,
sync::mpsc,
time::{Duration, UNIX_EPOCH},
};
fn watcher() -> (TestWatcher<PollWatcher>, Receiver) {
poll_watcher_channel()
}
const WRITE_TIME_MS: i64 = 1_700_000_000_000;
fn write_at(path: &Path, contents: &str, offset_ms: i64) {
fs::write(path, contents).expect("write contents");
fs::File::options()
.write(true)
.open(path)
.expect("open to set write time")
.set_modified(UNIX_EPOCH + Duration::from_millis((WRITE_TIME_MS + offset_ms) as u64))
.expect("set write time");
}
fn kinds_after_rewrite(config: Config, contents: &str, offset_ms: i64) -> Vec<EventKind> {
let tmpdir = testdir();
let path = tmpdir.path().join("entry");
write_at(&path, "initial", 0);
let (tx, rx) = mpsc::channel();
let mut watcher =
PollWatcher::new(tx, config.with_manual_polling()).expect("create watcher");
watcher
.watch(&path, RecursiveMode::NonRecursive)
.expect("watch file");
write_at(&path, contents, offset_ms);
watcher.poll_blocking().expect("poll for changes");
rx.try_iter()
.map(|event| event.expect("watch event must not be an error").kind)
.collect()
}
#[test]
fn poll_watcher_is_send_and_sync() {
fn check<T: Send + Sync>() {}
check::<PollWatcher>();
}
#[test]
fn watch_nonexistent_path_returns_path_not_found() {
let tmpdir = testdir();
let path = tmpdir.path().join("does_not_exist");
let mut watcher = PollWatcher::new(|_| {}, Config::default()).expect("create watcher");
let err = watcher
.watch(&path, RecursiveMode::Recursive)
.expect_err("watching a nonexistent path must return an error");
assert!(matches!(err.kind, crate::ErrorKind::PathNotFound));
assert_eq!(err.paths, vec![path]);
let watched = watcher.watched_paths().expect("list watched paths");
assert!(
watched.is_empty(),
"a failed watch must not be registered, got {watched:?}"
);
}
#[test]
fn watch_existing_paths_succeed() {
let tmpdir = testdir();
let file = tmpdir.path().join("entry");
std::fs::write(&file, "contents").expect("write file");
let mut watcher = PollWatcher::new(|_| {}, Config::default()).expect("create watcher");
watcher
.watch(&file, RecursiveMode::NonRecursive)
.expect("watch existing file");
watcher
.watch(tmpdir.path(), RecursiveMode::Recursive)
.expect("watch existing directory");
let watched = watcher.watched_paths().expect("list watched paths");
assert_eq!(watched.len(), 2);
}
#[test]
fn classifies_file_changes() {
let data = EventKind::Modify(ModifyKind::Data(DataChange::Any));
let write_time = EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime));
let cases = [
("updated", 10_000, Some(data), Some(data)),
("longer contents", 0, Some(data), Some(data)),
("updated", -10_000, Some(data), Some(data)),
("updated", 0, None, Some(data)),
("initial", 10_000, Some(data), Some(write_time)),
("initial", -10_000, Some(data), Some(write_time)),
("initial", 100, Some(data), Some(write_time)),
("initial", 0, None, None),
];
for (contents, offset_ms, without_hash, with_hash) in cases {
for (compare_contents, expected) in [(false, without_hash), (true, with_hash)] {
let config = Config::default().with_compare_contents(compare_contents);
assert_eq!(
kinds_after_rewrite(config, contents, offset_ms),
Vec::from_iter(expected),
"contents={contents:?}, offset_ms={offset_ms}, \
compare_contents={compare_contents}"
);
}
}
}
#[test]
fn modify_data_mask_passes_file_writes() {
for compare_contents in [false, true] {
let config = Config::default()
.with_event_kinds(EventKindMask::MODIFY_DATA)
.with_compare_contents(compare_contents);
assert_eq!(
kinds_after_rewrite(config, "updated", 10_000),
[EventKind::Modify(ModifyKind::Data(DataChange::Any))],
"compare_contents={compare_contents}"
);
}
}
#[cfg(unix)]
#[test]
fn reports_symlink_and_directory_mtime_changes_as_write_time() {
use std::os::unix::fs::symlink;
use nix::{
fcntl::AT_FDCWD,
sys::{
stat::{UtimensatFlags, utimensat},
time::TimeSpec,
},
};
use crate::event::Event;
for compare_contents in [false, true] {
let tmpdir = testdir();
let link = tmpdir.path().join("link");
symlink("missing", &link).expect("create dangling symlink");
let set_mtime = |path: &Path, secs, nanos| {
utimensat(
AT_FDCWD,
path,
&TimeSpec::UTIME_OMIT,
&TimeSpec::new(secs, nanos),
UtimensatFlags::NoFollowSymlink,
)
.expect("set mtime");
};
set_mtime(&link, 1_700_000_000, 100_000_000);
set_mtime(tmpdir.path(), 1_700_000_000, 0);
let (tx, rx) = mpsc::channel();
let config = Config::default()
.with_manual_polling()
.with_follow_symlinks(false)
.with_compare_contents(compare_contents);
let mut watcher = PollWatcher::new(tx, config).expect("create watcher");
watcher
.watch(tmpdir.path(), RecursiveMode::Recursive)
.expect("watch directory");
let steps = [
(link.as_path(), 1_700_000_000, 300_000_000),
(link.as_path(), 1_700_000_000, 200_000_000),
(tmpdir.path(), 1_700_000_002, 0),
(tmpdir.path(), 1_700_000_001, 0),
];
for (path, secs, nanos) in steps {
set_mtime(path, secs, nanos);
watcher.poll_blocking().expect("poll for changes");
let events = rx
.try_iter()
.collect::<crate::Result<Vec<_>>>()
.expect("watch events must not be errors");
assert_eq!(
events,
vec![
Event::new(EventKind::Modify(ModifyKind::Metadata(
MetadataKind::WriteTime,
)))
.add_path(path.to_path_buf())
],
"compare_contents={compare_contents}, secs={secs}, nanos={nanos}"
);
}
watcher.poll_blocking().expect("poll without changes");
assert!(rx.try_recv().is_err(), "unchanged paths emitted an event");
}
}
#[test]
fn watch_operations_recover_poisoned_mutexes() {
use std::{path::Path, sync::Arc};
let tmpdir = testdir();
let mut watcher = PollWatcher::new(|_| {}, Config::default().with_manual_polling())
.expect("create watcher");
let watches = Arc::clone(&watcher.watches);
let data_builder = Arc::clone(&watcher.data_builder);
std::thread::spawn(move || {
let _watches = watches.lock().expect("lock watches");
let _data_builder = data_builder.lock().expect("lock data builder");
panic!("poison polling mutexes for test");
})
.join()
.expect_err("poisoning thread must panic");
watcher
.watch(tmpdir.path(), RecursiveMode::Recursive)
.expect("watch after poisoning");
assert_eq!(
watcher.watched_paths().expect("list after poisoning"),
vec![WatchedPath::new(
tmpdir.path().to_path_buf(),
RecursiveMode::Recursive
)]
);
watcher.poll_blocking().expect("poll after poisoning");
watcher
.unwatch(tmpdir.path())
.expect("unwatch after poisoning");
assert!(watcher.watched_paths().unwrap().is_empty());
let result = watcher.unwatch_inner(Path::new("/path/that/is/not/watched"));
assert!(result.is_err());
}
#[test]
fn watched_paths_reflect_watch_and_unwatch() {
let tmpdir = testdir();
let dir_a = tmpdir.path().join("a");
let dir_b = tmpdir.path().join("b");
std::fs::create_dir(&dir_a).expect("create dir a");
std::fs::create_dir(&dir_b).expect("create dir b");
let mut watcher = PollWatcher::new(|_| {}, Config::default()).expect("create watcher");
watcher
.watch(&dir_a, RecursiveMode::Recursive)
.expect("watch dir a");
watcher
.watch(&dir_b, RecursiveMode::NonRecursive)
.expect("watch dir b");
let watched = watcher.watched_paths().expect("list watched paths");
assert!(watched.contains(&WatchedPath::new(
dir_a.canonicalize().expect("canonicalize dir a"),
RecursiveMode::Recursive,
)));
assert!(watched.contains(&WatchedPath::new(
dir_b.canonicalize().expect("canonicalize dir b"),
RecursiveMode::NonRecursive,
)));
watcher.unwatch(&dir_a).expect("unwatch dir a");
let watched = watcher
.watched_paths()
.expect("list watched paths after unwatch");
assert!(!watched.contains(&WatchedPath::new(
dir_a.canonicalize().expect("canonicalize dir a"),
RecursiveMode::Recursive,
)));
assert!(watched.contains(&WatchedPath::new(
dir_b.canonicalize().expect("canonicalize dir b"),
RecursiveMode::NonRecursive,
)));
}
#[test]
fn rewatching_same_path_replaces_recursive_mode() {
let tmpdir = testdir();
let root = tmpdir.path().canonicalize().expect("canonicalize root");
let mut watcher = PollWatcher::new(|_| {}, Config::default()).expect("create watcher");
watcher
.watch(tmpdir.path(), RecursiveMode::Recursive)
.expect("watch recursively");
watcher
.watch(tmpdir.path(), RecursiveMode::NonRecursive)
.expect("watch non-recursively");
let watched = watcher.watched_paths().expect("list watched paths");
assert!(watched.contains(&WatchedPath::new(root.clone(), RecursiveMode::NonRecursive)));
assert!(!watched.contains(&WatchedPath::new(root.clone(), RecursiveMode::Recursive)));
assert_eq!(
watched
.iter()
.filter(|watched| watched.path == root)
.count(),
1
);
watcher.unwatch(tmpdir.path()).expect("unwatch");
let watched = watcher.watched_paths().expect("list watched paths");
assert!(!watched.iter().any(|watched| watched.path == root));
}
#[test]
fn create_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
watcher.watch_recursively(&tmpdir);
let path = tmpdir.path().join("entry");
std::fs::File::create_new(&path).expect("Unable to create");
rx.sleep_until_parent_contains(&path);
rx.sleep_until_exists(&path);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [&path]);
rx.wait_unordered_exact([
expected(&path).create_file(),
expected(tmpdir.path()).modify_meta_mtime().optional(),
]);
}
#[test]
fn create_dir() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
watcher.watch_recursively(&tmpdir);
let path = tmpdir.path().join("entry");
std::fs::create_dir(&path).expect("Unable to create");
rx.sleep_until_parent_contains(&path);
rx.sleep_until_exists(&path);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [&path]);
rx.wait_unordered_exact([
expected(&path).create_folder(),
expected(tmpdir.path()).modify_meta_mtime().optional(),
]);
}
#[cfg(unix)]
#[test]
fn classifies_symlinks_according_to_follow_symlinks() {
use std::os::unix::fs::symlink;
let targets = testdir();
fs::write(targets.path().join("file"), "contents").expect("create target file");
fs::create_dir(targets.path().join("directory")).expect("create target directory");
let cases = [
(false, "file", CreateKind::Other, RemoveKind::Other),
(false, "directory", CreateKind::Other, RemoveKind::Other),
(false, "missing", CreateKind::Other, RemoveKind::Other),
(true, "file", CreateKind::File, RemoveKind::File),
(true, "directory", CreateKind::Folder, RemoveKind::Folder),
];
for (follow_symlinks, target, create_kind, remove_kind) in cases {
for compare_contents in [false, true] {
let tmpdir = testdir();
let path = tmpdir.path().join("link");
let (tx, rx) = mpsc::channel();
let config = Config::default()
.with_manual_polling()
.with_follow_symlinks(follow_symlinks)
.with_compare_contents(compare_contents)
.with_event_kinds(EventKindMask::CREATE | EventKindMask::REMOVE);
let mut watcher = PollWatcher::new(tx, config).expect("create watcher");
watcher
.watch(tmpdir.path(), RecursiveMode::Recursive)
.expect("watch directory");
symlink(targets.path().join(target), &path).expect("create symlink");
watcher.poll_blocking().expect("poll creation");
assert_eq!(
rx.try_iter().map(Result::unwrap).collect::<Vec<_>>(),
[Event::new(EventKind::Create(create_kind)).add_path(path.clone())],
"target={target}, follow_symlinks={follow_symlinks}, \
compare_contents={compare_contents}"
);
fs::remove_file(&path).expect("remove symlink");
watcher.poll_blocking().expect("poll removal");
assert_eq!(
rx.try_iter().map(Result::unwrap).collect::<Vec<_>>(),
[Event::new(EventKind::Remove(remove_kind)).add_path(path)],
"target={target}, follow_symlinks={follow_symlinks}, \
compare_contents={compare_contents}"
);
}
}
}
#[test]
fn modify_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::File::create_new(&path).expect("Unable to create");
rx.sleep_until_parent_contains(&path);
rx.sleep_until_exists(&path);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [&path]);
watcher.watch_recursively(&tmpdir);
std::fs::write(&path, b"123").expect("Unable to write");
assert!(
rx.sleep_until(|| std::fs::read_to_string(&path).is_ok_and(|content| content == "123")),
"the file wasn't modified"
);
rx.wait_ordered_exact([expected(&path).modify_data_any()]);
}
#[test]
fn remove_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::File::create_new(&path).expect("Unable to create");
rx.sleep_until_parent_contains(&path);
rx.sleep_until_exists(&path);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [&path]);
watcher.watch_recursively(&tmpdir);
std::fs::remove_file(&path).expect("Unable to remove");
rx.sleep_while_exists(&path);
rx.sleep_while_parent_contains(&path);
rx.sleep_until_walkdir_returns_set::<&str>(tmpdir.path(), []);
rx.wait_unordered_exact([
expected(&path).remove_file(),
expected(tmpdir.path()).modify_meta_mtime().optional(),
]);
}
#[test]
fn remove_dir() {
for compare_contents in [false, true] {
let tmpdir = testdir();
let path = tmpdir.path().join("entry");
fs::create_dir(&path).expect("create directory");
let (tx, rx) = mpsc::channel();
let config = Config::default()
.with_manual_polling()
.with_compare_contents(compare_contents)
.with_event_kinds(EventKindMask::REMOVE);
let mut watcher = PollWatcher::new(tx, config).expect("create watcher");
watcher
.watch(tmpdir.path(), RecursiveMode::NonRecursive)
.expect("watch directory");
fs::remove_dir(&path).expect("remove directory");
watcher.poll_blocking().expect("poll removal");
assert_eq!(
rx.try_iter().map(Result::unwrap).collect::<Vec<_>>(),
[Event::new(EventKind::Remove(RemoveKind::Folder)).add_path(path)],
"compare_contents={compare_contents}"
);
}
}
#[test]
fn removal_uses_last_observed_type() {
let tmpdir = testdir();
let path = tmpdir.path().join("entry");
fs::write(&path, "contents").expect("create file");
let (tx, rx) = mpsc::channel();
let config = Config::default()
.with_manual_polling()
.with_event_kinds(EventKindMask::REMOVE);
let mut watcher = PollWatcher::new(tx, config).expect("create watcher");
watcher
.watch(tmpdir.path(), RecursiveMode::NonRecursive)
.expect("watch directory");
fs::remove_file(&path).expect("remove file");
fs::create_dir(&path).expect("replace with directory");
watcher.poll_blocking().expect("poll replacement");
assert!(rx.try_iter().next().is_none());
fs::remove_dir(&path).expect("remove directory");
watcher.poll_blocking().expect("poll removal");
assert_eq!(
rx.try_iter().map(Result::unwrap).collect::<Vec<_>>(),
[Event::new(EventKind::Remove(RemoveKind::Folder)).add_path(path)]
);
}
#[test]
fn rename_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
let new_path = tmpdir.path().join("new_entry");
std::fs::File::create_new(&path).expect("Unable to create");
rx.sleep_until_parent_contains(&path);
rx.sleep_until_exists(&path);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [&path]);
watcher.watch_recursively(&tmpdir);
std::fs::rename(&path, &new_path).expect("Unable to remove");
rx.sleep_while_exists(&path);
rx.sleep_until_exists(&new_path);
rx.sleep_while_parent_contains(&path);
rx.sleep_until_parent_contains(&new_path);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [&new_path]);
rx.wait_unordered_exact([
expected(&path).remove_file(),
expected(&new_path).create_file(),
expected(tmpdir.path()).modify_meta_mtime().optional(),
]);
}
#[test]
fn create_write_overwrite() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let overwritten_file = tmpdir.path().join("overwritten_file");
let overwriting_file = tmpdir.path().join("overwriting_file");
std::fs::write(&overwritten_file, "123").expect("write1");
rx.sleep_until_parent_contains(&overwritten_file);
rx.sleep_until_exists(&overwritten_file);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [overwritten_file.clone()]);
watcher.watch_nonrecursively(&tmpdir);
std::fs::File::create(&overwriting_file).expect("create");
std::fs::write(&overwriting_file, "321").expect("write2");
std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");
rx.sleep_while_exists(&overwriting_file);
rx.sleep_while_parent_contains(&overwriting_file);
rx.sleep_until_walkdir_returns_set(tmpdir.path(), [overwritten_file.clone()]);
assert!(
rx.sleep_until(
|| std::fs::read_to_string(&overwritten_file).is_ok_and(|cnt| cnt == "321")
),
"file {overwritten_file:?} was not replaced"
);
rx.wait_unordered([expected(&overwritten_file).modify_data_any()]);
}
#[test]
fn poll_watcher_respects_event_kind_mask() {
use crate::{Config, Watcher};
use notify_types::event::EventKindMask;
use std::time::Duration;
let tmpdir = testdir();
let (tx, rx) = std::sync::mpsc::channel();
let config = Config::default()
.with_event_kinds(EventKindMask::CREATE)
.with_compare_contents(true)
.with_manual_polling();
let mut watcher = PollWatcher::new(tx, config).expect("create watcher");
watcher
.watch(tmpdir.path(), crate::RecursiveMode::Recursive)
.expect("watch");
let path = tmpdir.path().join("test_file");
std::fs::write(&path, "initial").expect("write initial");
watcher.poll().expect("poll 1");
let event = rx
.recv_timeout(Duration::from_secs(1))
.expect("should receive CREATE event")
.expect("event should not be an error");
assert_eq!(event.kind, EventKind::Create(CreateKind::File));
std::fs::write(&path, "modified content").expect("write modified");
watcher.poll().expect("poll 2");
std::thread::sleep(Duration::from_millis(100));
let remaining: Vec<_> = rx.try_iter().filter_map(|r| r.ok()).collect();
assert!(
!remaining.iter().any(|e| e.kind.is_modify()),
"Should not receive MODIFY events with CREATE-only mask, got: {remaining:?}"
);
}
}