use anyhow::{Context, Result};
use std::{
collections::{hash_map::DefaultHasher, BTreeMap},
fs,
hash::{Hash, Hasher},
io,
path::{Path, PathBuf},
time::Duration,
};
use tokio::{sync::mpsc, time::Instant};
const POLL_INTERVAL: Duration = Duration::from_millis(250);
const DEBOUNCE: Duration = Duration::from_millis(300);
type Snapshot = BTreeMap<PathBuf, u64>;
pub struct SourceWatcher {
root: PathBuf,
files: Snapshot,
}
impl SourceWatcher {
pub async fn new(root: PathBuf) -> Result<Self> {
let files = snapshot(root.clone()).await?;
Ok(Self { root, files })
}
pub async fn run(mut self, changes: mpsc::Sender<()>) -> Result<()> {
let mut tick = tokio::time::interval(POLL_INTERVAL);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut pending = None;
loop {
tick.tick().await;
let files = match snapshot(self.root.clone()).await {
Ok(files) => files,
Err(error)
if error
.downcast_ref::<io::Error>()
.is_some_and(|error| error.kind() == io::ErrorKind::NotFound) =>
{
continue;
}
Err(error) => return Err(error),
};
if files != self.files {
self.files = files;
pending = Some(Instant::now());
}
if pending.is_some_and(|since| since.elapsed() >= DEBOUNCE) {
if changes.send(()).await.is_err() {
return Ok(());
}
pending = None;
}
}
}
}
async fn snapshot(root: PathBuf) -> Result<Snapshot> {
tokio::task::spawn_blocking(move || {
let mut files = Snapshot::new();
scan(&root, &mut files).context("Could not watch backend source files")?;
Ok(files)
})
.await?
}
fn scan(directory: &Path, files: &mut Snapshot) -> io::Result<()> {
for entry in fs::read_dir(directory)? {
let entry = entry?;
let path = entry.path();
let kind = entry.file_type()?;
if kind.is_dir() {
let name = entry.file_name();
let name = name.to_string_lossy();
if !name.starts_with('.')
&& !matches!(
name.as_ref(),
"target" | "frontend" | "node_modules" | "generated"
)
{
scan(&path, files)?;
}
} else if (kind.is_file() || (kind.is_symlink() && path.is_file()))
&& (path.extension().is_some_and(|extension| extension == "rs")
|| entry.file_name() == "Cargo.toml"
|| (entry.file_name() == "api.toml"
&& directory.file_name().is_some_and(|name| name == "config")))
{
let mut hash = DefaultHasher::new();
fs::read(&path)?.hash(&mut hash);
files.insert(path, hash.finish());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn snapshots_track_new_edited_renamed_and_deleted_sources() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().to_path_buf();
let initial = snapshot(root.clone()).await.unwrap();
fs::create_dir_all(root.join("app/controllers")).unwrap();
let source = root.join("app/controllers/post.rs");
fs::write(&source, "first").unwrap();
let added = snapshot(root.clone()).await.unwrap();
assert_ne!(initial, added);
fs::write(&source, "other").unwrap();
let edited = snapshot(root.clone()).await.unwrap();
assert_ne!(added, edited);
fs::rename(&source, root.join("app/controllers/new.rs")).unwrap();
let renamed = snapshot(root.clone()).await.unwrap();
assert_ne!(edited, renamed);
fs::remove_dir_all(root.join("app")).unwrap();
assert_eq!(initial, snapshot(root).await.unwrap());
}
#[tokio::test]
async fn snapshots_ignore_runtime_build_and_frontend_files() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().to_path_buf();
for directory in ["target", ".git", "frontend", "node_modules", "generated"] {
fs::create_dir_all(root.join(directory)).unwrap();
fs::write(root.join(directory).join("generated.rs"), "ignored").unwrap();
}
for file in [
"database.sqlite",
"output.log",
"Cargo.lock",
".capy-generator.lock",
] {
fs::write(root.join(file), "ignored").unwrap();
}
assert!(snapshot(root.clone()).await.unwrap().is_empty());
fs::write(root.join("Cargo.toml"), "manifest").unwrap();
fs::write(root.join("build.rs"), "build script").unwrap();
fs::create_dir_all(root.join("config")).unwrap();
fs::write(root.join("config/api.toml"), "title = \"Updated\"").unwrap();
assert_eq!(snapshot(root).await.unwrap().len(), 3);
}
}