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, value_name = "DELAY")]
69 pub watch_delay: Option<String>,
70}
71
72impl WatchArgs {
73 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 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 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 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 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
271pub 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
279pub async fn watch_build(args: BuildArgs) -> Result<()> {
282 let config = args.watchexec_config()?;
283 run(config).await
284}
285
286pub async fn watch_gas_snapshot(args: GasSnapshotArgs) -> Result<()> {
289 let config = args.watchexec_config()?;
290 run(config).await
291}
292
293pub async fn watch_test(args: TestArgs) -> Result<()> {
296 let config: Config = args.build.load_config()?;
297 let filter = args.filter(&config)?;
298 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 return;
321 }
322
323 if changed_sol_test_files.is_empty() {
324 let last = last_test_files.lock();
326 if last.is_empty() {
327 return;
328 }
329 changed_sol_test_files = last.clone();
330 }
331
332 let mut file = changed_sol_test_files.iter().next().expect("test file present").clone();
334
335 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 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
367pub 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
376fn 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
389fn 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 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}