buckets_core/
config.rs

1use std::collections::HashMap;
2
3use oiseau::config::{Configuration, DatabaseConfig};
4use pathbufd::PathBufD;
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct Config {
9    /// The directory files are stored in (relative to cwd).
10    #[serde(default = "default_directory")]
11    pub directory: String,
12    /// The path to the default image to be served for the given buckets.
13    #[serde(default = "default_bucket_defaults")]
14    pub bucket_defaults: HashMap<String, (String, String)>,
15    /// Database configuration.
16    #[serde(default = "default_database")]
17    pub database: DatabaseConfig,
18}
19
20fn default_directory() -> String {
21    "buckets".to_string()
22}
23
24fn default_bucket_defaults() -> HashMap<String, (String, String)> {
25    HashMap::new()
26}
27
28fn default_database() -> DatabaseConfig {
29    DatabaseConfig::default()
30}
31
32impl Configuration for Config {
33    fn db_config(&self) -> DatabaseConfig {
34        self.database.to_owned()
35    }
36}
37
38impl Default for Config {
39    fn default() -> Self {
40        Self {
41            directory: default_directory(),
42            bucket_defaults: default_bucket_defaults(),
43            database: default_database(),
44        }
45    }
46}
47
48impl Config {
49    /// Read the configuration file.
50    pub fn read() -> Self {
51        toml::from_str(
52            &match std::fs::read_to_string(PathBufD::current().join("app.toml")) {
53                Ok(x) => x,
54                Err(_) => {
55                    let x = Config::default();
56
57                    std::fs::write(
58                        PathBufD::current().join("app.toml"),
59                        &toml::to_string_pretty(&x).expect("failed to serialize config"),
60                    )
61                    .expect("failed to write config");
62
63                    return x;
64                }
65            },
66        )
67        .expect("failed to deserialize config")
68    }
69}