Only watch directories, not files (#1859)

If a `DirectoryMonitor` is pointed at a file (and not a directory), fail on invocation of `start()`.

Validated with a unit test and manual testing using the `dir-monitor` example.
This commit is contained in:
Joe Ranweiler
2022-05-01 14:24:44 -07:00
committed by GitHub
parent 732400be1d
commit ebe5352da3
2 changed files with 21 additions and 0 deletions

View File

@ -40,6 +40,13 @@ impl DirectoryMonitor {
// Canonicalize so we can compare the watched dir to paths in the events.
self.dir = fs::canonicalize(&self.dir).await?;
// Make sure we are watching a directory.
//
// This check will pass for symlinks to directories.
if !fs::metadata(&self.dir).await?.is_dir() {
bail!("monitored path is not a directory: {}", self.dir.display());
}
// Initialize the watcher.
self.watcher.watch(&self.dir, RecursiveMode::NonRecursive)?;

View File

@ -37,6 +37,20 @@ timed_test!(test_monitor_nonexistent_path, async move {
Ok(())
});
timed_test!(test_monitor_file, async move {
let dir = tempdir()?;
// Create a file to erroneously watch.
let file_path = dir.path().join("some-file.txt");
tokio::fs::write(&file_path, "aaaaaa").await?;
let mut monitor = DirectoryMonitor::new(&file_path)?;
assert!(monitor.start().await.is_err());
Ok(())
});
timed_test!(test_monitor_dir, async move {
let dir = tempdir()?;
let mut monitor = DirectoryMonitor::new(dir.path())?;