1 #![allow(deprecated)]
2 use config::{Config, File};
3 use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher};
4 use std::collections::HashMap;
5 use std::sync::mpsc::channel;
6 use std::sync::RwLock;
7 use std::time::Duration;
8 
9 lazy_static::lazy_static! {
10     static ref SETTINGS: RwLock<Config> = RwLock::new({
11         let mut settings = Config::default();
12         settings.merge(File::with_name("examples/watch/Settings.toml")).unwrap();
13 
14         settings
15     });
16 }
17 
show()18 fn show() {
19     println!(
20         " * Settings :: \n\x1b[31m{:?}\x1b[0m",
21         SETTINGS
22             .read()
23             .unwrap()
24             .clone()
25             .try_deserialize::<HashMap<String, String>>()
26             .unwrap()
27     );
28 }
29 
watch()30 fn watch() {
31     // Create a channel to receive the events.
32     let (tx, rx) = channel();
33 
34     // Automatically select the best implementation for your platform.
35     // You can also access each implementation directly e.g. INotifyWatcher.
36     let mut watcher: RecommendedWatcher = Watcher::new(tx, Duration::from_secs(2)).unwrap();
37 
38     // Add a path to be watched. All files and directories at that path and
39     // below will be monitored for changes.
40     watcher
41         .watch("examples/watch/Settings.toml", RecursiveMode::NonRecursive)
42         .unwrap();
43 
44     // This is a simple loop, but you may want to use more complex logic here,
45     // for example to handle I/O.
46     loop {
47         match rx.recv() {
48             Ok(DebouncedEvent::Write(_)) => {
49                 println!(" * Settings.toml written; refreshing configuration ...");
50                 SETTINGS.write().unwrap().refresh().unwrap();
51                 show();
52             }
53 
54             Err(e) => println!("watch error: {:?}", e),
55 
56             _ => {
57                 // Ignore event
58             }
59         }
60     }
61 }
62 
main()63 fn main() {
64     // This is just an example of what could be done, today
65     // We do want this to be built-in to config-rs at some point
66     // Feel free to take a crack at a PR
67 
68     show();
69     watch();
70 }
71