//! The watcher, run once per backend (native and polling). Every wait is //! bounded by a timeout on the channel. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing )] mod common; use std::fs; use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, RecvTimeoutError}; use std::time::{Duration, Instant}; use common::{open, tree}; use lutra_vfs::{EntryKind, Project, VfsEvent, WatchBackend, WatchOptions, Watcher}; const TIMEOUT: Duration = Duration::from_secs(10); /// Receives events until one satisfies `want`, failing after [`TIMEOUT`]. /// Returns the events seen before it. fn wait_for(rx: &Receiver, want: impl Fn(&VfsEvent) -> bool) -> Vec { let deadline = Instant::now() + TIMEOUT; let mut seen = Vec::new(); loop { let left = deadline.saturating_duration_since(Instant::now()); match rx.recv_timeout(left) { Ok(event) if want(&event) => return seen, Ok(event) => seen.push(event), Err(RecvTimeoutError::Timeout) => panic!("timed out; saw {seen:?}"), Err(RecvTimeoutError::Disconnected) => panic!("watcher stopped; saw {seen:?}"), } } } /// Starts a watcher with `backend`, checking that the native backend /// really started on this machine. fn start( project: &Project, backend: WatchBackend, interval: Duration, ) -> (Watcher, Receiver) { let (watcher, rx) = project .watch_with(WatchOptions { interval, backend }) .unwrap(); assert_eq!(watcher.is_native(), backend == WatchBackend::Auto); (watcher, rx) } fn watch(project: &Project, backend: WatchBackend) -> (Watcher, Receiver) { start(project, backend, WatchOptions::default().interval) } /// Runs each listed test body once per backend. macro_rules! both_backends { ($($name:ident),* $(,)?) => { mod native { $(#[test] fn $name() { super::$name(super::WatchBackend::Auto) })* } mod polling { $(#[test] fn $name() { super::$name(super::WatchBackend::Polling) })* } }; } both_backends!( reports_create_modify_rename_and_delete, reports_directories_and_watched_subdirectories, ignored_hidden_and_excluded_directories_are_not_watched, changes_within_one_interval_are_coalesced, losing_the_root_degrades_to_an_error_event, dropping_the_watcher_closes_the_channel, ); fn is_created(path: &Path) -> impl Fn(&VfsEvent) -> bool + '_ { move |e| matches!(e, VfsEvent::Created { path: p, .. } if p == path) } fn reports_create_modify_rename_and_delete(backend: WatchBackend) { let dir = tree(&[("keep.php", "")]); let project = open(dir.path()); let (_watcher, rx) = watch(&project, backend); fs::write(dir.path().join("new.php"), "a").unwrap(); wait_for(&rx, is_created(Path::new("new.php"))); fs::write(dir.path().join("new.php"), "a longer body").unwrap(); wait_for( &rx, |e| matches!(e, VfsEvent::Modified { path } if path == Path::new("new.php")), ); fs::rename(dir.path().join("new.php"), dir.path().join("moved.php")).unwrap(); wait_for(&rx, |e| { *e == VfsEvent::Renamed { from: PathBuf::from("new.php"), to: PathBuf::from("moved.php"), } }); fs::remove_file(dir.path().join("moved.php")).unwrap(); wait_for( &rx, |e| matches!(e, VfsEvent::Removed { path } if path == Path::new("moved.php")), ); } fn reports_directories_and_watched_subdirectories(backend: WatchBackend) { let dir = tree(&[]); let project = open(dir.path()); let (watcher, rx) = watch(&project, backend); fs::create_dir(dir.path().join("src")).unwrap(); wait_for(&rx, |e| { *e == VfsEvent::Created { path: PathBuf::from("src"), kind: EntryKind::Directory, } }); assert!(watcher.watch_dir("src").unwrap()); assert_eq!( watcher.watched_dirs(), [PathBuf::new(), PathBuf::from("src")] ); fs::write(dir.path().join("src").join("A.php"), "").unwrap(); let inner = Path::new("src").join("A.php"); wait_for(&rx, is_created(&inner)); watcher.unwatch_dir("src"); assert_eq!(watcher.watched_dirs(), [PathBuf::new()]); } fn ignored_hidden_and_excluded_directories_are_not_watched(backend: WatchBackend) { let dir = tree(&[ (".gitignore", "target/\n"), ("target/", ""), ("node_modules/", ""), (".git/", ""), ("src/", ""), ]); let project = open(dir.path()); let (watcher, rx) = watch(&project, backend); assert!(!watcher.watch_dir("target").unwrap()); assert!(!watcher.watch_dir("node_modules").unwrap()); assert!(!watcher.watch_dir(".git").unwrap()); assert!(watcher.watch_dir("src").unwrap()); fs::write(dir.path().join("target").join("out.bin"), "x").unwrap(); fs::write(dir.path().join("node_modules").join("m.js"), "x").unwrap(); fs::write(dir.path().join(".git").join("index"), "x").unwrap(); fs::write(dir.path().join("src").join("marker.php"), "x").unwrap(); let marker = Path::new("src").join("marker.php"); let before = wait_for(&rx, is_created(&marker)); for event in &before { let text = format!("{event:?}"); assert!( !text.contains("target") && !text.contains("node_modules") && !text.contains(".git"), "unexpected event {event:?}" ); } } fn changes_within_one_interval_are_coalesced(backend: WatchBackend) { let dir = tree(&[]); let project = open(dir.path()); let (_watcher, rx) = start(&project, backend, Duration::from_secs(2)); let start = Instant::now(); fs::write(dir.path().join("flash.tmp"), "x").unwrap(); fs::remove_file(dir.path().join("flash.tmp")).unwrap(); fs::write(dir.path().join("marker.php"), "x").unwrap(); let before = wait_for(&rx, is_created(Path::new("marker.php"))); let polled_once_at_most = start.elapsed() < Duration::from_secs(2); if backend == WatchBackend::Auto || polled_once_at_most { assert!(before.is_empty(), "flash.tmp leaked: {before:?}"); } } fn losing_the_root_degrades_to_an_error_event(backend: WatchBackend) { let parent = tree(&[("project/a.php", "")]); let root = parent.path().join("project"); let project = open(&root); let (_watcher, rx) = watch(&project, backend); fs::remove_dir_all(&root).unwrap(); wait_for(&rx, |e| matches!(e, VfsEvent::Failed(_))); let deadline = Instant::now() + TIMEOUT; loop { match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { Ok(_) => continue, Err(RecvTimeoutError::Disconnected) => break, Err(RecvTimeoutError::Timeout) => panic!("watcher kept running"), } } } fn dropping_the_watcher_closes_the_channel(backend: WatchBackend) { let dir = tree(&[]); let project = open(dir.path()); let (watcher, rx) = watch(&project, backend); drop(watcher); assert_eq!( rx.recv_timeout(TIMEOUT), Err(RecvTimeoutError::Disconnected) ); }