Skip to main content

hyperlane_cli/watch/
fn.rs

1use super::*;
2
3/// Spawns `cargo run` as a managed child process that terminates cleanly on restart or drop.
4///
5/// # Returns
6///
7/// - `Result<Child, io::Error>` - The spawned child process handle.
8fn spawn_cargo_run() -> Result<Child, io::Error> {
9    Command::new(CARGO_RUN_PROGRAM)
10        .arg("run")
11        .kill_on_drop(true)
12        .stdout(Stdio::inherit())
13        .stderr(Stdio::inherit())
14        .spawn()
15}
16
17/// Terminates any active watched child process before restarting.
18///
19/// # Arguments
20///
21/// - `&mut Option<Child>` - The active child process handle, if one is running.
22async fn stop_cargo_run(child: &mut Option<Child>) {
23    if let Some(mut process) = child.take() {
24        let _: Result<(), io::Error> = process.kill().await;
25        let _: Result<_, io::Error> = process.wait().await;
26    }
27}
28
29/// Execute watch command using notify crate to monitor file changes
30/// and restart `cargo run` when source files are modified.
31///
32/// # Returns
33///
34/// - `Result<(), io::Error>` - Success or error
35pub async fn execute_watch() -> Result<(), io::Error> {
36    let src_path: PathBuf = PathBuf::from("src");
37    if !src_path.exists() {
38        return Err(io::Error::other(ERROR_SRC_DIRECTORY_NOT_FOUND));
39    }
40    let mut active_child: Option<Child> = Some(spawn_cargo_run()?);
41    let (tx, mut rx): (Sender<Event>, Receiver<Event>) = channel(Event::new(EventKind::Any));
42    let mut watcher: RecommendedWatcher =
43        recommended_watcher(move |result: Result<Event, Error>| {
44            if let Ok(event) = result {
45                let _: Result<(), SendError<Event>> = tx.send(event);
46            }
47        })
48        .map_err(|error: Error| io::Error::other(error.to_string()))?;
49    watcher
50        .watch(&src_path, RecursiveMode::Recursive)
51        .map_err(|error: Error| io::Error::other(error.to_string()))?;
52    log::info!("Watching src/ for changes...");
53    let mut debounce: Interval = interval(Duration::from_millis(500));
54    debounce.tick().await;
55    while rx.changed().await.is_ok() {
56        let event: Event = rx.borrow().clone();
57        let has_rust_change: bool = event
58            .paths
59            .iter()
60            .any(|path: &PathBuf| path.extension().is_some_and(|ext: &OsStr| ext == "rs"));
61        if !has_rust_change {
62            continue;
63        }
64        log::warn!("File change detected: {}", event.paths[0].display());
65        debounce.reset();
66        sleep(Duration::from_millis(300)).await;
67        stop_cargo_run(&mut active_child).await;
68        active_child = Some(spawn_cargo_run()?);
69    }
70    stop_cargo_run(&mut active_child).await;
71    Ok(())
72}