Skip to main content

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