watchexec/src/main.rs

243 lines
7.1 KiB
Rust
Raw Normal View History

#![feature(process_exec)]
2016-10-14 01:57:21 +02:00
#[macro_use]
2016-09-18 22:42:11 +02:00
extern crate clap;
2016-10-13 23:59:46 +02:00
extern crate env_logger;
extern crate libc;
2016-10-13 23:59:46 +02:00
#[macro_use]
extern crate log;
2016-10-22 21:37:03 +02:00
#[macro_use] extern crate lazy_static;
2016-09-18 22:42:11 +02:00
extern crate notify;
2016-09-14 15:30:59 +02:00
2016-10-22 21:37:03 +02:00
#[cfg(unix)] extern crate nix;
#[cfg(unix)] extern crate signal;
#[cfg(windows)] extern crate winapi;
#[cfg(windows)] extern crate kernel32;
2016-10-12 04:43:53 +02:00
mod gitignore;
2016-10-22 21:37:03 +02:00
mod interrupt_handler;
2016-09-23 21:52:50 +02:00
mod notification_filter;
mod runner;
mod watcher;
2016-09-21 23:02:20 +02:00
2016-09-14 21:43:58 +02:00
use std::sync::mpsc::{channel, Receiver, RecvError};
use std::{env, thread, time};
use std::path::{Path, PathBuf};
2016-09-18 22:42:11 +02:00
2016-10-12 15:43:22 +02:00
use clap::{App, Arg, ArgMatches};
2016-09-14 21:43:58 +02:00
2016-09-23 21:52:50 +02:00
use notification_filter::NotificationFilter;
use runner::Runner;
use watcher::{Event, Watcher};
2016-09-14 15:30:59 +02:00
// Starting at the specified path, search for gitignore files,
// stopping at the first one found.
fn find_gitignore_file(path: &Path) -> Option<PathBuf> {
let mut gitignore_path = path.join(".gitignore");
if gitignore_path.exists() {
return Some(gitignore_path);
}
let p = path.to_owned();
while let Some(p) = p.parent() {
gitignore_path = p.join(".gitignore");
if gitignore_path.exists() {
return Some(gitignore_path);
}
}
None
}
2016-10-12 15:43:22 +02:00
fn get_args<'a>() -> ArgMatches<'a> {
App::new("watchexec")
2016-10-14 01:57:21 +02:00
.version(crate_version!())
2016-09-23 21:49:55 +02:00
.about("Execute commands when watched files change")
2016-09-18 22:42:11 +02:00
.arg(Arg::with_name("path")
2016-09-23 21:49:55 +02:00
.help("Path to watch")
.short("w")
.long("watch")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.default_value("."))
2016-09-18 22:42:11 +02:00
.arg(Arg::with_name("command")
2016-09-23 21:49:55 +02:00
.help("Command to execute")
2016-09-21 23:02:20 +02:00
.multiple(true)
2016-09-18 22:42:11 +02:00
.required(true))
.arg(Arg::with_name("extensions")
.help("Comma-separated list of file extensions to watch (js,css,html)")
.short("e")
.long("exts")
.takes_value(true))
2016-09-18 22:42:11 +02:00
.arg(Arg::with_name("clear")
2016-09-23 21:49:55 +02:00
.help("Clear screen before executing command")
2016-09-18 22:42:11 +02:00
.short("c")
.long("clear"))
.arg(Arg::with_name("restart")
.help("Restart the process if it's still running")
.short("r")
.long("restart"))
.arg(Arg::with_name("debug")
.help("Print debugging messages to stderr")
.short("d")
.long("debug"))
2016-09-21 23:02:20 +02:00
.arg(Arg::with_name("filter")
2016-09-23 21:49:55 +02:00
.help("Ignore all modifications except those matching the pattern")
2016-09-21 23:02:20 +02:00
.short("f")
.long("filter")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
2016-09-21 23:02:20 +02:00
.arg(Arg::with_name("ignore")
2016-09-23 21:49:55 +02:00
.help("Ignore modifications to paths matching the pattern")
2016-09-21 23:02:20 +02:00
.short("i")
.long("ignore")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
2016-10-12 15:43:22 +02:00
.arg(Arg::with_name("no-vcs-ignore")
.help("Skip auto-loading of .gitignore files for filtering")
.long("no-vcs-ignore"))
.arg(Arg::with_name("run-initially")
.help("Run command initially, before first file change")
.long("run-initially"))
2016-10-20 02:19:01 +02:00
.arg(Arg::with_name("poll")
.help("Forces polling mode")
.long("force-poll")
.value_name("interval"))
2016-10-12 15:43:22 +02:00
.get_matches()
}
2016-09-14 22:50:14 +02:00
fn init_logger(debug: bool) {
2016-10-13 23:59:46 +02:00
let mut log_builder = env_logger::LogBuilder::new();
2016-10-18 15:39:40 +02:00
let level = if debug {
log::LogLevelFilter::Debug
} else {
log::LogLevelFilter::Warn
};
2016-10-13 23:59:46 +02:00
log_builder
.format(|r| format!("*** {}", r.args()))
.filter(None, level);
log_builder.init().expect("unable to initialize logger");
}
2016-10-12 15:43:22 +02:00
fn main() {
let args = get_args();
2016-10-13 23:59:46 +02:00
init_logger(args.is_present("debug"));
2016-09-21 23:02:20 +02:00
2016-10-12 15:43:22 +02:00
let cwd = env::current_dir()
.expect("unable to get cwd")
.canonicalize()
.expect("unable to canonicalize cwd");
2016-10-12 04:43:53 +02:00
let mut gitignore_file = None;
2016-10-12 15:43:22 +02:00
if !args.is_present("no-vcs-ignore") {
if let Some(gitignore_path) = find_gitignore_file(&cwd) {
2016-10-14 01:47:04 +02:00
debug!("Found .gitignore file: {:?}", gitignore_path);
2016-10-12 04:43:53 +02:00
2016-10-12 15:43:22 +02:00
gitignore_file = gitignore::parse(&gitignore_path).ok();
}
2016-10-12 04:43:53 +02:00
}
let mut filter = NotificationFilter::new(&cwd, gitignore_file).expect("unable to create notification filter");
2016-09-21 23:02:20 +02:00
2016-09-24 20:06:51 +02:00
// Add default ignore list
let dotted_dirs = Path::new(".*").join("*");
2016-10-14 02:23:38 +02:00
let default_filters = vec!["*/.DS_Store", "*.pyc", "*.swp", dotted_dirs.to_str().unwrap()];
2016-09-21 23:02:20 +02:00
for p in default_filters {
filter.add_ignore(p).expect("bad default filter");
}
if let Some(extensions) = args.values_of("extensions") {
for ext in extensions {
filter.add_extension(ext).expect("bad extension");
}
}
2016-09-21 23:02:20 +02:00
if let Some(filters) = args.values_of("filter") {
for p in filters {
filter.add_filter(p).expect("bad filter");
}
}
if let Some(ignores) = args.values_of("ignore") {
for i in ignores {
filter.add_ignore(i).expect("bad ignore pattern");
}
}
2016-09-14 15:30:59 +02:00
let (tx, rx) = channel();
2016-10-20 16:07:55 +02:00
// TODO: die on invalid input, seems to be a clap issue
let interval = value_t!(args.value_of("poll"), u32).unwrap_or(1000);
let force_poll = args.is_present("poll");
let mut watcher = Watcher::new(tx, force_poll, interval)
.expect("unable to create watcher");
2016-10-20 02:19:01 +02:00
if watcher.is_polling() {
warn!("Polling for changes every {} ms", interval);
}
2016-09-18 22:42:11 +02:00
let paths = args.values_of("path").unwrap();
for path in paths {
2016-09-27 15:43:28 +02:00
match Path::new(path).canonicalize() {
Ok(canonicalized) => watcher.watch(canonicalized).expect("unable to watch path"),
Err(_) => {
println!("invalid path: {}", path);
return;
}
}
2016-09-18 22:42:11 +02:00
}
2016-09-21 23:02:20 +02:00
let cmd_parts: Vec<&str> = args.values_of("command").unwrap().collect();
let cmd = cmd_parts.join(" ");
2016-10-13 23:59:46 +02:00
let mut runner = Runner::new(args.is_present("restart"), args.is_present("clear"));
2016-09-14 15:30:59 +02:00
if args.is_present("run-initially") {
runner.run_command(&cmd, vec![]);
}
2016-09-14 15:30:59 +02:00
loop {
2016-10-13 23:59:46 +02:00
let e = wait(&rx, &filter).expect("error when waiting for filesystem changes");
2016-10-13 23:59:46 +02:00
debug!("{:?}: {:?}", e.op, e.path);
2016-09-14 21:43:58 +02:00
// TODO: update wait to return all paths
let updated: Vec<&str> = e.path
.iter()
.map(|p| p.to_str().unwrap())
.collect();
runner.run_command(&cmd, updated);
2016-09-14 15:30:59 +02:00
}
}
2016-10-12 15:43:22 +02:00
2016-10-13 23:59:46 +02:00
fn wait(rx: &Receiver<Event>, filter: &NotificationFilter) -> Result<Event, RecvError> {
2016-10-12 15:43:22 +02:00
loop {
// Block on initial notification
let e = try!(rx.recv());
if let Some(ref path) = e.path {
2016-10-18 15:39:40 +02:00
if filter.is_excluded(path) {
2016-10-12 15:43:22 +02:00
continue;
}
}
// Accumulate subsequent events
thread::sleep(time::Duration::from_millis(250));
// Drain rx buffer and drop them
2016-10-18 15:39:40 +02:00
while let Ok(_) = rx.try_recv() {
// nothing to do here
2016-10-12 15:43:22 +02:00
}
return Ok(e);
}
}