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 crate::opts::Forge;
6use alloy_primitives::map::{HashMap, HashSet};
7use clap::{CommandFactory, Parser};
8use eyre::Result;
9use foundry_cli::utils::{self, FoundryPathExt, LoadConfig};
10use foundry_config::Config;
11use parking_lot::Mutex;
12use std::{
13    ffi::{OsStr, OsString},
14    io::IsTerminal,
15    path::PathBuf,
16    sync::{
17        Arc, OnceLock, Weak,
18        atomic::{AtomicU8, Ordering},
19    },
20    time::Duration,
21};
22use tokio::process::Command as TokioCommand;
23use watchexec::{
24    Watchexec,
25    action::ActionHandler,
26    command::{Command, Program},
27    job::{CommandState, Job},
28    paths::summarise_events_to_env,
29};
30use watchexec_events::{
31    Event, KeyCode, Keyboard, Priority, ProcessEnd, Tag,
32    filekind::{AccessKind, FileEventKind},
33};
34use watchexec_signals::Signal;
35use yansi::{Color, Paint};
36
37type SpawnHook = Arc<dyn Fn(&[Event], &mut TokioCommand) + Send + Sync + 'static>;
38type KeyboardConfig = Arc<OnceLock<Weak<watchexec::Config>>>;
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41enum KeyboardAction {
42    Rerun,
43    Quit,
44}
45
46fn keyboard_action(events: &[Event]) -> Option<KeyboardAction> {
47    let mut rerun = false;
48
49    for tag in events.iter().flat_map(|event| &event.tags) {
50        match tag {
51            Tag::Keyboard(Keyboard::Eof) => return Some(KeyboardAction::Quit),
52            Tag::Keyboard(Keyboard::Key { key: KeyCode::Char('a'), modifiers })
53                if modifiers.is_empty() =>
54            {
55                rerun = true;
56            }
57            _ => {}
58        }
59    }
60
61    rerun.then_some(KeyboardAction::Rerun)
62}
63
64/// What the watcher does with one batch of events.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66enum WatchAction {
67    /// A termination signal or the end of keyboard input: stop watching.
68    Quit,
69    /// Nothing that warrants running the command again.
70    Ignore,
71    /// Run the command, restarting it if it is still running and restarts are allowed.
72    Run,
73}
74
75/// Decides what the watcher does with a batch of `events` that came with `signals`.
76///
77/// `has_paths` is whether any of the events names a filesystem path.
78fn watch_action(signals: &[Signal], events: &[Event], has_paths: bool) -> WatchAction {
79    let keyboard_action = keyboard_action(events);
80    if signals.contains(&Signal::Terminate)
81        || signals.contains(&Signal::Interrupt)
82        || keyboard_action == Some(KeyboardAction::Quit)
83    {
84        return WatchAction::Quit;
85    }
86
87    // A keyboard rerun runs the command whatever else the batch holds.
88    if keyboard_action == Some(KeyboardAction::Rerun) {
89        return WatchAction::Run;
90    }
91
92    // Only filesystem or empty synthetic events below here.
93    let has_synthetic_events = events.iter().any(Event::is_empty);
94    if !has_paths && !has_synthetic_events {
95        debug!("no filesystem, rerun, or synthetic events, skip without doing more");
96        return WatchAction::Ignore;
97    }
98
99    // Reading a file now triggers `Access(Open)` events on Linux due to:
100    // https://github.com/notify-rs/notify/pull/612
101    // This causes an infinite rebuild loop: the build reads a file,
102    // which triggers a notification, which restarts the build, and so on.
103    // To prevent this, we ignore `Access(Open)` events during event processing.
104    if cfg!(target_os = "linux") && !has_synthetic_events && !has_file_events(events) {
105        debug!(
106            "no filesystem events (other than Access(Open)) or synthetic events, skip without doing more"
107        );
108        return WatchAction::Ignore;
109    }
110
111    WatchAction::Run
112}
113
114/// Whether any of `events` is a filesystem event other than `Access(Open)`.
115fn has_file_events(events: &[Event]) -> bool {
116    events.iter().flat_map(|event| &event.tags).any(|tag| {
117        matches!(
118            tag,
119            Tag::FileEventKind(kind) if !matches!(kind, FileEventKind::Access(AccessKind::Open(_)))
120        )
121    })
122}
123
124fn set_keyboard_events(config: &Option<KeyboardConfig>, enable: bool) {
125    if let Some(config) = config.as_ref().and_then(|config| config.get()).and_then(Weak::upgrade) {
126        config.keyboard_events(enable);
127    }
128}
129
130#[derive(Clone, Debug, Default, Parser)]
131#[command(next_help_heading = "Watch options")]
132pub struct WatchArgs {
133    /// Watch the given files or directories for changes.
134    ///
135    /// If no paths are provided, the source and test directories of the project are watched.
136    #[arg(long, short, num_args(0..), value_name = "PATH")]
137    pub watch: Option<Vec<PathBuf>>,
138
139    /// Do not restart the command while it's still running.
140    #[arg(long)]
141    pub no_restart: bool,
142
143    /// Explicitly re-run all tests when a change is made.
144    ///
145    /// By default, only the tests of the last modified test file are executed.
146    #[arg(long)]
147    pub run_all: bool,
148
149    /// Re-run only previously failed tests first when a change is made.
150    ///
151    /// If all previously failed tests pass, the full test suite will be run automatically.
152    /// This is particularly useful for TDD workflows where you want fast feedback on failures.
153    #[arg(long, alias = "rerun-failures")]
154    pub rerun_failed: bool,
155
156    /// File update debounce delay.
157    ///
158    /// During the delay, incoming change events are accumulated and
159    /// only once the delay has passed, is an action taken. Note that
160    /// this does not mean a command will be started: if --no-restart is
161    /// given and a command is already running, the outcome of the
162    /// action will be to do nothing.
163    ///
164    /// Defaults to 50ms. Parses as decimal seconds by default, but
165    /// using an integer with the `ms` suffix may be more convenient.
166    ///
167    /// When using --poll mode, you'll want a larger duration, or risk
168    /// overloading disk I/O.
169    #[arg(long, value_name = "DELAY")]
170    pub watch_delay: Option<String>,
171}
172
173impl WatchArgs {
174    /// Creates a new [`watchexec::Config`].
175    ///
176    /// If paths were provided as arguments the these will be used as the watcher's pathset,
177    /// otherwise the path the closure returns will be used.
178    pub fn watchexec_config<PS: IntoIterator<Item = P>, P: Into<PathBuf>>(
179        &self,
180        default_paths: impl FnOnce() -> Result<PS>,
181    ) -> Result<watchexec::Config> {
182        self.watchexec_config_generic(default_paths, None, None)
183    }
184
185    /// Creates a new [`watchexec::Config`] with a custom command spawn hook and optional keyboard
186    /// events while the command is idle.
187    ///
188    /// If paths were provided as arguments the these will be used as the watcher's pathset,
189    /// otherwise the path the closure returns will be used.
190    fn watchexec_config_with_override<PS: IntoIterator<Item = P>, P: Into<PathBuf>>(
191        &self,
192        default_paths: impl FnOnce() -> Result<PS>,
193        watch_keyboard: bool,
194        spawn_hook: impl Fn(&[Event], &mut TokioCommand) + Send + Sync + 'static,
195    ) -> Result<(watchexec::Config, Option<KeyboardConfig>)> {
196        let keyboard_config = watch_keyboard.then(|| Arc::new(OnceLock::new()));
197        let config = self.watchexec_config_generic(
198            default_paths,
199            Some(Arc::new(spawn_hook)),
200            keyboard_config.clone(),
201        )?;
202        Ok((config, keyboard_config))
203    }
204
205    fn watchexec_config_generic<PS: IntoIterator<Item = P>, P: Into<PathBuf>>(
206        &self,
207        default_paths: impl FnOnce() -> Result<PS>,
208        spawn_hook: Option<SpawnHook>,
209        keyboard_config: Option<KeyboardConfig>,
210    ) -> Result<watchexec::Config> {
211        let mut paths = self.watch.as_deref().unwrap_or_default();
212        let storage: Vec<_>;
213        if paths.is_empty() {
214            storage = default_paths()?.into_iter().map(Into::into).filter(|p| p.exists()).collect();
215            paths = &storage;
216        }
217        self.watchexec_config_inner(paths, spawn_hook, keyboard_config)
218    }
219
220    fn watchexec_config_inner(
221        &self,
222        paths: &[PathBuf],
223        spawn_hook: Option<SpawnHook>,
224        keyboard_config: Option<KeyboardConfig>,
225    ) -> Result<watchexec::Config> {
226        let config = watchexec::Config::default();
227
228        config.on_error(|err| {
229            let _ = sh_eprintln!("[[{err:?}]]");
230        });
231
232        if let Some(delay) = &self.watch_delay {
233            config.throttle(utils::parse_delay(delay)?);
234        }
235
236        config.pathset(paths.iter().map(|p| p.as_path()));
237
238        let base_command = Arc::new(watch_command(cmd_args())?);
239
240        let id = watchexec::Id::default();
241        let quit_again = Arc::new(AtomicU8::new(0));
242        let stop_timeout = Duration::from_secs(5);
243        let no_restart = self.no_restart;
244        let stop_signal = Signal::Terminate;
245        config.on_action(move |mut action| {
246            let base_command = base_command.clone();
247            let job = action.get_or_create_job(id, move || base_command.clone());
248
249            let events = action.events.clone();
250            let spawn_hook = spawn_hook.clone();
251            job.set_spawn_hook(move |command, _| {
252                // https://github.com/watchexec/watchexec/blob/72f069a8477c679e45f845219276b0bfe22fed79/crates/cli/src/emits.rs#L9
253                let env = summarise_events_to_env(events.iter());
254                for (k, v) in env {
255                    command.command_mut().env(format!("WATCHEXEC_{k}_PATH"), v);
256                }
257
258                if let Some(spawn_hook) = &spawn_hook {
259                    spawn_hook(&events, command.command_mut());
260                }
261            });
262
263            let clear_screen = || {
264                let _ = clearscreen::clear();
265            };
266
267            let quit = |mut action: ActionHandler| {
268                match quit_again.fetch_add(1, Ordering::Relaxed) {
269                    0 => {
270                        let _ = sh_eprintln!(
271                            "[Waiting {stop_timeout:?} for processes to exit before stopping... \
272                             Ctrl-C again to exit faster]"
273                        );
274                        action.quit_gracefully(stop_signal, stop_timeout);
275                    }
276                    1 => action.quit_gracefully(Signal::ForceStop, Duration::ZERO),
277                    _ => action.quit(),
278                }
279
280                action
281            };
282
283            let signals = action.signals().collect::<Vec<_>>();
284            let has_paths = action.paths().next().is_some();
285            match watch_action(&signals, &action.events, has_paths) {
286                WatchAction::Quit => return quit(action),
287                WatchAction::Ignore => return action,
288                WatchAction::Run => {}
289            }
290
291            // Let the child own stdin while it runs. This keeps prompts and the debugger from
292            // racing Watchexec's keyboard event source for terminal input.
293            set_keyboard_events(&keyboard_config, false);
294
295            job.run({
296                let job = job.clone();
297                let keyboard_config = keyboard_config.clone();
298                move |context| {
299                    if context.current.is_running() && no_restart {
300                        return;
301                    }
302                    job.restart_with_signal(stop_signal, stop_timeout);
303                    job.run({
304                        let job = job.clone();
305                        move |context| {
306                            clear_screen();
307                            setup_process(job, &context.command, keyboard_config)
308                        }
309                    });
310                }
311            });
312
313            action
314        });
315
316        Ok(config)
317    }
318}
319
320fn setup_process(job: Job, _command: &Command, keyboard_config: Option<KeyboardConfig>) {
321    tokio::spawn(async move {
322        job.to_wait().await;
323        job.run(move |context| end_of_process(context.current, keyboard_config));
324    });
325}
326
327fn end_of_process(state: &CommandState, keyboard_config: Option<KeyboardConfig>) {
328    // Hand stdin back to the watcher however the command ended: a command that failed to spawn
329    // leaves the job pending, and keyboard reruns would otherwise stay disabled for good.
330    set_keyboard_events(&keyboard_config, true);
331    let CommandState::Finished { status, started, finished } = state else {
332        return;
333    };
334
335    let duration = *finished - *started;
336    let timings = true;
337    let timing = if timings { format!(", lasted {duration:?}") } else { String::new() };
338    let (msg, fg) = match status {
339        ProcessEnd::ExitError(code) => (format!("Command exited with {code}{timing}"), Color::Red),
340        ProcessEnd::ExitSignal(sig) => {
341            (format!("Command killed by {sig:?}{timing}"), Color::Magenta)
342        }
343        ProcessEnd::ExitStop(sig) => (format!("Command stopped by {sig:?}{timing}"), Color::Blue),
344        ProcessEnd::Continued => (format!("Command continued{timing}"), Color::Cyan),
345        ProcessEnd::Exception(ex) => {
346            (format!("Command ended by exception {ex:#x}{timing}"), Color::Yellow)
347        }
348        ProcessEnd::Success => (format!("Command was successful{timing}"), Color::Green),
349    };
350
351    let quiet = false;
352    if !quiet {
353        let _ = sh_eprintln!("{}", format!("[{msg}]").paint(fg.foreground()));
354    }
355}
356
357/// Runs the given [`watchexec::Config`].
358pub async fn run(config: watchexec::Config) -> Result<()> {
359    run_inner(config, None).await
360}
361
362async fn run_inner(
363    config: watchexec::Config,
364    keyboard_config: Option<KeyboardConfig>,
365) -> Result<()> {
366    let wx = Watchexec::with_config(config)?;
367    if let Some(config) = keyboard_config {
368        debug_assert!(config.set(Arc::downgrade(&wx.config)).is_ok());
369    }
370    wx.send_event(Event::default(), Priority::Urgent).await?;
371    wx.main().await??;
372    Ok(())
373}
374
375/// Executes a [`Watchexec`] that listens for changes in the project's src dir and reruns `forge
376/// build`
377pub async fn watch_build(args: BuildArgs) -> Result<()> {
378    let config = args.watchexec_config()?;
379    run(config).await
380}
381
382/// Executes a [`Watchexec`] that listens for changes in the project's src dir and reruns `forge
383/// snapshot`
384pub async fn watch_gas_snapshot(args: GasSnapshotArgs) -> Result<()> {
385    let config = args.watchexec_config()?;
386    run(config).await
387}
388
389/// Executes a [`Watchexec`] that listens for changes in the project's src dir and reruns `forge
390/// test`
391pub async fn watch_test(args: TestArgs) -> Result<()> {
392    let config: Config = args.build.load_config()?;
393    let filter = args.filter(&config)?;
394    // Marker to check whether to override the command.
395    let no_reconfigure = filter.args().test_pattern.is_some()
396        || filter.args().path_pattern.is_some()
397        || filter.args().contract_pattern.is_some()
398        || args.watch.run_all;
399
400    let last_test_files = Mutex::new(HashSet::<String>::default());
401    let project_root = config.root.to_string_lossy().into_owned();
402    let test_failures_file = config.test_failures_file.clone();
403    let rerun_failed = args.watch.rerun_failed;
404    let watch_keyboard = std::io::stdin().is_terminal();
405
406    let (config, keyboard_config) = args.watch.watchexec_config_with_override(
407        || Ok([&config.test, &config.src]),
408        watch_keyboard,
409        move |events, command| {
410            let rerun = if keyboard_action(events) == Some(KeyboardAction::Rerun) {
411                TestRerun::Unchanged
412            } else if rerun_failed && test_failures_file.exists() {
413                TestRerun::Failures
414            } else {
415                changed_test_rerun(
416                    events,
417                    &mut last_test_files.lock(),
418                    &project_root,
419                    no_reconfigure,
420                )
421            };
422            rerun.apply(command);
423        },
424    )?;
425
426    if watch_keyboard {
427        let _ = sh_eprintln!("[Press 'a' to rerun all tests]");
428    }
429
430    run_inner(config, keyboard_config).await
431}
432
433/// How `forge test --watch` narrows the test command for one batch of events.
434#[derive(Clone, Debug, PartialEq, Eq)]
435enum TestRerun {
436    /// Run the command as given.
437    Unchanged,
438    /// Rerun the failures that the last run recorded, ahead of anything else.
439    Failures,
440    /// Run only the tests of this project-relative file.
441    MatchPath(String),
442}
443
444impl TestRerun {
445    fn apply(self, command: &mut TokioCommand) {
446        match self {
447            Self::Unchanged => {}
448            Self::Failures => {
449                // Don't add file-specific filters when rerunning failures.
450                trace!("Smart watch mode: will rerun failed tests first");
451                command.arg("--rerun");
452            }
453            Self::MatchPath(file) => {
454                command.arg("--match-path").arg(file);
455            }
456        }
457    }
458}
459
460/// Picks the tests to run for changed files: the one changed test file, or the last test files
461/// when only non-test files changed.
462///
463/// A single changed test file becomes the last test files, so later changes to non-test files
464/// keep running its tests.
465///
466/// `no_reconfigure` keeps the command as given, for runs that the user already filtered.
467fn changed_test_rerun(
468    events: &[Event],
469    last_test_files: &mut HashSet<String>,
470    project_root: &str,
471    no_reconfigure: bool,
472) -> TestRerun {
473    let mut changed_sol_test_files: HashSet<_> = events
474        .iter()
475        .flat_map(|e| e.paths())
476        .filter(|(path, _)| path.is_sol_test())
477        .filter_map(|(path, _)| path.to_str())
478        .map(str::to_string)
479        .collect();
480
481    if changed_sol_test_files.len() > 1 {
482        // Run all tests if multiple files were changed at once, for example when running
483        // `forge fmt`.
484        last_test_files.clear();
485        return TestRerun::Unchanged;
486    }
487
488    if changed_sol_test_files.is_empty() {
489        // Reuse the old test files if a non-test file was changed.
490        if last_test_files.is_empty() {
491            return TestRerun::Unchanged;
492        }
493        changed_sol_test_files = last_test_files.clone();
494    } else {
495        last_test_files.clone_from(&changed_sol_test_files);
496    }
497
498    let mut file = changed_sol_test_files.iter().next().expect("test file present").clone();
499
500    // remove the project root dir from the detected file
501    if let Some(f) = file.strip_prefix(project_root) {
502        file = f.trim_start_matches('/').to_string();
503    }
504
505    trace!(?file, "reconfigure test command");
506
507    if no_reconfigure { TestRerun::Unchanged } else { TestRerun::MatchPath(file) }
508}
509
510pub async fn watch_coverage(args: CoverageArgs) -> Result<()> {
511    args.ensure_mode_compatible()?;
512
513    let config = args.watch().watchexec_config(|| {
514        let config = args.load_config()?;
515        Ok([config.test, config.src])
516    })?;
517    run(config).await
518}
519
520pub async fn watch_fmt(args: FmtArgs) -> Result<()> {
521    let config = args.watch.watchexec_config(|| {
522        let config = args.load_config()?;
523        Ok([config.src, config.test, config.script])
524    })?;
525    run(config).await
526}
527
528/// Executes a [`Watchexec`] that listens for changes affecting the generated
529/// documentation: project sources, optionally library sources, the README that
530/// becomes the homepage, the deployments directory, and the foundry config file
531/// itself. Without these, the live preview goes silently stale on common edits.
532pub async fn watch_doc(args: DocArgs) -> Result<()> {
533    let include_libraries = args.include_libraries;
534    let deployments_arg = args.deployments.clone();
535    let config = args.watch.watchexec_config(|| {
536        let config = args.config()?;
537        let root = config.root.clone();
538
539        let mut paths = Vec::new();
540
541        // Solidity sources.
542        paths.push(config.src.clone());
543
544        // External libraries when explicitly opted in.
545        if include_libraries {
546            for lib in &config.libs {
547                paths.push(lib.clone());
548            }
549        }
550
551        // Homepage source: explicit override, else <root>/README.md when present.
552        if let Some(hp) = &config.doc.homepage {
553            let hp_path = if hp.is_absolute() { hp.clone() } else { root.join(hp) };
554            if hp_path.exists() {
555                paths.push(hp_path);
556            }
557        }
558        // Mirror vocs homepage resolution: <sources>/README.md takes priority over
559        // <root>/README.md.
560        let src_readme = config.src.join("README.md");
561        if src_readme.exists() {
562            paths.push(src_readme);
563        }
564        let readme = root.join("README.md");
565        if readme.exists() {
566            paths.push(readme);
567        }
568
569        // Deployments directory: only when the user enabled `--deployments`.
570        if let Some(dir_opt) = deployments_arg.as_ref() {
571            let dep_dir = match dir_opt {
572                Some(p) if p.is_absolute() => p.clone(),
573                Some(p) => root.join(p),
574                None => root.join("deployments"),
575            };
576            if dep_dir.exists() {
577                paths.push(dep_dir);
578            }
579        }
580
581        // Foundry config file (`foundry.toml`), when present.
582        let toml = root.join("foundry.toml");
583        if toml.exists() {
584            paths.push(toml);
585        }
586
587        Ok(paths)
588    })?;
589    run(config).await
590}
591
592/// Converts a list of arguments to a `watchexec::Command`.
593///
594/// The first index in `args` is the path to the executable.
595///
596/// # Panics
597///
598/// Panics if `args` is empty.
599fn watch_command(mut args: Vec<OsString>) -> Result<Command> {
600    debug_assert!(!args.is_empty());
601    let prog = PathBuf::from(args.remove(0));
602    let args = args
603        .into_iter()
604        .map(|arg| {
605            arg.into_string().map_err(|arg| {
606                eyre::eyre!(
607                    "watchexec requires UTF-8 command arguments; {arg:?} is not valid UTF-8"
608                )
609            })
610        })
611        .collect::<Result<Vec<_>>>()?;
612    Ok(Command { program: Program::Exec { prog, args }, options: Default::default() })
613}
614
615/// Returns the env args without the `--watch` flag from the args for the Watchexec command.
616///
617/// `args_os` is used instead of `args` because the latter panics on an argument that is not valid
618/// Unicode, and a watched path is a `PathBuf`, which is allowed to be non-Unicode on Unix.
619fn cmd_args() -> Vec<OsString> {
620    clean_cmd_args(std::env::args_os().collect())
621}
622
623/// How a command-line argument relates to the `watch` flag.
624enum WatchFlag {
625    /// Not the `watch` flag.
626    Other,
627    /// `--watch`, `-w`, or a short flag cluster ending in `w`, with the paths given as the
628    /// arguments that follow it. Holds the valueless short flags leading up to `w`, which are kept.
629    Bare(Option<OsString>),
630    /// `--watch=<PATH>`, `-w<PATH>`, or a short flag cluster with the path attached to its `w`.
631    /// Holds the valueless short flags leading up to `w`, which are kept.
632    Inline(Option<OsString>),
633}
634
635/// Removes the `--watch` flag from the args for the Watchexec command, so that the child command
636/// does not enter watch mode itself and spawn another watcher.
637///
638/// `watch` is an `Option<Vec<PathBuf>>`, so clap accepts the flag as `--watch <PATH>`,
639/// `--watch=<PATH>`, `-w <PATH>`, and `-w<PATH>`, combines it with other short flags (`-vw`,
640/// `-vw<PATH>`), and allows it to repeat, appending the paths of every occurrence.
641#[instrument(level = "debug", ret)]
642fn clean_cmd_args(cmd_args: Vec<OsString>) -> Vec<OsString> {
643    let mut cleaned = Vec::with_capacity(cmd_args.len());
644    let (value_less_short_flags, variable_options) = command_options(&cmd_args);
645    let mut args = cmd_args.into_iter().peekable();
646    cleaned.extend(args.next());
647    let mut deferred = Vec::new();
648
649    while let Some(arg) = args.next() {
650        if arg == "--" {
651            cleaned.append(&mut deferred);
652            cleaned.push(arg);
653            cleaned.extend(args);
654            break;
655        }
656
657        match watch_flag(&arg, &value_less_short_flags) {
658            WatchFlag::Other => {
659                let option = arg.as_encoded_bytes().strip_prefix(b"--").map(|bytes| {
660                    let end = bytes.iter().position(|&byte| byte == b'=').unwrap_or(bytes.len());
661                    (&bytes[..end], end < bytes.len())
662                });
663                if let Some((name, attached)) = option
664                    && let Ok(name) = std::str::from_utf8(name)
665                    && let Some(&max_values) = variable_options.get(name)
666                {
667                    // Keep greedy options and their original values together at the end, so
668                    // removing watch cannot make them consume a previously positional argument.
669                    deferred.push(arg);
670                    if !attached {
671                        for _ in 0..max_values {
672                            if !args.peek().is_some_and(|next| !looks_like_option(next)) {
673                                break;
674                            }
675                            deferred.extend(args.next());
676                        }
677                    }
678                } else {
679                    cleaned.push(arg);
680                }
681            }
682            WatchFlag::Inline(kept) => cleaned.extend(kept),
683            WatchFlag::Bare(kept) => {
684                cleaned.extend(kept);
685                // clap consumes the values of a `num_args(0..)` argument greedily, up to the next
686                // option-like argument, so the paths follow the flag until one of those.
687                while args.peek().is_some_and(|next| !looks_like_option(next)) {
688                    args.next();
689                }
690            }
691        }
692    }
693
694    cleaned.extend(deferred);
695    cleaned
696}
697
698/// Returns how `arg` relates to the `watch` flag.
699fn watch_flag(arg: &OsStr, value_less_short_flags: &HashSet<char>) -> WatchFlag {
700    let bytes = arg.as_encoded_bytes();
701    if bytes == b"--watch" || bytes == b"-w" {
702        return WatchFlag::Bare(None);
703    }
704    if bytes.starts_with(b"--watch=") {
705        return WatchFlag::Inline(None);
706    }
707    let Some(pos) = short_watch_pos(bytes, value_less_short_flags) else {
708        return WatchFlag::Other;
709    };
710    // Everything after `w` is the path attached to it; only the preceding valueless short flags
711    // are kept. The prefix is ASCII because it consists only of recognized option bytes.
712    let kept = (pos > 1).then(|| OsString::from(std::str::from_utf8(&bytes[..pos]).unwrap()));
713    if bytes.len() == pos + 1 { WatchFlag::Bare(kept) } else { WatchFlag::Inline(kept) }
714}
715
716/// Returns the byte index after `w` in a short flag cluster, if `arg` contains a watch flag.
717///
718/// clap parses a short flag cluster from left to right. Only short flags with no value in the
719/// active command may precede `w`; a value-taking flag such as `-D` or `-C` makes the remaining
720/// bytes its value instead.
721fn short_watch_pos(arg: &[u8], value_less_short_flags: &HashSet<char>) -> Option<usize> {
722    let cluster = arg.strip_prefix(b"-")?;
723    if cluster.is_empty() || cluster.starts_with(b"-") {
724        return None;
725    }
726    let pos = cluster.iter().position(|&byte| byte == b'w')?;
727    cluster[..pos]
728        .iter()
729        .all(|&byte| byte.is_ascii() && value_less_short_flags.contains(&(byte as char)))
730        .then_some(pos + 1)
731}
732
733/// Returns whether `arg` looks like an option, which is where clap stops consuming the values of a
734/// `num_args(0..)` argument. A lone `-` is a value.
735fn looks_like_option(arg: &OsStr) -> bool {
736    let bytes = arg.as_encoded_bytes();
737    bytes.len() > 1 && bytes.starts_with(b"-")
738}
739
740/// Returns valueless short flags and variable-arity long options for the active command.
741fn command_options(cmd_args: &[OsString]) -> (HashSet<char>, HashMap<String, usize>) {
742    let mut command = Forge::command();
743    let mut flags = HashSet::default();
744    let mut variable_options = HashMap::default();
745    if let Ok(matches) = command.try_get_matches_from_mut(cmd_args)
746        && let Some((name, _)) = matches.subcommand()
747        && let Some(command) = command.find_subcommand(name)
748    {
749        // Parsing builds the selected subcommand, including inherited global arguments.
750        for arg in command.get_arguments() {
751            let range = arg.get_num_args().unwrap_or_default();
752            if range.max_values() == 0 {
753                flags.extend(arg.get_short());
754                flags.extend(arg.get_all_short_aliases().unwrap_or_default());
755            } else if arg.get_id() != "watch"
756                && range.min_values() != range.max_values()
757                && let Some(long) = arg.get_long()
758            {
759                variable_options.insert(long.to_owned(), range.max_values());
760                for alias in arg.get_all_aliases().unwrap_or_default() {
761                    variable_options.insert(alias.to_owned(), range.max_values());
762                }
763            }
764        }
765    }
766    (flags, variable_options)
767}
768
769#[cfg(test)]
770mod tests {
771    use super::*;
772    use watchexec_events::Modifiers;
773
774    #[cfg(unix)]
775    use std::os::unix::ffi::OsStrExt;
776
777    fn key_event(key: char, modifiers: Modifiers) -> Event {
778        Event {
779            tags: vec![Tag::Keyboard(Keyboard::Key { key: KeyCode::Char(key), modifiers })],
780            ..Default::default()
781        }
782    }
783
784    fn clean(args: &[&str]) -> Vec<OsString> {
785        clean_cmd_args(args.iter().copied().map(OsString::from).collect())
786    }
787
788    #[test]
789    fn classifies_keyboard_actions() {
790        assert_eq!(
791            keyboard_action(&[key_event('a', Modifiers::default())]),
792            Some(KeyboardAction::Rerun)
793        );
794        assert_eq!(keyboard_action(&[key_event('x', Modifiers::default())]), None);
795        assert_eq!(
796            keyboard_action(&[key_event('a', Modifiers { ctrl: true, ..Default::default() })]),
797            None
798        );
799
800        let eof = Event { tags: vec![Tag::Keyboard(Keyboard::Eof)], ..Default::default() };
801        assert_eq!(
802            keyboard_action(&[key_event('a', Modifiers::default()), eof]),
803            Some(KeyboardAction::Quit)
804        );
805    }
806
807    fn file_event(kind: FileEventKind) -> Event {
808        Event {
809            tags: vec![
810                Tag::Path { path: PathBuf::from("src/A.sol"), file_type: None },
811                Tag::FileEventKind(kind),
812            ],
813            ..Default::default()
814        }
815    }
816
817    #[test]
818    fn classifies_watch_actions() {
819        let modify = file_event(FileEventKind::Modify(watchexec_events::filekind::ModifyKind::Any));
820        let open = file_event(FileEventKind::Access(AccessKind::Open(
821            watchexec_events::filekind::AccessMode::Any,
822        )));
823        let rerun = key_event('a', Modifiers::default());
824        let eof = Event { tags: vec![Tag::Keyboard(Keyboard::Eof)], ..Default::default() };
825        let other_key = key_event('x', Modifiers::default());
826
827        // Signals and the end of input quit, whatever the events.
828        assert_eq!(
829            watch_action(&[Signal::Interrupt], std::slice::from_ref(&modify), true),
830            WatchAction::Quit
831        );
832        assert_eq!(watch_action(&[Signal::Terminate], &[], false), WatchAction::Quit);
833        assert_eq!(watch_action(&[], &[rerun.clone(), eof], false), WatchAction::Quit);
834
835        // A keyboard rerun, a synthetic event or a file change runs the command.
836        assert_eq!(watch_action(&[], &[rerun], false), WatchAction::Run);
837        assert_eq!(watch_action(&[], &[Event::default()], false), WatchAction::Run);
838        assert_eq!(watch_action(&[], std::slice::from_ref(&modify), true), WatchAction::Run);
839        assert_eq!(watch_action(&[], &[open.clone(), modify], true), WatchAction::Run);
840
841        // Anything else is ignored.
842        assert_eq!(watch_action(&[], &[other_key], false), WatchAction::Ignore);
843        let opened = watch_action(&[], &[open], true);
844        if cfg!(target_os = "linux") {
845            assert_eq!(opened, WatchAction::Ignore);
846        } else {
847            assert_eq!(opened, WatchAction::Run);
848        }
849    }
850
851    fn path_event(path: &str) -> Event {
852        Event {
853            tags: vec![Tag::Path { path: PathBuf::from(path), file_type: None }],
854            ..Default::default()
855        }
856    }
857
858    #[test]
859    fn narrows_test_reruns_to_changed_test_file() {
860        let rerun = |events: &[Event], no_reconfigure| {
861            changed_test_rerun(events, &mut HashSet::default(), "/project", no_reconfigure)
862        };
863
864        assert_eq!(
865            rerun(&[path_event("/project/test/A.t.sol")], false),
866            TestRerun::MatchPath("test/A.t.sol".to_string())
867        );
868        assert_eq!(rerun(&[path_event("/project/test/A.t.sol")], true), TestRerun::Unchanged);
869        assert_eq!(
870            rerun(
871                &[path_event("/project/test/A.t.sol"), path_event("/project/test/B.t.sol")],
872                false
873            ),
874            TestRerun::Unchanged
875        );
876        assert_eq!(rerun(&[path_event("/project/src/A.sol")], false), TestRerun::Unchanged);
877
878        let mut last = HashSet::from_iter(["/project/test/B.t.sol".to_string()]);
879        assert_eq!(
880            changed_test_rerun(&[path_event("/project/src/A.sol")], &mut last, "/project", false),
881            TestRerun::MatchPath("test/B.t.sol".to_string())
882        );
883    }
884
885    #[test]
886    fn reruns_last_changed_test_file_after_source_change() {
887        let mut last = HashSet::default();
888        assert_eq!(
889            changed_test_rerun(
890                &[path_event("/project/test/A.t.sol")],
891                &mut last,
892                "/project",
893                false
894            ),
895            TestRerun::MatchPath("test/A.t.sol".to_string())
896        );
897        // A later change to a non-test file reruns the tests of the last changed test file.
898        assert_eq!(
899            changed_test_rerun(&[path_event("/project/src/A.sol")], &mut last, "/project", false),
900            TestRerun::MatchPath("test/A.t.sol".to_string())
901        );
902        // Multiple changed test files reset the selection for subsequent source changes.
903        assert_eq!(
904            changed_test_rerun(
905                &[path_event("/project/test/B.t.sol"), path_event("/project/test/C.t.sol")],
906                &mut last,
907                "/project",
908                false
909            ),
910            TestRerun::Unchanged
911        );
912        assert_eq!(
913            changed_test_rerun(&[path_event("/project/src/C.sol")], &mut last, "/project", false),
914            TestRerun::Unchanged
915        );
916    }
917
918    #[test]
919    fn reenables_keyboard_events_when_command_did_not_start() {
920        let config = Arc::new(watchexec::Config::default());
921        let keyboard_config = KeyboardConfig::default();
922        keyboard_config.set(Arc::downgrade(&config)).unwrap();
923        set_keyboard_events(&Some(keyboard_config.clone()), false);
924        assert!(!config.keyboard_events.get());
925
926        // A command that failed to spawn leaves the job pending rather than finished.
927        end_of_process(&CommandState::Pending, Some(keyboard_config));
928        assert!(config.keyboard_events.get());
929    }
930
931    #[test]
932    fn locked_survives_cleaning_watch_args() {
933        assert_eq!(
934            clean(&["forge", "build", "--locked", "--watch", "src", "test"]),
935            ["forge", "build", "--locked"]
936        );
937
938        assert_eq!(
939            clean(&["forge", "build", "--watch", "src", "--locked"]),
940            ["forge", "build", "--locked"]
941        );
942    }
943
944    #[test]
945    fn watch_spellings_survive_cleaning_watch_args() {
946        assert_eq!(clean(&["forge", "build", "-vw"]), ["forge", "build", "-v"]);
947        assert_eq!(clean(&["forge", "test", "--watch", "src"]), ["forge", "test"]);
948        assert_eq!(clean(&["forge", "test", "--watch=src"]), ["forge", "test"]);
949        assert_eq!(clean(&["forge", "test", "-w", "src"]), ["forge", "test"]);
950        assert_eq!(clean(&["forge", "test", "-wsrc"]), ["forge", "test"]);
951        assert_eq!(clean(&["forge", "test", "-vw", "src"]), ["forge", "test", "-v"]);
952        assert_eq!(clean(&["forge", "test", "-vwsrc"]), ["forge", "test", "-v"]);
953    }
954
955    #[test]
956    fn repeated_watch_survives_cleaning_watch_args() {
957        assert_eq!(
958            clean(&["forge", "test", "--watch", "src", "--watch", "test"]),
959            ["forge", "test"]
960        );
961
962        assert_eq!(clean(&["forge", "test", "--watch=src", "-w"]), ["forge", "test"]);
963        assert_eq!(clean(&["forge", "test", "-w", "--watch=src"]), ["forge", "test"]);
964    }
965
966    #[test]
967    fn other_flags_survive_cleaning_watch_args() {
968        // `--watch-delay` is a different flag.
969        assert_eq!(
970            clean(&["forge", "test", "--watch-delay", "1s"]),
971            ["forge", "test", "--watch-delay", "1s"]
972        );
973
974        // A `w` in the value attached to another short flag is not the watch flag.
975        assert_eq!(clean(&["forge", "test", "-C./workspace"]), ["forge", "test", "-C./workspace"]);
976
977        assert_eq!(clean(&["forge", "build", "-Dwarnings"]), ["forge", "build", "-Dwarnings"]);
978    }
979
980    #[test]
981    fn command_specific_short_flags_survive_cleaning_watch_args() {
982        assert_eq!(clean(&["forge", "build", "-qw", "src"]), ["forge", "build", "-q"]);
983        assert_eq!(clean(&["forge", "fmt", "-rw", "src"]), ["forge", "fmt", "-r"]);
984        assert_eq!(clean(&["forge", "b", "-vw"]), ["forge", "b", "-v"]);
985    }
986
987    #[test]
988    fn watch_cleanup_stops_after_double_dash() {
989        assert_eq!(
990            clean(&["forge", "fmt", "--watch", "src", "--", "--watch=keep.sol"]),
991            ["forge", "fmt", "--", "--watch=keep.sol"]
992        );
993    }
994
995    #[cfg(unix)]
996    #[test]
997    fn non_unicode_watch_survives_cleaning_watch_args() {
998        let mut args = ["forge", "test", "--watch"].map(OsString::from).to_vec();
999        args.push(OsStr::from_bytes(b"src/\xff").to_os_string());
1000
1001        assert_eq!(clean_cmd_args(args), ["forge", "test"]);
1002    }
1003
1004    #[cfg(unix)]
1005    #[test]
1006    fn non_unicode_watch_suffixes_and_options_are_preserved() {
1007        for path in [b"--watch=src/\xff".as_slice(), b"-wsrc/\xff".as_slice()] {
1008            let args = ["forge", "fmt"]
1009                .map(OsString::from)
1010                .into_iter()
1011                .chain([OsStr::from_bytes(path).to_os_string()])
1012                .collect();
1013            assert_eq!(clean_cmd_args(args), ["forge", "fmt"]);
1014        }
1015
1016        let args = ["forge", "build", "-w", "src"]
1017            .map(OsString::from)
1018            .into_iter()
1019            .chain([OsStr::from_bytes(b"--out=out/\xff").to_os_string()])
1020            .collect();
1021        assert_eq!(
1022            clean_cmd_args(args),
1023            vec![
1024                OsString::from("forge"),
1025                OsString::from("build"),
1026                OsStr::from_bytes(b"--out=out/\xff").to_os_string(),
1027            ]
1028        );
1029    }
1030
1031    #[cfg(unix)]
1032    #[test]
1033    fn non_unicode_program_path_is_preserved() {
1034        let args = vec![OsStr::from_bytes(b"forge\xff").to_os_string(), OsString::from("build")];
1035        let command = watch_command(args).unwrap();
1036        let Program::Exec { prog, args } = command.program else { panic!("expected exec program") };
1037        assert_eq!(prog, PathBuf::from(OsStr::from_bytes(b"forge\xff")));
1038        assert_eq!(args, ["build"]);
1039    }
1040
1041    #[test]
1042    fn watch_cleanup_preserves_argument_values() {
1043        for args in [
1044            vec!["forge", "build", "--optimize", "--watch=src", "src/Counter.sol", "--sizes"],
1045            vec!["forge", "snapshot", "--check", "--watch=src", "test/Counter.t.sol"],
1046            vec!["forge", "snapshot", "--optimize", "--check", "-wsrc", "test/Counter.t.sol"],
1047            vec![
1048                "forge",
1049                "snapshot",
1050                "--check",
1051                "--watch=src",
1052                "test/Counter.t.sol",
1053                "--snap",
1054                "custom",
1055            ],
1056            vec!["forge", "build", "--skip", "test", "script", "--watch=src", "src/Counter.sol"],
1057            vec![
1058                "forge",
1059                "build",
1060                "--skip",
1061                "test",
1062                "--watch=src",
1063                "src/Counter.sol",
1064                "--skip=script",
1065            ],
1066            vec!["forge", "build", "--optimize", "--watch=src", "--", "src/Counter.sol"],
1067        ] {
1068            let mut command = Forge::command();
1069            let parent = command.try_get_matches_from_mut(&args).unwrap();
1070            let child = Forge::command().try_get_matches_from(clean(&args)).unwrap();
1071            let (name, parent) = parent.subcommand().unwrap();
1072            let (_, child) = child.subcommand().unwrap();
1073            assert!(child.get_raw("watch").is_none(), "{args:?}");
1074            for arg in command.find_subcommand(name).unwrap().get_arguments() {
1075                let id = arg.get_id();
1076                if id == "watch" {
1077                    continue;
1078                }
1079                assert_eq!(
1080                    parent.get_raw(id.as_str()).map(|values| values.collect::<Vec<_>>()),
1081                    child.get_raw(id.as_str()).map(|values| values.collect::<Vec<_>>()),
1082                    "{args:?}: {id}"
1083                );
1084            }
1085        }
1086    }
1087
1088    #[test]
1089    fn watch_cleanup_preserves_program_name() {
1090        assert_eq!(clean(&["--watch=forge", "fmt", "--watch", "src"]), ["--watch=forge", "fmt"]);
1091    }
1092}