use std::collections::HashMap;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::io::RawFd;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use crate::error::{Error, Result};
pub struct Watcher {
fd: RawFd,
watches: Arc<Mutex<HashMap<u32, PathBuf>>>,
}
impl Watcher {
pub fn new() -> Result<Self> {
let fd = unsafe { libc::inotify_init() };
if fd < 0 {
return Err(Error::Io {
path: None,
error: std::io::Error::last_os_error(),
});
}
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFL);
if flags >= 0 {
libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
}
Ok(Watcher {
fd,
watches: Arc::new(Mutex::new(HashMap::new())),
})
}
pub fn watch(&mut self, path: impl AsRef<Path>) -> Result<WatchHandle> {
let path = path.as_ref();
let path_bytes = path.as_os_str().as_bytes();
let c_string = std::ffi::CString::new(path_bytes).map_err(|_| Error::Io {
path: Some(path.to_path_buf()),
error: std::io::Error::new(std::io::ErrorKind::InvalidInput, "path contains null byte"),
})?;
const MASK: u32 = libc::IN_ACCESS
| libc::IN_MODIFY
| libc::IN_CREATE
| libc::IN_DELETE
| libc::IN_MOVED_FROM
| libc::IN_MOVED_TO
| libc::IN_ISDIR;
let wd = unsafe { libc::inotify_add_watch(self.fd, c_string.as_ptr(), MASK) };
if wd < 0 {
return Err(Error::Io {
path: Some(path.to_path_buf()),
error: std::io::Error::last_os_error(),
});
}
let path_buf = std::path::Path::new(&path).to_path_buf();
self.watches
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(wd as u32, path_buf);
Ok(WatchHandle {
wd: wd as u32,
fd: self.fd,
watches: Arc::clone(&self.watches),
})
}
pub fn next_event(&self) -> Result<WatchEvent> {
loop {
match self.try_next_event()? {
Some(event) => return Ok(event),
None => {
let mut pollfd = libc::pollfd {
fd: self.fd,
events: libc::POLLIN,
revents: 0,
};
let ret = unsafe { libc::poll(&mut pollfd, 1, -1) };
if ret < 0 {
return Err(Error::Io {
path: None,
error: std::io::Error::last_os_error(),
});
}
}
}
}
}
pub fn try_next_event(&self) -> Result<Option<WatchEvent>> {
let mut buf = [0u8; 4096];
let n = unsafe { libc::read(self.fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
if n < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::WouldBlock {
return Ok(None);
}
return Err(Error::Io {
path: None,
error: err,
});
}
if n == 0 {
return Ok(None);
}
let mut offset = 0usize;
while offset < n as usize {
if offset + std::mem::size_of::<libc::inotify_event>() > n as usize {
break;
}
let ev_ptr = unsafe { buf.as_ptr().add(offset) as *const libc::inotify_event };
let ev = unsafe { &*ev_ptr };
let name_len = ev.len as usize;
let header_size = std::mem::size_of::<libc::inotify_event>();
let name_start = offset + header_size;
let name_end = name_start + name_len;
let name = if name_len > 0 && name_end <= n as usize {
let raw = &buf[name_start..name_end];
let trimmed = if let Some(pos) = raw.iter().position(|&b| b == 0) {
&raw[..pos]
} else {
raw
};
Some(std::path::PathBuf::from(std::ffi::OsString::from_vec(
trimmed.to_vec(),
)))
} else {
None
};
let total_event_size = header_size + name_len;
let aligned = (total_event_size + std::mem::size_of::<libc::c_long>() - 1)
& !(std::mem::size_of::<libc::c_long>() - 1);
offset += aligned;
let base_path = self
.watches
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&(ev.wd as u32))
.cloned();
let full_path = match (&base_path, &name) {
(Some(bp), Some(nm)) => Some(bp.join(nm)),
(Some(bp), None) => Some(bp.clone()),
_ => None,
};
if (ev.mask & libc::IN_CREATE) != 0 {
return Ok(Some(WatchEvent::Created(full_path)));
}
if (ev.mask & libc::IN_MODIFY) != 0 {
return Ok(Some(WatchEvent::Modified(full_path)));
}
if (ev.mask & libc::IN_DELETE) != 0 {
return Ok(Some(WatchEvent::Deleted(full_path)));
}
if (ev.mask & libc::IN_MOVED_FROM) != 0 {
return Ok(Some(WatchEvent::MovedFrom {
path: full_path,
cookie: ev.cookie,
}));
}
if (ev.mask & libc::IN_MOVED_TO) != 0 {
return Ok(Some(WatchEvent::MovedTo {
path: full_path,
cookie: ev.cookie,
}));
}
if (ev.mask & libc::IN_ACCESS) != 0 {
return Ok(Some(WatchEvent::Accessed(full_path)));
}
}
Ok(None)
}
#[allow(dead_code)]
fn remove_watch(&mut self, wd: u32) -> Result<()> {
let ret = unsafe { libc::inotify_rm_watch(self.fd, wd as libc::c_int) };
if ret < 0 {
return Err(Error::Io {
path: None,
error: std::io::Error::last_os_error(),
});
}
self.watches
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&wd);
Ok(())
}
}
impl Drop for Watcher {
fn drop(&mut self) {
unsafe {
libc::close(self.fd);
}
}
}
#[cfg(feature = "async")]
impl Watcher {
pub async fn next_event_async(&self) -> Result<WatchEvent> {
use tokio::io::unix::AsyncFd;
let afd = AsyncFd::new(self.fd).map_err(|e| Error::Io {
path: None,
error: std::io::Error::other(e.to_string()),
})?;
loop {
match self.try_next_event()? {
Some(event) => return Ok(event),
None => {
let guard = afd.readable().await.map_err(|e| Error::Io {
path: None,
error: std::io::Error::other(e.to_string()),
})?;
let mut guard = guard;
guard.clear_ready();
}
}
}
}
}
pub struct WatchHandle {
wd: u32,
fd: RawFd,
watches: Arc<Mutex<HashMap<u32, PathBuf>>>,
}
impl WatchHandle {
pub fn watch_descriptor(&self) -> u32 {
self.wd
}
}
impl Drop for WatchHandle {
fn drop(&mut self) {
unsafe {
let _ = libc::inotify_rm_watch(self.fd, self.wd as libc::c_int);
}
let _ = self.watches.lock().map(|mut m| m.remove(&self.wd));
}
}
#[derive(Debug, Clone)]
pub enum WatchEvent {
Created(Option<PathBuf>),
Modified(Option<PathBuf>),
Deleted(Option<PathBuf>),
MovedFrom {
path: Option<PathBuf>,
cookie: u32,
},
MovedTo {
path: Option<PathBuf>,
cookie: u32,
},
Accessed(Option<PathBuf>),
Unknown,
}
impl WatchEvent {
pub fn path(&self) -> Option<&Path> {
match self {
WatchEvent::Created(p) => p.as_deref(),
WatchEvent::Modified(p) => p.as_deref(),
WatchEvent::Deleted(p) => p.as_deref(),
WatchEvent::MovedFrom { path, .. } => path.as_deref(),
WatchEvent::MovedTo { path, .. } => path.as_deref(),
WatchEvent::Accessed(p) => p.as_deref(),
WatchEvent::Unknown => None,
}
}
}