aboutsummaryrefslogtreecommitdiff
path: root/src/load_config.rs
blob: 46a630e4d56bb32a77c2f61b7c2e46226f2a5965 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::env;
use std::{fs::File, io::Error, io::Read};
use yaml_rust::{yaml, YamlLoader};

pub struct Time {
    pub format: String,
    pub icon: String,
}

pub struct Memory {
    pub icon: String,
}

pub struct Disk {
    pub icon: String,
}

pub struct Settings {
    pub seperator: String,
    pub time: Time,
    pub memory: Memory,
    pub disk: Disk,
}

pub fn load() -> Result<Settings, Error> {
    let yml_source = env::var("HOME").unwrap() + "/.config/rsblocks/rsblocks.yml";
    let mut data = String::new();
    let mut file = match File::open(yml_source) {
        Ok(file) => file,
        Err(_) => {
            println!("~/.config/rsblocks/rsblocks.yml file not found, loading defaults!");
            return Ok(load_defaults());
        }
    };
    file.read_to_string(&mut data)?;

    let yml_doc = &YamlLoader::load_from_str(&data).unwrap()[0];
    let settings = gen_settings(yml_doc);
    Ok(settings)
}

fn gen_settings(doc: &yaml::Yaml) -> Settings {
    let seperator: String;
    let time_format: String;
    let time_icon: String;
    let mem_icon: String;
    let disk_icon: String;

    if doc["general"]["seperator"].is_badvalue() {
        seperator = String::from("|");
    } else {
        seperator = String::from(doc["general"]["seperator"].as_str().unwrap());
    }
    if doc["time"]["icon"].is_badvalue() {
        time_icon = String::from("")
    } else {
        time_icon = String::from(doc["time"]["icon"].as_str().unwrap());
    }
    if doc["time"]["format"].is_badvalue() {
        time_format = String::from("%T")
    } else {
        time_format = String::from(doc["time"]["format"].as_str().unwrap())
    }
    if doc["memory"]["icon"].is_badvalue() {
        mem_icon = String::from("")
    } else {
        mem_icon = String::from(doc["memory"]["icon"].as_str().unwrap());
    }
    if doc["disk"]["icon"].is_badvalue() {
        disk_icon = String::from("")
    } else {
        disk_icon = String::from(doc["disk"]["icon"].as_str().unwrap());
    }

    Settings {
        seperator,
        time: Time {
            format: time_format,
            icon: time_icon,
        },
        memory: Memory { icon: mem_icon },
        disk: Disk { icon: disk_icon },
    }
}

fn load_defaults() -> Settings {
    Settings {
        seperator: String::from("|"),
        time: Time {
            format: String::from("%T"),
            icon: String::from(""),
        },
        memory: Memory {
            icon: String::from(""),
        },
        disk: Disk {
            icon: String::from(""),
        },
    }
}