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
|
|
|
|
2023-06-14 18:29:19 -04:00
|
|
|
use crate::args::Flags;
|
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;
|
2023-08-25 09:43:07 -04:00
|
|
|
use std::io::IsTerminal;
|
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;
|
2023-06-14 18:29:19 -04:00
|
|
|
use tokio::sync::mpsc::UnboundedSender;
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-14 18:29:19 -04:00
|
|
|
async fn error_handler<F>(watch_future: F) -> bool
|
2021-05-10 02:06:13 -04:00
|
|
|
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: ")
|
|
|
|
);
|
2023-06-14 18:29:19 -04:00
|
|
|
false
|
|
|
|
} else {
|
|
|
|
true
|
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 || {
|
2023-08-25 09:43:07 -04:00
|
|
|
if clear_screen && std::io::stderr().is_terminal() {
|
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"),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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.
|
2023-06-14 18:29:19 -04:00
|
|
|
pub async fn watch_func<O, F>(
|
|
|
|
mut flags: Flags,
|
2022-06-08 06:07:25 -04:00
|
|
|
print_config: PrintConfig,
|
2023-06-14 18:29:19 -04:00
|
|
|
mut operation: O,
|
2022-06-08 06:07:25 -04:00
|
|
|
) -> Result<(), AnyError>
|
|
|
|
where
|
2023-06-14 18:29:19 -04:00
|
|
|
O: FnMut(
|
|
|
|
Flags,
|
|
|
|
UnboundedSender<Vec<PathBuf>>,
|
|
|
|
Option<Vec<PathBuf>>,
|
|
|
|
) -> Result<F, AnyError>,
|
2022-06-08 06:07:25 -04:00
|
|
|
F: Future<Output = Result<(), AnyError>>,
|
|
|
|
{
|
2023-06-14 18:29:19 -04:00
|
|
|
let (paths_to_watch_sender, mut paths_to_watch_receiver) =
|
|
|
|
tokio::sync::mpsc::unbounded_channel();
|
2022-06-08 06:07:25 -04:00
|
|
|
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!(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-14 18:29:19 -04:00
|
|
|
let mut changed_paths = None;
|
2022-06-08 06:07:25 -04:00
|
|
|
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());
|
|
|
|
}
|
|
|
|
};
|
2023-06-14 18:29:19 -04:00
|
|
|
let operation_future = error_handler(operation(
|
|
|
|
flags.clone(),
|
|
|
|
paths_to_watch_sender.clone(),
|
|
|
|
changed_paths.take(),
|
|
|
|
)?);
|
|
|
|
|
|
|
|
// don't reload dependencies after the first run
|
|
|
|
flags.reload = false;
|
2022-06-08 06:07:25 -04:00
|
|
|
|
|
|
|
select! {
|
|
|
|
_ = receiver_future => {},
|
2023-06-14 18:29:19 -04:00
|
|
|
received_changed_paths = watcher_receiver.recv() => {
|
2022-06-08 06:07:25 -04:00
|
|
|
print_after_restart();
|
2023-06-14 18:29:19 -04:00
|
|
|
changed_paths = received_changed_paths;
|
2022-06-08 06:07:25 -04:00
|
|
|
continue;
|
|
|
|
},
|
2023-06-14 18:29:19 -04:00
|
|
|
success = 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!(
|
2023-06-14 18:29:19 -04:00
|
|
|
"{} {} {}. Restarting on file change...",
|
2022-06-08 06:07:25 -04:00
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
job_name,
|
2023-06-14 18:29:19 -04:00
|
|
|
if success {
|
|
|
|
"finished"
|
|
|
|
} else {
|
|
|
|
"failed"
|
|
|
|
}
|
2022-06-08 06:07:25 -04:00
|
|
|
);
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
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 => {},
|
2023-06-14 18:29:19 -04:00
|
|
|
received_changed_paths = watcher_receiver.recv() => {
|
2022-06-08 06:07:25 -04:00
|
|
|
print_after_restart();
|
2023-06-14 18:29:19 -04:00
|
|
|
changed_paths = received_changed_paths;
|
2022-06-08 06:07:25 -04:00
|
|
|
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
|
|
|
}
|