use anyhow::Result; use serde::{Deserialize, Serialize}; use std::{ fs::{self, File}, io::Write, path::Path, }; pub const COMMAND_COUNT: usize = 8; #[derive(Debug, Serialize, Deserialize, Default)] pub struct Config { pub commands: [Option; COMMAND_COUNT], } impl Config { pub fn load_config() -> Result { 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)) } pub fn open(path: &str) -> Result { if Path::new(path).exists() { Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?) } else { Ok(Config::default()) } } pub fn save(&self, path: &str) -> Result<()> { let mut file = File::create(path)?; let s = serde_json::to_string(self)?; write!(file, "{}", s)?; Ok(()) } }