MacroBoard-rs/src/shared/config.rs

49 lines
1.2 KiB
Rust
Raw Normal View History

2022-07-15 17:08:22 +00:00
use anyhow::Result;
use serde::{Deserialize, Serialize};
2019-11-22 18:02:27 +00:00
2022-07-18 10:11:17 +00:00
use std::{
fs::{self, File},
io::Write,
path::Path,
};
2019-11-22 18:02:27 +00:00
2022-07-15 17:08:22 +00:00
pub const COMMAND_COUNT: usize = 8;
2019-11-22 18:02:27 +00:00
2022-07-15 17:17:08 +00:00
#[derive(Debug, Serialize, Deserialize, Default)]
2019-11-22 18:02:27 +00:00
pub struct Config {
pub commands: [Option<String>; COMMAND_COUNT],
}
impl Config {
2022-07-18 10:11:17 +00:00
pub fn load_config() -> Result<Config> {
let home_dir = std::env::var("HOME")?;
if !Path::new(&format!("{}/.config", home_dir)).exists() {
fs::create_dir(format!("{}/.config", home_dir))?;
}
if !Path::new(&format!("{}/.config/MacroBoard", home_dir)).exists() {
fs::create_dir(format!("{}/.config/MacroBoard", home_dir))?;
}
Config::open(&format!("{}/.config/MacroBoard/commands.cfg", home_dir))
}
2022-07-15 17:08:22 +00:00
pub fn open(path: &str) -> Result<Config> {
2022-07-15 17:17:08 +00:00
if Path::new(path).exists() {
Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
} else {
Ok(Config::default())
}
2019-11-22 18:02:27 +00:00
}
2022-07-15 17:08:22 +00:00
pub fn save(&self, path: &str) -> Result<()> {
let mut file = File::create(path)?;
let s = serde_json::to_string(self)?;
2019-11-22 18:02:27 +00:00
2022-07-15 17:08:22 +00:00
write!(file, "{}", s)?;
2019-11-22 18:02:27 +00:00
2022-07-15 17:08:22 +00:00
Ok(())
2019-11-22 18:02:27 +00:00
}
}