2023-03-02 02:51:06 +00:00
|
|
|
use bevy_utils::{default, HashMap, HashSet};
|
2020-05-17 03:18:30 +00:00
|
|
|
use crossbeam_channel::Receiver;
|
2023-03-02 02:51:06 +00:00
|
|
|
use notify::{Event, RecommendedWatcher, RecursiveMode, Result, Watcher};
|
|
|
|
use std::path::{Path, PathBuf};
|
2020-05-17 03:18:30 +00:00
|
|
|
|
2022-07-12 15:44:09 +00:00
|
|
|
/// Watches for changes to files on the local filesystem.
|
|
|
|
///
|
|
|
|
/// When hot-reloading is enabled, the [`AssetServer`](crate::AssetServer) uses this to reload
|
|
|
|
/// assets when their source files are modified.
|
2020-05-17 03:18:30 +00:00
|
|
|
pub struct FilesystemWatcher {
|
|
|
|
pub watcher: RecommendedWatcher,
|
|
|
|
pub receiver: Receiver<Result<Event>>,
|
2023-03-02 02:51:06 +00:00
|
|
|
pub path_map: HashMap<PathBuf, HashSet<PathBuf>>,
|
2020-05-17 03:18:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for FilesystemWatcher {
|
|
|
|
fn default() -> Self {
|
|
|
|
let (sender, receiver) = crossbeam_channel::unbounded();
|
2022-09-02 15:54:54 +00:00
|
|
|
let watcher: RecommendedWatcher = RecommendedWatcher::new(
|
|
|
|
move |res| {
|
|
|
|
sender.send(res).expect("Watch event send failure.");
|
|
|
|
},
|
2023-03-02 02:51:06 +00:00
|
|
|
default(),
|
2022-09-02 15:54:54 +00:00
|
|
|
)
|
2020-12-02 19:31:16 +00:00
|
|
|
.expect("Failed to create filesystem watcher.");
|
2023-03-02 02:51:06 +00:00
|
|
|
FilesystemWatcher {
|
|
|
|
watcher,
|
|
|
|
receiver,
|
|
|
|
path_map: default(),
|
|
|
|
}
|
2020-05-17 03:18:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FilesystemWatcher {
|
2022-07-12 15:44:09 +00:00
|
|
|
/// Watch for changes recursively at the provided path.
|
2023-03-02 02:51:06 +00:00
|
|
|
pub fn watch<P: AsRef<Path>>(&mut self, to_watch: P, to_reload: PathBuf) -> Result<()> {
|
|
|
|
self.path_map
|
|
|
|
.entry(to_watch.as_ref().to_owned())
|
|
|
|
.or_default()
|
|
|
|
.insert(to_reload);
|
|
|
|
self.watcher
|
|
|
|
.watch(to_watch.as_ref(), RecursiveMode::Recursive)
|
2020-05-17 03:18:30 +00:00
|
|
|
}
|
|
|
|
}
|