forge/cmd/
watch.rs

1use super::{
2    build::BuildArgs, coverage::CoverageArgs, doc::DocArgs, fmt::FmtArgs,
3    snapshot::GasSnapshotArgs, test::TestArgs,
4};
5use alloy_primitives::map::HashSet;
6use clap::Parser;
7use eyre::Result;
8use foundry_cli::utils::{self, FoundryPathExt, LoadConfig};
9use foundry_config::Config;
10use parking_lot::Mutex;
11use std::{
12    path::PathBuf,
13    sync::{
14        Arc,
15        atomic::{AtomicU8, Ordering},
16    },
17    time::Duration,
18};
19use tokio::process::Command as TokioCommand;
20use watchexec::{
21    Watchexec,
22    action::ActionHandler,
23    command::{Command, Program},
24    job::{CommandState, Job},
25    paths::summarise_events_to_env,
26};
27use watchexec_events::{
28    Event, Priority, ProcessEnd, Tag,
29    filekind::{AccessKind, FileEventKind},
30};
31use watchexec_signals::Signal;
32use yansi::{Color, Paint};
33
34type SpawnHook = Arc<dyn Fn(&[Event], &mut TokioCommand) + Send + Sync + 'static>;
35
36#[derive(Clone, Debug, Default, Parser)]
37#[command(next_help_heading = "Watch options")]
38pub struct WatchArgs {
39    /// Watch the given files or directories for changes.
40    ///
41    /// If no paths are provided, the source and test directories of the project are watched.
42    #[arg(long, short, num_args(0..), value_name = "PATH")]
43    pub watch: Option<Vec<PathBuf>>,
44
45    /// Do not restart the command while it's still running.
46    #[arg(long)]
47    pub no_restart: bool,
48
49    /// Explicitly re-run all tests when a change is made.
50    ///
51    /// By default, only the tests of the last modified test file are executed.
52    #[arg(long)]
53    pub run_all: bool,
54
55    /// File update debounce delay.
56    ///
57    /// During the delay, incoming change events are accumulated and
58    /// only once the delay has passed, is an action taken. Note that
59    /// this does not mean a command will be started: if --no-restart is
60    /// given and a command is already running, the outcome of the
61    /// action will be to do nothing.
62    ///
63    /// Defaults to 50ms. Parses as decimal seconds by default, but
64    /// using an integer with the `ms` suffix may be more convenient.
65    ///
66    /// When using --poll mode, you'll want a larger duration, or risk
67    /// overloading disk I/O.
68    #[arg(long, value_name = "DELAY")]
69    pub watch_delay: Option<String>,
70}
71
72impl WatchArgs {
73    /// Creates a new [`watchexec::Config`].
74    ///
75    /// If paths were provided as arguments the these will be used as the watcher's pathset,
76    /// otherwise the path the closure returns will be used.
77    pub fn watchexec_config<PS: IntoIterator<Item = P>, P: Into<PathBuf>>(
78        &self,
79        default_paths: impl FnOnce() -> Result<PS>,
80    ) -> Result<watchexec::Config> {
81        self.watchexec_config_generic(default_paths, None)
82    }
83
84    /// Creates a new [`watchexec::Config`] with a custom command spawn hook.
85    ///
86    /// If paths were provided as arguments the these will be used as the watcher's pathset,
87    /// otherwise the path the closure returns will be used.
88    pub fn watchexec_config_with_override<PS: IntoIterator<Item = P>, P: Into<PathBuf>>(
89        &self,
90        default_paths: impl FnOnce() -> Result<PS>,
91        spawn_hook: impl Fn(&[Event], &mut TokioCommand) + Send + Sync + 'static,
92    ) -> Result<watchexec::Config> {
93        self.watchexec_config_generic(default_paths, Some(Arc::new(spawn_hook)))
94    }
95
96    fn watchexec_config_generic<PS: IntoIterator<Item = P>, P: Into<PathBuf>>(
97        &self,
98        default_paths: impl FnOnce() -> Result<PS>,
99        spawn_hook: Option<SpawnHook>,
100    ) -> Result<watchexec::Config> {
101        let mut paths = self.watch.as_deref().unwrap_or_default();
102        let storage: Vec<_>;
103        if paths.is_empty() {
104            storage = default_paths()?.into_iter().map(Into::into).filter(|p| p.exists()).collect();
105            paths = &storage;
106        }
107        self.watchexec_config_inner(paths, spawn_hook)
108    }
109
110    fn watchexec_config_inner(
111        &self,
112        paths: &[PathBuf],
113        spawn_hook: Option<SpawnHook>,
114    ) -> Result<watchexec::Config> {
115        let config = watchexec::Config::default();
116
117        config.on_error(|err| {
118            let _ = sh_eprintln!("[[{err:?}]]");
119        });
120
121        if let Some(delay) = &self.watch_delay {
122            config.throttle(utils::parse_delay(delay)?);
123        }
124
125        config.pathset(paths.iter().map(|p| p.as_path()));
126
127        let n_path_args = self.watch.as_deref().unwrap_or_default().len();
128        let base_command = Arc::new(watch_command(cmd_args(n_path_args)));
129
130        let id = watchexec::Id::default();
131        let quit_again = Arc::new(AtomicU8::new(0));
132        let stop_timeout = Duration::from_secs(5);
133        let no_restart = self.no_restart;
134        let stop_signal = Signal::Terminate;
135        config.on_action(move |mut action| {
136            let base_command = base_command.clone();
137            let job = action.get_or_create_job(id, move || base_command.clone());
138
139            let events = action.events.clone();
140            let spawn_hook = spawn_hook.clone();
141            job.set_spawn_hook(move |command, _| {
142                // https://github.com/watchexec/watchexec/blob/72f069a8477c679e45f845219276b0bfe22fed79/crates/cli/src/emits.rs#L9
143                let env = summarise_events_to_env(events.iter());
144                for (k, v) in env {
145                    command.command_mut().env(format!("WATCHEXEC_{k}_PATH"), v);
146                }
147
148                if let Some(spawn_hook) = &spawn_hook {
149                    spawn_hook(&events, command.command_mut());
150                }
151            });
152
153            let clear_screen = || {
154                let _ = clearscreen::clear();
155            };
156
157            let quit = |mut action: ActionHandler| {
158                match quit_again.fetch_add(1, Ordering::Relaxed) {
159                    0 => {
160                        let _ = sh_eprintln!(
161                            "[Waiting {stop_timeout:?} for processes to exit before stopping... \
162                             Ctrl-C again to exit faster]"
163                        );
164                        action.quit_gracefully(stop_signal, stop_timeout);
165                    }
166                    1 => action.quit_gracefully(Signal::ForceStop, Duration::ZERO),
167                    _ => action.quit(),
168                }
169
170                action
171            };
172
173            let signals = action.signals().collect::<Vec<_>>();
174
175            if signals.contains(&Signal::Terminate) || signals.contains(&Signal::Interrupt) {
176                return quit(action);
177            }
178
179            // Only filesystem events below here (or empty synthetic events).
180            if action.paths().next().is_none() && !action.events.iter().any(|e| e.is_empty()) {
181                debug!("no filesystem or synthetic events, skip without doing more");
182                return action;
183            }
184
185            if cfg!(target_os = "linux") {
186                // Reading a file now triggers `Access(Open)` events on Linux due to:
187                // https://github.com/notify-rs/notify/pull/612
188                // This causes an infinite rebuild loop: the build reads a file,
189                // which triggers a notification, which restarts the build, and so on.
190                // To prevent this, we ignore `Access(Open)` events during event processing.
191                let mut has_file_events = false;
192                let mut has_synthetic_events = false;
193                'outer: for e in action.events.iter() {
194                    if e.is_empty() {
195                        has_synthetic_events = true;
196                        break;
197                    } else {
198                        for tag in &e.tags {
199                            if let Tag::FileEventKind(kind) = tag
200                                && !matches!(kind, FileEventKind::Access(AccessKind::Open(_))) {
201                                    has_file_events = true;
202                                    break 'outer;
203                                }
204                        }
205                    }
206                }
207                if !has_file_events && !has_synthetic_events {
208                    debug!("no filesystem events (other than Access(Open)) or synthetic events, skip without doing more");
209                    return action;
210                }
211            }
212
213            job.run({
214                let job = job.clone();
215                move |context| {
216                    if context.current.is_running() && no_restart {
217                        return;
218                    }
219                    job.restart_with_signal(stop_signal, stop_timeout);
220                    job.run({
221                        let job = job.clone();
222                        move |context| {
223                            clear_screen();
224                            setup_process(job, &context.command)
225                        }
226                    });
227                }
228            });
229
230            action
231        });
232
233        Ok(config)
234    }
235}
236
237fn setup_process(job: Job, _command: &Command) {
238    tokio::spawn(async move {
239        job.to_wait().await;
240        job.run(move |context| end_of_process(context.current));
241    });
242}
243
244fn end_of_process(state: &CommandState) {
245    let CommandState::Finished { status, started, finished } = state else {
246        return;
247    };
248
249    let duration = *finished - *started;
250    let timings = true;
251    let timing = if timings { format!(", lasted {duration:?}") } else { String::new() };
252    let (msg, fg) = match status {
253        ProcessEnd::ExitError(code) => (format!("Command exited with {code}{timing}"), Color::Red),
254        ProcessEnd::ExitSignal(sig) => {
255            (format!("Command killed by {sig:?}{timing}"), Color::Magenta)
256        }
257        ProcessEnd::ExitStop(sig) => (format!("Command stopped by {sig:?}{timing}"), Color::Blue),
258        ProcessEnd::Continued => (format!("Command continued{timing}"), Color::Cyan),
259        ProcessEnd::Exception(ex) => {
260            (format!("Command ended by exception {ex:#x}{timing}"), Color::Yellow)
261        }
262        ProcessEnd::Success => (format!("Command was successful{timing}"), Color::Green),
263    };
264
265    let quiet = false;
266    if !quiet {
267        let _ = sh_eprintln!("{}", format!("[{msg}]").paint(fg.foreground()));
268    }
269}
270
271/// Runs the given [`watchexec::Config`].
272pub async fn run(config: watchexec::Config) -> Result<()> {
273    let wx = Watchexec::with_config(config)?;
274    wx.send_event(Event::default(), Priority::Urgent).await?;
275    wx.main().await??;
276    Ok(())
277}
278
279/// Executes a [`Watchexec`] that listens for changes in the project's src dir and reruns `forge
280/// build`
281pub async fn watch_build(args: BuildArgs) -> Result<()> {
282    let config = args.watchexec_config()?;
283    run(config).await
284}
285
286/// Executes a [`Watchexec`] that listens for changes in the project's src dir and reruns `forge
287/// snapshot`
288pub async fn watch_gas_snapshot(args: GasSnapshotArgs) -> Result<()> {
289    let config = args.watchexec_config()?;
290    run(config).await
291}
292
293/// Executes a [`Watchexec`] that listens for changes in the project's src dir and reruns `forge
294/// test`
295pub async fn watch_test(args: TestArgs) -> Result<()> {
296    let config: Config = args.build.load_config()?;
297    let filter = args.filter(&config)?;
298    // Marker to check whether to override the command.
299    let no_reconfigure = filter.args().test_pattern.is_some()
300        || filter.args().path_pattern.is_some()
301        || filter.args().contract_pattern.is_some()
302        || args.watch.run_all;
303
304    let last_test_files = Mutex::new(HashSet::<String>::default());
305    let project_root = config.root.to_string_lossy().into_owned();
306    let config = args.watch.watchexec_config_with_override(
307        || Ok([&config.test, &config.src]),
308        move |events, command| {
309            let mut changed_sol_test_files: HashSet<_> = events
310                .iter()
311                .flat_map(|e| e.paths())
312                .filter(|(path, _)| path.is_sol_test())
313                .filter_map(|(path, _)| path.to_str())
314                .map(str::to_string)
315                .collect();
316
317            if changed_sol_test_files.len() > 1 {
318                // Run all tests if multiple files were changed at once, for example when running
319                // `forge fmt`.
320                return;
321            }
322
323            if changed_sol_test_files.is_empty() {
324                // Reuse the old test files if a non-test file was changed.
325                let last = last_test_files.lock();
326                if last.is_empty() {
327                    return;
328                }
329                changed_sol_test_files = last.clone();
330            }
331
332            // append `--match-path` glob
333            let mut file = changed_sol_test_files.iter().next().expect("test file present").clone();
334
335            // remove the project root dir from the detected file
336            if let Some(f) = file.strip_prefix(&project_root) {
337                file = f.trim_start_matches('/').to_string();
338            }
339
340            trace!(?file, "reconfigure test command");
341
342            // Before appending `--match-path`, check if it already exists
343            if !no_reconfigure {
344                command.arg("--match-path").arg(file);
345            }
346        },
347    )?;
348    run(config).await
349}
350
351pub async fn watch_coverage(args: CoverageArgs) -> Result<()> {
352    let config = args.watch().watchexec_config(|| {
353        let config = args.load_config()?;
354        Ok([config.test, config.src])
355    })?;
356    run(config).await
357}
358
359pub async fn watch_fmt(args: FmtArgs) -> Result<()> {
360    let config = args.watch.watchexec_config(|| {
361        let config = args.load_config()?;
362        Ok([config.src, config.test, config.script])
363    })?;
364    run(config).await
365}
366
367/// Executes a [`Watchexec`] that listens for changes in the project's sources directory
368pub async fn watch_doc(args: DocArgs) -> Result<()> {
369    let config = args.watch.watchexec_config(|| {
370        let config = args.config()?;
371        Ok([config.src])
372    })?;
373    run(config).await
374}
375
376/// Converts a list of arguments to a `watchexec::Command`.
377///
378/// The first index in `args` is the path to the executable.
379///
380/// # Panics
381///
382/// Panics if `args` is empty.
383fn watch_command(mut args: Vec<String>) -> Command {
384    debug_assert!(!args.is_empty());
385    let prog = args.remove(0);
386    Command { program: Program::Exec { prog: prog.into(), args }, options: Default::default() }
387}
388
389/// Returns the env args without the `--watch` flag from the args for the Watchexec command
390fn cmd_args(num: usize) -> Vec<String> {
391    clean_cmd_args(num, std::env::args().collect())
392}
393
394#[instrument(level = "debug", ret)]
395fn clean_cmd_args(num: usize, mut cmd_args: Vec<String>) -> Vec<String> {
396    if let Some(pos) = cmd_args.iter().position(|arg| arg == "--watch" || arg == "-w") {
397        cmd_args.drain(pos..=(pos + num));
398    }
399
400    // There's another edge case where short flags are combined into one which is supported by clap,
401    // like `-vw` for verbosity and watch
402    // this removes any `w` from concatenated short flags
403    if let Some(pos) = cmd_args.iter().position(|arg| {
404        fn contains_w_in_short(arg: &str) -> Option<bool> {
405            let mut iter = arg.chars().peekable();
406            if *iter.peek()? != '-' {
407                return None;
408            }
409            iter.next();
410            if *iter.peek()? == '-' {
411                return None;
412            }
413            Some(iter.any(|c| c == 'w'))
414        }
415        contains_w_in_short(arg).unwrap_or(false)
416    }) {
417        let clean_arg = cmd_args[pos].replace('w', "");
418        if clean_arg == "-" {
419            cmd_args.remove(pos);
420        } else {
421            cmd_args[pos] = clean_arg;
422        }
423    }
424
425    cmd_args
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn parse_cmd_args() {
434        let args = vec!["-vw".to_string()];
435        let cleaned = clean_cmd_args(0, args);
436        assert_eq!(cleaned, vec!["-v".to_string()]);
437    }
438}