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;
|
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::ready;
|
2020-10-28 07:41:18 -04:00
|
|
|
use deno_core::futures::stream::{Stream, StreamExt};
|
2021-01-13 00:48:55 -05:00
|
|
|
use deno_core::futures::Future;
|
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-01-13 00:48:55 -05:00
|
|
|
use pin_project::pin_project;
|
2020-09-11 12:19:49 -04:00
|
|
|
use std::path::PathBuf;
|
|
|
|
use std::pin::Pin;
|
2020-10-28 07:41:18 -04:00
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use std::sync::Arc;
|
2021-01-13 00:48:55 -05:00
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
2020-10-28 07:41:18 -04:00
|
|
|
use std::time::Duration;
|
2021-01-13 00:48:55 -05:00
|
|
|
use tokio::pin;
|
2020-09-11 12:19:49 -04:00
|
|
|
use tokio::select;
|
2021-01-12 02:50:02 -05:00
|
|
|
use tokio::time::sleep;
|
2021-01-13 00:48:55 -05:00
|
|
|
use tokio::time::Instant;
|
|
|
|
use tokio::time::Sleep;
|
2020-10-28 07:41:18 -04:00
|
|
|
|
2021-01-13 00:48:55 -05:00
|
|
|
const DEBOUNCE_INTERVAL: Duration = Duration::from_millis(200);
|
2020-09-11 12:19:49 -04:00
|
|
|
|
2020-11-28 09:18:13 -05:00
|
|
|
type FileWatcherFuture<T> = Pin<Box<dyn Future<Output = T>>>;
|
2020-09-11 12:19:49 -04:00
|
|
|
|
2021-01-13 00:48:55 -05:00
|
|
|
#[pin_project(project = DebounceProjection)]
|
2020-10-28 07:41:18 -04:00
|
|
|
struct Debounce {
|
2021-01-13 00:48:55 -05:00
|
|
|
#[pin]
|
|
|
|
timer: Sleep,
|
2020-10-28 07:41:18 -04:00
|
|
|
event_detected: Arc<AtomicBool>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debounce {
|
|
|
|
fn new() -> Self {
|
|
|
|
Self {
|
2021-01-13 00:48:55 -05:00
|
|
|
timer: sleep(DEBOUNCE_INTERVAL),
|
2020-10-28 07:41:18 -04:00
|
|
|
event_detected: Arc::new(AtomicBool::new(false)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Stream for Debounce {
|
|
|
|
type Item = ();
|
|
|
|
|
2021-01-13 00:48:55 -05:00
|
|
|
/// Note that this never returns `Poll::Ready(None)`, which means that the
|
|
|
|
/// file watcher will be alive until the Deno process is terminated.
|
2020-10-28 07:41:18 -04:00
|
|
|
fn poll_next(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context,
|
|
|
|
) -> Poll<Option<Self::Item>> {
|
2021-01-13 01:26:44 -05:00
|
|
|
if self.event_detected.swap(false, Ordering::Relaxed) {
|
2020-10-28 07:41:18 -04:00
|
|
|
Poll::Ready(Some(()))
|
|
|
|
} else {
|
2021-01-13 00:48:55 -05:00
|
|
|
let mut timer = self.project().timer;
|
|
|
|
ready!(timer.as_mut().poll(cx));
|
|
|
|
timer.reset(Instant::now() + DEBOUNCE_INTERVAL);
|
|
|
|
Poll::Pending
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-28 09:18:13 -05:00
|
|
|
async fn error_handler(watch_future: FileWatcherFuture<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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-22 15:45:44 -05:00
|
|
|
/// This function adds watcher functionality to subcommands like `fmt` or `lint`.
|
|
|
|
/// The difference from [`watch_func_with_module_resolution`] is that this doesn't depend on
|
|
|
|
/// [`ModuleGraph`].
|
|
|
|
///
|
|
|
|
/// - `target_resolver` is used for resolving file paths to be watched at every restarting of the watcher. The
|
|
|
|
/// return value of this closure will then be passed to `operation` as an argument.
|
|
|
|
///
|
|
|
|
/// - `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 apply `fmt`, then `operation` would
|
|
|
|
/// have the logic for it like calling `format_source_files`.
|
|
|
|
///
|
|
|
|
/// - `job_name` is just used for printing watcher status to terminal.
|
|
|
|
///
|
|
|
|
/// Note that the watcher will stop working if `target_resolver` fails at some point.
|
|
|
|
///
|
|
|
|
/// [`ModuleGraph`]: crate::module_graph::Graph
|
|
|
|
pub async fn watch_func<F, G>(
|
|
|
|
target_resolver: F,
|
|
|
|
operation: G,
|
|
|
|
job_name: &str,
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<(), AnyError>
|
2020-09-11 12:19:49 -04:00
|
|
|
where
|
2020-11-22 15:45:44 -05:00
|
|
|
F: Fn() -> Result<Vec<PathBuf>, AnyError>,
|
2020-11-28 09:18:13 -05:00
|
|
|
G: Fn(Vec<PathBuf>) -> FileWatcherFuture<Result<(), AnyError>>,
|
2020-09-11 12:19:49 -04:00
|
|
|
{
|
2021-01-13 00:48:55 -05:00
|
|
|
let debounce = Debounce::new();
|
|
|
|
pin!(debounce);
|
2020-10-28 07:41:18 -04:00
|
|
|
|
2020-09-11 12:19:49 -04:00
|
|
|
loop {
|
2020-11-22 15:45:44 -05:00
|
|
|
let paths = target_resolver()?;
|
|
|
|
let _watcher = new_watcher(&paths, &debounce)?;
|
|
|
|
let func = error_handler(operation(paths));
|
2020-09-11 12:19:49 -04:00
|
|
|
let mut is_file_changed = false;
|
|
|
|
select! {
|
2020-10-28 07:41:18 -04:00
|
|
|
_ = debounce.next() => {
|
|
|
|
is_file_changed = true;
|
|
|
|
info!(
|
|
|
|
"{} File change detected! Restarting!",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
_ = func => {},
|
2020-11-22 15:45:44 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
if !is_file_changed {
|
|
|
|
info!(
|
|
|
|
"{} {} finished! Restarting on file change...",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
job_name,
|
|
|
|
);
|
|
|
|
debounce.next().await;
|
|
|
|
info!(
|
|
|
|
"{} File change detected! Restarting!",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-28 09:18:13 -05:00
|
|
|
pub enum ModuleResolutionResult<T> {
|
|
|
|
Success {
|
|
|
|
paths_to_watch: Vec<PathBuf>,
|
|
|
|
module_info: T,
|
|
|
|
},
|
|
|
|
Fail {
|
|
|
|
source_path: PathBuf,
|
|
|
|
error: AnyError,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2020-11-22 15:45:44 -05:00
|
|
|
/// This function adds watcher functionality to subcommands like `run` or `bundle`.
|
|
|
|
/// The difference from [`watch_func`] is that this does depend on [`ModuleGraph`].
|
|
|
|
///
|
|
|
|
/// - `module_resolver` is used for both resolving file paths to be watched at every restarting
|
|
|
|
/// of the watcher and building [`ModuleGraph`] or [`ModuleSpecifier`] which will then be passed
|
|
|
|
/// to `operation`.
|
|
|
|
///
|
|
|
|
/// - `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 doing bundle with the help of [`ModuleGraph`].
|
|
|
|
///
|
|
|
|
/// - `job_name` is just used for printing watcher status to terminal.
|
|
|
|
///
|
|
|
|
/// Note that the watcher will try to continue watching files using the previously resolved
|
|
|
|
/// data if `module_resolver` fails at some point, which means the watcher won't work at all
|
|
|
|
/// if `module_resolver` fails at the first attempt.
|
|
|
|
///
|
|
|
|
/// [`ModuleGraph`]: crate::module_graph::Graph
|
|
|
|
/// [`ModuleSpecifier`]: deno_core::ModuleSpecifier
|
|
|
|
pub async fn watch_func_with_module_resolution<F, G, T>(
|
|
|
|
module_resolver: F,
|
|
|
|
operation: G,
|
|
|
|
job_name: &str,
|
|
|
|
) -> Result<(), AnyError>
|
|
|
|
where
|
2020-11-28 09:18:13 -05:00
|
|
|
F: Fn() -> FileWatcherFuture<ModuleResolutionResult<T>>,
|
|
|
|
G: Fn(T) -> FileWatcherFuture<Result<(), AnyError>>,
|
2020-11-22 15:45:44 -05:00
|
|
|
T: Clone,
|
|
|
|
{
|
2021-01-13 00:48:55 -05:00
|
|
|
let debounce = Debounce::new();
|
|
|
|
pin!(debounce);
|
|
|
|
|
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-01-12 02:53:58 -05:00
|
|
|
let mut paths = Vec::new();
|
2020-11-22 15:45:44 -05:00
|
|
|
let mut module = None;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
match module_resolver().await {
|
2020-11-28 09:18:13 -05:00
|
|
|
ModuleResolutionResult::Success {
|
|
|
|
paths_to_watch,
|
|
|
|
module_info,
|
|
|
|
} => {
|
|
|
|
paths = paths_to_watch;
|
|
|
|
module = Some(module_info);
|
2020-11-22 15:45:44 -05:00
|
|
|
}
|
2020-11-28 09:18:13 -05:00
|
|
|
ModuleResolutionResult::Fail { source_path, error } => {
|
2021-01-12 02:53:58 -05:00
|
|
|
if paths.is_empty() {
|
|
|
|
paths = vec![source_path];
|
|
|
|
}
|
|
|
|
|
2020-11-28 09:18:13 -05:00
|
|
|
if module.is_none() {
|
|
|
|
eprintln!("{}: {}", colors::red_bold("error"), error);
|
2020-11-22 15:45:44 -05:00
|
|
|
}
|
|
|
|
}
|
2020-10-28 07:41:18 -04:00
|
|
|
}
|
2020-11-28 09:18:13 -05:00
|
|
|
let _watcher = new_watcher(&paths, &debounce)?;
|
2020-11-22 15:45:44 -05:00
|
|
|
|
2020-11-28 09:18:13 -05:00
|
|
|
if let Some(module) = &module {
|
|
|
|
let func = error_handler(operation(module.clone()));
|
|
|
|
let mut is_file_changed = false;
|
|
|
|
select! {
|
|
|
|
_ = debounce.next() => {
|
|
|
|
is_file_changed = true;
|
|
|
|
info!(
|
|
|
|
"{} File change detected! Restarting!",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
_ = func => {},
|
|
|
|
};
|
|
|
|
|
|
|
|
if !is_file_changed {
|
|
|
|
info!(
|
|
|
|
"{} {} finished! Restarting on file change...",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
job_name,
|
|
|
|
);
|
|
|
|
debounce.next().await;
|
2020-11-22 15:45:44 -05:00
|
|
|
info!(
|
|
|
|
"{} File change detected! Restarting!",
|
|
|
|
colors::intense_blue("Watcher"),
|
|
|
|
);
|
2020-11-28 09:18:13 -05:00
|
|
|
}
|
|
|
|
} else {
|
2020-09-11 12:19:49 -04:00
|
|
|
info!(
|
2020-11-28 09:18:13 -05:00
|
|
|
"{} {} failed! Restarting on file change...",
|
2020-10-28 07:41:18 -04:00
|
|
|
colors::intense_blue("Watcher"),
|
2020-11-22 15:45:44 -05:00
|
|
|
job_name,
|
2020-09-11 12:19:49 -04:00
|
|
|
);
|
2020-10-28 07:41:18 -04:00
|
|
|
debounce.next().await;
|
2020-09-11 12:19:49 -04:00
|
|
|
info!(
|
|
|
|
"{} File change detected! Restarting!",
|
2020-10-28 07:41:18 -04:00
|
|
|
colors::intense_blue("Watcher"),
|
2020-09-11 12:19:49 -04:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-28 07:41:18 -04:00
|
|
|
fn new_watcher(
|
|
|
|
paths: &[PathBuf],
|
|
|
|
debounce: &Debounce,
|
|
|
|
) -> Result<RecommendedWatcher, AnyError> {
|
|
|
|
let event_detected = Arc::clone(&debounce.event_detected);
|
2020-09-11 12:19:49 -04:00
|
|
|
|
2020-12-13 13:45:53 -05:00
|
|
|
let mut watcher: RecommendedWatcher =
|
|
|
|
Watcher::new_immediate(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(_)
|
|
|
|
) {
|
2020-10-28 07:41:18 -04:00
|
|
|
event_detected.store(true, Ordering::Relaxed);
|
|
|
|
}
|
|
|
|
}
|
2020-12-13 13:45:53 -05:00
|
|
|
})?;
|
2020-09-11 12:19:49 -04:00
|
|
|
|
|
|
|
watcher.configure(Config::PreciseEvents(true)).unwrap();
|
|
|
|
|
|
|
|
for path in paths {
|
2020-11-22 15:45:44 -05:00
|
|
|
// Ignore any error e.g. `PathNotFound`
|
|
|
|
let _ = watcher.watch(path, RecursiveMode::NonRecursive);
|
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
|
|
|
}
|