mirror of
https://github.com/hulthe/inkopslista.git
synced 2026-08-03 23:11:28 +02:00
53 lines
1.5 KiB
Rust
53 lines
1.5 KiB
Rust
use anyhow::{Context, Ok};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json;
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
|
|
pub struct Config {
|
|
pub address: String,
|
|
}
|
|
|
|
impl Default for Config {
|
|
fn default() -> Self {
|
|
Self {
|
|
address: "http://localhost:8000".to_string(),
|
|
}
|
|
}
|
|
}
|
|
const CONFIG_FILE_NAME: &'static str = "config.json";
|
|
const XDG_PREFIX: &'static str = "inköpslista";
|
|
|
|
pub fn save_config(address: String) -> Result<(), anyhow::Error> {
|
|
let xdg_dirs = xdg::BaseDirectories::with_prefix(XDG_PREFIX);
|
|
let conf = Config { address: address };
|
|
let conf = serde_json::to_string(&conf).context("unable to serialize config")?;
|
|
|
|
let path = xdg_dirs
|
|
.place_config_file(CONFIG_FILE_NAME)
|
|
.context("unable to create config directory")?;
|
|
|
|
tokio::spawn(async {
|
|
let res = tokio::fs::write(path, conf)
|
|
.await
|
|
.context("unable to write config file");
|
|
if let Err(err) = res {
|
|
eprintln!("{err:?}");
|
|
}
|
|
});
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn get_config() -> Result<Config, anyhow::Error> {
|
|
let xdg_dirs = xdg::BaseDirectories::with_prefix(XDG_PREFIX);
|
|
let file = xdg_dirs
|
|
.get_config_file(CONFIG_FILE_NAME)
|
|
.context("no config file")?;
|
|
let content = tokio::fs::read_to_string(file)
|
|
.await
|
|
.context("failed to read config file")?;
|
|
|
|
let conf: Config = serde_json::from_str(&content).context("Unable to deserealize contect")?;
|
|
Ok(conf)
|
|
}
|