diff --git a/Cargo.toml b/Cargo.toml index e750b6c..3d04189 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ percent-encoding = "1.0.1" hyper = "0.12.10" log = "0.4.6" beautylog = "0.1.0" +notify = "4.0.10" [[bin]] name = "mars-server" diff --git a/src/lib.rs b/src/lib.rs index 8e54835..08549d9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,14 @@ -use std::io; +#[macro_use] +extern crate log; + +use std::{io, thread}; use std::process::{Command, ExitStatus}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::fs::{File, create_dir_all}; +use std::sync::mpsc::channel; +use std::time::Duration; + +use notify::{Watcher, RecursiveMode, DebouncedEvent, watcher}; use notify_rust::Notification; @@ -100,6 +107,29 @@ pub fn builder_arguments_from_string(uri: &str) -> (PathBuf, Vec) { (path, args) } +/// Watches a directory and builds it when a modification occurs. +pub fn watch>(p: P) -> Result<(), Error> { + let path = PathBuf::from(p.as_ref()); + thread::spawn(move || { + let (tx, rx) = channel(); + let mut watcher = watcher(tx, Duration::from_secs(10)).unwrap(); + watcher.watch(&path, RecursiveMode::Recursive).unwrap(); + + loop { + match rx.recv() { + Ok(DebouncedEvent::NoticeWrite(_)) => { + let builder = GeneralBuilder::new(); + builder.build(&path, &vec![]).ok(); + }, + Err(e) => error!("watch error: {:?}", e), + _ => (), + } + } + }); + + Ok(()) +} + /// A general builders that contains many builders and can build any type of code. pub struct GeneralBuilder { /// The path to the success icon. diff --git a/src/server.rs b/src/server.rs index 32c7be1..19a8640 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,7 +1,7 @@ #[macro_use] extern crate log; -use std::thread; +use std::{thread, env}; use std::sync::{Mutex, Arc, mpsc}; use colored::*; @@ -12,12 +12,20 @@ use hyper::{Body, Response, Server}; use hyper::service::service_fn_ok; use hyper::rt::Future; -use mars::{GeneralBuilder, builder_arguments_from_string}; +use mars::{GeneralBuilder, builder_arguments_from_string, watch}; fn main() { beautylog::init(log::LevelFilter::Info).ok(); + let args = env::args().collect::>(); + + if args.len() == 3 && args[1] == "-w" { + if let Err(e) = watch(&args[2]) { + error!("{:?}", e); + } + } + let (tx, rx) = mpsc::channel(); let tasks = Arc::new(Mutex::new(vec![]));