2021-01-11 12:13:41 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-09-21 08:26:41 -04:00
|
|
|
|
2020-09-11 12:19:49 -04:00
|
|
|
use crate::colors;
|
2021-11-01 16:22:08 -04:00
|
|
|
use crate::fs_util::canonicalize_path;
|
|
|
|
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2021-01-13 00:48:55 -05:00
|
|
|
use deno_core::futures::Future;
|
2021-03-26 12:34:25 -04:00
|
|
|
use log::info;
|
2020-09-11 12:19:49 -04:00
|
|
|
use notify::event::Event as NotifyEvent;
|
|
|
|
use notify::event::EventKind;
|
|
|
|
use notify::Config;
|
|
|
|
use notify::Error as NotifyError;
|
|
|
|
use notify::RecommendedWatcher;
|
|
|
|
use notify::RecursiveMode;
|
|
|
|
use notify::Watcher;
|
2021-05-10 02:06:13 -04:00
|
|
|
use std::collections::HashSet;
|
2020-09-11 12:19:49 -04:00
|
|
|
use std::path::PathBuf;
|
2020-10-28 07:41:18 -04:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::time::Duration;
|
2020-09-11 12:19:49 -04:00
|
|
|
use tokio::select;
|
2021-12-09 20:24:37 -05:00
|
|
|
use tokio::sync::mpsc;
|
2021-01-12 02:50:02 -05:00
|
|
|
use tokio::time::sleep;
|
2020-10-28 07:41:18 -04:00
|
|
|
|
2021-12-10 19:12:25 -05:00
|
|
|
const CLEAR_SCREEN: &str = "\x1B[2J\x1B[1;1H";
|
2021-01-13 00:48:55 -05:00
|
|
|
const DEBOUNCE_INTERVAL: Duration = Duration::from_millis(200);
|
2020-09-11 12:19:49 -04:00
|
|
|
|
2021-12-09 20:24:37 -05:00
|
|
|
struct DebouncedReceiver {
|
|
|
|
receiver: mpsc::UnboundedReceiver<Vec<PathBuf>>,
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
|
|
|
|
2021-12-09 20:24:37 -05:00
|
|
|
impl DebouncedReceiver {
|
|
|
|
fn new_with_sender() -> (Arc<mpsc::UnboundedSender<Vec<PathBuf>>>, Self) {
|
|
|
|
let (sender, receiver) = mpsc::unbounded_channel();
|
|
|
|
(Arc::new(sender), Self { receiver })
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
|
|
|
|
2021-12-09 20:24:37 -05:00
|
|
|
async fn recv(&mut self) -> Option<Vec<PathBuf>> {
|
|
|
|
let mut received_items = self
|
|
|
|
.receiver
|
|
|
|
.recv()
|
|
|
|
.await?
|
|
|
|
.into_iter()
|
|
|
|
.collect::<HashSet<_>>(); // prevent duplicates
|
|
|
|
loop {
|
|
|
|
tokio::select! {
|
|
|
|
items = self.receiver.recv() => {
|
|
|
|
received_items.extend(items?);
|
|
|
|
}
|
|
|
|
_ = sleep(DEBOUNCE_INTERVAL) => {
|
|
|
|
return Some(received_items.into_iter().collect());
|
|
|
|
}
|
2021-05-10 02:06:13 -04:00
|
|
|
}
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
async fn error_handler<F>(watch_future: F)
|
|
|
|
where
|
|
|
|
F: Future<Output = Result<(), AnyError>>,
|
|
|
|
{
|
2020-09-11 12:19:49 -04:00
|
|
|
let result = watch_future.await;
|
|
|
|
if let Err(err) = result {
|
|
|
|
let msg = format!("{}: {}", colors::red_bold("error"), err.to_string(),);
|
|
|
|
eprintln!("{}", msg);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
pub enum ResolutionResult<T> {
|
|
|
|
Restart {
|
|
|
|
paths_to_watch: Vec<PathBuf>,
|
|
|
|
result: Result<T, AnyError>,
|
|
|
|
},
|
|
|
|
Ignore,
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn next_restart<R, T, F>(
|
|
|
|
resolver: &mut R,
|
2021-12-09 20:24:37 -05:00
|
|
|
debounced_receiver: &mut DebouncedReceiver,
|
2021-05-10 02:06:13 -04:00
|
|
|
) -> (Vec<PathBuf>, Result<T, AnyError>)
|
2020-09-11 12:19:49 -04:00
|
|
|
where
|
2021-05-10 02:06:13 -04:00
|
|
|
R: FnMut(Option<Vec<PathBuf>>) -> F,
|
|
|
|
F: Future<Output = ResolutionResult<T>>,
|
2020-09-11 12:19:49 -04:00
|
|
|
{
|
|
|
|
loop {
|
2021-12-09 20:24:37 -05:00
|
|
|
let changed = debounced_receiver.recv().await;
|
2021-05-10 02:06:13 -04:00
|
|
|
match resolver(changed).await {
|
|
|
|
ResolutionResult::Ignore => {
|
|
|
|
log::debug!("File change ignored")
|
|
|
|
}
|
|
|
|
ResolutionResult::Restart {
|
|
|
|
paths_to_watch,
|
|
|
|
result,
|
|
|
|
} => {
|
2021-12-10 19:12:25 -05:00
|
|
|
// Clear screen first
|
|
|
|
eprint!("{}", CLEAR_SCREEN);
|
2020-10-28 07:41:18 -04:00
|
|
|
info!(
|
|
|
|
"{} File change detected! Restarting!",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
);
|
2021-05-10 02:06:13 -04:00
|
|
|
return (paths_to_watch, result);
|
|
|
|
}
|
2020-11-22 15:45:44 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
/// Creates a file watcher, which will call `resolver` with every file change.
|
2020-11-22 15:45:44 -05:00
|
|
|
///
|
2021-05-10 02:06:13 -04:00
|
|
|
/// - `resolver` is used for resolving file paths to be watched at every restarting
|
|
|
|
/// of the watcher, and can also return a value to be passed to `operation`.
|
|
|
|
/// It returns a [`ResolutionResult`], which can either instruct the watcher to restart or ignore the change.
|
|
|
|
/// This always contains paths to watch;
|
2020-11-22 15:45:44 -05:00
|
|
|
///
|
|
|
|
/// - `operation` is the actual operation we want to run every time the watcher detects file
|
|
|
|
/// changes. For example, in the case where we would like to bundle, then `operation` would
|
2021-05-10 02:06:13 -04:00
|
|
|
/// have the logic for it like bundling the code.
|
2020-11-22 15:45:44 -05:00
|
|
|
///
|
|
|
|
/// - `job_name` is just used for printing watcher status to terminal.
|
2021-05-10 02:06:13 -04:00
|
|
|
pub async fn watch_func<R, O, T, F1, F2>(
|
|
|
|
mut resolver: R,
|
|
|
|
mut operation: O,
|
2020-11-22 15:45:44 -05:00
|
|
|
job_name: &str,
|
|
|
|
) -> Result<(), AnyError>
|
|
|
|
where
|
2021-05-10 02:06:13 -04:00
|
|
|
R: FnMut(Option<Vec<PathBuf>>) -> F1,
|
|
|
|
O: FnMut(T) -> F2,
|
|
|
|
F1: Future<Output = ResolutionResult<T>>,
|
|
|
|
F2: Future<Output = Result<(), AnyError>>,
|
2020-11-22 15:45:44 -05:00
|
|
|
{
|
2021-12-09 20:24:37 -05:00
|
|
|
let (sender, mut receiver) = DebouncedReceiver::new_with_sender();
|
2021-01-13 00:48:55 -05:00
|
|
|
|
2020-11-22 15:45:44 -05:00
|
|
|
// Store previous data. If module resolution fails at some point, the watcher will try to
|
|
|
|
// continue watching files using these data.
|
2021-05-10 02:06:13 -04:00
|
|
|
let mut paths_to_watch;
|
|
|
|
let mut resolution_result;
|
|
|
|
|
|
|
|
match resolver(None).await {
|
|
|
|
ResolutionResult::Ignore => {
|
|
|
|
// The only situation where it makes sense to ignore the initial 'change'
|
|
|
|
// is if the command isn't supposed to do anything until something changes,
|
|
|
|
// e.g. a variant of `deno test` which doesn't run the entire test suite to start with,
|
|
|
|
// but instead does nothing until you make a change.
|
|
|
|
//
|
|
|
|
// In that case, this is probably the correct output.
|
|
|
|
info!(
|
|
|
|
"{} Waiting for file changes...",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
);
|
2021-01-12 02:53:58 -05:00
|
|
|
|
2021-12-09 20:24:37 -05:00
|
|
|
let (paths, result) = next_restart(&mut resolver, &mut receiver).await;
|
2021-05-10 02:06:13 -04:00
|
|
|
paths_to_watch = paths;
|
|
|
|
resolution_result = result;
|
|
|
|
}
|
|
|
|
ResolutionResult::Restart {
|
|
|
|
paths_to_watch: paths,
|
|
|
|
result,
|
|
|
|
} => {
|
|
|
|
paths_to_watch = paths;
|
|
|
|
resolution_result = result;
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
2021-05-10 02:06:13 -04:00
|
|
|
};
|
2020-11-22 15:45:44 -05:00
|
|
|
|
2021-12-10 19:12:25 -05:00
|
|
|
// Clear screen first
|
|
|
|
eprint!("{}", CLEAR_SCREEN);
|
|
|
|
info!("{} {} started.", colors::intense_blue("Watcher"), job_name,);
|
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
loop {
|
2021-12-09 20:24:37 -05:00
|
|
|
let watcher = new_watcher(&paths_to_watch, sender.clone())?;
|
2021-05-10 02:06:13 -04:00
|
|
|
|
|
|
|
match resolution_result {
|
|
|
|
Ok(operation_arg) => {
|
|
|
|
let fut = error_handler(operation(operation_arg));
|
|
|
|
select! {
|
2021-12-09 20:24:37 -05:00
|
|
|
(paths, result) = next_restart(&mut resolver, &mut receiver) => {
|
2021-05-10 02:06:13 -04:00
|
|
|
if result.is_ok() {
|
|
|
|
paths_to_watch = paths;
|
|
|
|
}
|
|
|
|
resolution_result = result;
|
|
|
|
continue;
|
|
|
|
},
|
|
|
|
_ = fut => {},
|
|
|
|
};
|
2020-11-28 09:18:13 -05:00
|
|
|
|
|
|
|
info!(
|
2021-05-10 02:06:13 -04:00
|
|
|
"{} {} finished. Restarting on file change...",
|
2020-11-28 09:18:13 -05:00
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
job_name,
|
|
|
|
);
|
2021-05-10 02:06:13 -04:00
|
|
|
}
|
|
|
|
Err(error) => {
|
|
|
|
eprintln!("{}: {}", colors::red_bold("error"), error);
|
2020-11-22 15:45:44 -05:00
|
|
|
info!(
|
2021-05-10 02:06:13 -04:00
|
|
|
"{} {} failed. Restarting on file change...",
|
2020-11-22 15:45:44 -05:00
|
|
|
colors::intense_blue("Watcher"),
|
2021-05-10 02:06:13 -04:00
|
|
|
job_name,
|
2020-11-22 15:45:44 -05:00
|
|
|
);
|
2020-11-28 09:18:13 -05:00
|
|
|
}
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|
2021-05-10 02:06:13 -04:00
|
|
|
|
2021-12-09 20:24:37 -05:00
|
|
|
let (paths, result) = next_restart(&mut resolver, &mut receiver).await;
|
2021-05-10 02:06:13 -04:00
|
|
|
if result.is_ok() {
|
|
|
|
paths_to_watch = paths;
|
|
|
|
}
|
|
|
|
resolution_result = result;
|
|
|
|
|
|
|
|
drop(watcher);
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-28 07:41:18 -04:00
|
|
|
fn new_watcher(
|
|
|
|
paths: &[PathBuf],
|
2021-12-09 20:24:37 -05:00
|
|
|
sender: Arc<mpsc::UnboundedSender<Vec<PathBuf>>>,
|
2020-10-28 07:41:18 -04:00
|
|
|
) -> Result<RecommendedWatcher, AnyError> {
|
2020-12-13 13:45:53 -05:00
|
|
|
let mut watcher: RecommendedWatcher =
|
2021-09-02 17:38:44 -04:00
|
|
|
Watcher::new(move |res: Result<NotifyEvent, NotifyError>| {
|
2020-10-28 07:41:18 -04:00
|
|
|
if let Ok(event) = res {
|
2020-12-13 13:45:53 -05:00
|
|
|
if matches!(
|
|
|
|
event.kind,
|
|
|
|
EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
|
|
|
|
) {
|
2021-05-10 02:06:13 -04:00
|
|
|
let paths = event
|
|
|
|
.paths
|
|
|
|
.iter()
|
2021-12-09 20:24:37 -05:00
|
|
|
.filter_map(|path| canonicalize_path(path).ok())
|
|
|
|
.collect();
|
|
|
|
sender.send(paths).unwrap();
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
|
|
|
}
|
2020-12-13 13:45:53 -05:00
|
|
|
})?;
|
2020-09-11 12:19:49 -04:00
|
|
|
|
|
|
|
watcher.configure(Config::PreciseEvents(true)).unwrap();
|
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
log::debug!("Watching paths: {:?}", paths);
|
2020-09-11 12:19:49 -04:00
|
|
|
for path in paths {
|
2020-11-22 15:45:44 -05:00
|
|
|
// Ignore any error e.g. `PathNotFound`
|
2021-05-10 02:06:13 -04:00
|
|
|
let _ = watcher.watch(path, RecursiveMode::Recursive);
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|
|
|
|
|
2020-10-28 07:41:18 -04:00
|
|
|
Ok(watcher)
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|