ombre: Add `watcher` module
e6126efd644ea2410c9e3ffeeffb8d6e3ca37418
Contains a file watcher based on `inotify`.
1 parent
dc2f3f16
Cargo.lock
+10 -0
| 130 | 130 | "libc", |
|
| 131 | 131 | "log", |
|
| 132 | 132 | "nonempty", |
|
| 133 | 133 | "ombre", |
|
| 134 | 134 | "ombre-derive", |
|
| 135 | + | "popol", |
|
| 135 | 136 | "termcolor", |
|
| 136 | 137 | ] |
|
| 137 | 138 | ||
| 138 | 139 | [[package]] |
|
| 139 | 140 | name = "ombre-derive" |
| 147 | 148 | name = "once_cell" |
|
| 148 | 149 | version = "1.18.0" |
|
| 149 | 150 | source = "registry+https://github.com/rust-lang/crates.io-index" |
|
| 150 | 151 | checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" |
|
| 151 | 152 | ||
| 153 | + | [[package]] |
|
| 154 | + | name = "popol" |
|
| 155 | + | version = "3.0.1" |
|
| 156 | + | source = "registry+https://github.com/rust-lang/crates.io-index" |
|
| 157 | + | checksum = "eaac4c1cff8bea6334f5c2646ca0f007648dc14d0471cf3e522cd34900126568" |
|
| 158 | + | dependencies = [ |
|
| 159 | + | "libc", |
|
| 160 | + | ] |
|
| 161 | + | ||
| 152 | 162 | [[package]] |
|
| 153 | 163 | name = "proc-macro2" |
|
| 154 | 164 | version = "1.0.70" |
|
| 155 | 165 | source = "registry+https://github.com/rust-lang/crates.io-index" |
|
| 156 | 166 | checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" |
Cargo.toml
+1 -0
| 12 | 12 | ] |
|
| 13 | 13 | resolver = "2" |
|
| 14 | 14 | ||
| 15 | 15 | [workspace.dependencies] |
|
| 16 | 16 | lexopt = { version = "0.3.0" } |
|
| 17 | + | popol = { version = "3.0.1" } |
|
| 17 | 18 | ||
| 18 | 19 | [workspace.lints] |
|
| 19 | 20 | clippy.unwrap_used = "warn" |
|
| 20 | 21 | clippy.let_unit_value = "allow" |
|
| 21 | 22 | clippy.single_match = "allow" |
README
+1 -0
| 15 | 15 | ├─ runtime ░ application runtime on top of platform |
|
| 16 | 16 | ├─ gfx ░ graphics abstraction around 3D APIs |
|
| 17 | 17 | ├─ draw ░ 2D drawing library |
|
| 18 | 18 | ├─ math ░ linear algebra and trigonometry library |
|
| 19 | 19 | ├─ rng ░ random number generation |
|
| 20 | + | ├─ watcher ░ file watcher, based on `inotify` |
|
| 20 | 21 | ├─ bytes ░ general byte manipulation |
|
| 21 | 22 | ├─ ui ░ user interface toolkit |
|
| 22 | 23 | ├─ bench ░ benchmarking library |
|
| 23 | 24 | └─ lisp ░ small shadowy lisp implementation |
|
| 24 | 25 | arbre ░ living documents |
ombre/Cargo.toml
+1 -0
| 19 | 19 | glfw = { version = "0.58.0", optional = true } |
|
| 20 | 20 | glow = { version = "0.16.0" } |
|
| 21 | 21 | libc = { version = "0.2.169", optional = true } |
|
| 22 | 22 | log = { version = "0.4.20", features = ["std"] } |
|
| 23 | 23 | ombre-derive = { version = "0.1.0", path = "../ombre-derive", optional = true } |
|
| 24 | + | popol = { workspace = true } |
|
| 24 | 25 | nonempty = { version = "0.10.0" } |
|
| 25 | 26 | termcolor = { version = "1.4.0", optional = true } |
|
| 26 | 27 | ||
| 27 | 28 | [lints] |
|
| 28 | 29 | workspace = true |
ombre/src/fs.rs
added
+4 -0
| 1 | + | mod watcher; |
|
| 2 | + | ||
| 3 | + | pub use std::fs::*; |
|
| 4 | + | pub use watcher::{watcher, Event, FileWatcher}; |
ombre/src/fs/watcher.rs
added
+622 -0
| 1 | + | //! File system watcher implementation using Linux's `inotify` API. |
|
| 2 | + | //! This module provides functionality to watch directories for changes |
|
| 3 | + | //! and receive notifications about file system events. |
|
| 4 | + | #![warn(missing_docs)] |
|
| 5 | + | use std::collections::HashMap; |
|
| 6 | + | use std::ffi::CString; |
|
| 7 | + | use std::os::unix::ffi::OsStrExt; |
|
| 8 | + | use std::os::unix::io::RawFd; |
|
| 9 | + | use std::path::{Path, PathBuf}; |
|
| 10 | + | use std::sync::mpsc; |
|
| 11 | + | use std::sync::mpsc::{Receiver, Sender}; |
|
| 12 | + | use std::sync::Arc; |
|
| 13 | + | use std::{fs, io, mem, thread}; |
|
| 14 | + | ||
| 15 | + | /// Constants for `inotify` event masks. |
|
| 16 | + | /// These define the different types of events we can watch for. |
|
| 17 | + | mod inotify { |
|
| 18 | + | use std::ffi::CStr; |
|
| 19 | + | ||
| 20 | + | /// Raw `inotify` event. |
|
| 21 | + | pub use libc::inotify_event as Event; |
|
| 22 | + | ||
| 23 | + | /// Event cookie, used for renames. |
|
| 24 | + | pub type EventCookie = u32; |
|
| 25 | + | ||
| 26 | + | /// File/directory was created. |
|
| 27 | + | pub const CREATE: u32 = libc::IN_CREATE; |
|
| 28 | + | /// File/directory was deleted. |
|
| 29 | + | pub const DELETE: u32 = libc::IN_DELETE; |
|
| 30 | + | /// File was moved from this location. |
|
| 31 | + | pub const MOVED_FROM: u32 = libc::IN_MOVED_FROM; |
|
| 32 | + | /// File was moved to this location. |
|
| 33 | + | pub const MOVED_TO: u32 = libc::IN_MOVED_TO; |
|
| 34 | + | /// File was closed after being written to. |
|
| 35 | + | pub const CLOSE_WRITE: u32 = libc::IN_CLOSE_WRITE; |
|
| 36 | + | /// Event occurred on a directory. |
|
| 37 | + | pub const IS_DIR: u32 = libc::IN_ISDIR; |
|
| 38 | + | /// Combined mask of all events we want to watch for. |
|
| 39 | + | pub const WATCH_MASK: u32 = CREATE | DELETE | MOVED_FROM | MOVED_TO | CLOSE_WRITE; |
|
| 40 | + | ||
| 41 | + | /// Decode raw `inotify` event buffer. |
|
| 42 | + | pub fn decode_events(buffer: &[u8]) -> Vec<(Event, Option<String>)> { |
|
| 43 | + | let mut events = Vec::new(); |
|
| 44 | + | let mut offset = 0; |
|
| 45 | + | ||
| 46 | + | while offset + std::mem::size_of::<Event>() <= buffer.len() { |
|
| 47 | + | let event = unsafe { *(buffer.as_ptr().add(offset) as *const libc::inotify_event) }; |
|
| 48 | + | offset += std::mem::size_of::<Event>(); |
|
| 49 | + | ||
| 50 | + | let name = if event.len > 0 { |
|
| 51 | + | Some(unsafe { |
|
| 52 | + | CStr::from_ptr(buffer.as_ptr().add(offset) as *const i8) |
|
| 53 | + | .to_string_lossy() |
|
| 54 | + | .into_owned() |
|
| 55 | + | }) |
|
| 56 | + | } else { |
|
| 57 | + | None |
|
| 58 | + | }; |
|
| 59 | + | offset += event.len as usize; |
|
| 60 | + | events.push((event, name)); |
|
| 61 | + | } |
|
| 62 | + | events |
|
| 63 | + | } |
|
| 64 | + | } |
|
| 65 | + | ||
| 66 | + | /// Convert the result of a syscall to an [`io::Result`]. |
|
| 67 | + | fn syscall<T: PartialEq + From<i32>>(result: T) -> io::Result<T> { |
|
| 68 | + | if result == T::from(-1) { |
|
| 69 | + | Err(io::Error::last_os_error()) |
|
| 70 | + | } else { |
|
| 71 | + | Ok(result) |
|
| 72 | + | } |
|
| 73 | + | } |
|
| 74 | + | ||
| 75 | + | /// Types of filesystem events that can occur. |
|
| 76 | + | #[derive(Debug, Clone, PartialEq, Eq)] |
|
| 77 | + | pub enum EventKind { |
|
| 78 | + | /// A file or directory was created. |
|
| 79 | + | Create, |
|
| 80 | + | /// A file was modified. |
|
| 81 | + | Modify, |
|
| 82 | + | /// A file or directory was deleted. |
|
| 83 | + | Delete, |
|
| 84 | + | /// A file or directory was renamed. |
|
| 85 | + | Rename { |
|
| 86 | + | /// The new path after the rename. |
|
| 87 | + | to: PathBuf, |
|
| 88 | + | }, |
|
| 89 | + | } |
|
| 90 | + | ||
| 91 | + | /// Represents a filesystem event with its path and type. |
|
| 92 | + | #[derive(Debug, Clone)] |
|
| 93 | + | pub struct Event { |
|
| 94 | + | /// The path where the event occurred. |
|
| 95 | + | pub path: PathBuf, |
|
| 96 | + | /// The type of event that occurred. |
|
| 97 | + | pub kind: EventKind, |
|
| 98 | + | } |
|
| 99 | + | ||
| 100 | + | /// Commands sent from the main thread to the watch thread. |
|
| 101 | + | enum Command { |
|
| 102 | + | /// Add a new path to watch. |
|
| 103 | + | Watch { |
|
| 104 | + | path: PathBuf, |
|
| 105 | + | done: Sender<io::Result<()>>, |
|
| 106 | + | }, |
|
| 107 | + | } |
|
| 108 | + | ||
| 109 | + | /// Main watcher interface that manages the background watch thread. |
|
| 110 | + | pub struct FileWatcher { |
|
| 111 | + | /// Channel for sending commands to the watch thread. |
|
| 112 | + | cmd_tx: Sender<Command>, |
|
| 113 | + | /// Waker for watcher thread. |
|
| 114 | + | waker: Arc<popol::Waker>, |
|
| 115 | + | /// Background thread handle (only used for `Drop`). |
|
| 116 | + | _thread: thread::JoinHandle<io::Result<()>>, |
|
| 117 | + | } |
|
| 118 | + | ||
| 119 | + | impl FileWatcher { |
|
| 120 | + | /// Add a new path to watch after initialization. |
|
| 121 | + | pub fn watch<P: AsRef<Path>>(&self, path: P) -> io::Result<()> { |
|
| 122 | + | let (tx, rx) = mpsc::channel(); |
|
| 123 | + | self.cmd_tx |
|
| 124 | + | .send(Command::Watch { |
|
| 125 | + | path: path.as_ref().to_owned(), |
|
| 126 | + | done: tx, |
|
| 127 | + | }) |
|
| 128 | + | .map_err(|_| io::Error::new(io::ErrorKind::Other, "failed to send command"))?; |
|
| 129 | + | // Wake up thread to have it read from the command channel. |
|
| 130 | + | self.waker.wake()?; |
|
| 131 | + | // Wait for command to be processed before returning to caller. |
|
| 132 | + | rx.recv() |
|
| 133 | + | .map_err(|_| io::Error::new(io::ErrorKind::Other, "receive failed"))? |
|
| 134 | + | } |
|
| 135 | + | } |
|
| 136 | + | ||
| 137 | + | /// Source of a file descriptor event. |
|
| 138 | + | #[derive(Copy, Clone, Debug, PartialEq, Eq)] |
|
| 139 | + | enum EventSource { |
|
| 140 | + | Waker, |
|
| 141 | + | Watcher, |
|
| 142 | + | } |
|
| 143 | + | ||
| 144 | + | /// Internal thread that handles the `inotify` file descriptor and event processing. |
|
| 145 | + | struct WatchThread { |
|
| 146 | + | /// File descriptor for the inotify instance. |
|
| 147 | + | fd: RawFd, |
|
| 148 | + | /// Callback for dispatching filesystem events. |
|
| 149 | + | callback: Box<dyn Fn(Event) + Send>, |
|
| 150 | + | /// Channel receiver for commands from the main thread. |
|
| 151 | + | cmd_rx: Receiver<Command>, |
|
| 152 | + | /// Maps watch descriptors to their corresponding paths. |
|
| 153 | + | descriptors: HashMap<i32, PathBuf>, |
|
| 154 | + | /// Sources of file events. |
|
| 155 | + | sources: popol::Sources<EventSource>, |
|
| 156 | + | } |
|
| 157 | + | ||
| 158 | + | impl WatchThread { |
|
| 159 | + | /// Create a new watch thread state. |
|
| 160 | + | fn new( |
|
| 161 | + | callback: Box<dyn Fn(Event) + Send>, |
|
| 162 | + | waker: Arc<popol::Waker>, |
|
| 163 | + | cmd_rx: Receiver<Command>, |
|
| 164 | + | ) -> io::Result<Self> { |
|
| 165 | + | let fd = syscall(unsafe { libc::inotify_init() })?; |
|
| 166 | + | popol::set_nonblocking(&fd, true)?; |
|
| 167 | + | ||
| 168 | + | let mut sources = popol::Sources::new(); |
|
| 169 | + | sources.register(EventSource::Waker, &waker, popol::interest::READ); |
|
| 170 | + | sources.register(EventSource::Watcher, &fd, popol::interest::READ); |
|
| 171 | + | ||
| 172 | + | Ok(WatchThread { |
|
| 173 | + | fd, |
|
| 174 | + | callback, |
|
| 175 | + | cmd_rx, |
|
| 176 | + | descriptors: HashMap::new(), |
|
| 177 | + | sources, |
|
| 178 | + | }) |
|
| 179 | + | } |
|
| 180 | + | ||
| 181 | + | /// Process a single `inotify` event. |
|
| 182 | + | /// |
|
| 183 | + | /// * Handles directory creation by setting up new watches. |
|
| 184 | + | /// * Converts raw events into our Event type. |
|
| 185 | + | /// * Sends events through the channel. |
|
| 186 | + | fn handle_inotify_event(&mut self, event: &inotify::Event, path: PathBuf) -> io::Result<()> { |
|
| 187 | + | match event.mask { |
|
| 188 | + | m if m & inotify::CREATE != 0 => { |
|
| 189 | + | (self.callback)(Event { |
|
| 190 | + | path: path.clone(), |
|
| 191 | + | kind: EventKind::Create, |
|
| 192 | + | }); |
|
| 193 | + | if m & inotify::IS_DIR != 0 { |
|
| 194 | + | let c_path = CString::new(path.as_os_str().as_bytes())?; |
|
| 195 | + | // Nb. Fails if the file was removed in the meantime, which we can just ignore. |
|
| 196 | + | if let Ok(wd) = syscall(unsafe { |
|
| 197 | + | libc::inotify_add_watch(self.fd, c_path.as_ptr(), inotify::WATCH_MASK) |
|
| 198 | + | }) { |
|
| 199 | + | self.descriptors.insert(wd, path); |
|
| 200 | + | } |
|
| 201 | + | } |
|
| 202 | + | } |
|
| 203 | + | m if m & inotify::DELETE != 0 => { |
|
| 204 | + | (self.callback)(Event { |
|
| 205 | + | path: path.clone(), |
|
| 206 | + | kind: EventKind::Delete, |
|
| 207 | + | }); |
|
| 208 | + | // Clean up watch descriptor if it was a directory |
|
| 209 | + | if m & inotify::IS_DIR != 0 { |
|
| 210 | + | if let Some(wd) = |
|
| 211 | + | self.descriptors.iter().find(|(_, p)| **p == path).map(|(wd, _)| *wd) |
|
| 212 | + | { |
|
| 213 | + | // Nb. Fails if the file descriptor is not valid, which we can ignore. |
|
| 214 | + | syscall(unsafe { libc::inotify_rm_watch(self.fd, wd) }).ok(); |
|
| 215 | + | self.descriptors.remove(&wd); |
|
| 216 | + | } |
|
| 217 | + | } |
|
| 218 | + | } |
|
| 219 | + | m if m & inotify::CLOSE_WRITE != 0 => (self.callback)(Event { |
|
| 220 | + | path: path.clone(), |
|
| 221 | + | kind: EventKind::Modify, |
|
| 222 | + | }), |
|
| 223 | + | _ => {} |
|
| 224 | + | } |
|
| 225 | + | Ok(()) |
|
| 226 | + | } |
|
| 227 | + | ||
| 228 | + | /// Recursively adds watches for a directory and all its subdirectories. |
|
| 229 | + | fn add_watch_recursive(&mut self, path: &Path) -> io::Result<()> { |
|
| 230 | + | let c_path = CString::new(path.as_os_str().as_bytes())?; |
|
| 231 | + | let wd = syscall(unsafe { |
|
| 232 | + | libc::inotify_add_watch(self.fd, c_path.as_ptr(), inotify::WATCH_MASK) |
|
| 233 | + | })?; |
|
| 234 | + | self.descriptors.insert(wd, path.to_path_buf()); |
|
| 235 | + | ||
| 236 | + | if path.is_dir() { |
|
| 237 | + | for entry in fs::read_dir(path)? { |
|
| 238 | + | let entry = entry?; |
|
| 239 | + | let path = entry.path(); |
|
| 240 | + | ||
| 241 | + | if path.is_dir() { |
|
| 242 | + | self.add_watch_recursive(&path)?; |
|
| 243 | + | } |
|
| 244 | + | } |
|
| 245 | + | } |
|
| 246 | + | Ok(()) |
|
| 247 | + | } |
|
| 248 | + | ||
| 249 | + | /// Read events from buffer. Handles interrupts and partial reads. |
|
| 250 | + | fn read_events(&self, buffer: &mut [u8]) -> io::Result<usize> { |
|
| 251 | + | let mut total_read = 0; |
|
| 252 | + | while total_read < mem::size_of::<inotify::Event>() { |
|
| 253 | + | match unsafe { |
|
| 254 | + | libc::read( |
|
| 255 | + | self.fd, |
|
| 256 | + | buffer.as_mut_ptr().add(total_read) as *mut libc::c_void, |
|
| 257 | + | buffer.len() - total_read, |
|
| 258 | + | ) |
|
| 259 | + | } { |
|
| 260 | + | -1 => { |
|
| 261 | + | let err = io::Error::last_os_error(); |
|
| 262 | + | if err.kind() == io::ErrorKind::Interrupted { |
|
| 263 | + | continue; |
|
| 264 | + | } |
|
| 265 | + | return Err(err); |
|
| 266 | + | } |
|
| 267 | + | 0 => break, |
|
| 268 | + | n => total_read += n as usize, |
|
| 269 | + | } |
|
| 270 | + | } |
|
| 271 | + | Ok(total_read) |
|
| 272 | + | } |
|
| 273 | + | ||
| 274 | + | /// Main event loop that reads from the `inotify` file descriptor. |
|
| 275 | + | /// |
|
| 276 | + | /// * Processes initial watch commands. |
|
| 277 | + | /// * Reads raw events from the inotify fd. |
|
| 278 | + | /// * Parses the binary event data. |
|
| 279 | + | /// * Handles rename events by pairing MOVED_FROM/MOVED_TO. |
|
| 280 | + | /// * Processes each event through handle_inotify_event. |
|
| 281 | + | fn run(mut self) -> io::Result<()> { |
|
| 282 | + | let mut buffer = [0u8; 8192]; |
|
| 283 | + | let mut rename: Option<(inotify::EventCookie, PathBuf)> = None; |
|
| 284 | + | let mut events = Vec::with_capacity(16); |
|
| 285 | + | ||
| 286 | + | loop { |
|
| 287 | + | self.sources.wait(&mut events)?; |
|
| 288 | + | ||
| 289 | + | for event in events.drain(..) { |
|
| 290 | + | match event.key { |
|
| 291 | + | EventSource::Waker => { |
|
| 292 | + | // Check for new watch commands. |
|
| 293 | + | if let Ok(Command::Watch { path, done }) = self.cmd_rx.try_recv() { |
|
| 294 | + | done.send(self.add_watch_recursive(&path)).ok(); |
|
| 295 | + | } |
|
| 296 | + | } |
|
| 297 | + | EventSource::Watcher => { |
|
| 298 | + | // Read available events from `inotify`. |
|
| 299 | + | let len = self.read_events(&mut buffer)?; |
|
| 300 | + | // Parse all events in the buffer. |
|
| 301 | + | let events = inotify::decode_events(&buffer[..len]); |
|
| 302 | + | ||
| 303 | + | // Process each event. |
|
| 304 | + | for (event, event_name) in events { |
|
| 305 | + | // Look up the base path for this watch descriptor. |
|
| 306 | + | if let Some(base_path) = self.descriptors.get(&event.wd) { |
|
| 307 | + | let mut path = base_path.clone(); |
|
| 308 | + | ||
| 309 | + | // Add the filename if present. |
|
| 310 | + | if let Some(name) = event_name { |
|
| 311 | + | path.push(name); |
|
| 312 | + | } |
|
| 313 | + | // Handle rename events. |
|
| 314 | + | if event.mask & inotify::MOVED_FROM != 0 { |
|
| 315 | + | rename = Some((event.cookie, path)); |
|
| 316 | + | continue; |
|
| 317 | + | } |
|
| 318 | + | if event.mask & inotify::MOVED_TO != 0 { |
|
| 319 | + | if let Some((cookie, from_path)) = rename.take() { |
|
| 320 | + | if cookie == event.cookie { |
|
| 321 | + | (self.callback)(Event { |
|
| 322 | + | path: from_path, |
|
| 323 | + | kind: EventKind::Rename { to: path.clone() }, |
|
| 324 | + | }); |
|
| 325 | + | continue; |
|
| 326 | + | } |
|
| 327 | + | } |
|
| 328 | + | } |
|
| 329 | + | // Process other types of events. |
|
| 330 | + | self.handle_inotify_event(&event, path)?; |
|
| 331 | + | } |
|
| 332 | + | } |
|
| 333 | + | } |
|
| 334 | + | } |
|
| 335 | + | } |
|
| 336 | + | } |
|
| 337 | + | } |
|
| 338 | + | } |
|
| 339 | + | ||
| 340 | + | impl Drop for WatchThread { |
|
| 341 | + | fn drop(&mut self) { |
|
| 342 | + | unsafe { |
|
| 343 | + | libc::close(self.fd); |
|
| 344 | + | } |
|
| 345 | + | } |
|
| 346 | + | } |
|
| 347 | + | ||
| 348 | + | /// Creates a new file watcher with the given callback. |
|
| 349 | + | pub fn watcher<F>(callback: F) -> io::Result<FileWatcher> |
|
| 350 | + | where |
|
| 351 | + | F: Fn(Event) + Send + 'static, |
|
| 352 | + | { |
|
| 353 | + | let (cmd_tx, cmd_rx) = mpsc::channel(); |
|
| 354 | + | let waker = popol::Waker::new().map(Arc::new)?; |
|
| 355 | + | let handle = thread::spawn({ |
|
| 356 | + | let waker = waker.clone(); |
|
| 357 | + | move || WatchThread::new(Box::new(callback), waker, cmd_rx)?.run() |
|
| 358 | + | }); |
|
| 359 | + | ||
| 360 | + | Ok(FileWatcher { |
|
| 361 | + | cmd_tx, |
|
| 362 | + | waker, |
|
| 363 | + | _thread: handle, |
|
| 364 | + | }) |
|
| 365 | + | } |
|
| 366 | + | ||
| 367 | + | #[cfg(test)] |
|
| 368 | + | #[allow(clippy::unwrap_used)] |
|
| 369 | + | mod tests { |
|
| 370 | + | use std::fs; |
|
| 371 | + | use std::fs::File; |
|
| 372 | + | use std::io::Write; |
|
| 373 | + | use std::time::Duration; |
|
| 374 | + | ||
| 375 | + | use super::*; |
|
| 376 | + | use crate::tempdir::TempDir; |
|
| 377 | + | ||
| 378 | + | fn watch<P: AsRef<Path>>(paths: &[P]) -> io::Result<(FileWatcher, Receiver<Event>)> { |
|
| 379 | + | let (tx, rx) = mpsc::channel(); |
|
| 380 | + | let watcher = watcher(move |event| { |
|
| 381 | + | tx.send(event).unwrap(); |
|
| 382 | + | })?; |
|
| 383 | + | for path in paths { |
|
| 384 | + | watcher.watch(path)?; |
|
| 385 | + | } |
|
| 386 | + | Ok((watcher, rx)) |
|
| 387 | + | } |
|
| 388 | + | ||
| 389 | + | #[test] |
|
| 390 | + | fn test_file_creation() -> io::Result<()> { |
|
| 391 | + | let temp = TempDir::new()?; |
|
| 392 | + | let (_watcher, rx) = watch(&[temp.path()])?; |
|
| 393 | + | ||
| 394 | + | let test_file = temp.path().join("test.txt"); |
|
| 395 | + | File::create(&test_file)?; |
|
| 396 | + | ||
| 397 | + | // Wait for and verify the events. |
|
| 398 | + | let event = rx |
|
| 399 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 400 | + | .expect("No event received for file creation"); |
|
| 401 | + | assert_eq!(event.path, test_file); |
|
| 402 | + | assert_eq!(event.kind, EventKind::Create); |
|
| 403 | + | ||
| 404 | + | let event = rx |
|
| 405 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 406 | + | .expect("No event received for file creation"); |
|
| 407 | + | assert_eq!(event.path, test_file); |
|
| 408 | + | assert_eq!(event.kind, EventKind::Modify); |
|
| 409 | + | ||
| 410 | + | rx.try_recv().unwrap_err(); |
|
| 411 | + | ||
| 412 | + | Ok(()) |
|
| 413 | + | } |
|
| 414 | + | ||
| 415 | + | #[test] |
|
| 416 | + | fn test_file_modification() -> io::Result<()> { |
|
| 417 | + | let temp = TempDir::new()?; |
|
| 418 | + | let (_watcher, rx) = watch(&[temp.path()])?; |
|
| 419 | + | ||
| 420 | + | // Create and modify a file |
|
| 421 | + | let test_file = temp.path().join("test.txt"); |
|
| 422 | + | let mut file = File::create(&test_file)?; |
|
| 423 | + | ||
| 424 | + | // Clear creation event |
|
| 425 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 426 | + | ||
| 427 | + | // Modify file |
|
| 428 | + | file.write_all(b"Hello")?; |
|
| 429 | + | drop(file); |
|
| 430 | + | ||
| 431 | + | // Wait for and verify the event |
|
| 432 | + | let event = rx |
|
| 433 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 434 | + | .expect("No event received for file modification"); |
|
| 435 | + | assert_eq!(event.path, test_file); |
|
| 436 | + | assert_eq!(event.kind, EventKind::Modify); |
|
| 437 | + | ||
| 438 | + | rx.try_recv().unwrap_err(); |
|
| 439 | + | ||
| 440 | + | Ok(()) |
|
| 441 | + | } |
|
| 442 | + | ||
| 443 | + | #[test] |
|
| 444 | + | fn test_file_rename() -> io::Result<()> { |
|
| 445 | + | let temp = TempDir::new()?; |
|
| 446 | + | let (_watcher, rx) = watch(&[temp.path()])?; |
|
| 447 | + | ||
| 448 | + | // Create and rename a file |
|
| 449 | + | let test_file = temp.path().join("test.txt"); |
|
| 450 | + | File::create(&test_file)?; |
|
| 451 | + | ||
| 452 | + | // Clear creation events. |
|
| 453 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 454 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 455 | + | ||
| 456 | + | // Rename file |
|
| 457 | + | let new_name = temp.path().join("renamed.txt"); |
|
| 458 | + | fs::rename(&test_file, &new_name)?; |
|
| 459 | + | ||
| 460 | + | // Wait for and verify the event |
|
| 461 | + | let event = rx |
|
| 462 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 463 | + | .expect("No event received for file rename"); |
|
| 464 | + | assert_eq!(event.path, test_file); |
|
| 465 | + | assert_eq!(event.kind, EventKind::Rename { to: new_name }); |
|
| 466 | + | ||
| 467 | + | rx.try_recv().unwrap_err(); |
|
| 468 | + | ||
| 469 | + | Ok(()) |
|
| 470 | + | } |
|
| 471 | + | ||
| 472 | + | #[test] |
|
| 473 | + | fn test_file_deletion() -> io::Result<()> { |
|
| 474 | + | let temp = TempDir::new()?; |
|
| 475 | + | let (_watcher, rx) = watch(&[temp.path()])?; |
|
| 476 | + | ||
| 477 | + | // Create and delete a file |
|
| 478 | + | let test_file = temp.path().join("test.txt"); |
|
| 479 | + | File::create(&test_file)?; |
|
| 480 | + | ||
| 481 | + | // Clear creation and modification event. |
|
| 482 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 483 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 484 | + | ||
| 485 | + | // Delete file |
|
| 486 | + | fs::remove_file(&test_file)?; |
|
| 487 | + | ||
| 488 | + | // Wait for and verify the event |
|
| 489 | + | let event = rx |
|
| 490 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 491 | + | .expect("No event received for file deletion"); |
|
| 492 | + | assert_eq!(event.path, test_file); |
|
| 493 | + | assert_eq!(event.kind, EventKind::Delete); |
|
| 494 | + | ||
| 495 | + | rx.try_recv().unwrap_err(); |
|
| 496 | + | ||
| 497 | + | Ok(()) |
|
| 498 | + | } |
|
| 499 | + | ||
| 500 | + | #[test] |
|
| 501 | + | fn test_recursive_watch() -> io::Result<()> { |
|
| 502 | + | let temp = TempDir::new()?; |
|
| 503 | + | let (_watcher, rx) = watch(&[temp.path()])?; |
|
| 504 | + | let sub_dir = temp.path().join("subdir"); |
|
| 505 | + | fs::create_dir(&sub_dir)?; |
|
| 506 | + | ||
| 507 | + | // Clear directory creation event |
|
| 508 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 509 | + | ||
| 510 | + | // Create a file in the subdirectory |
|
| 511 | + | let test_file = sub_dir.join("test.txt"); |
|
| 512 | + | File::create(&test_file)?; |
|
| 513 | + | ||
| 514 | + | // Wait for and verify the event |
|
| 515 | + | let event = rx |
|
| 516 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 517 | + | .expect("No event received for file creation in subdirectory"); |
|
| 518 | + | assert_eq!(event.path, test_file); |
|
| 519 | + | assert_eq!(event.kind, EventKind::Create); |
|
| 520 | + | ||
| 521 | + | rx.try_recv().unwrap_err(); |
|
| 522 | + | ||
| 523 | + | Ok(()) |
|
| 524 | + | } |
|
| 525 | + | ||
| 526 | + | #[test] |
|
| 527 | + | fn test_multiple_watches() -> io::Result<()> { |
|
| 528 | + | let temp = TempDir::new()?; |
|
| 529 | + | let path1 = temp.path().join("1"); |
|
| 530 | + | let path2 = temp.path().join("2"); |
|
| 531 | + | ||
| 532 | + | fs::create_dir(&path1).unwrap(); |
|
| 533 | + | fs::create_dir(&path2).unwrap(); |
|
| 534 | + | ||
| 535 | + | let (_watcher, rx) = watch(&[&path1, &path2])?; |
|
| 536 | + | ||
| 537 | + | // Create files in both directories with a small delay between |
|
| 538 | + | let file1 = path1.join("test1.txt"); |
|
| 539 | + | File::create(&file1)?; |
|
| 540 | + | let file2 = path2.join("test2.txt"); |
|
| 541 | + | File::create(&file2)?; |
|
| 542 | + | ||
| 543 | + | let e1 = rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 544 | + | assert_eq!(e1.kind, EventKind::Create); |
|
| 545 | + | let e1 = rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 546 | + | assert_eq!(e1.kind, EventKind::Modify); |
|
| 547 | + | ||
| 548 | + | let e2 = rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 549 | + | assert_eq!(e2.kind, EventKind::Create); |
|
| 550 | + | let e2 = rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 551 | + | assert_eq!(e2.kind, EventKind::Modify); |
|
| 552 | + | ||
| 553 | + | rx.try_recv().unwrap_err(); |
|
| 554 | + | ||
| 555 | + | Ok(()) |
|
| 556 | + | } |
|
| 557 | + | ||
| 558 | + | #[test] |
|
| 559 | + | fn test_watch_created_files() -> io::Result<()> { |
|
| 560 | + | let temp = TempDir::new()?; |
|
| 561 | + | let (_watcher, rx) = watch(&[temp.path()])?; |
|
| 562 | + | let test_file = temp.path().join("test.txt"); |
|
| 563 | + | ||
| 564 | + | File::create(&test_file)?; |
|
| 565 | + | ||
| 566 | + | // Clear creation event |
|
| 567 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 568 | + | ||
| 569 | + | // Modify the newly created file |
|
| 570 | + | let mut file = fs::OpenOptions::new().append(true).open(&test_file)?; |
|
| 571 | + | file.write_all(b"Hello")?; |
|
| 572 | + | drop(file); |
|
| 573 | + | ||
| 574 | + | // Verify we get a modify event for the new file |
|
| 575 | + | let event = rx |
|
| 576 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 577 | + | .expect("No modify event received for newly created file"); |
|
| 578 | + | assert_eq!(event.path, test_file); |
|
| 579 | + | assert_eq!(event.kind, EventKind::Modify); |
|
| 580 | + | ||
| 581 | + | rx.try_recv().unwrap_err(); |
|
| 582 | + | ||
| 583 | + | Ok(()) |
|
| 584 | + | } |
|
| 585 | + | ||
| 586 | + | #[test] |
|
| 587 | + | fn test_watch_renamed_files() -> io::Result<()> { |
|
| 588 | + | let temp = TempDir::new()?; |
|
| 589 | + | let (_watcher, rx) = watch(&[temp.path()])?; |
|
| 590 | + | let test_file = temp.path().join("test.txt"); |
|
| 591 | + | ||
| 592 | + | // Create file |
|
| 593 | + | File::create(&test_file)?; |
|
| 594 | + | ||
| 595 | + | // Clear creation event |
|
| 596 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 597 | + | ||
| 598 | + | // Rename the file |
|
| 599 | + | let new_name = temp.path().join("renamed.txt"); |
|
| 600 | + | fs::rename(&test_file, &new_name)?; |
|
| 601 | + | ||
| 602 | + | // Clear rename events. |
|
| 603 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 604 | + | rx.recv_timeout(Duration::from_secs(3)).unwrap(); |
|
| 605 | + | ||
| 606 | + | // Modify the renamed file |
|
| 607 | + | let mut file = fs::OpenOptions::new().write(true).open(&new_name)?; |
|
| 608 | + | file.write_all(b"Hello")?; |
|
| 609 | + | drop(file); |
|
| 610 | + | ||
| 611 | + | // Verify we get a modify event for the renamed file |
|
| 612 | + | let event = rx |
|
| 613 | + | .recv_timeout(Duration::from_secs(3)) |
|
| 614 | + | .expect("No modify event received for renamed file"); |
|
| 615 | + | assert_eq!(event.path, new_name); |
|
| 616 | + | assert_eq!(event.kind, EventKind::Modify); |
|
| 617 | + | ||
| 618 | + | rx.try_recv().unwrap_err(); |
|
| 619 | + | ||
| 620 | + | Ok(()) |
|
| 621 | + | } |
|
| 622 | + | } |
ombre/src/lib.rs
+1 -0
| 10 | 10 | ||
| 11 | 11 | pub mod array; |
|
| 12 | 12 | pub mod bench; |
|
| 13 | 13 | pub mod bytes; |
|
| 14 | 14 | pub mod collections; |
|
| 15 | + | pub mod fs; |
|
| 15 | 16 | pub mod gfx; |
|
| 16 | 17 | pub mod lenses; |
|
| 17 | 18 | pub mod lisp; |
|
| 18 | 19 | pub mod logger; |
|
| 19 | 20 | pub mod math; |