1use std::{env, path::{MAIN_SEPARATOR, Path}, fs::create_dir_all};
2
3use anyhow::Result;
4use confy::ConfyError;
5use directories_next::ProjectDirs;
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Serialize, Deserialize)]
9pub struct AppConfig {
10 pub data_dir: String,
11 pub datetime_format: String,
12}
13
14impl AppConfig {
15 pub fn database_url(&self) -> String {
16 let path = Path::new(&self.data_dir);
17
18 if !path.exists() {
19 create_dir_all(path).expect(&format!("Failed to create data directory {}", self.data_dir));
20 }
21 let default = format!("{}{}{}", self.data_dir, MAIN_SEPARATOR, "frames.db");
22
23 env::var("DATABASE_URL").unwrap_or(default)
24 }
25}
26
27impl Default for AppConfig {
28 fn default() -> Self {
29 if let Some(proj_dirs) = ProjectDirs::from("ch", "lethani", "aze") {
30 return AppConfig {
31 data_dir: proj_dirs.data_dir().to_str().unwrap().to_string(),
32 datetime_format: "%Y-%m-%d %H:%M".to_string(),
33 };
34 }
35
36 panic!("Could not evaluate data_dir");
37 }
38}
39
40pub fn load_config() -> AppConfig {
41 let cfg: Result<AppConfig, ConfyError> = confy::load("aze");
42
43 cfg.unwrap_or_default()
44}
45
46#[cfg(test)]
47mod tests {
48 use directories_next::ProjectDirs;
49
50 #[test]
51 fn default_config_dir() {
52 let config = super::load_config();
53
54 if let Some(proj_dirs) = ProjectDirs::from("ch", "lethani", "aze") {
55 assert_eq!(
56 proj_dirs.data_dir().to_str().unwrap().to_string(),
57 config.data_dir
58 );
59 } else {
60 panic!("Could not evaluate directory");
61 }
62 }
63}