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 #[arg(long, short, num_args(0..), value_name = "PATH")]
43 pub watch: Option<Vec<PathBuf>>,
44
45 #[arg(long)]
47 pub no_restart: bool,
48
49 #[arg(long)]
53 pub run_all: bool,
54
55 #[arg(long, alias = "rerun-failures")]
60 pub rerun_failed: bool,
61
62 #[arg(long, value_name = "DELAY")]
76 pub watch_delay: Option<String>,
77}
78
79impl WatchArgs {
80 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 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 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 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 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
277pub 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
285pub async fn watch_build(args: BuildArgs) -> Result<()> {
288 let config = args.watchexec_config()?;
289 run(config).await
290}
291
292pub async fn watch_gas_snapshot(args: GasSnapshotArgs) -> Result<()> {
295 let config = args.watchexec_config()?;
296 run(config).await
297}
298
299pub async fn watch_test(args: TestArgs) -> Result<()> {
302 let config: Config = args.build.load_config()?;
303 let filter = args.filter(&config)?;
304 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 let has_failures = rerun_failed && test_failures_file.exists();
320
321 if has_failures {
322 trace!("Smart watch mode: will rerun failed tests first");
324 command.arg("--rerun");
325 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 return;
341 }
342
343 if changed_sol_test_files.is_empty() {
344 let last = last_test_files.lock();
346 if last.is_empty() {
347 return;
348 }
349 changed_sol_test_files = last.clone();
350 }
351
352 let mut file = changed_sol_test_files.iter().next().expect("test file present").clone();
354
355 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 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
387pub 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
396fn 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
409fn 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 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}