use std::path::{Path, PathBuf};
use std::time::Duration;
use notify::Watcher as _;
use crate::config::Config;
const DEBOUNCE: Duration = Duration::from_millis(150);
const STOP_POLL: Duration = Duration::from_millis(500);
pub(crate) struct WatchGuard {
_stop: std::sync::mpsc::Sender<()>,
}
struct InputFilter {
templates: Vec<PathBuf>,
}
impl InputFilter {
fn new(cfg: &Config) -> Self {
let mut templates = Vec::new();
if let Some(dir) = &cfg.templating.dir {
templates.push(dir.clone());
if let Ok(canonical) = dir.canonicalize()
&& !templates.contains(&canonical)
{
templates.push(canonical);
}
}
Self { templates }
}
fn is_input(&self, path: &Path) -> bool {
path.extension().is_some_and(|ext| ext == "lua")
|| self.templates.iter().any(|root| path.starts_with(root))
}
}
fn relevant(event: ¬ify::Event, filter: &InputFilter) -> bool {
use notify::EventKind;
let content_change = matches!(
event.kind,
EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
);
content_change && event.paths.iter().any(|path| filter.is_input(path))
}
fn watch_roots(cfg: &Config, extra: &[PathBuf]) -> Vec<PathBuf> {
let mut roots = Vec::new();
let mut push = |path: Option<&Path>| {
let path = match path {
Some(p) if p.as_os_str().is_empty() => Some(Path::new(".")),
other => other,
};
if let Some(path) = path
&& path.exists()
&& !roots.iter().any(|r| path.starts_with(r))
{
roots.push(path.to_path_buf());
}
};
push(cfg.handler_script.parent());
push(cfg.config_script.as_deref().and_then(Path::parent));
push(cfg.templating.dir.as_deref());
for dir in extra {
push(Some(dir.as_path()));
}
roots
}
pub(crate) fn spawn(
cfg: &Config,
extra: &[PathBuf],
reload: tokio::sync::mpsc::Sender<()>,
) -> Option<WatchGuard> {
let roots = watch_roots(cfg, extra);
if roots.is_empty() {
return None;
}
let filter = InputFilter::new(cfg);
let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
std::thread::spawn(move || {
let (tx, rx) = std::sync::mpsc::channel::<()>();
let mut watcher =
match notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
if let Ok(event) = res
&& relevant(&event, &filter)
{
let _ = tx.send(());
}
}) {
Ok(watcher) => watcher,
Err(err) => {
tracing::warn!(
"dev-mode file watcher unavailable ({err}); reload via SIGHUP instead"
);
return;
}
};
for root in &roots {
if let Err(err) = watcher.watch(root, notify::RecursiveMode::Recursive) {
tracing::warn!("cannot watch {} for changes: {err}", root.display());
}
}
tracing::debug!(
"watching {} for changes",
roots
.iter()
.map(|r| r.display().to_string())
.collect::<Vec<_>>()
.join(", ")
);
loop {
match rx.recv_timeout(STOP_POLL) {
Ok(()) => {
while rx.recv_timeout(DEBOUNCE).is_ok() {}
let _ = reload.try_send(());
}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return,
}
match stop_rx.try_recv() {
Err(std::sync::mpsc::TryRecvError::Empty) => {}
_ => return,
}
}
});
Some(WatchGuard { _stop: stop_tx })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::TemplatingConfig;
#[test]
fn roots_deduplicate_and_skip_missing_paths() {
let dir = std::env::temp_dir().join(format!("nitr-watch-{}", std::process::id()));
std::fs::create_dir_all(dir.join("templates")).expect("mkdir");
std::fs::write(dir.join("app.lua"), "-- app").expect("write");
std::fs::write(dir.join("config.lua"), "-- config").expect("write");
let mut cfg = Config {
handler_script: dir.join("app.lua"),
config_script: Some(dir.join("config.lua")),
templating: TemplatingConfig {
dir: Some(dir.join("templates")),
},
..Config::default()
};
let roots = watch_roots(&cfg, &[]);
assert_eq!(roots, vec![dir.clone()]);
cfg.templating.dir = Some(PathBuf::from("/nonexistent/templates"));
let roots = watch_roots(&cfg, &[]);
assert_eq!(roots, vec![dir.clone()]);
std::fs::remove_dir_all(&dir).ok();
}
fn filter_with_templates(dir: Option<&Path>) -> InputFilter {
let cfg = Config {
templating: TemplatingConfig {
dir: dir.map(Path::to_path_buf),
},
..Config::default()
};
InputFilter::new(&cfg)
}
#[test]
fn only_content_events_on_inputs_are_relevant() {
use notify::{Event, EventKind};
let filter = filter_with_templates(None);
let modify = EventKind::Modify(notify::event::ModifyKind::Any);
let content = Event::new(modify).add_path(PathBuf::from("scripts/handler.lua"));
assert!(relevant(&content, &filter));
let noise = Event::new(modify).add_path(PathBuf::from("scripts/file.db"));
assert!(!relevant(&noise, &filter));
let access = Event::new(EventKind::Access(notify::event::AccessKind::Any))
.add_path(PathBuf::from("scripts/handler.lua"));
assert!(!relevant(&access, &filter));
}
#[test]
fn rebuild_side_effects_and_editor_noise_are_not_inputs() {
let filter = filter_with_templates(Some(Path::new("scripts/templates")));
for input in [
"scripts/handler.lua",
"scripts/config.lua",
"scripts/routes/notes.lua",
"scripts/templates/response.j2",
"scripts/templates/partials/header.html",
] {
assert!(filter.is_input(Path::new(input)), "must reload: {input}");
}
for noise in [
"scripts/file.db",
"scripts/file.db-wal",
"scripts/file.db-shm",
"scripts/.handler.lua.swp",
"scripts/handler.lua~",
"scripts/4913", "scripts/server.log",
] {
assert!(!filter.is_input(Path::new(noise)), "must ignore: {noise}");
}
}
#[test]
fn canonical_template_paths_are_recognized() {
let dir = std::env::temp_dir().join(format!("nitr-watch-canon-{}", std::process::id()));
std::fs::create_dir_all(dir.join("templates")).expect("mkdir");
let filter = filter_with_templates(Some(&dir.join("templates")));
let canonical = dir
.join("templates")
.canonicalize()
.expect("canonicalize")
.join("page.html");
assert!(filter.is_input(&canonical));
std::fs::remove_dir_all(&dir).ok();
}
}