watchexec/src/main.rs

83 lines
1.8 KiB
Rust
Raw Normal View History

2016-09-14 15:30:59 +02:00
extern crate notify;
extern crate libc;
2016-09-14 22:11:35 +02:00
use std::env;
2016-09-14 15:30:59 +02:00
use libc::system;
2016-09-14 21:43:58 +02:00
use notify::{Event, RecommendedWatcher, Watcher};
2016-09-14 15:30:59 +02:00
use std::ffi::CString;
2016-09-14 22:11:35 +02:00
use std::path::{Path,PathBuf};
2016-09-14 15:30:59 +02:00
use std::string::String;
2016-09-14 21:43:58 +02:00
use std::sync::mpsc::{channel, Receiver, RecvError};
use std::{thread, time};
fn clear() {
let s = CString::new("clear").unwrap();
unsafe {
system(s.as_ptr());
}
}
2016-09-14 15:30:59 +02:00
2016-09-14 22:11:35 +02:00
fn ignored(relpath: &Path) -> bool {
if relpath.to_str().unwrap().starts_with(".") {
return true;
}
false
}
2016-09-14 15:30:59 +02:00
fn invoke(cmd: &String) {
let s = CString::new(cmd.clone()).unwrap();
unsafe {
system(s.as_ptr());
}
}
2016-09-14 22:11:35 +02:00
fn wait(rx: &Receiver<Event>, cwd: &PathBuf) -> Result<Event, RecvError> {
loop {
let e = try!(rx.recv());
let ignored = match e.path {
Some(ref path) => {
let stripped = path.strip_prefix(cwd).unwrap();
ignored(stripped)
},
None => false
};
2016-09-14 21:43:58 +02:00
2016-09-14 22:11:35 +02:00
if ignored {
continue;
}
2016-09-14 21:43:58 +02:00
2016-09-14 22:11:35 +02:00
thread::sleep(time::Duration::from_millis(250));
loop {
match rx.try_recv() {
Ok(_) => continue,
Err(_) => break,
}
2016-09-14 21:43:58 +02:00
}
2016-09-14 22:11:35 +02:00
return Ok(e);
}
2016-09-14 21:43:58 +02:00
}
2016-09-14 15:30:59 +02:00
fn main() {
2016-09-14 22:11:35 +02:00
let cmd = env::args().nth(1).expect("Argument 1 needs to be a command");
let cwd = env::current_dir().unwrap();
2016-09-14 15:30:59 +02:00
let (tx, rx) = channel();
let mut watcher: RecommendedWatcher = Watcher::new(tx)
.expect("unable to create watcher");
2016-09-14 20:19:05 +02:00
watcher.watch(".")
2016-09-14 15:30:59 +02:00
.expect("unable to start watching directory");
loop {
2016-09-14 22:11:35 +02:00
clear();
let e = wait(&rx, &cwd)
2016-09-14 21:43:58 +02:00
.expect("error when waiting for filesystem changes");
println!("{:?} {:?}", e.op, e.path);
invoke(&cmd);
2016-09-14 15:30:59 +02:00
}
}