hacker_news/
config.rs

1use std::path::Path;
2use std::fs::File;
3use std::io::BufReader;
4use std::error::Error;
5use serde::Deserialize;
6
7#[derive(Debug, Deserialize)]
8pub struct HNConfig {
9    user: Option<HNConfigUser>
10}
11
12#[derive(Debug, Deserialize)]
13struct HNConfigUser {
14    username: Option<String>,
15}
16
17impl HNConfig {
18
19    pub fn from_file(path: &Path) -> Result<HNConfig, Box<dyn Error>> {
20        let f = File::open(path)?;
21        let rd = BufReader::new(f);
22        let config = serde_json::from_reader(rd)?;
23    
24        Ok(config)
25    }
26
27}
28
29#[cfg(test)]
30mod tests {
31
32    use std::path::PathBuf;
33    use std::error::Error;
34    use super::HNConfig;
35
36    // This test is marked as ignored, as the feature it supports is not
37    // really implemented
38    #[ignore]
39    #[test]
40    fn test_read_config_file() -> Result<(), Box<dyn Error>> {
41        let home = std::env::var("HOME")
42            .expect("Failed to read `$HOME` environment variable");
43        println!("$HOME = {:?}", home);
44        let mut path = PathBuf::from(home);
45        path.push(".hn.json");
46        println!("path = {:?}", path);
47
48        let config = HNConfig::from_file(&path)?;
49        println!("config = {:#?}", config);
50
51        Ok(())
52    }
53
54}