| 1 |
//! A simple poll-based filesystem watcher. |
| 2 |
//! |
| 3 |
//! This exists because the native change notifications have historically had |
| 4 |
//! lots of problems. Various operating systems and different filesystems have |
| 5 |
//! had problems correctly reporting changes. |
| 6 |
|
| 7 |
use ignore::gitignore::Gitignore; |
| 8 |
use mdbook_driver::MDBook; |
| 9 |
use pathdiff::diff_paths; |
| 10 |
use std::collections::HashMap; |
| 11 |
use std::fs::FileType; |
| 12 |
use std::path::{Path, PathBuf}; |
| 13 |
use std::time::{Duration, Instant, SystemTime}; |
| 14 |
use tracing::{debug, error, info, trace, warn}; |
| 15 |
use walkdir::WalkDir; |
| 16 |
|
| 17 |
/// Calls the closure when a book source file is changed, blocking indefinitely. |
| 18 |
pub fn rebuild_on_change( |
| 19 |
book_dir: &Path, |
| 20 |
update_config: &dyn Fn(&mut MDBook), |
| 21 |
post_build: &dyn Fn(), |
| 22 |
) { |
| 23 |
let mut book = MDBook::load(book_dir).unwrap_or_else(|e| { |
| 24 |
error!("failed to load book: {e}"); |
| 25 |
std::process::exit(1); |
| 26 |
}); |
| 27 |
|
| 28 |
let mut watcher = Watcher::new(book_dir); |
| 29 |
|
| 30 |
info!("Watching for changes..."); |
| 31 |
// Scan once to initialize the starting point. |
| 32 |
watcher.set_roots(&book); |
| 33 |
watcher.scan(); |
| 34 |
|
| 35 |
// Track average scan time, to help investigate if the poller is taking |
| 36 |
// undesirably long. This is not a rigorous benchmark, just a rough |
| 37 |
// estimate. |
| 38 |
const AVG_SIZE: usize = 60; |
| 39 |
let mut avgs = vec![0.0; AVG_SIZE]; |
| 40 |
let mut avg_i = 0; |
| 41 |
|
| 42 |
loop { |
| 43 |
std::thread::sleep(Duration::new(1, 0)); |
| 44 |
let start = Instant::now(); |
| 45 |
let paths = watcher.scan(); |
| 46 |
let elapsed = start.elapsed().as_secs_f64(); |
| 47 |
avgs[avg_i] = elapsed; |
| 48 |
avg_i += 1; |
| 49 |
if avg_i >= AVG_SIZE { |
| 50 |
avg_i = 0; |
| 51 |
let avg = avgs.iter().sum::<f64>() / (avgs.len() as f64); |
| 52 |
trace!( |
| 53 |
"scan average time: {avg:.2}s, scan size is {}", |
| 54 |
watcher.path_data.len() |
| 55 |
); |
| 56 |
} |
| 57 |
|
| 58 |
if !paths.is_empty() { |
| 59 |
info!("Files changed: {paths:?}"); |
| 60 |
match MDBook::load(book_dir) { |
| 61 |
Ok(mut b) => { |
| 62 |
update_config(&mut b); |
| 63 |
if let Err(e) = b.build() { |
| 64 |
error!("failed to build the book: {e:?}"); |
| 65 |
} else { |
| 66 |
post_build(); |
| 67 |
} |
| 68 |
book = b; |
| 69 |
watcher.set_roots(&book); |
| 70 |
} |
| 71 |
Err(e) => error!("failed to load book config: {e:?}"), |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
#[derive(PartialEq)] |
| 78 |
struct PathData { |
| 79 |
file_type: FileType, |
| 80 |
mtime: SystemTime, |
| 81 |
size: u64, |
| 82 |
} |
| 83 |
|
| 84 |
/// A very simple poll-watcher that scans for modified files. |
| 85 |
#[derive(Default)] |
| 86 |
struct Watcher { |
| 87 |
/// The root paths where it will recursively scan for changes. |
| 88 |
root_paths: Vec<PathBuf>, |
| 89 |
/// Data about files on disk. |
| 90 |
path_data: HashMap<PathBuf, PathData>, |
| 91 |
/// Filters paths that will be watched. |
| 92 |
ignore: Option<(PathBuf, Gitignore)>, |
| 93 |
} |
| 94 |
|
| 95 |
impl Watcher { |
| 96 |
fn new(book_root: &Path) -> Watcher { |
| 97 |
// FIXME: ignore should be reloaded when it changes. |
| 98 |
let ignore = super::find_gitignore(book_root).map(|gitignore_path| { |
| 99 |
let (ignore, err) = Gitignore::new(&gitignore_path); |
| 100 |
if let Some(err) = err { |
| 101 |
warn!( |
| 102 |
"error reading gitignore `{}`: {err}", |
| 103 |
gitignore_path.display() |
| 104 |
); |
| 105 |
} |
| 106 |
// Note: The usage of `canonicalize` may encounter occasional |
| 107 |
// failures on the Windows platform, presenting a potential risk. |
| 108 |
// For more details, refer to [Pull Request |
| 109 |
// #2229](https://github.com/rust-lang/mdBook/pull/2229#discussion_r1408665981). |
| 110 |
let ignore_path = ignore |
| 111 |
.path() |
| 112 |
.canonicalize() |
| 113 |
.expect("ignore root canonicalize error"); |
| 114 |
(ignore_path, ignore) |
| 115 |
}); |
| 116 |
|
| 117 |
Watcher { |
| 118 |
ignore, |
| 119 |
..Default::default() |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
/// Sets the root directories where scanning will start. |
| 124 |
fn set_roots(&mut self, book: &MDBook) { |
| 125 |
let mut root_paths = vec![ |
| 126 |
book.source_dir(), |
| 127 |
book.theme_dir(), |
| 128 |
book.root.join("book.toml"), |
| 129 |
]; |
| 130 |
root_paths.extend( |
| 131 |
book.config |
| 132 |
.build |
| 133 |
.extra_watch_dirs |
| 134 |
.iter() |
| 135 |
.map(|path| book.root.join(path)), |
| 136 |
); |
| 137 |
if let Some(html_config) = book.config.html_config() { |
| 138 |
root_paths.extend( |
| 139 |
html_config |
| 140 |
.additional_css |
| 141 |
.iter() |
| 142 |
.chain(html_config.additional_js.iter()) |
| 143 |
.map(|path| book.root.join(path)), |
| 144 |
); |
| 145 |
} |
| 146 |
|
| 147 |
self.root_paths = root_paths; |
| 148 |
} |
| 149 |
|
| 150 |
/// Scans for changes. |
| 151 |
/// |
| 152 |
/// Returns the paths that have changed. |
| 153 |
fn scan(&mut self) -> Vec<PathBuf> { |
| 154 |
let ignore = &self.ignore; |
| 155 |
let new_path_data: HashMap<_, _> = self |
| 156 |
.root_paths |
| 157 |
.iter() |
| 158 |
.filter(|root| root.exists()) |
| 159 |
.flat_map(|root| { |
| 160 |
WalkDir::new(root) |
| 161 |
.follow_links(true) |
| 162 |
.into_iter() |
| 163 |
.filter_entry(|entry| { |
| 164 |
if let Some((ignore_path, ignore)) = ignore { |
| 165 |
let path = entry.path(); |
| 166 |
// Canonicalization helps with removing `..` and |
| 167 |
// `.` entries, which can cause issues with |
| 168 |
// diff_paths. |
| 169 |
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); |
| 170 |
let relative_path = diff_paths(&path, &ignore_path) |
| 171 |
.expect("One of the paths should be an absolute"); |
| 172 |
if ignore |
| 173 |
.matched_path_or_any_parents(&relative_path, relative_path.is_dir()) |
| 174 |
.is_ignore() |
| 175 |
{ |
| 176 |
trace!("ignoring {path:?}"); |
| 177 |
return false; |
| 178 |
} |
| 179 |
} |
| 180 |
true |
| 181 |
}) |
| 182 |
.filter_map(move |entry| { |
| 183 |
let entry = match entry { |
| 184 |
Ok(e) => e, |
| 185 |
Err(e) => { |
| 186 |
debug!("failed to scan {root:?}: {e}"); |
| 187 |
return None; |
| 188 |
} |
| 189 |
}; |
| 190 |
if entry.file_type().is_dir() { |
| 191 |
// Changes to directories themselves aren't |
| 192 |
// particularly interesting. |
| 193 |
return None; |
| 194 |
} |
| 195 |
let path = entry.path().to_path_buf(); |
| 196 |
|
| 197 |
let meta = match entry.metadata() { |
| 198 |
Ok(meta) => meta, |
| 199 |
Err(e) => { |
| 200 |
debug!("failed to scan {path:?}: {e}"); |
| 201 |
return None; |
| 202 |
} |
| 203 |
}; |
| 204 |
let mtime = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); |
| 205 |
let pd = PathData { |
| 206 |
file_type: meta.file_type(), |
| 207 |
mtime, |
| 208 |
size: meta.len(), |
| 209 |
}; |
| 210 |
Some((path, pd)) |
| 211 |
}) |
| 212 |
}) |
| 213 |
.collect(); |
| 214 |
let mut paths = Vec::new(); |
| 215 |
for (new_path, new_data) in &new_path_data { |
| 216 |
match self.path_data.get(new_path) { |
| 217 |
Some(old_data) => { |
| 218 |
if new_data != old_data { |
| 219 |
paths.push(new_path.to_path_buf()); |
| 220 |
} |
| 221 |
} |
| 222 |
None => { |
| 223 |
paths.push(new_path.clone()); |
| 224 |
} |
| 225 |
} |
| 226 |
} |
| 227 |
for old_path in self.path_data.keys() { |
| 228 |
if !new_path_data.contains_key(old_path) { |
| 229 |
paths.push(old_path.to_path_buf()); |
| 230 |
} |
| 231 |
} |
| 232 |
self.path_data = new_path_data; |
| 233 |
paths |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
#[cfg(test)] |
| 238 |
mod tests { |
| 239 |
use super::*; |
| 240 |
|
| 241 |
/// Helper for testing the watcher. |
| 242 |
fn check_watch_behavior( |
| 243 |
gitignore_path: &str, |
| 244 |
gitignore: &str, |
| 245 |
book_root_path: &str, |
| 246 |
ignored: &[&str], |
| 247 |
not_ignored: &[&str], |
| 248 |
extra_setup: &dyn Fn(&Path), |
| 249 |
) { |
| 250 |
// Create the book and initialize things. |
| 251 |
let temp = tempfile::Builder::new() |
| 252 |
.prefix("mdbook-") |
| 253 |
.tempdir() |
| 254 |
.unwrap(); |
| 255 |
let root = temp.path(); |
| 256 |
let book_root = root.join(book_root_path); |
| 257 |
// eprintln!("book_root={book_root:?}",); |
| 258 |
MDBook::init(&book_root).build().unwrap(); |
| 259 |
std::fs::write(root.join(gitignore_path), gitignore).unwrap(); |
| 260 |
let create = |paths: &[&str]| { |
| 261 |
let mut paths = paths |
| 262 |
.iter() |
| 263 |
.map(|path| root.join(path)) |
| 264 |
.inspect(|path| { |
| 265 |
std::fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 266 |
std::fs::write(path, "initial content").unwrap(); |
| 267 |
}) |
| 268 |
.map(|path| path.canonicalize().unwrap()) |
| 269 |
.collect::<Vec<_>>(); |
| 270 |
paths.sort(); |
| 271 |
paths |
| 272 |
}; |
| 273 |
let ignored = create(ignored); |
| 274 |
let not_ignored = create(not_ignored); |
| 275 |
extra_setup(&book_root); |
| 276 |
// Create a watcher and check its behavior. |
| 277 |
let book = MDBook::load(&book_root).unwrap(); |
| 278 |
let mut watcher = Watcher::new(&book_root); |
| 279 |
watcher.set_roots(&book); |
| 280 |
// Do an initial scan to initialize its state. |
| 281 |
watcher.scan(); |
| 282 |
// Verify the steady state is empty. |
| 283 |
let changed = watcher.scan(); |
| 284 |
assert_eq!(changed, Vec::<PathBuf>::new()); |
| 285 |
// Modify all files, and verify that only not_ignored are detected. |
| 286 |
for path in ignored.iter().chain(not_ignored.iter()) { |
| 287 |
std::fs::write(path, "modified").unwrap(); |
| 288 |
} |
| 289 |
let changed = watcher.scan(); |
| 290 |
let mut changed = changed |
| 291 |
.into_iter() |
| 292 |
.map(|p| p.canonicalize().unwrap()) |
| 293 |
.collect::<Vec<_>>(); |
| 294 |
changed.sort(); |
| 295 |
assert_eq!(changed, not_ignored); |
| 296 |
// Verify again that steady state is empty. |
| 297 |
let changed = watcher.scan(); |
| 298 |
assert_eq!(changed, Vec::<PathBuf>::new()); |
| 299 |
} |
| 300 |
|
| 301 |
#[test] |
| 302 |
fn test_ignore() { |
| 303 |
// Basic gitignore test. |
| 304 |
check_watch_behavior( |
| 305 |
"foo/.gitignore", |
| 306 |
"*.tmp", |
| 307 |
"foo", |
| 308 |
&["foo/src/somefile.tmp"], |
| 309 |
&["foo/src/chapter.md"], |
| 310 |
&|_book_root| {}, |
| 311 |
); |
| 312 |
} |
| 313 |
|
| 314 |
#[test] |
| 315 |
fn test_ignore_in_parent() { |
| 316 |
// gitignore is in the parent of the book |
| 317 |
check_watch_behavior( |
| 318 |
".gitignore", |
| 319 |
"*.tmp\nsomedir/\n/inroot\n/foo/src/inbook\n", |
| 320 |
"foo", |
| 321 |
&[ |
| 322 |
"foo/src/somefile.tmp", |
| 323 |
"foo/src/somedir/somefile", |
| 324 |
"inroot/somefile", |
| 325 |
"foo/src/inbook/somefile", |
| 326 |
], |
| 327 |
&["foo/src/inroot/somefile"], |
| 328 |
&|_book_root| {}, |
| 329 |
); |
| 330 |
} |
| 331 |
|
| 332 |
#[test] |
| 333 |
fn test_ignore_canonical() { |
| 334 |
// test with path with .. |
| 335 |
check_watch_behavior( |
| 336 |
".gitignore", |
| 337 |
"*.tmp\nsomedir/\n/foo/src/inbook\n", |
| 338 |
"bar/../foo", |
| 339 |
&[ |
| 340 |
"foo/src/somefile.tmp", |
| 341 |
"foo/src/somedir/somefile", |
| 342 |
"foo/src/inbook/somefile", |
| 343 |
], |
| 344 |
&["foo/src/chapter.md"], |
| 345 |
&|_book_root| {}, |
| 346 |
); |
| 347 |
} |
| 348 |
|
| 349 |
#[test] |
| 350 |
fn test_scan_extra_watch() { |
| 351 |
// Check behavior with extra-watch-dirs |
| 352 |
check_watch_behavior( |
| 353 |
".gitignore", |
| 354 |
"*.tmp\n/outside-root/ignoreme\n/foo/examples/ignoreme\n", |
| 355 |
"foo", |
| 356 |
&[ |
| 357 |
"foo/src/somefile.tmp", |
| 358 |
"foo/examples/example.tmp", |
| 359 |
"outside-root/somefile.tmp", |
| 360 |
"outside-root/ignoreme", |
| 361 |
"foo/examples/ignoreme", |
| 362 |
], |
| 363 |
&[ |
| 364 |
"foo/src/chapter.md", |
| 365 |
"foo/examples/example.rs", |
| 366 |
"foo/examples/example2.rs", |
| 367 |
"outside-root/image.png", |
| 368 |
], |
| 369 |
&|book_root| { |
| 370 |
std::fs::write( |
| 371 |
book_root.join("book.toml"), |
| 372 |
r#" |
| 373 |
[book] |
| 374 |
title = "foo" |
| 375 |
|
| 376 |
[build] |
| 377 |
extra-watch-dirs = [ |
| 378 |
"examples", |
| 379 |
"../outside-root", |
| 380 |
] |
| 381 |
"#, |
| 382 |
) |
| 383 |
.unwrap(); |
| 384 |
}, |
| 385 |
); |
| 386 |
} |
| 387 |
} |