2023-01-02 16:00:42 -05:00
|
|
|
// Copyright 2018-2023 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;
|
2022-11-28 17:28:54 -05:00
|
|
|
use crate::util::fs::canonicalize_path;
|
2021-11-01 16:22:08 -04:00
|
|
|
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2022-07-13 16:01:09 -04:00
|
|
|
use deno_core::error::JsError;
|
2021-01-13 00:48:55 -05:00
|
|
|
use deno_core::futures::Future;
|
2022-09-02 16:53:23 -04:00
|
|
|
use deno_runtime::fmt_errors::format_js_error;
|
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::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;
|
2022-06-08 06:07:25 -04:00
|
|
|
use tokio::sync::mpsc::UnboundedReceiver;
|
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 {
|
2022-04-19 10:12:30 -04:00
|
|
|
// The `recv()` call could be used in a tokio `select!` macro,
|
|
|
|
// and so we store this state on the struct to ensure we don't
|
|
|
|
// lose items if a `recv()` never completes
|
|
|
|
received_items: HashSet<PathBuf>,
|
2022-07-14 17:52:44 -04:00
|
|
|
receiver: 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();
|
2022-04-19 10:12:30 -04:00
|
|
|
(
|
|
|
|
Arc::new(sender),
|
|
|
|
Self {
|
|
|
|
receiver,
|
|
|
|
received_items: HashSet::new(),
|
|
|
|
},
|
|
|
|
)
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
|
|
|
|
2021-12-09 20:24:37 -05:00
|
|
|
async fn recv(&mut self) -> Option<Vec<PathBuf>> {
|
2022-04-19 10:12:30 -04:00
|
|
|
if self.received_items.is_empty() {
|
|
|
|
self
|
|
|
|
.received_items
|
|
|
|
.extend(self.receiver.recv().await?.into_iter());
|
|
|
|
}
|
|
|
|
|
2021-12-09 20:24:37 -05:00
|
|
|
loop {
|
2022-07-14 17:52:44 -04:00
|
|
|
select! {
|
2021-12-09 20:24:37 -05:00
|
|
|
items = self.receiver.recv() => {
|
2022-04-19 10:12:30 -04:00
|
|
|
self.received_items.extend(items?);
|
2021-12-09 20:24:37 -05:00
|
|
|
}
|
|
|
|
_ = sleep(DEBOUNCE_INTERVAL) => {
|
2022-04-19 10:12:30 -04:00
|
|
|
return Some(self.received_items.drain().collect());
|
2021-12-09 20:24:37 -05:00
|
|
|
}
|
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 {
|
2022-07-13 16:01:09 -04:00
|
|
|
let error_string = match err.downcast_ref::<JsError>() {
|
|
|
|
Some(e) => format_js_error(e),
|
2023-01-27 10:43:16 -05:00
|
|
|
None => format!("{err:?}"),
|
2022-07-13 16:01:09 -04:00
|
|
|
};
|
|
|
|
eprintln!(
|
|
|
|
"{}: {}",
|
|
|
|
colors::red_bold("error"),
|
|
|
|
error_string.trim_start_matches("error: ")
|
|
|
|
);
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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 {
|
2023-01-07 15:22:09 -05:00
|
|
|
mut paths_to_watch,
|
2021-05-10 02:06:13 -04:00
|
|
|
result,
|
|
|
|
} => {
|
2023-01-07 15:22:09 -05:00
|
|
|
// watch the current directory when empty
|
|
|
|
if paths_to_watch.is_empty() {
|
|
|
|
paths_to_watch.push(PathBuf::from("."));
|
|
|
|
}
|
2021-05-10 02:06:13 -04:00
|
|
|
return (paths_to_watch, result);
|
|
|
|
}
|
2020-11-22 15:45:44 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-31 11:39:39 -05:00
|
|
|
pub struct PrintConfig {
|
|
|
|
/// printing watcher status to terminal.
|
|
|
|
pub job_name: String,
|
2022-12-19 12:59:32 -05:00
|
|
|
/// determine whether to clear the terminal screen; applicable to TTY environments only.
|
2022-01-31 11:39:39 -05:00
|
|
|
pub clear_screen: bool,
|
|
|
|
}
|
|
|
|
|
2022-06-08 06:07:25 -04:00
|
|
|
fn create_print_after_restart_fn(clear_screen: bool) -> impl Fn() {
|
|
|
|
move || {
|
2022-12-19 12:59:32 -05:00
|
|
|
if clear_screen && atty::is(atty::Stream::Stderr) {
|
2023-01-27 10:43:16 -05:00
|
|
|
eprint!("{CLEAR_SCREEN}");
|
2022-06-08 06:07:25 -04:00
|
|
|
}
|
|
|
|
info!(
|
|
|
|
"{} File change detected! Restarting!",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
pub async fn watch_func<R, O, T, F1, F2>(
|
|
|
|
mut resolver: R,
|
|
|
|
mut operation: O,
|
2022-01-31 11:39:39 -05:00
|
|
|
print_config: PrintConfig,
|
2020-11-22 15:45:44 -05:00
|
|
|
) -> 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
|
|
|
|
2022-01-31 11:39:39 -05:00
|
|
|
let PrintConfig {
|
|
|
|
job_name,
|
|
|
|
clear_screen,
|
|
|
|
} = print_config;
|
|
|
|
|
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;
|
|
|
|
|
2022-06-08 06:07:25 -04:00
|
|
|
let print_after_restart = create_print_after_restart_fn(clear_screen);
|
2022-01-31 11:39:39 -05:00
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
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;
|
2022-01-31 11:39:39 -05:00
|
|
|
|
|
|
|
print_after_restart();
|
2021-05-10 02:06:13 -04:00
|
|
|
}
|
|
|
|
ResolutionResult::Restart {
|
2023-01-07 15:22:09 -05:00
|
|
|
paths_to_watch: mut paths,
|
2021-05-10 02:06:13 -04:00
|
|
|
result,
|
|
|
|
} => {
|
2023-01-07 15:22:09 -05:00
|
|
|
// watch the current directory when empty
|
|
|
|
if paths.is_empty() {
|
|
|
|
paths.push(PathBuf::from("."));
|
|
|
|
}
|
2021-05-10 02:06:13 -04:00
|
|
|
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
|
|
|
info!("{} {} started.", colors::intense_blue("Watcher"), job_name,);
|
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
loop {
|
2022-06-08 06:07:25 -04:00
|
|
|
let mut watcher = new_watcher(sender.clone())?;
|
|
|
|
add_paths_to_watcher(&mut watcher, &paths_to_watch);
|
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;
|
2022-01-31 11:39:39 -05:00
|
|
|
|
|
|
|
print_after_restart();
|
2021-05-10 02:06:13 -04:00
|
|
|
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;
|
|
|
|
|
2022-01-31 11:39:39 -05:00
|
|
|
print_after_restart();
|
|
|
|
|
2021-05-10 02:06:13 -04:00
|
|
|
drop(watcher);
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-08 06:07:25 -04:00
|
|
|
/// Creates a file watcher.
|
|
|
|
///
|
|
|
|
/// - `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
|
|
|
|
/// have the logic for it like bundling the code.
|
|
|
|
pub async fn watch_func2<T: Clone, O, F>(
|
2022-07-14 17:52:44 -04:00
|
|
|
mut paths_to_watch_receiver: UnboundedReceiver<Vec<PathBuf>>,
|
2022-06-08 06:07:25 -04:00
|
|
|
mut operation: O,
|
|
|
|
operation_args: T,
|
|
|
|
print_config: PrintConfig,
|
|
|
|
) -> Result<(), AnyError>
|
|
|
|
where
|
2022-08-10 15:13:53 -04:00
|
|
|
O: FnMut(T) -> Result<F, AnyError>,
|
2022-06-08 06:07:25 -04:00
|
|
|
F: Future<Output = Result<(), AnyError>>,
|
|
|
|
{
|
|
|
|
let (watcher_sender, mut watcher_receiver) =
|
|
|
|
DebouncedReceiver::new_with_sender();
|
|
|
|
|
|
|
|
let PrintConfig {
|
|
|
|
job_name,
|
|
|
|
clear_screen,
|
|
|
|
} = print_config;
|
|
|
|
|
|
|
|
let print_after_restart = create_print_after_restart_fn(clear_screen);
|
|
|
|
|
|
|
|
info!("{} {} started.", colors::intense_blue("Watcher"), job_name,);
|
|
|
|
|
|
|
|
fn consume_paths_to_watch(
|
|
|
|
watcher: &mut RecommendedWatcher,
|
|
|
|
receiver: &mut UnboundedReceiver<Vec<PathBuf>>,
|
|
|
|
) {
|
|
|
|
loop {
|
|
|
|
match receiver.try_recv() {
|
|
|
|
Ok(paths) => {
|
|
|
|
add_paths_to_watcher(watcher, &paths);
|
|
|
|
}
|
|
|
|
Err(e) => match e {
|
|
|
|
mpsc::error::TryRecvError::Empty => {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
// there must be at least one receiver alive
|
|
|
|
_ => unreachable!(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
loop {
|
2023-05-08 03:52:56 -04:00
|
|
|
// We may need to give the runtime a tick to settle, as cancellations may need to propagate
|
|
|
|
// to tasks. We choose yielding 10 times to the runtime as a decent heuristic. If watch tests
|
|
|
|
// start to fail, this may need to be increased.
|
|
|
|
for _ in 0..10 {
|
|
|
|
tokio::task::yield_now().await;
|
|
|
|
}
|
|
|
|
|
2022-06-08 06:07:25 -04:00
|
|
|
let mut watcher = new_watcher(watcher_sender.clone())?;
|
|
|
|
consume_paths_to_watch(&mut watcher, &mut paths_to_watch_receiver);
|
|
|
|
|
|
|
|
let receiver_future = async {
|
|
|
|
loop {
|
|
|
|
let maybe_paths = paths_to_watch_receiver.recv().await;
|
|
|
|
add_paths_to_watcher(&mut watcher, &maybe_paths.unwrap());
|
|
|
|
}
|
|
|
|
};
|
2022-08-10 15:13:53 -04:00
|
|
|
let operation_future = error_handler(operation(operation_args.clone())?);
|
2022-06-08 06:07:25 -04:00
|
|
|
|
|
|
|
select! {
|
|
|
|
_ = receiver_future => {},
|
|
|
|
_ = watcher_receiver.recv() => {
|
|
|
|
print_after_restart();
|
|
|
|
continue;
|
|
|
|
},
|
|
|
|
_ = operation_future => {
|
2023-02-03 14:15:16 -05:00
|
|
|
consume_paths_to_watch(&mut watcher, &mut paths_to_watch_receiver);
|
2022-06-08 06:07:25 -04:00
|
|
|
// TODO(bartlomieju): print exit code here?
|
|
|
|
info!(
|
|
|
|
"{} {} finished. Restarting on file change...",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
job_name,
|
|
|
|
);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
let receiver_future = async {
|
|
|
|
loop {
|
|
|
|
let maybe_paths = paths_to_watch_receiver.recv().await;
|
|
|
|
add_paths_to_watcher(&mut watcher, &maybe_paths.unwrap());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
select! {
|
|
|
|
_ = receiver_future => {},
|
|
|
|
_ = watcher_receiver.recv() => {
|
|
|
|
print_after_restart();
|
|
|
|
continue;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-28 07:41:18 -04:00
|
|
|
fn new_watcher(
|
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> {
|
2022-09-16 19:11:30 -04:00
|
|
|
let watcher = 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
|
|
|
}
|
|
|
|
}
|
2022-09-16 19:11:30 -04:00
|
|
|
},
|
|
|
|
Default::default(),
|
|
|
|
)?;
|
2020-09-11 12:19:49 -04:00
|
|
|
|
2022-06-08 06:07:25 -04:00
|
|
|
Ok(watcher)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn add_paths_to_watcher(watcher: &mut RecommendedWatcher, paths: &[PathBuf]) {
|
|
|
|
// Ignore any error e.g. `PathNotFound`
|
2020-09-11 12:19:49 -04:00
|
|
|
for path in paths {
|
2021-05-10 02:06:13 -04:00
|
|
|
let _ = watcher.watch(path, RecursiveMode::Recursive);
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|
2022-06-08 06:07:25 -04:00
|
|
|
log::debug!("Watching paths: {:?}", paths);
|
2020-09-11 12:19:49 -04:00
|
|
|
}
|