1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
/*
Hurry Curry! - a game about cooking
Copyright 2024 metamuffin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, version 3 of the License only.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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 {
pub 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(),
})
}
}
|