runwhen/src/file.rs

173 lines
5.2 KiB
Rust
Raw Normal View History

2017-01-29 16:39:48 -06:00
// Copyright 2017 Jeremy Wall <jeremy@marzhillstudios.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
2017-01-29 16:39:48 -06:00
use notify::{watcher, RecursiveMode, Watcher};
2017-01-29 16:39:48 -06:00
use error::CommandError;
use events::WatchEventType;
2022-08-24 14:19:52 -04:00
use exec::CancelableProcess;
use traits::Process;
2017-01-29 16:39:48 -06:00
pub struct FileProcess<'a> {
cmd: &'a str,
2022-08-24 14:19:52 -04:00
env: Option<Vec<String>>,
2022-05-31 23:00:59 -04:00
files: Vec<&'a str>,
2017-01-29 16:39:48 -06:00
method: WatchEventType,
poll: Duration,
}
impl<'a> FileProcess<'a> {
pub fn new(
cmd: &'a str,
2022-08-24 14:19:52 -04:00
env: Option<Vec<String>>,
2022-05-31 23:00:59 -04:00
file: Vec<&'a str>,
method: WatchEventType,
poll: Duration,
) -> FileProcess<'a> {
FileProcess {
2022-08-24 14:19:52 -04:00
cmd,
env,
method,
poll,
2022-05-31 23:00:59 -04:00
files: file,
}
2017-01-29 16:39:48 -06:00
}
}
fn spawn_runner_thread(
lock: Arc<Mutex<bool>>,
cmd: String,
2022-08-24 14:19:52 -04:00
env: Option<Vec<String>>,
poll: Duration,
) {
let copied_env = env.and_then(|v| {
Some(
v.iter()
.cloned()
.map(|s| String::from(s))
.collect::<Vec<String>>(),
)
});
2017-01-29 16:39:48 -06:00
thread::spawn(move || {
2022-08-24 14:19:52 -04:00
let mut exec = CancelableProcess::new(&cmd, copied_env);
exec.spawn().expect("Failed to start command");
2017-01-29 16:39:48 -06:00
loop {
// Wait our requisit number of seconds
thread::sleep(poll);
// Default to not running the command.
2022-08-24 14:19:52 -04:00
if !run_loop_step(lock.clone(), &mut exec) {
exec.reset().expect("Failed to start command");
2017-01-29 16:39:48 -06:00
}
}
});
}
2022-08-24 14:19:52 -04:00
fn run_loop_step(lock: Arc<Mutex<bool>>, exec: &mut CancelableProcess) -> bool {
match lock.lock() {
Ok(mut signal) => {
// We always want to check on our process each iteration of the loop.
if let Err(err) = exec.check() {
println!("{:?}", err);
return false;
}
if *signal {
// set signal to false so we won't trigger on the
// next loop iteration unless we recieved more events.
*signal = false;
// On a true signal we want to start or restart our process.
if let Err(err) = exec.reset() {
println!("{:?}", err);
return false;
}
}
return true;
}
Err(err) => {
println!("Unexpected error; {}", err);
return false;
}
}
}
fn wait_for_fs_events(
lock: Arc<Mutex<bool>>,
method: WatchEventType,
2022-05-31 23:00:59 -04:00
files: &Vec<&str>,
) -> Result<(), CommandError> {
2017-01-29 16:39:48 -06:00
// Notify requires a channel for communication.
let (tx, rx) = channel();
let mut watcher = watcher(tx, Duration::from_secs(1))?;
2017-01-29 16:39:48 -06:00
// TODO(jwall): Better error handling.
2022-05-31 23:00:59 -04:00
for file in files {
// NOTE(jwall): this is necessary because notify::fsEventWatcher panics
// if the path doesn't exist. :-(
if !Path::new(*file).exists() {
return Err(CommandError::new(
format!("No such path! {0}", *file).to_string(),
));
}
watcher.watch(*file, RecursiveMode::Recursive)?;
println!("Watching {:?}", *file);
}
2017-01-29 16:39:48 -06:00
loop {
let evt: WatchEventType = match rx.recv() {
Ok(event) => WatchEventType::from(event),
Err(_) => WatchEventType::Error,
2017-01-29 16:39:48 -06:00
};
match evt {
WatchEventType::Ignore => {
// We ignore this one.
}
2017-01-29 16:39:48 -06:00
WatchEventType::Error => {
// We log this one.
}
2017-01-29 16:39:48 -06:00
WatchEventType::Touched => {
if method == WatchEventType::Touched {
let mut signal = lock.lock().unwrap();
2017-01-29 16:39:48 -06:00
*signal = true;
2022-05-31 23:00:59 -04:00
} else {
println!("Ignoring touched event");
2017-01-29 16:39:48 -06:00
}
}
WatchEventType::Changed => match lock.lock() {
Ok(mut signal) => *signal = true,
Err(err) => {
println!("Unexpected error; {}", err);
return Ok(());
}
},
2017-01-29 16:39:48 -06:00
}
}
}
impl<'a> Process for FileProcess<'a> {
2022-08-24 14:19:52 -04:00
fn run(&mut self) -> Result<(), CommandError> {
// TODO(jeremy): Is this sufficent or do we want to ignore
// any events that come in while the command is running?
let lock = Arc::new(Mutex::new(false));
spawn_runner_thread(
lock.clone(),
self.cmd.to_string(),
self.env.clone(),
self.poll,
);
2022-05-31 23:00:59 -04:00
wait_for_fs_events(lock, self.method.clone(), &self.files)
2017-01-29 16:39:48 -06:00
}
}