use crate::config::{ProjectConfig, UserConfig};
use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};
pub struct ConfigLoader;
impl ConfigLoader {
pub fn load_user_config() -> Result<UserConfig> {
let config_path = Self::user_config_path()?;
if !config_path.exists() {
return Ok(UserConfig::default());
}
let content = fs::read_to_string(&config_path)
.with_context(|| format!("Failed to read user config from {:?}", config_path))?;
let config: UserConfig = serde_yaml::from_str(&content)
.with_context(|| "Failed to parse user config")?;
Ok(config)
}
pub fn load_project_config(project_path: &Path) -> Result<Option<ProjectConfig>> {
let config_path = project_path.join(".darpan.yml");
if !config_path.exists() {
return Ok(None);
}
let content = fs::read_to_string(&config_path)
.with_context(|| format!("Failed to read project config from {:?}", config_path))?;
let config: ProjectConfig = serde_yaml::from_str(&content)
.with_context(|| "Failed to parse project config")?;
Ok(Some(config))
}
pub fn save_project_config(project_path: &Path, config: &ProjectConfig) -> Result<()> {
let config_path = project_path.join(".darpan.yml");
let yaml = serde_yaml::to_string(config)?;
fs::write(&config_path, yaml)?;
Ok(())
}
pub fn user_config_path() -> Result<PathBuf> {
let config_dir = dirs::config_dir()
.context("Could not determine config directory")?
.join("darpan");
fs::create_dir_all(&config_dir)?;
Ok(config_dir.join("config.yml"))
}
pub fn create_default_project_config(project_path: &Path) -> Result<()> {
let config_path = project_path.join(".darpan.yml");
if config_path.exists() {
anyhow::bail!(".darpan.yml already exists");
}
let template = ProjectConfig::default_template();
fs::write(&config_path, template)?;
Ok(())
}
}