runwhen/src/file.rs

161 lines
4.8 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;
2023-08-14 18:56:34 -04:00
use std::sync::mpsc::{channel, Receiver, Sender};
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,
2023-08-14 18:56:34 -04:00
poll: Option<Duration>,
2017-01-29 16:39:48 -06:00
}
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,
2023-08-14 18:56:34 -04:00
poll: Option<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
}
}
2023-08-14 18:56:34 -04:00
fn watch_for_change_events(
ch: Receiver<()>,
cmd: String,
2022-08-24 14:19:52 -04:00
env: Option<Vec<String>>,
2023-08-14 18:56:34 -04:00
poll: Option<Duration>,
) {
let copied_env = env.and_then(|v| {
Some(
v.iter()
.cloned()
.map(|s| String::from(s))
.collect::<Vec<String>>(),
)
});
2023-08-14 18:56:34 -04:00
let mut exec = CancelableProcess::new(&cmd, copied_env);
println!("Spawning command");
exec.spawn().expect("Failed to start command");
println!("Starting watch loop");
loop {
// Wait our requisit number of seconds
if let Some(poll) = poll {
thread::sleep(dbg!(poll));
2017-01-29 16:39:48 -06:00
}
2023-08-14 18:56:34 -04:00
//if let Err(err) = exec.check() {
// println!("Error running command! {}", err);
// println!("Continuing");
//};
// Default to not running the command.
if !run_loop_step(&ch, &mut exec) {
println!("Failed to start command");
}
}
2017-01-29 16:39:48 -06:00
}
2023-08-14 18:56:34 -04:00
fn run_loop_step(ch: &Receiver<()>, exec: &mut CancelableProcess) -> bool {
let _ = ch.recv().unwrap();
// We always want to check on our process each iteration of the loop.
// set signal to false so we won't trigger on the
// next loop iteration unless we recieved more events.
// On a true signal we want to start or restart our process.
println!("Restarting process");
if let Err(err) = exec.reset() {
println!("{:?}", err);
return false;
2022-08-24 14:19:52 -04:00
}
2023-08-14 18:56:34 -04:00
return true;
2022-08-24 14:19:52 -04:00
}
fn wait_for_fs_events(
2023-08-14 18:56:34 -04:00
ch: Sender<()>,
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))?;
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),
2023-08-14 18:56:34 -04:00
Err(e) => {
println!("Watch Error: {}", e);
WatchEventType::Error
}
2017-01-29 16:39:48 -06:00
};
match evt {
2023-08-14 18:56:34 -04:00
WatchEventType::Ignore | WatchEventType::Error => {
// We ignore these.
//println!("Event: Ignore");
}
2017-01-29 16:39:48 -06:00
WatchEventType::Touched => {
if method == WatchEventType::Touched {
2023-08-14 18:56:34 -04:00
ch.send(()).unwrap();
2017-01-29 16:39:48 -06:00
}
}
2023-08-14 18:56:34 -04:00
WatchEventType::Changed => {
ch.send(()).unwrap();
}
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?
2023-08-14 18:56:34 -04:00
let (tx, rx) = channel();
thread::spawn({
let cmd = self.cmd.to_string();
let env = self.env.clone();
let poll = self.poll.clone();
move || {
watch_for_change_events(rx, cmd, env, poll);
}
});
wait_for_fs_events(tx, self.method.clone(), &self.files)?;
Ok(())
2017-01-29 16:39:48 -06:00
}
}