Implement most existing options and mark the rest

This commit is contained in:
Félix Saparelli 2021-08-24 22:45:31 +12:00
parent 6767948daa
commit 58b37940b8
3 changed files with 254 additions and 131 deletions

View File

@ -11,128 +11,129 @@ use color_eyre::eyre::{Context, Report, Result};
pub fn get_args() -> Result<ArgMatches<'static>> { pub fn get_args() -> Result<ArgMatches<'static>> {
let app = App::new("watchexec") let app = App::new("watchexec")
.version(crate_version!()) .version(crate_version!())
.about("Execute commands when watched files change") .about("Execute commands when watched files change")
.after_help("Use @argfile as first argument to load arguments from the file `argfile` (one argument per line) which will be inserted in place of the @argfile (further arguments on the CLI will override or add onto those in the file).") .after_help("Use @argfile as first argument to load arguments from the file `argfile` (one argument per line) which will be inserted in place of the @argfile (further arguments on the CLI will override or add onto those in the file).")
.arg(Arg::with_name("command") .arg(Arg::with_name("command")
.help("Command to execute") .help("Command to execute")
.multiple(true) .multiple(true)
.required(true)) .required(true))
.arg(Arg::with_name("extensions") .arg(Arg::with_name("extensions") // TODO
.help("Comma-separated list of file extensions to watch (e.g. js,css,html)") .help("Comma-separated list of file extensions to watch (e.g. js,css,html)")
.short("e") .short("e")
.long("exts") .long("exts")
.takes_value(true)) .takes_value(true))
.arg(Arg::with_name("path") .arg(Arg::with_name("paths")
.help("Watch a specific file or directory") .help("Watch a specific file or directory")
.short("w") .short("w")
.long("watch") .long("watch")
.number_of_values(1) .number_of_values(1)
.multiple(true) .multiple(true)
.takes_value(true)) .takes_value(true))
.arg(Arg::with_name("clear") .arg(Arg::with_name("clear")
.help("Clear screen before executing command") .help("Clear screen before executing command")
.short("c") .short("c")
.long("clear")) .long("clear"))
.arg(Arg::with_name("on-busy-update") .arg(Arg::with_name("on-busy-update")
.help("Select the behaviour to use when receiving events while the command is running. Current default is queue, will change to do-nothing in 2.0.") .help("Select the behaviour to use when receiving events while the command is running. Current default is queue, will change to do-nothing in 2.0.")
.takes_value(true) .takes_value(true)
.possible_values(&["do-nothing", "queue", "restart", "signal"]) .possible_values(&["do-nothing", "queue", "restart", "signal"])
.long("on-busy-update")) .long("on-busy-update"))
.arg(Arg::with_name("restart") .arg(Arg::with_name("restart")
.help("Restart the process if it's still running. Shorthand for --on-busy-update=restart") .help("Restart the process if it's still running. Shorthand for --on-busy-update=restart")
.short("r") .short("r")
.long("restart")) .long("restart"))
.arg(Arg::with_name("signal") .arg(Arg::with_name("signal")
.help("Send signal to process upon changes, e.g. SIGHUP") .help("Specify the signal to send when using --on-busy-update=signal")
.short("s") .short("s")
.long("signal") .long("signal")
.takes_value(true) .takes_value(true)
.number_of_values(1) .value_name("signal")
.value_name("signal")) .default_value("SIGTERM")
.arg(Arg::with_name("kill") .hidden(cfg!(windows)))
.hidden(true) .arg(Arg::with_name("kill")
.short("k") .hidden(true)
.long("kill")) .short("k")
.arg(Arg::with_name("debounce") .long("kill"))
.help("Set the timeout between detected change and command execution, defaults to 100ms") .arg(Arg::with_name("debounce")
.takes_value(true) .help("Set the timeout between detected change and command execution, defaults to 100ms")
.value_name("milliseconds") .takes_value(true)
.short("d") .value_name("milliseconds")
.long("debounce")) .short("d")
.long("debounce"))
.arg(Arg::with_name("verbose") .arg(Arg::with_name("verbose")
.help("Print debugging messages to stderr") .help("Print debugging messages (-v, -vv, -vvv; use -vvv for bug reports)")
.short("v") .multiple(true)
.long("verbose")) .short("v")
.arg(Arg::with_name("changes") .long("verbose"))
.help("Only print path change information. Overridden by --verbose") .arg(Arg::with_name("print-events")
.long("changes-only")) .help("Print events that trigger actions")
.long("print-events")
.arg(Arg::with_name("filter") .alias("changes-only")) // --changes-only is deprecated (remove at v2)
.help("Ignore all modifications except those matching the pattern") .arg(Arg::with_name("filter") // TODO
.short("f") .help("Ignore all modifications except those matching the pattern")
.long("filter") .short("f")
.number_of_values(1) .long("filter")
.multiple(true) .number_of_values(1)
.takes_value(true) .multiple(true)
.value_name("pattern")) .takes_value(true)
.arg(Arg::with_name("ignore") .value_name("pattern"))
.help("Ignore modifications to paths matching the pattern") .arg(Arg::with_name("ignore") // TODO
.short("i") .help("Ignore modifications to paths matching the pattern")
.long("ignore") .short("i")
.number_of_values(1) .long("ignore")
.multiple(true) .number_of_values(1)
.takes_value(true) .multiple(true)
.value_name("pattern")) .takes_value(true)
.arg(Arg::with_name("no-vcs-ignore") .value_name("pattern"))
.help("Skip auto-loading of .gitignore files for filtering") .arg(Arg::with_name("no-vcs-ignore") // TODO
.long("no-vcs-ignore")) .help("Skip auto-loading of .gitignore files for filtering")
.arg(Arg::with_name("no-ignore") .long("no-vcs-ignore"))
.help("Skip auto-loading of ignore files (.gitignore, .ignore, etc.) for filtering") .arg(Arg::with_name("no-ignore") // TODO
.long("no-ignore")) .help("Skip auto-loading of ignore files (.gitignore, .ignore, etc.) for filtering")
.arg(Arg::with_name("no-default-ignore") .long("no-ignore"))
.help("Skip auto-ignoring of commonly ignored globs") .arg(Arg::with_name("no-default-ignore") // TODO
.long("no-default-ignore")) .help("Skip auto-ignoring of commonly ignored globs")
.arg(Arg::with_name("postpone") .long("no-default-ignore"))
.help("Wait until first change to execute command") .arg(Arg::with_name("postpone")
.short("p") .help("Wait until first change to execute command")
.long("postpone")) .short("p")
.arg(Arg::with_name("poll") .long("postpone"))
.help("Force polling mode (interval in milliseconds)") .arg(Arg::with_name("poll")
.long("force-poll") .help("Force polling mode (interval in milliseconds)")
.value_name("interval")) .long("force-poll")
.arg(Arg::with_name("shell") .value_name("interval"))
.help(if cfg!(windows) { .arg(Arg::with_name("shell")
"Use a different shell, or `none`. Try --shell=powershell, which will become the default in 2.0." .help(if cfg!(windows) {
} else { "Use a different shell, or `none`. Try --shell=powershell, which will become the default in 2.0."
"Use a different shell, or `none`. E.g. --shell=bash" } else {
}) "Use a different shell, or `none`. E.g. --shell=bash"
.takes_value(true) })
.long("shell")) .takes_value(true)
// -n short form will not be removed, and instead become a shorthand for --shell=none .long("shell"))
.arg(Arg::with_name("no-shell") // -n short form will not be removed, and instead become a shorthand for --shell=none
.help("Do not wrap command in a shell. Deprecated: use --shell=none instead.") .arg(Arg::with_name("no-shell")
.short("n") .help("Do not wrap command in a shell. Deprecated: use --shell=none instead.")
.long("no-shell")) .short("n")
.arg(Arg::with_name("no-meta") .long("no-shell"))
.help("Ignore metadata changes") .arg(Arg::with_name("no-meta") // TODO
.long("no-meta")) .help("Ignore metadata changes")
.arg(Arg::with_name("no-environment") .long("no-meta"))
.help("Do not set WATCHEXEC_*_PATH environment variables for the command") .arg(Arg::with_name("no-environment") // TODO
.long("no-environment")) .help("Do not set WATCHEXEC_*_PATH environment variables for the command")
.arg(Arg::with_name("no-process-group") .long("no-environment"))
.help("Do not use a process group when running the command") .arg(Arg::with_name("no-process-group") // TODO
.long("no-process-group")) .help("Do not use a process group when running the command")
.arg(Arg::with_name("once").short("1").hidden(true)) .long("no-process-group"))
.arg(Arg::with_name("watch-when-idle") .arg(Arg::with_name("once").short("1").hidden(true))
.help("Deprecated alias for --on-busy-update=do-nothing, which will become the default in 2.0.") .arg(Arg::with_name("watch-when-idle")
.short("W") .help("Deprecated alias for --on-busy-update=do-nothing, which will become the default in 2.0.")
.long("watch-when-idle")) .short("W")
.arg(Arg::with_name("notif") .long("watch-when-idle"))
.help("Send a desktop notification when watchexec notices a change (experimental, behaviour may change)") .arg(Arg::with_name("notif") // TODO
.short("N") .help("Send a desktop notification when watchexec notices a change (experimental, behaviour may change)")
.long("notify")); .short("N")
.long("notify"));
let mut raw_args: Vec<OsString> = env::args_os().collect(); let mut raw_args: Vec<OsString> = env::args_os().collect();

View File

@ -1,25 +1,139 @@
use std::{
convert::Infallible, env::current_dir, io::stderr, path::Path, str::FromStr, time::Duration,
};
use clap::ArgMatches; use clap::ArgMatches;
use color_eyre::eyre::{eyre, Result}; use color_eyre::eyre::{eyre, Result};
use watchexec::{ use watchexec::{
action::{Action, Outcome, Signal},
command::Shell, command::Shell,
config::{InitConfig, RuntimeConfig}, config::{InitConfig, RuntimeConfig},
event::Event,
fs::Watcher,
handler::PrintDisplay,
}; };
pub fn new(args: &ArgMatches<'static>) -> Result<(InitConfig, RuntimeConfig)> { pub fn new(args: &ArgMatches<'static>) -> Result<(InitConfig, RuntimeConfig)> {
Ok((init(&args)?, runtime(&args)?)) Ok((init(args)?, runtime(args)?))
} }
fn init(args: &ArgMatches<'static>) -> Result<InitConfig> { fn init(_args: &ArgMatches<'static>) -> Result<InitConfig> {
let mut config = InitConfig::builder(); let mut config = InitConfig::builder();
Ok(config.build()?) config.on_error(PrintDisplay(stderr()));
Ok(config.build()?)
} }
fn runtime(args: &ArgMatches<'static>) -> Result<RuntimeConfig> { fn runtime(args: &ArgMatches<'static>) -> Result<RuntimeConfig> {
let mut config = RuntimeConfig::default(); let mut config = RuntimeConfig::default();
config.command(
args.values_of_lossy("command")
.ok_or_else(|| eyre!("(clap) Bug: command is not present"))?
.iter(),
);
Ok(config) config.pathset(match args.values_of_os("paths") {
Some(paths) => paths.map(|os| Path::new(os).to_owned()).collect(),
None => vec![current_dir()?],
});
config.action_throttle(Duration::from_millis(
args.value_of("debounce").unwrap_or("100").parse()?,
));
if let Some(interval) = args.value_of("poll") {
config.file_watcher(Watcher::Poll(Duration::from_millis(interval.parse()?)));
}
config.command_shell(if args.is_present("no-shell") {
Shell::None
} else if let Some(s) = args.value_of("shell") {
if s.eq_ignore_ascii_case("powershell") {
Shell::Powershell
} else if s.eq_ignore_ascii_case("none") {
Shell::None
} else if s.eq_ignore_ascii_case("cmd") {
cmd_shell(s.into())
} else {
Shell::Unix(s.into())
}
} else {
default_shell()
});
let clear = args.is_present("clear");
let mut on_busy = args
.value_of("on-busy-update")
.unwrap_or("queue")
.to_owned();
if args.is_present("restart") {
on_busy = "restart".into();
}
if args.is_present("watch-when-idle") {
on_busy = "do-nothing".into();
}
let mut signal = args
.value_of("signal")
.map(|s| Signal::from_str(s))
.transpose()?
.unwrap_or(Signal::SIGTERM);
if args.is_present("kill") {
signal = Signal::SIGKILL;
}
let print_events = args.is_present("print-events");
let once = args.is_present("once");
config.on_action(move |action: Action| {
let fut = async { Ok::<(), Infallible>(()) };
if print_events {
for event in &action.events {
for path in event.paths() {
eprintln!("[EVENT] Path: {}", path.display());
}
for signal in event.signals() {
eprintln!("[EVENT] Signal: {:?}", signal);
}
}
}
if once && !action.events.iter().any(|e| e == &Event::default()) {
action.outcome(Outcome::Exit);
return fut;
}
let when_running = match (clear, on_busy.as_str()) {
(_, "do-nothing") => Outcome::DoNothing,
(true, "restart") => {
Outcome::both(Outcome::Stop, Outcome::both(Outcome::Clear, Outcome::Start))
}
(false, "restart") => Outcome::both(Outcome::Stop, Outcome::Start),
(_, "signal") => Outcome::Signal(signal),
// (true, "queue") => Outcome::wait(Outcome::both(Outcome::Clear, Outcome::Start)),
// (false, "queue") => Outcome::wait(Outcome::Start),
_ => Outcome::DoNothing,
};
let when_idle = if clear {
Outcome::both(Outcome::Clear, Outcome::Start)
} else {
Outcome::Start
};
action.outcome(Outcome::if_running(when_running, when_idle));
fut
});
Ok(config)
} }
// until 2.0 // until 2.0

View File

@ -2,7 +2,7 @@ use std::env::var;
use color_eyre::eyre::Result; use color_eyre::eyre::Result;
use tracing_subscriber::filter::LevelFilter; use tracing_subscriber::filter::LevelFilter;
use watchexec::Watchexec; use watchexec::{event::Event, Watchexec};
mod args; mod args;
mod config; mod config;
@ -19,16 +19,24 @@ async fn main() -> Result<()> {
if args.is_present("verbose") { if args.is_present("verbose") {
tracing_subscriber::fmt() tracing_subscriber::fmt()
.with_max_level(LevelFilter::DEBUG) .with_max_level(match args.occurrences_of("verbose") {
0 => unreachable!(),
1 => LevelFilter::INFO,
2 => LevelFilter::DEBUG,
_ => LevelFilter::TRACE,
})
.try_init() .try_init()
.ok(); .ok();
} }
let (init, runtime) = config::new(&args)?; let (init, runtime) = config::new(&args)?;
let config = runtime.clone();
let wx = Watchexec::new(init, runtime)?; let wx = Watchexec::new(init, runtime)?;
if !args.is_present("postpone") {
wx.send_event(Event::default()).await?;
}
wx.main().await??; wx.main().await??;
Ok(()) Ok(())