use crate::ignore::Ignored;
use crate::refresh::{refresh_once_quiet, wait_for_change};
use anyhow::Result;
use file_id::FileId;
use notify_debouncer_full::notify::ErrorKind as WatchError;
use notify_debouncer_full::notify::event::{AccessKind, AccessMode, MetadataKind};
use notify_debouncer_full::notify::{
self, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, event::ModifyKind,
};
use notify_debouncer_full::{
DebounceEventResult, DebouncedEvent, Debouncer, NoCache, new_debouncer_opt,
};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};
use tower_livereload::Reloader;
const DEBOUNCE_DELAY: Duration = Duration::from_millis(200);
pub(crate) const POLL_INTERVAL: Duration = Duration::from_secs(1);
const CHECK_INTERVAL: Duration = Duration::from_millis(100);
const TRIES_AGAIN_AFTER: Duration = Duration::from_secs(1);
const MOST_PROBLEMS: usize = 20;
type Debounced<W> = Debouncer<W, NoCache>;
enum Rewatch {
Replaced,
WatchFailed,
}
pub(crate) fn start(root: &Path, poll: bool, ignored: Ignored, reloader: Reloader) -> Result<()> {
let (failed, failures) = mpsc::channel();
let (changed, changes) = mpsc::channel();
std::thread::spawn(move || {
refresh_once_quiet(
|until| wait_for_change(&changes, until),
|worth_a_line| {
if worth_a_line {
println!(" File changed, reloading...");
}
reloader.reload();
},
);
});
let rebuilds = Rebuilds::new(poll);
let report = report_changes(
root.to_path_buf(),
poll,
ignored,
rebuilds.clone(),
changed.clone(),
failed,
);
if poll {
let debouncer = new_debouncer_opt::<_, PollWatcher, _>(
DEBOUNCE_DELAY,
None,
report,
NoCache::new(),
notify::Config::default()
.with_poll_interval(POLL_INTERVAL)
.with_compare_contents(true)
.with_follow_symlinks(false),
)
.map_err(|error| cannot_watch_here(root, &error))?;
keep_watching(debouncer, root, failures, rebuilds, changed)
} else {
let debouncer = new_debouncer_opt::<_, RecommendedWatcher, _>(
DEBOUNCE_DELAY,
None,
report,
NoCache::new(),
notify::Config::default(),
)
.map_err(|error| cannot_watch_here(root, &error))?;
keep_watching(debouncer, root, failures, rebuilds, changed)
}
}
#[derive(Clone)]
struct Rebuilds {
announced: Arc<Mutex<Option<Instant>>>,
watching: Arc<Mutex<Option<FileId>>>,
same_rebuild: Duration,
}
impl Rebuilds {
fn new(poll: bool) -> Rebuilds {
Rebuilds {
announced: Arc::new(Mutex::new(None)),
watching: Arc::new(Mutex::new(None)),
same_rebuild: same_rebuild(poll),
}
}
}
const SETTLING_IN: Duration = Duration::from_secs(3);
fn report_changes(
root: PathBuf,
polling: bool,
ignored: Ignored,
rebuilds: Rebuilds,
changed: mpsc::Sender<bool>,
failed: mpsc::Sender<()>,
) -> impl FnMut(DebounceEventResult) + Send + 'static {
let mut told: Vec<String> = Vec::new();
let watch_went_on = SystemTime::now();
let watching_since = Instant::now();
move |result| match result {
Ok(events) => {
if replaced_under_the_watch(&rebuilds.watching, &root) {
return;
}
let settling = settling_in(polling, watching_since, Instant::now());
if events.iter().any(|event| {
is_change(&ignored, &root, event, polling)
&& !(settling && from_before_the_watch(event, watch_went_on))
}) {
let echo =
just_announced(&rebuilds.announced, Instant::now(), rebuilds.same_rebuild);
let _ = changed.send(!echo);
}
}
Err(errors) if polling => {
for problem in errors
.iter()
.filter_map(|error| cannot_look(&ignored, &root, error))
{
if !told.contains(&problem) && told.len() < MOST_PROBLEMS {
eprintln!(" {problem}");
told.push(problem);
}
}
}
Err(errors) => {
let (out_of_watches, down): (Vec<_>, Vec<_>) = errors
.iter()
.partition(|error| matches!(error.kind, WatchError::MaxFilesWatch));
for error in out_of_watches {
let problem = format!(
"Cannot watch {}: {}. New directories are not watched from here on",
short_name(&root, error.paths.first().map_or(&root, PathBuf::as_path)),
cannot_watch(error)
);
if !told.contains(&problem) && told.len() < MOST_PROBLEMS {
eprintln!(" {problem}");
told.push(problem);
}
}
if !down.is_empty() {
for error in down {
eprintln!(" Cannot watch for changes: {}", cannot_watch(error));
}
let _ = failed.send(());
}
}
}
}
fn keep_watching<W: notify::Watcher + Send + 'static>(
mut debouncer: Debounced<W>,
root: &Path,
failures: Receiver<()>,
rebuilds: Rebuilds,
changed: mpsc::Sender<bool>,
) -> Result<()> {
let first_look = Watched::at(root);
debouncer
.watch(root, RecursiveMode::Recursive)
.map_err(|error| cannot_watch_here(root, &error))?;
let first_look = first_look.filter(|it| Some(it.id) == directory_id(root));
remember(&rebuilds.watching, &first_look);
let root = root.to_path_buf();
std::thread::spawn(move || supervise(debouncer, root, failures, first_look, rebuilds, changed));
Ok(())
}
fn supervise<W: notify::Watcher>(
mut debouncer: Debounced<W>,
root: PathBuf,
failures: Receiver<()>,
mut watched: Option<Watched>,
rebuilds: Rebuilds,
changed: mpsc::Sender<bool>,
) {
let mut was_missing = false;
loop {
let reason = match failures.recv_timeout(CHECK_INTERVAL) {
Ok(()) => Rewatch::WatchFailed,
Err(mpsc::RecvTimeoutError::Disconnected) => return,
Err(mpsc::RecvTimeoutError::Timeout) => {
let Some(now) = directory_id(&root) else {
was_missing = true;
continue;
};
match watched.as_ref().map(|it| it.id) {
Some(before) if before != now => Rewatch::Replaced,
Some(_) if was_missing => {
was_missing = false;
announce(&rebuilds.announced);
println!(" Directory back, reloading...");
let _ = changed.send(false);
continue;
}
Some(_) => continue,
None => {
watched = watch_again(&mut debouncer, &root, &failures, None);
remember(&rebuilds.watching, &watched);
continue;
}
}
}
};
let rebuild = matches!(reason, Rewatch::Replaced).then_some(&*rebuilds.announced);
if let Some(at) = rebuild {
announce(at);
}
watched = watch_again(&mut debouncer, &root, &failures, rebuild);
remember(&rebuilds.watching, &watched);
was_missing = false;
match reason {
Rewatch::Replaced => {
announce(&rebuilds.announced);
println!(" Directory replaced, reloading...");
}
Rewatch::WatchFailed => println!(" Watching again, reloading..."),
}
let _ = changed.send(false);
}
}
fn watch_again<W: notify::Watcher>(
debouncer: &mut Debounced<W>,
root: &Path,
failures: &Receiver<()>,
rebuild: Option<&Mutex<Option<Instant>>>,
) -> Option<Watched> {
let mut told = None;
loop {
if !root.is_dir() {
std::thread::sleep(CHECK_INTERVAL);
continue;
}
let _ = debouncer.unwatch(root);
if let Some(at) = rebuild {
announce(at);
}
while failures.try_recv().is_ok() {}
let looked_at = Watched::at(root);
let watched = debouncer.watch(root, RecursiveMode::Recursive);
match watched {
Ok(()) if same_directory(looked_at.as_ref(), directory_id(root)) => {
return looked_at;
}
Ok(()) => {}
Err(error) if was_not_there(&error) || !root.is_dir() => {}
Err(error) => {
let problem = format!(
"Cannot watch {}: {}. Nothing will refresh until the watch can go on",
short_name(root, error.paths.first().map_or(root, PathBuf::as_path)),
cannot_watch(&error)
);
if told.as_ref() != Some(&problem) {
eprintln!(" {problem}");
told = Some(problem);
}
std::thread::sleep(TRIES_AGAIN_AFTER);
continue;
}
}
std::thread::sleep(CHECK_INTERVAL);
}
}
fn same_directory(before: Option<&Watched>, after: Option<FileId>) -> bool {
before.is_some_and(|it| Some(it.id) == after)
}
fn settling_in(polling: bool, watching_since: Instant, now: Instant) -> bool {
!polling && now.saturating_duration_since(watching_since) < SETTLING_IN
}
fn from_before_the_watch(event: &DebouncedEvent, watch_went_on: SystemTime) -> bool {
!event.need_rescan()
&& !event.paths.is_empty()
&& event.paths.iter().all(|path| {
std::fs::metadata(path)
.and_then(|about| about.modified())
.is_ok_and(|written| written <= watch_went_on)
})
}
fn is_change(ignored: &Ignored, root: &Path, event: &DebouncedEvent, polling: bool) -> bool {
if event.need_rescan() {
return true;
}
let written = match event.kind {
EventKind::Create(_) | EventKind::Remove(_) | EventKind::Any => true,
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)) => {
polling && event.paths.iter().any(|path| !path.is_dir())
}
EventKind::Modify(ModifyKind::Metadata(_)) => false,
EventKind::Modify(_) => true,
EventKind::Access(AccessKind::Close(AccessMode::Write)) => true,
EventKind::Access(_) | EventKind::Other => false,
};
written && event.paths.iter().any(|path| !ignored.contains(root, path))
}
struct Watched {
#[cfg(unix)]
_open: Option<std::fs::File>,
id: FileId,
}
impl Watched {
#[cfg(unix)]
fn at(path: &Path) -> Option<Watched> {
let open = std::fs::File::open(path).ok();
Some(Watched {
_open: open,
id: directory_id(path)?,
})
}
#[cfg(not(unix))]
fn at(path: &Path) -> Option<Watched> {
Some(Watched {
id: directory_id(path)?,
})
}
}
fn directory_id(path: &Path) -> Option<FileId> {
file_id::get_file_id(path).ok()
}
fn same_rebuild(poll: bool) -> Duration {
let hears_within = if poll {
POLL_INTERVAL + DEBOUNCE_DELAY
} else {
DEBOUNCE_DELAY
};
hears_within + CHECK_INTERVAL
}
fn announce(at: &Mutex<Option<Instant>>) {
if let Ok(mut at) = at.lock() {
*at = Some(Instant::now());
}
}
fn remember(watching: &Mutex<Option<FileId>>, watched: &Option<Watched>) {
if let Ok(mut watching) = watching.lock() {
*watching = watched.as_ref().map(|it| it.id);
}
}
fn replaced_under_the_watch(watching: &Mutex<Option<FileId>>, root: &Path) -> bool {
let Some(watched) = watching.lock().ok().and_then(|watching| *watching) else {
return false;
};
match file_id::get_file_id(root) {
Ok(now) => now != watched,
Err(trouble) => trouble.kind() == ErrorKind::NotFound,
}
}
fn just_announced(at: &Mutex<Option<Instant>>, now: Instant, within: Duration) -> bool {
let Ok(at) = at.lock() else {
return false;
};
at.is_some_and(|when| now.saturating_duration_since(when) < within)
}
fn cannot_look(
ignored: &Ignored,
root: &Path,
error: ¬ify_debouncer_full::notify::Error,
) -> Option<String> {
let Some(path) = error.paths.first() else {
return Some(format!(
"Cannot look at part of the directory: {}",
cannot_watch(error)
));
};
if ignored.contains(root, path) {
return None;
}
if was_not_there(error) {
return None;
}
Some(format!(
"Cannot look at {}: {}",
short_name(root, path),
cannot_watch(error)
))
}
fn short_name(root: &Path, path: &Path) -> String {
match path.strip_prefix(root) {
Ok(below) if !below.as_os_str().is_empty() => below.display().to_string(),
_ => path.display().to_string(),
}
}
fn was_not_there(error: ¬ify_debouncer_full::notify::Error) -> bool {
match &error.kind {
WatchError::Io(io) => io.kind() == ErrorKind::NotFound,
WatchError::PathNotFound => true,
_ => false,
}
}
fn cannot_watch(error: ¬ify_debouncer_full::notify::Error) -> String {
match &error.kind {
WatchError::MaxFilesWatch => "the system has no file watches left — serve the build \
output rather than the whole project, or raise the limit"
.to_string(),
WatchError::PathNotFound => "there is no such directory".to_string(),
WatchError::Io(io) => crate::errors::why(io),
_ => error.to_string(),
}
}
fn cannot_watch_here(root: &Path, error: ¬ify_debouncer_full::notify::Error) -> anyhow::Error {
let named = error.paths.first().map_or(root, PathBuf::as_path);
let mut why = cannot_watch(error);
if named != root && may_not_read(error) {
why.push_str(" — --poll watches what it may, and --no-reload serves without watching");
}
anyhow::Error::msg(why).context(format!("cannot watch {} for changes", named.display()))
}
fn may_not_read(error: ¬ify_debouncer_full::notify::Error) -> bool {
matches!(&error.kind, WatchError::Io(io) if io.kind() == ErrorKind::PermissionDenied)
}
#[cfg(test)]
mod tests {
use super::*;
use notify_debouncer_full::notify::Event;
use notify_debouncer_full::notify::event::{CreateKind, DataChange, RemoveKind};
fn event(kind: EventKind, paths: &[&str]) -> DebouncedEvent {
let event = paths
.iter()
.fold(Event::new(kind), |event, path| event.add_path(path.into()));
DebouncedEvent::new(event, Instant::now())
}
fn written(paths: &[&str]) -> DebouncedEvent {
event(EventKind::Modify(ModifyKind::Data(DataChange::Any)), paths)
}
const ROOT: &str = "/site";
fn nothing_chosen() -> Ignored {
Ignored::from(&[], &[]).expect("no patterns to refuse")
}
#[test]
fn reading_a_file_is_not_a_change() {
let read = event(
EventKind::Access(AccessKind::Open(AccessMode::Any)),
&["/site/index.html"],
);
assert!(!is_change(¬hing_chosen(), Path::new(ROOT), &read, false));
}
#[test]
fn a_finished_save_is_a_change() {
let saved = event(
EventKind::Access(AccessKind::Close(AccessMode::Write)),
&["/site/index.html"],
);
assert!(is_change(¬hing_chosen(), Path::new(ROOT), &saved, false));
}
#[test]
fn a_poll_says_a_file_was_written_by_its_write_time() {
let rewritten = event(
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)),
&["/site/index.html"],
);
assert!(is_change(
¬hing_chosen(),
Path::new(ROOT),
&rewritten,
true
));
assert!(!is_change(
¬hing_chosen(),
Path::new(ROOT),
&rewritten,
false
));
}
#[cfg(any(unix, windows))]
#[test]
fn a_directorys_own_write_time_is_not_a_change() {
let root = std::env::temp_dir().join(format!("servio-dir-time-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let touched = event(
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)),
&[root.to_str().unwrap()],
);
assert!(!is_change(¬hing_chosen(), &root, &touched, true));
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn permissions_and_timestamps_are_not_changes() {
let touched = event(
EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)),
&["/site/index.html"],
);
assert!(!is_change(
¬hing_chosen(),
Path::new(ROOT),
&touched,
false
));
}
#[test]
fn dropped_events_are_a_change_whatever_was_ignored_and_however_new_the_watch() {
use notify_debouncer_full::notify::event::Flag;
let dropped = DebouncedEvent::new(
Event::new(EventKind::Other).set_flag(Flag::Rescan),
Instant::now(),
);
assert!(is_change(
¬hing_chosen(),
Path::new(ROOT),
&dropped,
false
));
assert!(
!from_before_the_watch(&dropped, SystemTime::now()),
"a report naming no file was taken for one about old files"
);
}
#[test]
fn writing_creating_and_deleting_are_changes() {
let root = Path::new(ROOT);
assert!(is_change(
¬hing_chosen(),
root,
&written(&["/site/app.css"]),
false
));
assert!(is_change(
¬hing_chosen(),
root,
&event(EventKind::Create(CreateKind::File), &["/site/new.css"]),
false
));
assert!(is_change(
¬hing_chosen(),
root,
&event(EventKind::Remove(RemoveKind::File), &["/site/old.css"]),
false
));
}
#[test]
fn writing_an_ignored_file_is_not_a_change() {
assert!(!is_change(
¬hing_chosen(),
Path::new(ROOT),
&written(&["/site/app.css.swp"]),
false
));
}
#[test]
fn one_real_file_among_ignored_ones_is_a_change() {
let mixed = written(&["/site/app.css.swp", "/site/app.css"]);
assert!(is_change(¬hing_chosen(), Path::new(ROOT), &mixed, false));
}
#[test]
fn polling_waits_longer_to_recognise_the_echo_of_a_rebuild() {
assert!(same_rebuild(true) >= same_rebuild(false) + POLL_INTERVAL);
}
#[test]
fn what_arrives_inside_the_window_after_a_rebuild_is_its_echo() {
let window = same_rebuild(false);
let announced_at = Instant::now();
let announced = Mutex::new(Some(announced_at));
let a_moment = Duration::from_millis(1);
assert!(just_announced(&announced, announced_at, window));
assert!(just_announced(
&announced,
announced_at + window - a_moment,
window
));
assert!(
!just_announced(&announced, announced_at + window, window),
"a change made once the window closed was taken for the rebuild"
);
assert!(
!just_announced(&Mutex::new(None), announced_at, window),
"a change was taken for a rebuild nobody announced"
);
}
#[test]
fn a_watch_is_settling_in_only_at_first_and_never_when_polling() {
let went_on = Instant::now();
let a_moment = Duration::from_millis(1);
assert!(settling_in(false, went_on, went_on));
assert!(settling_in(
false,
went_on,
went_on + SETTLING_IN - a_moment
));
assert!(
!settling_in(false, went_on, went_on + SETTLING_IN),
"a change made once the watch had settled was checked against old times"
);
assert!(
!settling_in(true, went_on, went_on),
"a poll was taken to hand over old files"
);
}
fn could_not_read(path: &Path, kind: ErrorKind) -> notify_debouncer_full::notify::Error {
notify_debouncer_full::notify::Error::io(kind.into()).add_path(path.to_path_buf())
}
#[test]
fn a_path_that_was_not_there_is_not_worth_a_word() {
let root = Path::new(ROOT);
let rewritten = Path::new("/site/app.css");
assert_eq!(
cannot_look(
¬hing_chosen(),
root,
&could_not_read(rewritten, ErrorKind::NotFound)
),
None
);
let said = cannot_look(
¬hing_chosen(),
root,
&could_not_read(rewritten, ErrorKind::PermissionDenied),
)
.expect("a path that cannot be read should be reported");
assert!(said.starts_with("Cannot look at app.css:"), "{said}");
assert!(!said.contains("directory"), "{said}");
}
#[test]
fn trouble_with_no_path_is_not_a_watch_that_went_down() {
let error = notify_debouncer_full::notify::Error::generic("a walk with no end");
let said =
cannot_look(¬hing_chosen(), Path::new(ROOT), &error).expect("it should be reported");
assert!(!said.contains("Cannot watch for changes"), "{said}");
assert!(said.contains("a walk with no end"), "{said}");
}
#[cfg(any(unix, windows))]
#[test]
fn a_new_directory_of_the_same_name_is_a_different_directory() {
let path = std::env::temp_dir().join(format!("servio-id-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
let watched = Watched::at(&path).expect("could not look at the directory");
assert_eq!(
directory_id(&path),
Some(watched.id),
"the same directory read twice"
);
std::fs::remove_dir_all(&path).unwrap();
assert_eq!(directory_id(&path), None, "there is no directory to read");
std::fs::create_dir_all(&path).unwrap();
assert_ne!(
directory_id(&path),
Some(watched.id),
"a rebuilt directory read as the old one"
);
std::fs::remove_dir_all(&path).unwrap();
}
#[cfg(any(unix, windows))]
#[test]
fn a_watch_put_on_nothing_is_not_on_a_directory() {
let path = std::env::temp_dir().join(format!("servio-nothing-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
let before = Watched::at(&path).expect("could not look at the directory");
assert!(same_directory(Some(&before), directory_id(&path)));
assert!(
!same_directory(None, None),
"nothing was taken for a directory"
);
assert!(!same_directory(Some(&before), None));
std::fs::remove_dir_all(&path).unwrap();
}
#[cfg(any(unix, windows))]
#[test]
fn what_the_watcher_reports_is_left_to_the_check_once_the_directory_is_replaced() {
let path = std::env::temp_dir().join(format!("servio-replaced-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
let watched = Watched::at(&path).expect("could not look at the directory");
let watching = Mutex::new(Some(watched.id));
assert!(
!replaced_under_the_watch(&watching, &path),
"the directory at the name is the one watched"
);
std::fs::remove_dir_all(&path).unwrap();
assert!(
replaced_under_the_watch(&watching, &path),
"taken away, and the check says when it is back"
);
std::fs::create_dir_all(&path).unwrap();
assert!(
replaced_under_the_watch(&watching, &path),
"rebuilt, and the check has not looked yet"
);
assert!(!replaced_under_the_watch(&Mutex::new(None), &path));
std::fs::remove_dir_all(&path).unwrap();
}
#[test]
fn a_watcher_that_went_down_is_set_up_again_but_a_look_that_could_not_read_is_not() {
let (changed, _changes) = mpsc::channel();
let trouble = || Err(vec![notify::Error::generic("the watcher went down")]);
let (failed, failures) = mpsc::channel();
let mut report = report_changes(
PathBuf::from(ROOT),
false,
nothing_chosen(),
Rebuilds::new(false),
changed.clone(),
failed,
);
report(trouble());
assert!(
failures.try_recv().is_ok(),
"a watcher that went down was left down"
);
let (failed, failures) = mpsc::channel();
let mut report = report_changes(
PathBuf::from(ROOT),
false,
nothing_chosen(),
Rebuilds::new(false),
changed.clone(),
failed,
);
report(Err(vec![
notify::Error::new(WatchError::MaxFilesWatch).add_path(PathBuf::from("/site/new")),
]));
assert!(
failures.try_recv().is_err(),
"running out of watches tore down the watch that was on"
);
let (failed, failures) = mpsc::channel();
let mut report = report_changes(
PathBuf::from(ROOT),
true,
nothing_chosen(),
Rebuilds::new(true),
changed,
failed,
);
report(trouble());
assert!(
failures.try_recv().is_err(),
"one path a look could not read was taken for a watch that went down"
);
}
#[test]
fn a_file_written_before_the_watch_went_on_is_not_a_change() {
let dir = std::env::temp_dir().join(format!("servio-settling-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let page = dir.join("index.html");
std::fs::write(&page, "<html>before</html>").unwrap();
let written_at = std::fs::metadata(&page).unwrap().modified().unwrap();
let about_the_page = written(&[page.to_str().unwrap()]);
assert!(
from_before_the_watch(&about_the_page, written_at),
"a file nobody touched was taken for one that changed"
);
assert!(
!from_before_the_watch(&about_the_page, written_at - Duration::from_millis(1)),
"a file written since the watch went on is a change"
);
std::fs::remove_file(&page).unwrap();
assert!(!from_before_the_watch(&about_the_page, written_at));
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(unix)]
#[test]
fn a_directory_that_cannot_be_read_is_not_one_that_went() {
use std::os::unix::fs::PermissionsExt;
let above = std::env::temp_dir().join(format!("servio-unreadable-{}", std::process::id()));
let path = above.join("site");
let _ = std::fs::remove_dir_all(&above);
std::fs::create_dir_all(&path).unwrap();
let mode = |mode| std::fs::set_permissions(&above, std::fs::Permissions::from_mode(mode));
let watched = Watched::at(&path).expect("could not look at the directory");
let watching = Mutex::new(Some(watched.id));
mode(0o000).unwrap();
let went = replaced_under_the_watch(&watching, &path);
mode(0o755).unwrap();
assert!(
!went,
"a directory that could not be read was taken for one that went"
);
std::fs::remove_dir_all(&above).unwrap();
}
}