use std::path::PathBuf; use serde::{Deserialize, Serialize}; use crate::{Error, Result}; const STYLE: &str = include_str!("../examples/simple-gruvbox.css"); const BOOKMARKS: &str = include_str!("../examples/bookmarks.json"); const FAVICON: &str = include_str!("../examples/favicon.svg"); #[derive(Deserialize, Serialize, Clone)] pub struct Config { pub port: u16, pub style_file: PathBuf, pub bookmarks_file: PathBuf, pub favicon_file: PathBuf, } impl Config { pub fn new() -> Result { let config_home = if let Ok(xdg_config_home) = std::env::var("XDG_CONFIG_HOME") { PathBuf::from(xdg_config_home).join("sbm-rs") } else if let Ok(home) = std::env::var("HOME") { PathBuf::from(home).join(".config/sbm-rs") } else { return Err(Error::ConfigNotFound); }; if config_home.exists() { Config::load_config(&config_home) } else { Config::generate_defaults(&config_home) } } pub fn load_config(config_home: &PathBuf) -> Result { let config = config_home.join("config.toml"); let config = std::fs::read_to_string(config)?; let config: Config = toml::from_str(&config)?; Ok(config) } pub fn generate_defaults(config_home: &PathBuf) -> Result { std::fs::create_dir_all(&config_home)?; let style_file = config_home.join("style.css"); let bookmarks_file = config_home.join("bookmarks.json"); let favicon_file = config_home.join("favicon.svg"); let config_file = config_home.join("config.toml"); std::fs::write(&style_file, &STYLE)?; std::fs::write(&bookmarks_file, &BOOKMARKS)?; std::fs::write(&favicon_file, &FAVICON)?; let config = Config { port: 8080, style_file, bookmarks_file, favicon_file, }; let config_file_content = toml::to_string(&config)?; std::fs::write(config_file, config_file_content)?; Ok(config) } }