databeam/
config.rs

1//! Application config manager
2use serde::{Deserialize, Serialize};
3use rainbeam_shared::fs;
4use pathbufd::PathBufD;
5use std::io::Result;
6
7/// Configuration file
8#[derive(Clone, Serialize, Deserialize, Debug)]
9#[derive(Default)]
10pub struct Config {
11    pub connection: crate::sql::DatabaseOpts,
12}
13
14
15impl Config {
16    /// Read configuration file into [`Config`]
17    pub fn read(contents: String) -> Self {
18        toml::from_str::<Self>(&contents).unwrap()
19    }
20
21    /// Pull configuration file
22    pub fn get_config() -> Self {
23        let path = PathBufD::current().extend(&[".config", "databeam", "config.toml"]);
24
25        match fs::read(path) {
26            Ok(c) => Config::read(c),
27            Err(_) => {
28                Self::update_config(Self::default()).expect("failed to write default config");
29                Self::default()
30            }
31        }
32    }
33
34    /// Update configuration file
35    pub fn update_config(contents: Self) -> Result<()> {
36        let c = fs::canonicalize(".").unwrap();
37        let here = c.to_str().unwrap();
38
39        fs::write(
40            format!("{here}/.config/databeam/config.toml"),
41            toml::to_string_pretty::<Self>(&contents).unwrap(),
42        )
43    }
44}