use anyhow::{anyhow, Result}; use serde::{Deserialize, Serialize}; use std::{ fs::{read_to_string, rename, File}, io::Write, path::PathBuf, }; #[derive(Serialize, Deserialize)] pub struct Config { username: String, } impl Config { pub fn path() -> Result { Ok(xdg::BaseDirectories::with_prefix("pixelcurry")?.place_config_file("config.toml")?) } pub fn load() -> Result { let path = Self::path()?; if path.exists() { Ok(toml::from_str(&read_to_string(path)?)?) } else { File::create(path)?.write_all(toml::to_string(&Self::initial()?)?.as_bytes())?; Self::load() } } pub fn save(&self) -> Result<()> { let path = Self::path()?; let temp = path.with_added_extension("~"); File::create(&temp)?.write_all(toml::to_string(self)?.as_bytes())?; rename(temp, path)?; Ok(()) } pub fn initial() -> Result { Ok(Config { username: users::get_current_username() .ok_or(anyhow!("current user has no name"))? .to_str() .ok_or(anyhow!("current user's name is not valid UTF8"))? .to_owned(), }) } }