use crate::paths::{WatchPath, absolute_path};
use crate::{BoundSender, Config, Receiver, Sender, bounded, unbounded};
use crate::{
Error, EventHandler, RecursiveMode, Result, WatchedPath, Watcher, WindowsPathSeparatorStyle,
};
use crate::{WatcherKind, event::*};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::ffi::OsString;
use std::io;
use std::os::raw::c_void;
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::ptr;
use std::rc::Rc;
use std::slice;
use std::sync::{Arc, Mutex};
use std::thread;
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_ACCESS_DENIED, ERROR_NOTIFY_ENUM_DIR, ERROR_OPERATION_ABORTED,
ERROR_SUCCESS, FARPROC, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_ACTION_ADDED, FILE_ACTION_MODIFIED, FILE_ACTION_REMOVED,
FILE_ACTION_RENAMED_NEW_NAME, FILE_ACTION_RENAMED_OLD_NAME, FILE_ATTRIBUTE_DIRECTORY,
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY,
FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_CREATION, FILE_NOTIFY_CHANGE_DIR_NAME,
FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SECURITY,
FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_EXTENDED_INFORMATION, FILE_NOTIFY_INFORMATION,
FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_STANDARD_INFO, FileStandardInfo,
GetFileInformationByHandleEx, OPEN_EXISTING, ReadDirectoryChangesW,
ReadDirectoryNotifyExtendedInformation,
};
use windows_sys::Win32::System::IO::{CancelIo, LPOVERLAPPED_COMPLETION_ROUTINE, OVERLAPPED};
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows_sys::Win32::System::Threading::{
CreateSemaphoreW, INFINITE, ReleaseSemaphore, WaitForSingleObjectEx,
};
const BUF_SIZE: u32 = 65536;
type ReadDirectoryChangesExFn = unsafe extern "system" fn(
HANDLE,
*mut c_void,
u32,
windows_sys::core::BOOL,
u32,
*mut u32,
*mut OVERLAPPED,
LPOVERLAPPED_COMPLETION_ROUTINE,
i32,
) -> windows_sys::core::BOOL;
fn lookup_read_directory_changes_ex() -> FARPROC {
unsafe {
let module = GetModuleHandleW(windows_sys::w!("kernel32.dll"));
if module.is_null() {
return None;
}
GetProcAddress(module, windows_sys::s!("ReadDirectoryChangesExW"))
}
}
fn resolve_extended_information(
enabled: bool,
lookup: impl FnOnce() -> FARPROC,
) -> Result<Option<ReadDirectoryChangesExFn>> {
if !enabled {
return Ok(None);
}
let address = lookup().ok_or_else(|| {
Error::io(io::Error::new(
io::ErrorKind::Unsupported,
"ReadDirectoryChangesExW is unavailable; extended information requires Windows 10 1709 / Windows Server 2019 or later",
))
})?;
Ok(Some(unsafe {
std::mem::transmute::<unsafe extern "system" fn() -> isize, ReadDirectoryChangesExFn>(
address,
)
}))
}
fn read_buffer() -> Box<[u32]> {
vec![0; BUF_SIZE as usize / size_of::<u32>()].into_boxed_slice()
}
#[derive(Clone, Copy)]
enum SeparatorStyle {
Slash,
Backslash,
}
impl SeparatorStyle {
fn resolve(configured_style: WindowsPathSeparatorStyle, path: &Path) -> Self {
match configured_style {
WindowsPathSeparatorStyle::Auto => Self::from_path(path),
WindowsPathSeparatorStyle::Slash => Self::Slash,
WindowsPathSeparatorStyle::Backslash => Self::Backslash,
}
}
fn from_path(path: &Path) -> Self {
let mut has_forward_slash = false;
let mut has_backslash = false;
for ch in path.as_os_str().encode_wide() {
if ch == '/' as u16 {
has_forward_slash = true;
} else if ch == '\\' as u16 {
has_backslash = true;
}
if has_forward_slash && has_backslash {
return Self::Backslash;
}
}
if has_forward_slash {
Self::Slash
} else {
Self::Backslash
}
}
fn as_u16(self) -> u16 {
match self {
Self::Slash => '/' as u16,
Self::Backslash => '\\' as u16,
}
}
}
fn trim_leading_separators(path: &[u16]) -> &[u16] {
let mut start = 0;
while start < path.len() && (path[start] == '/' as u16 || path[start] == '\\' as u16) {
start += 1;
}
&path[start..]
}
fn windows_namespace_prefix_len(path: &[u16]) -> usize {
let is_separator = |ch: u16| ch == '/' as u16 || ch == '\\' as u16;
if path.len() >= 4
&& is_separator(path[0])
&& is_separator(path[1])
&& (path[2] == '?' as u16 || path[2] == '.' as u16)
&& is_separator(path[3])
{
4
} else {
0
}
}
fn normalize_path_separators(path: PathBuf, separator_style: SeparatorStyle) -> PathBuf {
let separator = separator_style.as_u16();
let mut encoded_path: Vec<u16> = path.as_os_str().encode_wide().collect();
let prefix_len = windows_namespace_prefix_len(&encoded_path);
for ch in encoded_path.iter_mut().skip(prefix_len) {
if *ch == '/' as u16 || *ch == '\\' as u16 {
*ch = separator;
}
}
PathBuf::from(OsString::from_wide(&encoded_path))
}
struct WatchTarget {
watch_path: PathBuf,
reported_path: PathBuf,
separator_style: SeparatorStyle,
user_data: Option<u64>,
}
enum WatchTargets {
Directory(WatchTarget),
Files(HashMap<OsString, WatchTarget>),
}
impl WatchTargets {
fn for_each(&self, mut f: impl FnMut(&WatchTarget)) {
match self {
Self::Directory(target) => f(target),
Self::Files(files) => files.values().for_each(f),
}
}
}
struct ReadData {
id: u64,
dir: PathBuf,
handle: HANDLE,
complete_sem: HANDLE,
is_recursive: bool,
targets: RefCell<WatchTargets>,
stopping: Cell<bool>,
read_directory_changes_ex: Option<ReadDirectoryChangesExFn>,
event_handler: Arc<Mutex<dyn EventHandler>>,
event_kinds: EventKindMask,
action_tx: Sender<Action>,
}
struct ReadDirectoryRequest {
overlapped: OVERLAPPED,
buffer: Box<[u32]>,
data: Rc<ReadData>,
}
impl ReadData {
fn emit_event(&self, target: &WatchTarget, mut result: Result<Event>) {
if let Ok(event) = &result
&& !event.need_rescan()
&& !self.event_kinds.matches(&event.kind)
{
return;
}
if let Ok(event) = &mut result
&& let Some(user_data) = target.user_data
{
event.attrs.set_user_data(user_data);
}
if let Ok(mut handler) = self.event_handler.lock() {
handler.handle_event(result);
}
}
fn emit_error(&self, error: io::Error) {
self.targets.borrow().for_each(|target| {
let error = match error.raw_os_error() {
Some(code) => io::Error::from_raw_os_error(code),
None => io::Error::new(error.kind(), error.to_string()),
};
self.emit_event(
target,
Err(Error::io(error)
.add_path(target.reported_path.clone())
.set_user_data_opt(target.user_data)),
);
});
}
fn emit_rescan(&self) {
self.targets.borrow().for_each(|target| {
self.emit_event(
target,
Ok(Event::new(EventKind::Other).set_flag(Flag::Rescan)),
);
});
}
fn unwatch(&self) {
self.stopping.set(true);
let _ = self.action_tx.send(Action::Unwatch(self.id));
}
}
enum Action {
Watch(WatchPath, RecursiveMode, SeparatorStyle),
Unwatch(u64),
UnwatchAck(PathBuf),
GetWatchedPaths(Sender<Vec<WatchedPath>>),
Stop,
Configure(Config, BoundSender<Result<bool>>),
}
struct WatchState {
directory_id: u64,
recursive_mode: RecursiveMode,
reported_path: PathBuf,
}
#[derive(Debug)]
struct WakeupSem(HANDLE);
impl Drop for WakeupSem {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
unsafe impl Send for WakeupSem {}
unsafe impl Sync for WakeupSem {}
struct ReadDirectoryChangesServer {
tx: Sender<Action>,
rx: Receiver<Action>,
event_handler: Arc<Mutex<dyn EventHandler>>,
event_kinds: EventKindMask,
cmd_tx: Sender<Result<PathBuf>>,
watches: HashMap<PathBuf, WatchState>,
directories: HashMap<u64, Rc<ReadData>>,
file_directories: HashMap<PathBuf, u64>,
next_directory_id: u64,
wakeup_sem: Arc<WakeupSem>,
read_directory_changes_ex: Option<ReadDirectoryChangesExFn>,
}
impl ReadDirectoryChangesServer {
fn start(
event_handler: Arc<Mutex<dyn EventHandler>>,
event_kinds: EventKindMask,
cmd_tx: Sender<Result<PathBuf>>,
wakeup_sem: Arc<WakeupSem>,
read_directory_changes_ex: Option<ReadDirectoryChangesExFn>,
) -> Result<Sender<Action>> {
let (action_tx, action_rx) = unbounded();
thread::Builder::new()
.name("notify-rs windows loop".to_string())
.spawn({
let tx = action_tx.clone();
move || {
let server = ReadDirectoryChangesServer {
tx,
rx: action_rx,
event_handler,
event_kinds,
cmd_tx,
watches: HashMap::new(),
directories: HashMap::new(),
file_directories: HashMap::new(),
next_directory_id: 0,
wakeup_sem,
read_directory_changes_ex,
};
server.run();
}
})?;
Ok(action_tx)
}
fn run(mut self) {
loop {
let mut stopped = false;
while let Ok(action) = self.rx.try_recv() {
match action {
Action::Watch(path, recursive_mode, separator_style) => {
let res =
self.add_watch(path, recursive_mode.is_recursive(), separator_style);
let _ = self.cmd_tx.send(res);
}
Action::Unwatch(id) => {
self.remove_directory(id);
}
Action::UnwatchAck(path) => {
let res = if self.remove_watch(path.clone()) {
Ok(path)
} else {
Err(Error::watch_not_found().add_path(path))
};
let _ = self.cmd_tx.send(res);
}
Action::GetWatchedPaths(tx) => {
let _ = tx.send(
self.watches
.values()
.map(|state| {
WatchedPath::new(
state.reported_path.clone(),
state.recursive_mode,
)
})
.collect(),
);
}
Action::Stop => {
stopped = true;
for data in self.directories.values() {
stop_watch(data);
}
break;
}
Action::Configure(config, tx) => {
self.configure_raw_mode(config, tx);
}
}
}
if stopped {
break;
}
unsafe {
WaitForSingleObjectEx(self.wakeup_sem.0, INFINITE, 1);
}
}
}
fn add_watch(
&mut self,
path: WatchPath,
is_recursive: bool,
separator_style: SeparatorStyle,
) -> Result<PathBuf> {
let metadata = match path.absolute.metadata() {
Ok(metadata) => metadata,
Err(err) => return Err(Error::io_watch(err).add_path(path.requested)),
};
if !metadata.is_dir() && !metadata.is_file() {
return Err(
Error::generic("Input watch path is neither a file nor a directory.")
.add_path(path.requested),
);
}
let (watching_file, dir_target) = if metadata.is_dir() {
(false, path.absolute.clone())
} else {
(true, path.absolute.parent().unwrap().to_path_buf())
};
let watched_path = path.absolute.clone();
let reported_path = path.requested.clone();
let user_data = path.user_data;
let target = WatchTarget {
watch_path: watched_path.clone(),
reported_path: normalize_path_separators(path.requested, separator_style),
separator_style,
user_data,
};
let recursive_mode = if is_recursive {
RecursiveMode::Recursive
} else {
RecursiveMode::NonRecursive
};
let shared_id = watching_file
.then(|| self.file_directories.get(&dir_target).copied())
.flatten()
.filter(|id| !self.directories[id].stopping.get());
let id = if let Some(id) = shared_id {
let WatchTargets::Files(files) = &mut *self.directories[&id].targets.borrow_mut()
else {
unreachable!();
};
files.insert(watched_path.file_name().unwrap().to_os_string(), target);
id
} else {
let targets = if watching_file {
WatchTargets::Files(HashMap::from([(
watched_path.file_name().unwrap().to_os_string(),
target,
)]))
} else {
WatchTargets::Directory(target)
};
let id = self.next_directory_id;
self.next_directory_id += 1;
let data = self
.open_directory(id, &dir_target, is_recursive && !watching_file, targets)
.map_err(|error| {
error
.add_path(reported_path.clone())
.set_user_data_opt(user_data)
})?;
self.directories.insert(id, data);
if watching_file {
self.file_directories.insert(dir_target, id);
}
id
};
if self
.watches
.get(&watched_path)
.is_some_and(|watch| watch.directory_id != id)
{
self.remove_watch(watched_path.clone());
}
self.watches.insert(
watched_path.clone(),
WatchState {
directory_id: id,
recursive_mode,
reported_path,
},
);
Ok(watched_path)
}
fn open_directory(
&self,
id: u64,
dir: &Path,
is_recursive: bool,
targets: WatchTargets,
) -> Result<Rc<ReadData>> {
let encoded_path: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
let handle;
unsafe {
handle = CreateFileW(
encoded_path.as_ptr(),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
ptr::null_mut(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
ptr::null_mut(),
);
if handle == INVALID_HANDLE_VALUE {
return Err(Error::io(io::Error::last_os_error()));
}
}
let semaphore = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
if semaphore.is_null() || semaphore == INVALID_HANDLE_VALUE {
let err = io::Error::last_os_error();
unsafe {
CloseHandle(handle);
}
return Err(Error::io(err));
}
let data = Rc::new(ReadData {
id,
dir: dir.to_path_buf(),
handle,
complete_sem: semaphore,
is_recursive,
targets: RefCell::new(targets),
stopping: Cell::new(false),
read_directory_changes_ex: self.read_directory_changes_ex,
event_handler: self.event_handler.clone(),
event_kinds: self.event_kinds,
action_tx: self.tx.clone(),
});
let request = Box::new(ReadDirectoryRequest {
overlapped: OVERLAPPED::default(),
buffer: read_buffer(),
data: data.clone(),
});
if let Err(err) = start_read(request) {
unsafe {
CloseHandle(handle);
CloseHandle(semaphore);
}
return Err(Error::io(err));
}
Ok(data)
}
fn remove_watch(&mut self, path: PathBuf) -> bool {
let Some(watch) = self.watches.remove(&path) else {
return false;
};
let remove_directory =
match &mut *self.directories[&watch.directory_id].targets.borrow_mut() {
WatchTargets::Directory(_) => true,
WatchTargets::Files(files) => {
files.remove(path.file_name().unwrap());
files.is_empty()
}
};
if remove_directory {
self.remove_directory(watch.directory_id);
}
true
}
fn remove_directory(&mut self, id: u64) {
let Some(data) = self.directories.remove(&id) else {
return;
};
data.targets.borrow().for_each(|target| {
if self
.watches
.get(&target.watch_path)
.is_some_and(|watch| watch.directory_id == id)
{
self.watches.remove(&target.watch_path);
}
});
if self.file_directories.get(&data.dir) == Some(&id) {
self.file_directories.remove(&data.dir);
}
stop_watch(&data);
}
fn configure_raw_mode(&mut self, _config: Config, tx: BoundSender<Result<bool>>) {
tx.send(Ok(false))
.expect("configuration channel disconnect");
}
}
fn stop_watch(ws: &ReadData) {
ws.stopping.set(true);
unsafe {
if CancelIo(ws.handle) == 0 {
log::error!("CancelIo failed; leaking the directory handle of a stopped watch");
} else {
while WaitForSingleObjectEx(ws.complete_sem, INFINITE, 1) != WAIT_OBJECT_0 {
}
CloseHandle(ws.handle);
CloseHandle(ws.complete_sem);
}
}
}
fn start_read(mut request: Box<ReadDirectoryRequest>) -> io::Result<()> {
request.overlapped = OVERLAPPED::default();
let flags = FILE_NOTIFY_CHANGE_FILE_NAME
| FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_ATTRIBUTES
| FILE_NOTIFY_CHANGE_SIZE
| FILE_NOTIFY_CHANGE_LAST_WRITE
| FILE_NOTIFY_CHANGE_CREATION
| FILE_NOTIFY_CHANGE_SECURITY;
let monitor_subdir = i32::from(request.data.is_recursive);
unsafe {
let request = Box::leak(request);
let overlapped = &raw mut request.overlapped;
(*overlapped).hEvent = request as *mut _ as _;
let buffer = request.buffer.as_mut_ptr().cast();
let buffer_size = std::mem::size_of_val(&*request.buffer) as u32;
let data = &request.data;
let ret = if let Some(read_extended) = data.read_directory_changes_ex {
read_extended(
data.handle,
buffer,
buffer_size,
monitor_subdir,
flags,
ptr::null_mut(), overlapped,
Some(handle_event),
ReadDirectoryNotifyExtendedInformation,
)
} else {
ReadDirectoryChangesW(
data.handle,
buffer,
buffer_size,
monitor_subdir,
flags,
ptr::null_mut(),
overlapped,
Some(handle_event),
)
};
if ret == 0 {
let err = std::io::Error::last_os_error();
let request = Box::from_raw(request);
ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
return Err(err);
}
}
Ok(())
}
fn is_delete_pending(handle: HANDLE) -> bool {
let mut info = FILE_STANDARD_INFO::default();
let success = unsafe {
GetFileInformationByHandleEx(
handle,
FileStandardInfo,
&mut info as *mut _ as *mut c_void,
std::mem::size_of_val(&info) as u32,
)
};
success != 0 && info.DeletePending
}
fn completion_rescan_event(error_code: u32, bytes_written: u32) -> Option<Event> {
(error_code == ERROR_NOTIFY_ENUM_DIR || (error_code == ERROR_SUCCESS && bytes_written == 0))
.then(|| Event::new(EventKind::Other).set_flag(Flag::Rescan))
}
#[derive(Debug)]
struct Notification {
action: u32,
attributes: Option<u32>,
name: OsString,
}
struct PendingNotification<'a> {
target: &'a WatchTarget,
notification: Notification,
}
fn invalid_notification() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidData,
"invalid directory notification record",
)
}
fn decode_notification(bytes: &[u8], extended: bool) -> io::Result<(Notification, &[u8])> {
let name_offset = if extended {
std::mem::offset_of!(FILE_NOTIFY_EXTENDED_INFORMATION, FileName)
} else {
std::mem::offset_of!(FILE_NOTIFY_INFORMATION, FileName)
};
if bytes.len() < name_offset {
return Err(invalid_notification());
}
let read_u32 = |offset| u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap());
let next_offset = read_u32(0) as usize;
let name_len = read_u32(name_offset - 4) as usize;
let name_end = name_offset
.checked_add(name_len)
.ok_or_else(invalid_notification)?;
if !name_len.is_multiple_of(2) || name_end > bytes.len() {
return Err(invalid_notification());
}
let rest = if next_offset == 0 {
&[][..]
} else {
if next_offset < name_end || next_offset >= bytes.len() {
return Err(invalid_notification());
}
&bytes[next_offset..]
};
let name: Vec<u16> = bytes[name_offset..name_end]
.chunks_exact(2)
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
.collect();
let notification = Notification {
action: read_u32(4),
attributes: extended.then(|| {
read_u32(std::mem::offset_of!(
FILE_NOTIFY_EXTENDED_INFORMATION,
FileAttributes
))
}),
name: OsString::from_wide(trim_leading_separators(&name)),
};
Ok((notification, rest))
}
fn notification_mask(action: u32) -> EventKindMask {
match action {
FILE_ACTION_ADDED => EventKindMask::CREATE,
FILE_ACTION_REMOVED => EventKindMask::REMOVE,
FILE_ACTION_MODIFIED => EventKindMask::ALL_MODIFY,
FILE_ACTION_RENAMED_OLD_NAME | FILE_ACTION_RENAMED_NEW_NAME => EventKindMask::MODIFY_NAME,
_ => EventKindMask::empty(),
}
}
fn notification_kind(notification: &Notification, dir: &Path) -> Option<EventKind> {
let is_directory = notification
.attributes
.map(|attrs| attrs & FILE_ATTRIBUTE_DIRECTORY != 0);
Some(match notification.action {
FILE_ACTION_ADDED => EventKind::Create(match is_directory {
Some(true) => CreateKind::Folder,
Some(false) => CreateKind::File,
None => std::fs::metadata(dir.join(¬ification.name)).map_or(
CreateKind::Any,
|metadata| {
if metadata.is_dir() {
CreateKind::Folder
} else if metadata.is_file() {
CreateKind::File
} else {
CreateKind::Any
}
},
),
}),
FILE_ACTION_REMOVED => EventKind::Remove(match is_directory {
Some(true) => RemoveKind::Folder,
Some(false) => RemoveKind::File,
None => RemoveKind::Any,
}),
FILE_ACTION_MODIFIED => EventKind::Modify(ModifyKind::Any),
FILE_ACTION_RENAMED_OLD_NAME => EventKind::Modify(ModifyKind::Name(RenameMode::From)),
FILE_ACTION_RENAMED_NEW_NAME => EventKind::Modify(ModifyKind::Name(RenameMode::To)),
_ => return None,
})
}
fn collect_notifications<'a>(
request: &ReadDirectoryRequest,
bytes_written: u32,
targets: &'a WatchTargets,
) -> Vec<io::Result<PendingNotification<'a>>> {
let buffer_size = std::mem::size_of_val(&*request.buffer);
if bytes_written as usize > buffer_size {
return vec![Err(invalid_notification())];
}
let mut bytes = unsafe {
slice::from_raw_parts(request.buffer.as_ptr().cast::<u8>(), bytes_written as usize)
};
let mut pending = Vec::new();
while !bytes.is_empty() {
let (notification, rest) =
match decode_notification(bytes, request.data.read_directory_changes_ex.is_some()) {
Ok(decoded) => decoded,
Err(error) => {
pending.push(Err(error));
break;
}
};
bytes = rest;
if !request
.data
.event_kinds
.intersects(notification_mask(notification.action))
{
continue;
}
let target = match targets {
WatchTargets::Directory(target) => target,
WatchTargets::Files(files) => {
let Some(target) = files.get(¬ification.name) else {
continue;
};
target
}
};
pending.push(Ok(PendingNotification {
target,
notification,
}));
}
pending
}
fn dispatch_notifications(
data: &ReadData,
targets: &WatchTargets,
pending: Vec<io::Result<PendingNotification<'_>>>,
) -> io::Result<()> {
let watching_file = matches!(targets, WatchTargets::Files(_));
for pending in pending {
let PendingNotification {
target,
notification,
} = pending?;
let Some(kind) = notification_kind(¬ification, &data.dir) else {
continue;
};
let path = if watching_file {
target.reported_path.clone()
} else {
let path = target.reported_path.join(¬ification.name);
match target.separator_style {
SeparatorStyle::Slash => normalize_path_separators(path, SeparatorStyle::Slash),
SeparatorStyle::Backslash => path,
}
};
log::trace!(
"Event: path = `{}`, action = {:?}",
path.display(),
notification.action
);
data.emit_event(target, Ok(Event::new(kind).add_path(path)));
}
Ok(())
}
unsafe extern "system" fn handle_event(
error_code: u32,
bytes_written: u32,
overlapped: *mut OVERLAPPED,
) {
let request: Box<ReadDirectoryRequest> = unsafe { Box::from_raw((*overlapped).hEvent.cast()) };
let data = request.data.clone();
if data.stopping.get() {
unsafe { ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut()) };
return;
}
match error_code {
ERROR_OPERATION_ABORTED => {
unsafe { ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut()) };
return;
}
ERROR_ACCESS_DENIED => {
if matches!(data.dir.try_exists(), Ok(false)) || is_delete_pending(data.handle) {
if let WatchTargets::Directory(target) = &*data.targets.borrow() {
let event = Event::new(EventKind::Remove(RemoveKind::Folder))
.add_path(target.reported_path.clone());
data.emit_event(target, Ok(event));
}
data.unwatch();
unsafe { ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut()) };
return;
}
}
ERROR_SUCCESS | ERROR_NOTIFY_ENUM_DIR => {
}
_ => {
data.emit_error(io::Error::from_raw_os_error(error_code as i32));
data.unwatch();
unsafe { ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut()) };
return;
}
}
let rescan = completion_rescan_event(error_code, bytes_written).is_some();
let targets = data.targets.borrow();
let pending = if rescan {
Vec::new()
} else {
collect_notifications(&request, bytes_written, &targets)
};
let rearm_error = start_read(request).err();
if rescan {
data.emit_rescan();
} else if let Err(error) = dispatch_notifications(&data, &targets, pending) {
data.emit_error(error);
data.emit_rescan();
}
if let Some(err) = rearm_error {
data.emit_error(err);
data.unwatch();
}
}
#[derive(Debug)]
pub struct ReadDirectoryChangesWatcher {
tx: Sender<Action>,
cmd_rx: Receiver<Result<PathBuf>>,
wakeup_sem: Arc<WakeupSem>,
windows_path_separator_style: WindowsPathSeparatorStyle,
}
impl ReadDirectoryChangesWatcher {
fn create(
event_handler: Arc<Mutex<dyn EventHandler>>,
event_kinds: EventKindMask,
windows_path_separator_style: WindowsPathSeparatorStyle,
read_directory_changes_ex: Option<ReadDirectoryChangesExFn>,
) -> Result<ReadDirectoryChangesWatcher> {
let (cmd_tx, cmd_rx) = unbounded();
let wakeup_sem = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
if wakeup_sem.is_null() || wakeup_sem == INVALID_HANDLE_VALUE {
return Err(Error::io(io::Error::last_os_error()));
}
let wakeup_sem = Arc::new(WakeupSem(wakeup_sem));
let action_tx = ReadDirectoryChangesServer::start(
event_handler,
event_kinds,
cmd_tx,
wakeup_sem.clone(),
read_directory_changes_ex,
)?;
Ok(ReadDirectoryChangesWatcher {
tx: action_tx,
cmd_rx,
wakeup_sem,
windows_path_separator_style,
})
}
fn wakeup_server(&self) {
unsafe {
ReleaseSemaphore(self.wakeup_sem.0, 1, ptr::null_mut());
}
}
fn send_action_require_ack(&mut self, action: Action, pb: &PathBuf) -> Result<()> {
self.tx
.send(action)
.map_err(|_| Error::generic("Error sending to internal channel"))?;
self.wakeup_server();
let ack_pb = self
.cmd_rx
.recv()
.map_err(|_| Error::generic("Error receiving from command channel"))??;
if pb.as_path() != ack_pb.as_path() {
Err(Error::generic(&format!(
"Expected ack for {:?} but got \
ack for {:?}",
pb, ack_pb
)))
} else {
Ok(())
}
}
fn watch_inner(&mut self, path: &Path, config: crate::WatchPathConfig) -> Result<()> {
let separator_style = SeparatorStyle::resolve(self.windows_path_separator_style, path);
let pb = WatchPath::new(path, config.user_data())?;
self.send_action_require_ack(
Action::Watch(pb.clone(), config.recursive_mode(), separator_style),
&pb.absolute,
)
}
fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
let pb = absolute_path(path)?;
self.send_action_require_ack(Action::UnwatchAck(pb.clone()), &pb)
}
fn watched_paths_inner(&self) -> Result<Vec<WatchedPath>> {
let (tx, rx) = unbounded();
self.tx
.send(Action::GetWatchedPaths(tx))
.map_err(|_| Error::generic("Error sending to internal channel"))?;
self.wakeup_server();
rx.recv().map_err(Error::from)
}
}
impl Watcher for ReadDirectoryChangesWatcher {
fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> {
let read_directory_changes_ex = resolve_extended_information(
config.windows_extended_information(),
lookup_read_directory_changes_ex,
)?;
let event_handler = Arc::new(Mutex::new(event_handler));
Self::create(
event_handler,
config.event_kinds(),
config.windows_path_separator_style(),
read_directory_changes_ex,
)
}
fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
self.watch_with(path, crate::WatchPathConfig::new(recursive_mode))
}
fn watch_with(&mut self, path: &Path, config: crate::WatchPathConfig) -> 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) -> Result<()> {
self.unwatch_inner(path)
}
fn configure(&mut self, config: Config) -> Result<bool> {
let (tx, rx) = bounded(1);
self.tx.send(Action::Configure(config, tx))?;
self.wakeup_server();
rx.recv()?
}
fn watched_paths(&self) -> Result<Vec<WatchedPath>> {
self.watched_paths_inner()
}
fn kind() -> crate::WatcherKind {
WatcherKind::ReadDirectoryChangesWatcher
}
}
impl Drop for ReadDirectoryChangesWatcher {
fn drop(&mut self) {
let _ = self.tx.send(Action::Stop);
self.wakeup_server();
}
}
unsafe impl Send for ReadDirectoryChangesWatcher {}
unsafe impl Sync for ReadDirectoryChangesWatcher {}
#[cfg(test)]
mod extended_information_tests;
#[cfg(test)]
mod shared_watch_tests;
#[cfg(test)]
mod tests {
use std::env;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, mpsc};
use std::thread;
use tempfile::{tempdir, tempdir_in};
use super::extended_information_tests::{complete, request, target_mut};
use super::{
SeparatorStyle, completion_rescan_event, normalize_path_separators, trim_leading_separators,
};
use crate::{
Config, Error, ErrorKind, Event, EventKind, ReadDirectoryChangesWatcher, RecursiveMode,
Watcher, WindowsPathSeparatorStyle, test::*,
};
use std::time::Duration;
fn watcher() -> (TestWatcher<ReadDirectoryChangesWatcher>, Receiver) {
channel()
}
#[test]
fn trash_dir() -> std::result::Result<(), Box<dyn std::error::Error>> {
let dir = tempdir()?;
let child_dir = dir.path().join("child");
std::fs::create_dir(&child_dir)?;
let mut watcher = crate::recommended_watcher(|_| {
})?;
watcher.watch(&child_dir, RecursiveMode::NonRecursive)?;
trash::delete(&child_dir)?;
watcher.watch(dir.path(), RecursiveMode::NonRecursive)?;
Ok(())
}
#[test]
fn configure_and_drop_do_not_need_a_timed_wakeup() {
let dir = tempdir().expect("tempdir");
let (done_tx, done_rx) = mpsc::channel();
let (event_tx, event_rx) = mpsc::channel();
let path = dir.path().to_path_buf();
thread::spawn(move || {
let mut watcher = crate::recommended_watcher(event_tx).expect("watcher");
watcher
.watch(&path, RecursiveMode::Recursive)
.expect("watch");
thread::sleep(Duration::from_millis(300));
let configured = watcher.configure(Config::default());
thread::sleep(Duration::from_millis(300));
drop(watcher);
let _ = done_tx.send(configured.is_ok());
});
let configured = done_rx
.recv_timeout(Duration::from_secs(10))
.expect("configure or drop hung");
assert!(configured);
assert!(
matches!(
event_rx.recv_timeout(Duration::from_secs(10)),
Err(mpsc::RecvTimeoutError::Disconnected)
),
"server did not stop after drop"
);
}
#[test]
fn events_arrive_after_the_server_has_been_idle() {
let dir = tempdir().expect("tempdir");
let (tx, rx) = mpsc::channel();
let mut watcher = crate::recommended_watcher(tx).expect("watcher");
watcher
.watch(dir.path(), RecursiveMode::Recursive)
.expect("watch");
thread::sleep(Duration::from_millis(300));
std::fs::write(dir.path().join("file"), b"x").expect("write");
let event = rx
.recv_timeout(Duration::from_secs(10))
.expect("no event after an idle wait");
assert!(event.is_ok());
}
#[test]
fn watcher_is_send_and_sync() {
fn check<T: Send + Sync>() {}
check::<ReadDirectoryChangesWatcher>();
}
#[test]
fn watch_nonexistent_path_returns_path_not_found() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("does_not_exist");
let mut watcher = crate::recommended_watcher(|_| {}).expect("watcher");
let err = watcher
.watch(&path, RecursiveMode::Recursive)
.expect_err("watching a nonexistent path must return an error");
assert!(matches!(err.kind, ErrorKind::PathNotFound), "{err:?}");
assert_eq!(err.paths, vec![path]);
assert!(watcher.watched_paths().expect("watched paths").is_empty());
}
#[test]
fn posix_watch_path_uses_slash_separator_style() {
let style = SeparatorStyle::from_path(Path::new("G:/Feature film/"));
assert!(matches!(style, SeparatorStyle::Slash));
}
#[test]
fn explicit_separator_style_overrides_watch_path_style() {
let style = SeparatorStyle::resolve(
WindowsPathSeparatorStyle::Backslash,
Path::new("G:/Feature film/"),
);
assert!(matches!(style, SeparatorStyle::Backslash));
}
#[test]
fn trim_leading_separators_removes_root_separators() {
let input = [
'\\' as u16,
'/' as u16,
's' as u16,
'u' as u16,
'b' as u16,
'\\' as u16,
'f' as u16,
'i' as u16,
'l' as u16,
'e' as u16,
];
let trimmed = trim_leading_separators(&input);
assert_eq!(
trimmed,
[
's' as u16,
'u' as u16,
'b' as u16,
'\\' as u16,
'f' as u16,
'i' as u16,
'l' as u16,
'e' as u16,
]
);
}
#[test]
fn normalize_joined_event_path_for_posix_watch_path() {
let dir = PathBuf::from("G:/Feature");
let raw_event_name: Vec<u16> = "\\22.mp4".encode_utf16().collect();
let relative = PathBuf::from(OsString::from_wide(trim_leading_separators(
&raw_event_name,
)));
let path = normalize_path_separators(dir.join(relative), SeparatorStyle::Slash);
assert_eq!(path, PathBuf::from("G:/Feature/22.mp4"));
}
#[test]
fn normalize_path_separators_keeps_windows_namespace_prefix() {
let path = PathBuf::from(r"\\?\C:\very\long\file");
let normalized = normalize_path_separators(path, SeparatorStyle::Slash);
assert_eq!(normalized, PathBuf::from(r"\\?\C:/very/long/file"));
}
#[test]
fn lost_change_details_produce_a_pathless_rescan_event() {
use windows_sys::Win32::Foundation::{
ERROR_NOTIFY_ENUM_DIR, ERROR_OPERATION_ABORTED, ERROR_SUCCESS,
};
let event: Event = completion_rescan_event(ERROR_SUCCESS, 0).expect("rescan event");
assert_eq!(event.kind, EventKind::Other);
assert!(event.paths.is_empty());
assert!(event.need_rescan());
assert!(completion_rescan_event(ERROR_NOTIFY_ENUM_DIR, 0).is_some());
assert!(completion_rescan_event(ERROR_SUCCESS, 12).is_none());
assert!(completion_rescan_event(ERROR_OPERATION_ABORTED, 0).is_none());
}
#[test]
fn access_denied_existence_error_does_not_emit_remove() {
use std::ptr;
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_ACCESS_DENIED};
use windows_sys::Win32::System::Threading::CreateSemaphoreW;
let invalid_path = PathBuf::from(OsString::from_wide(&[0]));
assert!(invalid_path.try_exists().is_err());
let complete_sem = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
assert!(!complete_sem.is_null());
let (mut request, event_rx, _action_rx) = request(false);
let data = Rc::get_mut(&mut request.data).unwrap();
data.complete_sem = complete_sem;
data.dir = invalid_path.clone();
target_mut(data).watch_path = invalid_path.clone();
target_mut(data).reported_path = invalid_path;
complete(request, ERROR_ACCESS_DENIED, 0);
unsafe { CloseHandle(complete_sem) };
let events = event_rx.try_iter().collect::<Vec<_>>();
assert!(
!events.iter().any(|res| matches!(
res,
Ok(event) if event.kind == EventKind::Remove(crate::event::RemoveKind::Folder)
)),
"unexpected remove event: {events:#?}"
);
}
#[test]
fn stopped_watch_does_not_rearm_queued_successful_completion() {
use std::ptr;
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_SUCCESS, WAIT_OBJECT_0};
use windows_sys::Win32::System::Threading::{CreateSemaphoreW, WaitForSingleObjectEx};
let complete_sem = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
assert!(!complete_sem.is_null());
let (mut request, event_rx, action_rx) = request(false);
let data = Rc::get_mut(&mut request.data).unwrap();
data.complete_sem = complete_sem;
data.stopping.set(true);
complete(request, ERROR_SUCCESS, 0);
unsafe {
assert_eq!(WaitForSingleObjectEx(complete_sem, 0, 0), WAIT_OBJECT_0);
CloseHandle(complete_sem);
}
assert!(event_rx.try_iter().next().is_none(), "unexpected event");
assert!(action_rx.try_iter().next().is_none(), "unexpected action");
}
#[test]
fn stop_watch_closes_handles_after_queued_completion() {
use std::os::windows::ffi::OsStrExt;
use std::ptr;
use std::sync::atomic::{AtomicIsize, AtomicU32};
use std::time::Instant;
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY,
FILE_NOTIFY_CHANGE_FILE_NAME, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
FILE_STANDARD_INFO, FileStandardInfo, GetFileInformationByHandleEx, OPEN_EXISTING,
ReadDirectoryChangesW,
};
use windows_sys::Win32::System::IO::OVERLAPPED;
use windows_sys::Win32::System::Threading::{CreateSemaphoreW, ReleaseSemaphore};
const STATUS_PENDING: usize = 0x103;
const NOT_RUN: u32 = 0;
const HANDLE_OPEN: u32 = 1;
const HANDLE_CLOSED: u32 = 2;
static WATCHED_HANDLE: AtomicIsize = AtomicIsize::new(0);
static COMPLETE_SEM: AtomicIsize = AtomicIsize::new(0);
static SEEN: AtomicU32 = AtomicU32::new(NOT_RUN);
unsafe extern "system" fn completion(
_error: u32,
_bytes: u32,
overlapped: *mut OVERLAPPED,
) {
drop(unsafe { Box::from_raw(overlapped) });
let mut info = FILE_STANDARD_INFO::default();
let ok = unsafe {
GetFileInformationByHandleEx(
WATCHED_HANDLE.load(Ordering::SeqCst) as HANDLE,
FileStandardInfo,
&mut info as *mut _ as *mut _,
std::mem::size_of_val(&info) as u32,
)
};
SEEN.store(
if ok != 0 { HANDLE_OPEN } else { HANDLE_CLOSED },
Ordering::SeqCst,
);
unsafe {
ReleaseSemaphore(
COMPLETE_SEM.load(Ordering::SeqCst) as HANDLE,
1,
ptr::null_mut(),
)
};
}
let dir = tempdir().unwrap();
let encoded: Vec<u16> = dir
.path()
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
let dir_handle = unsafe {
CreateFileW(
encoded.as_ptr(),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
ptr::null_mut(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
ptr::null_mut(),
)
};
assert_ne!(dir_handle, INVALID_HANDLE_VALUE);
let complete_sem = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
assert!(!complete_sem.is_null());
WATCHED_HANDLE.store(dir_handle as isize, Ordering::SeqCst);
COMPLETE_SEM.store(complete_sem as isize, Ordering::SeqCst);
let mut buffer = Box::new([0u8; super::BUF_SIZE as usize]);
let overlapped = Box::into_raw(Box::new(unsafe { std::mem::zeroed::<OVERLAPPED>() }));
let ret = unsafe {
ReadDirectoryChangesW(
dir_handle,
buffer.as_mut_ptr() as *mut _,
super::BUF_SIZE,
0,
FILE_NOTIFY_CHANGE_FILE_NAME,
ptr::null_mut(),
overlapped,
Some(completion),
)
};
assert_ne!(ret, 0);
std::fs::write(dir.path().join("a.log"), b"x").unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while unsafe { ptr::read_volatile(&(*overlapped).Internal) } == STATUS_PENDING {
assert!(Instant::now() < deadline, "read never completed");
thread::sleep(Duration::from_millis(1));
}
assert_eq!(SEEN.load(Ordering::SeqCst), NOT_RUN);
let (mut request, _events, _actions) = request(false);
let data = Rc::get_mut(&mut request.data).unwrap();
data.handle = dir_handle;
data.complete_sem = complete_sem;
super::stop_watch(data);
assert_eq!(
SEEN.load(Ordering::SeqCst),
HANDLE_OPEN,
"the queued completion must run before the directory handle is closed"
);
}
#[test]
fn request_unwatch_identifies_the_directory_registration() {
let (mut request, _events, actions) = request(false);
let data = Rc::get_mut(&mut request.data).unwrap();
data.id = 42;
data.dir = PathBuf::from(r"C:\tmp");
target_mut(data).watch_path = PathBuf::from(r"C:\tmp\file.txt");
data.unwatch();
assert!(matches!(
actions.recv().unwrap(),
super::Action::Unwatch(42)
));
assert!(data.stopping.get());
}
#[test]
fn auto_separator_style_keeps_relative_slash_watch_style()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let cwd = env::current_dir()?;
let root = tempdir_in(&cwd)?;
let watched_dir = root.path().join("sub").join("dir");
std::fs::create_dir_all(&watched_dir)?;
let watched_file = watched_dir.join("entry");
let relative_watch_path = watched_dir.strip_prefix(&cwd)?;
let slash_watch_path =
PathBuf::from(relative_watch_path.to_string_lossy().replace('\\', "/"));
let (mut watcher, mut rx) = channel_with_config::<ReadDirectoryChangesWatcher>(
ChannelConfig::default().with_watcher_config(
crate::Config::default()
.with_windows_path_separator_style(WindowsPathSeparatorStyle::Auto),
),
);
watcher.watch_nonrecursively(&slash_watch_path);
std::fs::File::create_new(&watched_file)?;
let expected_path =
normalize_path_separators(slash_watch_path.join("entry"), SeparatorStyle::Slash);
rx.wait_unordered([expected(&expected_path).create_file()]);
Ok(())
}
#[test]
fn single_file_filter_matches_with_explicit_separator_style() {
let watched_file = PathBuf::from(r"G:\Feature\a.txt");
let watched_dir = PathBuf::from(r"G:\Feature");
let separator_style =
SeparatorStyle::resolve(WindowsPathSeparatorStyle::Slash, &watched_file);
let normalized_watch_path =
normalize_path_separators(watched_file.clone(), separator_style);
let raw_event_name: Vec<u16> = "\\a.txt".encode_utf16().collect();
let relative_path = PathBuf::from(OsString::from_wide(trim_leading_separators(
&raw_event_name,
)));
let normalized_event_path =
normalize_path_separators(watched_dir.join(relative_path), separator_style);
assert_eq!(normalized_watch_path, normalized_event_path);
assert_eq!(normalized_event_path, PathBuf::from("G:/Feature/a.txt"));
}
#[test]
fn single_file_filter_matches_bare_relative_file() {
let watched_file = PathBuf::from("a.txt");
let reported_dir = watched_file
.parent()
.map_or_else(PathBuf::new, Path::to_path_buf);
let separator_style =
SeparatorStyle::resolve(WindowsPathSeparatorStyle::Auto, &watched_file);
let normalized_watch_path =
normalize_path_separators(watched_file.clone(), separator_style);
let raw_event_name: Vec<u16> = "a.txt".encode_utf16().collect();
let relative_path = PathBuf::from(OsString::from_wide(trim_leading_separators(
&raw_event_name,
)));
let normalized_event_path =
normalize_path_separators(reported_dir.join(relative_path), separator_style);
assert_eq!(normalized_watch_path, normalized_event_path);
assert_eq!(normalized_event_path, watched_file);
}
#[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("create");
rx.wait_ordered_exact([expected(&path).create_file()])
.ensure_no_tail();
}
#[test]
fn recursive_temp_dir_write_reports_created_file_kind() {
let tmpdir = tempdir().expect("create tempdir");
let (mut watcher, mut rx) = watcher();
watcher.watch_recursively(tmpdir.path());
let path = tmpdir.path().join("new.txt");
std::fs::write(&path, b"hello").expect("write");
rx.wait_ordered([expected(&path).create_file()]);
}
#[test]
fn write_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::File::create_new(&path).expect("create");
watcher.watch_recursively(&tmpdir);
std::fs::write(&path, b"123").expect("write");
rx.wait_ordered_exact([expected(&path).modify_any().multiple()])
.ensure_no_tail();
}
#[test]
fn chmod_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
let file = std::fs::File::create_new(&path).expect("create");
let mut permissions = file.metadata().expect("metadata").permissions();
permissions.set_readonly(true);
watcher.watch_recursively(&tmpdir);
file.set_permissions(permissions).expect("set_permissions");
rx.wait_ordered_exact([expected(&path).modify_any()])
.ensure_no_tail();
}
#[test]
fn rename_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::File::create_new(&path).expect("create");
watcher.watch_recursively(&tmpdir);
let new_path = tmpdir.path().join("renamed");
std::fs::rename(&path, &new_path).expect("rename");
rx.wait_ordered_exact([
expected(&path).rename_from(),
expected(&new_path).rename_to(),
])
.ensure_no_tail();
}
#[test]
fn delete_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let file = tmpdir.path().join("file");
std::fs::write(&file, "").expect("write");
watcher.watch_nonrecursively(&tmpdir);
std::fs::remove_file(&file).expect("remove");
rx.wait_ordered_exact([expected(&file).remove_any()])
.ensure_no_tail();
}
#[test]
fn delete_self_file() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let file = tmpdir.path().join("file");
std::fs::write(&file, "").expect("write");
watcher.watch_nonrecursively(&file);
std::fs::remove_file(&file).expect("remove");
rx.wait_ordered_exact([expected(&file).remove_any()]);
}
#[test]
fn delete_self_dir() {
let tmpdir = testdir();
let dir = tmpdir.path().join("dir");
std::fs::create_dir(&dir).expect("create");
let (mut watcher, mut rx) = watcher();
watcher.watch_nonrecursively(&dir);
std::fs::remove_dir(&dir).expect("remove");
rx.wait_unordered([expected(&dir).remove_folder()]);
}
#[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");
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.wait_ordered_exact([
expected(&overwriting_file).create(),
expected(&overwriting_file).modify_any().multiple(),
expected(&overwritten_file).remove_any(),
expected(&overwriting_file).rename_from(),
expected(&overwritten_file).rename_to(),
])
.ensure_no_tail();
}
#[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("create");
rx.wait_ordered_exact([expected(&path).create_folder()])
.ensure_no_tail();
}
#[test]
fn chmod_dir() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::create_dir(&path).expect("create_dir");
let mut permissions = std::fs::metadata(&path).expect("metadata").permissions();
permissions.set_readonly(true);
watcher.watch_recursively(&tmpdir);
std::fs::set_permissions(&path, permissions).expect("set_permissions");
rx.wait_ordered_exact([expected(&path).modify_any()])
.ensure_no_tail();
}
#[test]
fn rename_dir() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
let new_path = tmpdir.path().join("new_path");
std::fs::create_dir(&path).expect("create_dir");
watcher.watch_recursively(&tmpdir);
std::fs::rename(&path, &new_path).expect("rename");
rx.wait_ordered_exact([
expected(&path).rename_from(),
expected(&new_path).rename_to(),
])
.ensure_no_tail();
}
#[test]
fn delete_dir() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::create_dir(&path).expect("create_dir");
watcher.watch_recursively(&tmpdir);
std::fs::remove_dir(&path).expect("remove");
rx.wait_ordered_exact([expected(&path).remove_any()])
.ensure_no_tail();
}
#[test]
fn rename_dir_twice() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
let new_path = tmpdir.path().join("new_path");
let new_path2 = tmpdir.path().join("new_path2");
std::fs::create_dir(&path).expect("create_dir");
watcher.watch_recursively(&tmpdir);
std::fs::rename(&path, &new_path).expect("rename");
std::fs::rename(&new_path, &new_path2).expect("rename2");
rx.wait_ordered_exact([
expected(&path).rename_from(),
expected(&new_path).rename_to(),
expected(&new_path).rename_from(),
expected(&new_path2).rename_to(),
])
.ensure_no_tail();
}
#[test]
fn move_out_of_watched_dir() {
let tmpdir = testdir();
let subdir = tmpdir.path().join("subdir");
let (mut watcher, mut rx) = watcher();
let path = subdir.join("entry");
std::fs::create_dir_all(&subdir).expect("create_dir_all");
std::fs::File::create_new(&path).expect("create");
watcher.watch_recursively(&subdir);
let new_path = tmpdir.path().join("entry");
std::fs::rename(&path, &new_path).expect("rename");
let event = rx.recv();
assert_eq!(event, expected(path).remove_any());
rx.ensure_empty();
}
#[test]
fn create_write_write_rename_write_remove() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let file1 = tmpdir.path().join("entry");
let file2 = tmpdir.path().join("entry2");
std::fs::File::create_new(&file2).expect("create file2");
let new_path = tmpdir.path().join("renamed");
watcher.watch_recursively(&tmpdir);
std::fs::write(&file1, "123").expect("write 1");
std::fs::write(&file2, "321").expect("write 2");
std::fs::rename(&file1, &new_path).expect("rename");
std::fs::write(&new_path, b"1").expect("write 3");
std::fs::remove_file(&new_path).expect("remove");
rx.wait_ordered_exact([
expected(&file1).create(),
expected(&file1).modify_any().multiple(),
expected(&file2).modify_any().multiple(),
expected(&file1).rename_from(),
expected(&new_path).rename_to(),
expected(&new_path).modify_any().multiple(),
expected(&new_path).remove_any(),
]);
}
#[test]
fn rename_twice() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::File::create_new(&path).expect("create");
watcher.watch_recursively(&tmpdir);
let new_path1 = tmpdir.path().join("renamed1");
let new_path2 = tmpdir.path().join("renamed2");
std::fs::rename(&path, &new_path1).expect("rename1");
std::fs::rename(&new_path1, &new_path2).expect("rename2");
rx.wait_ordered_exact([
expected(&path).rename_from(),
expected(&new_path1).rename_to(),
expected(&new_path1).rename_from(),
expected(&new_path2).rename_to(),
])
.ensure_no_tail();
}
#[test]
fn set_file_mtime() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
let file = std::fs::File::create_new(&path).expect("create");
watcher.watch_recursively(&tmpdir);
file.set_modified(
std::time::SystemTime::now()
.checked_sub(Duration::from_secs(60 * 60))
.expect("time"),
)
.expect("set_time");
assert_eq!(rx.recv(), expected(&path).modify_any());
rx.ensure_empty();
}
#[test]
fn write_file_non_recursive_watch() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let path = tmpdir.path().join("entry");
std::fs::File::create_new(&path).expect("create");
watcher.watch_nonrecursively(&path);
std::fs::write(&path, b"123").expect("write");
rx.wait_ordered_exact([expected(&path).modify_any().multiple()])
.ensure_no_tail();
}
#[test]
fn write_to_a_hardlink_pointed_to_the_file_in_the_watched_dir_doesnt_trigger_an_event() {
let tmpdir = testdir();
let (mut watcher, mut rx) = watcher();
let subdir = tmpdir.path().join("subdir");
let file = subdir.join("file");
let hardlink = tmpdir.path().join("hardlink");
std::fs::create_dir(&subdir).expect("create");
std::fs::write(&file, "").expect("file");
std::fs::hard_link(&file, &hardlink).expect("hardlink");
watcher.watch_nonrecursively(&subdir);
std::fs::write(&hardlink, "123123").expect("write to the hard link");
let events = rx.iter().collect::<Vec<_>>();
assert!(events.is_empty(), "unexpected events: {events:#?}");
}
#[test]
fn recursive_creation() {
let tmpdir = testdir();
let nested1 = tmpdir.path().join("1");
let nested2 = tmpdir.path().join("1/2");
let nested3 = tmpdir.path().join("1/2/3");
let nested4 = tmpdir.path().join("1/2/3/4");
let nested5 = tmpdir.path().join("1/2/3/4/5");
let nested6 = tmpdir.path().join("1/2/3/4/5/6");
let nested7 = tmpdir.path().join("1/2/3/4/5/6/7");
let nested8 = tmpdir.path().join("1/2/3/4/5/6/7/8");
let nested9 = tmpdir.path().join("1/2/3/4/5/6/7/8/9");
let (mut watcher, mut rx) = watcher();
watcher.watch_recursively(&tmpdir);
std::fs::create_dir_all(&nested9).expect("create_dir_all");
rx.wait_ordered([
expected(&nested1).create_folder(),
expected(&nested2).create_folder(),
expected(&nested3).create_folder(),
expected(&nested4).create_folder(),
expected(&nested5).create_folder(),
expected(&nested6).create_folder(),
expected(&nested7).create_folder(),
expected(&nested8).create_folder(),
expected(&nested9).create_folder(),
]);
}
#[test]
fn unwatch_waits_for_pending_callback_before_returning() {
let tmpdir = testdir();
let watched_dir = tmpdir.path().join("watched");
std::fs::create_dir(&watched_dir).expect("create watched dir");
let first = watched_dir.join("new_dir");
let second = watched_dir.join("should_not_be_seen");
let first_for_handler = first.clone();
let (event_tx, event_rx) = mpsc::channel();
let (started_tx, started_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let (unwatch_done_tx, unwatch_done_rx) = mpsc::channel();
let (finish_tx, finish_rx) = mpsc::channel();
let blocked_once = Arc::new(AtomicBool::new(false));
let blocked_once_for_handler = blocked_once.clone();
let mut watcher = ReadDirectoryChangesWatcher::new(
move |res: crate::Result<crate::Event>| {
if let Ok(event) = &res
&& event.paths.iter().any(|path| path == &first_for_handler)
&& !blocked_once_for_handler.swap(true, Ordering::SeqCst)
{
started_tx.send(()).expect("signal callback start");
release_rx.recv().expect("release callback");
}
event_tx.send(res).expect("forward event");
},
crate::Config::default(),
)
.expect("create watcher");
watcher
.watch(&watched_dir, RecursiveMode::NonRecursive)
.expect("watch dir");
std::fs::create_dir(&first).expect("create first dir");
started_rx
.recv_timeout(Duration::from_secs(5))
.expect("wait for callback to block");
let unwatch_path = watched_dir.clone();
let join = thread::spawn(move || {
let mut watcher = watcher;
let result = watcher.unwatch(&unwatch_path);
unwatch_done_tx.send(result).expect("send unwatch result");
finish_rx.recv().expect("finish watcher thread");
});
assert!(
unwatch_done_rx
.recv_timeout(Duration::from_millis(100))
.is_err(),
"unwatch returned before the pending callback finished"
);
release_tx.send(()).expect("release callback");
unwatch_done_rx
.recv_timeout(Duration::from_secs(5))
.expect("wait for unwatch result")
.expect("unwatch dir");
std::fs::create_dir(&second).expect("create second dir");
let first_event = event_rx
.recv_timeout(Duration::from_secs(5))
.expect("receive first event")
.expect("first event result");
assert_eq!(first_event, expected(&first).create_folder());
while let Ok(res) = event_rx.recv_timeout(Duration::from_millis(200)) {
let event = res.expect("event result");
assert!(
!event.paths.iter().any(|path| path == &second),
"unexpected event after unwatch: {event:#?}"
);
}
finish_tx.send(()).expect("finish watcher thread");
join.join().expect("join watcher thread");
}
#[test]
fn unwatch_not_watched_path_returns_watch_not_found() {
let tmpdir = tempdir().expect("create tempdir");
let mut watcher =
ReadDirectoryChangesWatcher::new(|_| {}, Config::default()).expect("create watcher");
let result = watcher.unwatch(tmpdir.path());
assert!(
matches!(
result,
Err(Error {
kind: ErrorKind::WatchNotFound,
..
})
),
"unexpected result: {result:?}"
);
watcher
.watch(tmpdir.path(), RecursiveMode::Recursive)
.expect("watch dir");
watcher.unwatch(tmpdir.path()).expect("unwatch dir");
let result = watcher.unwatch(tmpdir.path());
assert!(
matches!(
result,
Err(Error {
kind: ErrorKind::WatchNotFound,
..
})
),
"unexpected result: {result:?}"
);
}
}