From f4fad94a58c2eef5e1e49b4f2b150eac0efbd360 Mon Sep 17 00:00:00 2001 From: Ryan Leckey Date: Thu, 22 Jun 2017 23:59:39 -0700 Subject: Add a watcher example --- examples/watch/Cargo.toml | 8 +++++ examples/watch/Settings.toml | 3 ++ examples/watch/src/main.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 examples/watch/Cargo.toml create mode 100644 examples/watch/Settings.toml create mode 100644 examples/watch/src/main.rs (limited to 'examples') diff --git a/examples/watch/Cargo.toml b/examples/watch/Cargo.toml new file mode 100644 index 0000000..8c8a505 --- /dev/null +++ b/examples/watch/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "watch" +version = "0.1.0" + +[dependencies] +config = { path = "../../" } +lazy_static = "^0.2.8" +notify = "^4.0.0" diff --git a/examples/watch/Settings.toml b/examples/watch/Settings.toml new file mode 100644 index 0000000..f7881bb --- /dev/null +++ b/examples/watch/Settings.toml @@ -0,0 +1,3 @@ +debug = true +port = 8080 +host = "0.0.0.0" diff --git a/examples/watch/src/main.rs b/examples/watch/src/main.rs new file mode 100644 index 0000000..70fb7ef --- /dev/null +++ b/examples/watch/src/main.rs @@ -0,0 +1,70 @@ +extern crate config; +extern crate notify; + +#[macro_use] +extern crate lazy_static; + +use config::*; +use std::collections::HashMap; +use std::sync::RwLock; +use notify::{RecommendedWatcher, DebouncedEvent, Watcher, RecursiveMode}; +use std::sync::mpsc::channel; +use std::time::Duration; + +lazy_static! { + static ref SETTINGS: RwLock = RwLock::new(Config::default() + .merge(File::with_name("Settings.toml")) + .unwrap() + ); +} + +fn show() { + println!(" * Settings :: \n\x1b[31m{:?}\x1b[0m", + SETTINGS + .read() + .unwrap() + .deserialize::>() + .unwrap()); +} + +fn watch() { + // Create a channel to receive the events. + let (tx, rx) = channel(); + + // Automatically select the best implementation for your platform. + // You can also access each implementation directly e.g. INotifyWatcher. + let mut watcher: RecommendedWatcher = Watcher::new(tx, Duration::from_secs(2)).unwrap(); + + // Add a path to be watched. All files and directories at that path and + // below will be monitored for changes. + watcher + .watch("./Settings.toml", RecursiveMode::NonRecursive) + .unwrap(); + + // This is a simple loop, but you may want to use more complex logic here, + // for example to handle I/O. + loop { + match rx.recv() { + Ok(DebouncedEvent::Write(_)) => { + println!(" * Settings.toml written; refreshing configuration ..."); + SETTINGS.write().unwrap().refresh().unwrap(); + show(); + } + + Err(e) => println!("watch error: {:?}", e), + + _ => { + // Ignore event + } + } + } +} + +fn main() { + // This is just an example of what could be done, today + // We do want this to be built-in to config-rs at some point + // Feel free to take a crack at a PR + + show(); + watch(); +} -- cgit v1.2.3