diff options
author | metamuffin <metamuffin@disroot.org> | 2024-08-14 21:40:30 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2024-08-14 21:40:30 +0200 |
commit | c44b86bcd86762dcdf1268ebfd3be9899ccf24ba (patch) | |
tree | 7ac984467e973f5abfa78c913e692ce06c0ca4e6 /pixel-client/src/config.rs | |
parent | c4ecfadbdfa8487a390958dbd80240f58b286303 (diff) | |
download | hurrycurry-c44b86bcd86762dcdf1268ebfd3be9899ccf24ba.tar hurrycurry-c44b86bcd86762dcdf1268ebfd3be9899ccf24ba.tar.bz2 hurrycurry-c44b86bcd86762dcdf1268ebfd3be9899ccf24ba.tar.zst |
pc: add itembubble and config save/load
Diffstat (limited to 'pixel-client/src/config.rs')
-rw-r--r-- | pixel-client/src/config.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/pixel-client/src/config.rs b/pixel-client/src/config.rs new file mode 100644 index 00000000..6d74fbe7 --- /dev/null +++ b/pixel-client/src/config.rs @@ -0,0 +1,43 @@ +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<PathBuf> { + Ok(xdg::BaseDirectories::with_prefix("pixelcurry")?.place_config_file("config.toml")?) + } + pub fn load() -> Result<Self> { + 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<Self> { + 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(), + }) + } +} |