| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use std::path::PathBuf; |
| 3 | |
| 4 | #[derive(Debug, Default, Serialize, Deserialize)] |
| 5 | pub struct Config { |
| 6 | pub remote_url: Option<String>, |
| 7 | pub api_key: Option<String>, |
| 8 | } |
| 9 | |
| 10 | pub fn config_path() -> PathBuf { |
| 11 | let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); |
| 12 | PathBuf::from(home).join(".config/sipp/config.toml") |
| 13 | } |
| 14 | |
| 15 | pub fn load_config() -> Config { |
| 16 | let path = config_path(); |
| 17 | match std::fs::read_to_string(&path) { |
| 18 | Ok(contents) => toml::from_str(&contents).unwrap_or_default(), |
| 19 | Err(_) => Config::default(), |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | pub fn save_config(config: &Config) -> Result<(), Box<dyn std::error::Error>> { |
| 24 | let path = config_path(); |
| 25 | if let Some(parent) = path.parent() { |
| 26 | std::fs::create_dir_all(parent)?; |
| 27 | } |
| 28 | let contents = toml::to_string_pretty(config)?; |
| 29 | std::fs::write(&path, contents)?; |
| 30 | Ok(()) |
| 31 | } |