buckets/crates/buckets-core/src/config.rs

70 lines
1.9 KiB
Rust
Raw Normal View History

2025-08-23 14:48:51 -04:00
use std::collections::HashMap;
2025-08-21 02:50:26 +00:00
use oiseau::config::{Configuration, DatabaseConfig};
use pathbufd::PathBufD;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Config {
2025-08-21 00:30:58 -04:00
/// The directory files are stored in (relative to cwd).
#[serde(default = "default_directory")]
pub directory: String,
2025-08-23 14:48:51 -04:00
/// The path to the default image to be served for the given buckets.
#[serde(default = "default_bucket_defaults")]
pub bucket_defaults: HashMap<String, (String, String)>,
2025-08-21 02:50:26 +00:00
/// Database configuration.
#[serde(default = "default_database")]
pub database: DatabaseConfig,
}
2025-08-21 00:30:58 -04:00
fn default_directory() -> String {
"buckets".to_string()
2025-08-21 02:50:26 +00:00
}
2025-08-23 14:48:51 -04:00
fn default_bucket_defaults() -> HashMap<String, (String, String)> {
HashMap::new()
}
2025-08-21 02:50:26 +00:00
fn default_database() -> DatabaseConfig {
DatabaseConfig::default()
}
impl Configuration for Config {
fn db_config(&self) -> DatabaseConfig {
self.database.to_owned()
}
}
impl Default for Config {
fn default() -> Self {
Self {
2025-08-21 00:30:58 -04:00
directory: default_directory(),
2025-08-23 14:48:51 -04:00
bucket_defaults: default_bucket_defaults(),
2025-08-21 02:50:26 +00:00
database: default_database(),
}
}
}
impl Config {
/// Read the configuration file.
pub fn read() -> Self {
toml::from_str(
&match std::fs::read_to_string(PathBufD::current().join("app.toml")) {
Ok(x) => x,
Err(_) => {
let x = Config::default();
std::fs::write(
PathBufD::current().join("app.toml"),
&toml::to_string_pretty(&x).expect("failed to serialize config"),
)
.expect("failed to write config");
return x;
}
},
)
.expect("failed to deserialize config")
}
}