use crate::compiler::diagnostic::Message;
use crate::compiler::include::{Files, Include, Included};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};
pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);
type Stamp = Option<(SystemTime, u64)>;
fn stamp(path: &Path) -> Stamp {
let meta = std::fs::metadata(path).ok()?;
Some((meta.modified().ok()?, meta.len()))
}
#[derive(Debug)]
pub struct Watcher {
entries: Vec<(PathBuf, Stamp)>,
interval: Duration,
last: Instant,
}
impl Watcher {
pub fn new(paths: impl IntoIterator<Item = PathBuf>, interval: Duration) -> Self {
let entries = paths
.into_iter()
.map(|p| {
let s = stamp(&p);
(p, s)
})
.collect();
Watcher {
entries,
interval,
last: Instant::now(),
}
}
pub fn set_paths(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
*self = Watcher::new(paths, self.interval);
}
pub fn poll(&mut self) -> bool {
if self.last.elapsed() < self.interval {
return false;
}
self.check()
}
pub fn check(&mut self) -> bool {
self.last = Instant::now();
let mut changed = false;
for (path, old) in &mut self.entries {
let now = stamp(path);
if now != *old {
*old = now;
changed = true;
}
}
changed
}
pub fn paths(&self) -> impl Iterator<Item = &Path> {
self.entries.iter().map(|(p, _)| p.as_path())
}
}
#[derive(Debug)]
pub struct WatchedFiles {
files: Files,
seen: Mutex<Vec<PathBuf>>,
}
impl WatchedFiles {
pub fn beside(file: impl AsRef<Path>) -> Self {
WatchedFiles {
files: Files::beside(file),
seen: Mutex::new(Vec::new()),
}
}
fn remember(&self, path: PathBuf) {
if let Ok(mut seen) = self.seen.lock() {
if !seen.contains(&path) {
seen.push(path);
}
}
}
pub fn paths(&self) -> Vec<PathBuf> {
self.seen.lock().map(|s| s.clone()).unwrap_or_default()
}
}
impl Include for WatchedFiles {
fn load(&self, path: &str, from: Option<&str>) -> Result<Included, Message> {
let inc = self.files.load(path, from)?;
self.remember(PathBuf::from(&inc.name));
Ok(inc)
}
fn load_bytes(&self, path: &str) -> Result<Arc<[u8]>, Message> {
let bytes = self.files.load_bytes(path)?;
let full = self.files.base().join(path);
self.remember(std::fs::canonicalize(&full).unwrap_or(full));
Ok(bytes)
}
}
pub fn resume_tick(position: u64, new_length_ticks: u64) -> u64 {
if position < new_length_ticks {
position
} else {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("pikopiko-watch-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn unchanged_files_are_quiet() {
let dir = temp("quiet");
let f = dir.join("a.mml");
std::fs::write(&f, "A c").unwrap();
let mut w = Watcher::new([f], Duration::ZERO);
assert!(!w.check());
assert!(!w.poll());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_rewrite_is_reported_once() {
let dir = temp("rewrite");
let f = dir.join("a.mml");
std::fs::write(&f, "A c").unwrap();
let mut w = Watcher::new([f.clone()], Duration::ZERO);
std::fs::write(&f, "A c d e").unwrap();
assert!(w.check());
assert!(!w.check());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_removed_or_new_file_counts_as_a_change() {
let dir = temp("gone");
let f = dir.join("a.mml");
let mut w = Watcher::new([f.clone()], Duration::ZERO);
assert!(!w.check());
std::fs::write(&f, "A c").unwrap();
assert!(w.check());
std::fs::remove_file(&f).unwrap();
assert!(w.check());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn poll_waits_for_the_interval() {
let dir = temp("interval");
let f = dir.join("a.mml");
std::fs::write(&f, "A c").unwrap();
let mut w = Watcher::new([f.clone()], Duration::from_secs(3600));
std::fs::write(&f, "A c d e").unwrap();
assert!(!w.poll(), "間隔の途中では見比べない");
assert!(w.check(), "check は待たない");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn watched_files_remember_what_the_song_read() {
let dir = temp("recorded");
std::fs::write(dir.join("riff.mml"), "$riff = c d e").unwrap();
let main = dir.join("main.mml");
std::fs::write(&main, "#include \"riff.mml\"\nA $riff").unwrap();
let files = WatchedFiles::beside(&main);
let opts = crate::CompileOptions {
include: Some(&files),
..Default::default()
};
let (song, diags) = crate::compile_with("#include \"riff.mml\"\nA $riff", &opts);
assert!(song.is_some(), "{diags:?}");
let paths = files.paths();
assert_eq!(paths.len(), 1);
assert!(paths[0].ends_with("riff.mml"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn resume_keeps_the_position_or_returns_to_the_start() {
assert_eq!(resume_tick(100, 1000), 100);
assert_eq!(resume_tick(1000, 1000), 0);
assert_eq!(resume_tick(5000, 1000), 0);
assert_eq!(resume_tick(10, 0), 0);
}
}