Normalizing formatting with cargo fmt

This commit is contained in:
Jeremy Wall 2017-02-02 19:23:01 -06:00
parent 6d2ebc40fb
commit 3641b1b238
6 changed files with 81 additions and 55 deletions

View File

@ -23,9 +23,7 @@ pub struct CommandError {
impl CommandError { impl CommandError {
pub fn new(msg: String) -> CommandError { pub fn new(msg: String) -> CommandError {
CommandError{ CommandError { msg: msg }
msg: msg
}
} }
} }

View File

@ -18,7 +18,7 @@ pub enum WatchEventType {
Touched, Touched,
Changed, Changed,
Error, Error,
Ignore Ignore,
} }
impl From<DebouncedEvent> for WatchEventType { impl From<DebouncedEvent> for WatchEventType {
@ -32,7 +32,7 @@ impl From<DebouncedEvent> for WatchEventType {
DebouncedEvent::NoticeRemove(_) => WatchEventType::Ignore, DebouncedEvent::NoticeRemove(_) => WatchEventType::Ignore,
DebouncedEvent::NoticeWrite(_) => WatchEventType::Ignore, DebouncedEvent::NoticeWrite(_) => WatchEventType::Ignore,
DebouncedEvent::Rescan => WatchEventType::Ignore, DebouncedEvent::Rescan => WatchEventType::Ignore,
DebouncedEvent::Error(_, _) => WatchEventType::Ignore DebouncedEvent::Error(_, _) => WatchEventType::Ignore,
} }
} }
} }

View File

@ -14,7 +14,7 @@
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use subprocess::{Exec,PopenError,ExitStatus}; use subprocess::{Exec, PopenError, ExitStatus};
use traits::Process; use traits::Process;
use error::CommandError; use error::CommandError;
@ -39,7 +39,11 @@ pub struct ExecProcess<'a> {
impl<'a> ExecProcess<'a> { impl<'a> ExecProcess<'a> {
pub fn new(test_cmd: &'a str, cmd: &'a str, poll: Duration) -> ExecProcess<'a> { pub fn new(test_cmd: &'a str, cmd: &'a str, poll: Duration) -> ExecProcess<'a> {
ExecProcess{test_cmd: test_cmd, cmd: cmd, poll: poll} ExecProcess {
test_cmd: test_cmd,
cmd: cmd,
poll: poll,
}
} }
} }

View File

