use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub store_path: PathBuf,
pub auto_open: bool,
pub note_template: Option<String>,
}
fn hitchmark_config_dir() -> anyhow::Result<PathBuf> {
if let Ok(dir) = std::env::var("HK_CONFIG_DIR") {
return Ok(PathBuf::from(dir));
}
dirs::config_dir()
.map(|d| d.join("hitchmark"))
.ok_or_else(|| anyhow::anyhow!(
"Could not determine config directory. \
Ensure $HOME (or $XDG_CONFIG_HOME) is set."
))
}
impl Default for Config {
fn default() -> Self {
let store_path = if let Ok(p) = std::env::var("HK_STORE_PATH") {
PathBuf::from(p)
} else {
dirs::config_dir()
.map(|d| d.join("hitchmark").join("store.db"))
.unwrap_or_else(|| PathBuf::from(".hitchmark/store.db"))
};
Config {
store_path,
auto_open: false,
note_template: None,
}
}
}
impl Config {
pub fn load() -> anyhow::Result<Self> {
let config_path = hitchmark_config_dir()?.join("config.toml");
let mut cfg = if config_path.exists() {
let content = std::fs::read_to_string(&config_path)?;
toml::from_str(&content)?
} else {
Config::default()
};
if let Ok(p) = std::env::var("HK_STORE_PATH") {
cfg.store_path = PathBuf::from(p);
}
Ok(cfg)
}
pub fn ensure_dir(&self) -> anyhow::Result<()> {
let hitchmark_dir = hitchmark_config_dir()?;
if !hitchmark_dir.exists() {
std::fs::create_dir_all(&hitchmark_dir)?;
}
if let Some(parent) = self.store_path.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent)?;
}
}
Ok(())
}
}