databeam/
config.rs

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
//! Application config manager
use serde::{Deserialize, Serialize};
use rainbeam_shared::fs;
use pathbufd::PathBufD;
use std::io::Result;

/// Configuration file
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Config {
    pub connection: crate::sql::DatabaseOpts,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            connection: crate::sql::DatabaseOpts::default(),
        }
    }
}

impl Config {
    /// Read configuration file into [`Config`]
    pub fn read(contents: String) -> Self {
        toml::from_str::<Self>(&contents).unwrap()
    }

    /// Pull configuration file
    pub fn get_config() -> Self {
        let path = PathBufD::current().extend(&[".config", "databeam", "config.toml"]);

        match fs::read(path) {
            Ok(c) => Config::read(c),
            Err(_) => {
                Self::update_config(Self::default()).expect("failed to write default config");
                Self::default()
            }
        }
    }

    /// Update configuration file
    pub fn update_config(contents: Self) -> Result<()> {
        let c = fs::canonicalize(".").unwrap();
        let here = c.to_str().unwrap();

        fs::write(
            format!("{here}/.config/databeam/config.toml"),
            toml::to_string_pretty::<Self>(&contents).unwrap(),
        )
    }
}