@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::thread; use std::thread;
use std::sync::{Arc,Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use std::path::Path; use std::path::Path;
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use notify::{Watcher,RecursiveMode,watcher}; use notify::{Watcher, RecursiveMode, watcher};
use traits::Process; use traits::Process;
use error::CommandError; use error::CommandError;
@ -32,8 +32,17 @@ pub struct FileProcess<'a> {
} }
impl<'a> FileProcess<'a> { impl<'a> FileProcess<'a> {
pub fn new(cmd: &'a str, file: &'a str, method: WatchEventType, poll: Duration) -> FileProcess<'a> { pub fn new(cmd: &'a str,
FileProcess{ cmd: cmd, file: file, method: method, poll: poll} file: &'a str,
method: WatchEventType,
poll: Duration)
-> FileProcess<'a> {
FileProcess {
cmd: cmd,
file: file,
method: method,
poll: poll,
}
} }
} }
@ -57,7 +66,10 @@ fn spawn_runner_thread(lock: Arc<Mutex<bool>>, cmd: String, poll: Duration) {
}); });
} }
fn wait_for_fs_events(lock: Arc<Mutex<bool>>, method: WatchEventType, file: &str) -> Result<(), CommandError> { fn wait_for_fs_events(lock: Arc<Mutex<bool>>,
method: WatchEventType,
file: &str)
-> Result<(), CommandError> {
// Notify requires a channel for communication. // Notify requires a channel for communication.
let (tx, rx) = channel(); let (tx, rx) = channel();
let mut watcher = try!(watcher(tx, Duration::from_secs(1))); let mut watcher = try!(watcher(tx, Duration::from_secs(1)));
@ -66,26 +78,22 @@ fn wait_for_fs_events(lock: Arc<Mutex<bool>>, method: WatchEventType, file: &str
println!("Watching {:?}", file); println!("Watching {:?}", file);
loop { loop {
let evt: WatchEventType = match rx.recv() { let evt: WatchEventType = match rx.recv() {
Ok(event) => { Ok(event) => WatchEventType::from(event),
WatchEventType::from(event) Err(_) => WatchEventType::Error,
},
Err(_) => {
WatchEventType::Error
}
}; };
match evt { match evt {
WatchEventType::Ignore => { WatchEventType::Ignore => {
// We ignore this one. // We ignore this one.
}, }
WatchEventType::Error => { WatchEventType::Error => {
// We log this one. // We log this one.
}, }
WatchEventType::Touched => { WatchEventType::Touched => {
if method == WatchEventType::Touched { if method == WatchEventType::Touched {
let mut signal = lock.lock().unwrap(); let mut signal = lock.lock().unwrap();
*signal = true; *signal = true;
} }
}, }
WatchEventType::Changed => { WatchEventType::Changed => {
let mut signal = lock.lock().unwrap(); let mut signal = lock.lock().unwrap();
*signal = true; *signal = true;
@ -96,15 +104,15 @@ fn wait_for_fs_events(lock: Arc<Mutex<bool>>, method: WatchEventType, file: &str
impl<'a> Process for FileProcess<'a> { impl<'a> Process for FileProcess<'a> {
fn run(&self) -> Result<(), CommandError> { fn run(&self) -> Result<(), CommandError> {
// NOTE(jwall): this is necessary because notify::fsEventWatcher panics // NOTE(jwall): this is necessary because notify::fsEventWatcher panics
// if the path doesn't exist. :-( // if the path doesn't exist. :-(
if !Path::new(self.file).exists() { if !Path::new(self.file).exists() {
return Err(CommandError::new(format!("No such path! {0}", self.file).to_string())) return Err(CommandError::new(format!("No such path! {0}", self.file).to_string()));
} }
// TODO(jeremy): Is this sufficent or do we want to ignore // TODO(jeremy): Is this sufficent or do we want to ignore
// any events that come in while the command is running? // any events that come in while the command is running?
let lock = Arc::new(Mutex::new(false)); let lock = Arc::new(Mutex::new(false));
spawn_runner_thread(lock.clone(), self.cmd.to_string(), self.poll); spawn_runner_thread(lock.clone(), self.cmd.to_string(), self.poll);
wait_for_fs_events(lock, self.method.clone(), self.file) wait_for_fs_events(lock, self.method.clone(), self.file)
} }
} }

View File

@ -11,7 +11,7 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! runwhen - A utility that runs commands on user defined triggers. // runwhen - A utility that runs commands on user defined triggers.
#[macro_use] #[macro_use]
extern crate clap; extern crate clap;
extern crate humantime; extern crate humantime;
@ -44,21 +44,29 @@ fn do_flags<'a>() -> clap::ArgMatches<'a> {
(@subcommand watch => (@subcommand watch =>
(about: "Trigger that fires when a file or directory changes.") (about: "Trigger that fires when a file or directory changes.")
// TODO(jeremy): We need to support filters // TODO(jeremy): We need to support filters
(@arg file: -f --file +takes_value "File/Directory to watch. (default current working directory)") (@arg file: -f --file +takes_value
(@arg filetouch: --touch "Watches for attribute modifications as well as content changes.") "File/Directory to watch. (default current working directory)")
(@arg wait: --poll +takes_value "How frequently to poll for events (default 5s)") (@arg filetouch: --touch
"Watches for attribute modifications as well as content changes.")
(@arg wait: --poll +takes_value
"How frequently to poll for events (default 5s)")
) )
(@subcommand timer => (@subcommand timer =>
(about: "Trigger that fires on a timer.") (about: "Trigger that fires on a timer.")
(@arg duration: -t --duration +required +takes_value "Defines timer frequency.") (@arg duration: -t --duration +required +takes_value
(@arg repeat: -n --repeat +takes_value "Defines an optional max number times to run on repeat.") "Defines timer frequency.")
(@arg repeat: -n --repeat +takes_value
"Defines an optional max number times to run on repeat.")
) )
(@subcommand success => (@subcommand success =>
(about: "Trigger that fires if a command runs successful.") (about: "Trigger that fires if a command runs successful.")
(@arg ifcmd: --if +required +takes_value "The command to test for successful exit from") (@arg ifcmd: --if +required +takes_value
(@arg wait: --poll +takes_value "How frequently to test command (default 5s)") "The command to test for successful exit from")
(@arg wait: --poll +takes_value
"How frequently to test command (default 5s)")
) )
).get_matches() )
.get_matches()
} }
fn main() { fn main() {
@ -78,9 +86,10 @@ fn main() {
process = Some(Box::new(FileProcess::new(cmd, file, method, dur))); process = Some(Box::new(FileProcess::new(cmd, file, method, dur)));
} else if let Some(matches) = app.subcommand_matches("timer") { } else if let Some(matches) = app.subcommand_matches("timer") {
// Unwrap because this flag is required. // Unwrap because this flag is required.
let dur = humantime::parse_duration(matches.value_of("duration").expect("duration flag is required")); let dur = humantime::parse_duration(matches.value_of("duration")
.expect("duration flag is required"));
match dur { match dur {
Ok(duration) =>{ Ok(duration) => {
let max_repeat = if let Some(val) = matches.value_of("repeat") { let max_repeat = if let Some(val) = matches.value_of("repeat") {
match u32::from_str(val) { match u32::from_str(val) {
Ok(n) => Some(n), Ok(n) => Some(n),
@ -94,7 +103,7 @@ fn main() {
None None
}; };
process = Some(Box::new(TimerProcess::new(cmd, duration, max_repeat))); process = Some(Box::new(TimerProcess::new(cmd, duration, max_repeat)));
}, }
Err(msg) => { Err(msg) => {
println!("Malformed duration {:?}", msg); println!("Malformed duration {:?}", msg);
process::exit(1); process::exit(1);
@ -103,8 +112,7 @@ fn main() {
} else if let Some(matches) = app.subcommand_matches("success") { } else if let Some(matches) = app.subcommand_matches("success") {
// unwrap because this is required. // unwrap because this is required.
let ifcmd = matches.value_of("ifcmd").expect("ifcmd flag is required"); let ifcmd = matches.value_of("ifcmd").expect("ifcmd flag is required");
let dur = humantime::parse_duration( let dur = humantime::parse_duration(matches.value_of("poll").unwrap_or("5s"));
matches.value_of("poll").unwrap_or("5s"));
process = match dur { process = match dur {
Ok(duration) => Some(Box::new(ExecProcess::new(ifcmd, cmd, duration))), Ok(duration) => Some(Box::new(ExecProcess::new(ifcmd, cmd, duration))),
Err(msg) => { Err(msg) => {
@ -114,16 +122,18 @@ fn main() {
} }
} }
match process { match process {
Some(process) => match process.run() { Some(process) => {
Ok(_) => return, match process.run() {
Err(err) => { Ok(_) => return,
println!("{0}", err); Err(err) => {
process::exit(1) println!("{0}", err);
process::exit(1)
}
} }
}, }
None => { None => {
println!("You must specify a subcommand."); println!("You must specify a subcommand.");
process::exit(1) process::exit(1)
}, }
} }
} }

View File

@ -21,12 +21,16 @@ use exec::run_cmd;
pub struct TimerProcess<'a> { pub struct TimerProcess<'a> {
cmd: &'a str, cmd: &'a str,
poll_duration: Duration, poll_duration: Duration,
max_repeat: Option<u32> max_repeat: Option<u32>,
} }
impl<'a> TimerProcess<'a> { impl<'a> TimerProcess<'a> {
pub fn new(cmd: &'a str, poll_duration: Duration, max_repeat: Option<u32>) -> TimerProcess<'a> { pub fn new(cmd: &'a str, poll_duration: Duration, max_repeat: Option<u32>) -> TimerProcess<'a> {
TimerProcess{cmd: cmd, poll_duration: poll_duration, max_repeat: max_repeat} TimerProcess {
cmd: cmd,
poll_duration: poll_duration,
max_repeat: max_repeat,
}
} }
} }
@ -41,7 +45,9 @@ impl<'a> Process for TimerProcess<'a> {
println!("{:?}", err) println!("{:?}", err)
} }
thread::sleep(self.poll_duration); thread::sleep(self.poll_duration);
if self.max_repeat.is_some() { counter += 1 } if self.max_repeat.is_some() {
counter += 1
}
} }
} }
} }