email_notif/
config.rs

1use serde::Deserialize;
2use std::env;
3use std::fs::File;
4use std::io::Read;
5
6/// Configuration object. Stores information about the email account used to
7/// send mail. This struct is deserialised from the configuration file in
8/// your home directory at "$HOME/.email_notifier.json".
9#[derive(Deserialize)]
10pub struct Config {
11    pub smtp_server: String,
12    pub sender_email: String,
13    pub password: String,
14    pub recipient_email: String,
15    pub port: u16,
16}
17
18impl Config {
19    /// Returns "$HOME/.email_notifier.json"
20    fn config_path() -> String {
21        let home = env::var("HOME").unwrap();
22        format!("{}/{}", home, ".email_notifier.json")
23    }
24
25    /// Load configuration from config file and return config struct.
26    pub fn load() -> Self {
27        let config_path = Self::config_path();
28        let mut f = File::open(config_path.clone())
29            .expect(format!("error opening config file at {}", config_path).as_str());
30        let mut data = String::new();
31        f.read_to_string(&mut data).unwrap();
32        serde_json::from_str(data.as_str()).unwrap()
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn test_config() {
42        let _ = Config::load();
43    }
44}