use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
pub shortcut: String,
#[serde(default)]
pub openai_api_key: Option<String>,
}
impl Default for Settings {
fn default() -> Self {
Self {
shortcut: "Ctrl+Shift+R".to_string(),
openai_api_key: None,
}
}
}
impl Settings {
pub fn path() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("whis")
.join("settings.json")
}
pub fn load() -> Self {
let path = Self::path();
if let Ok(content) = fs::read_to_string(&path) {
if let Ok(settings) = serde_json::from_str(&content) {
return settings;
}
}
Self::default()
}
pub fn save(&self) -> Result<()> {
let path = Self::path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let content = serde_json::to_string_pretty(self)?;
fs::write(&path, &content)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
}