1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use watchexec::{
    cli::Args,
    error::Result,
    pathop::PathOp,
    run::{ExecHandler, Handler},
};

pub struct CwHandler {
    cmd: String,
    once: bool,
    quiet: bool,
    inner: ExecHandler,
}

impl Handler for CwHandler {
    fn args(&self) -> Args {
        self.inner.args()
    }

    fn on_manual(&self) -> Result<bool> {
        if self.once {
            Ok(true)
        } else {
            self.start();
            self.inner.on_manual()
        }
    }

    fn on_update(&self, ops: &[PathOp]) -> Result<bool> {
        self.start();
        self.inner.on_update(ops)
    }
}

impl CwHandler {
    pub fn new(mut args: Args, quiet: bool) -> Result<Self> {
        let cmd = args.cmd.join(" && ");
        let mut final_cmd = cmd.clone();
        if !quiet {
            #[cfg(unix)]
            final_cmd.push_str("; echo [Finished running. Exit status: $?]");
            #[cfg(windows)]
            final_cmd.push_str(" & echo [Finished running. Exit status: %ERRORLEVEL%]");
            #[cfg(not(any(unix, windows)))]
            final_cmd.push_str(" ; echo [Finished running]");
            // ^ could be wrong depending on the platform, to be fixed on demand
        }

        args.cmd = vec![final_cmd];

        Ok(Self {
            once: args.once,
            cmd,
            inner: ExecHandler::new(args)?,
            quiet,
        })
    }

    fn start(&self) {
        if !self.quiet {
            println!("[Running '{}']", self.cmd);
        }
    }
}