use super::types::UnifiedConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigInitResult {
Created,
AlreadyExists,
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigLoadError {
#[error("Failed to read config file: {0}")]
Io(#[from] std::io::Error),
#[error("Failed to parse TOML: {0}")]
Toml(#[from] toml::de::Error),
}
pub const DEFAULT_UNIFIED_CONFIG: &str = include_str!("../../../examples/ralph-workflow.toml");
impl UnifiedConfig {
#[must_use]
pub fn load_default() -> Option<Self> {
Self::load_with_env(&super::super::path_resolver::RealConfigEnvironment)
}
pub fn load_with_env(env: &dyn super::super::path_resolver::ConfigEnvironment) -> Option<Self> {
env.unified_config_path().and_then(|path| {
if env.file_exists(&path) {
Self::load_from_path_with_env(&path, env).ok()
} else {
None
}
})
}
pub fn load_from_path_with_env(
path: &std::path::Path,
env: &dyn super::super::path_resolver::ConfigEnvironment,
) -> Result<Self, ConfigLoadError> {
let contents = env.read_file(path)?;
let config: Self = toml::from_str(&contents)?;
Ok(config)
}
pub fn load_from_content(content: &str) -> Result<Self, ConfigLoadError> {
let config: Self = toml::from_str(content)?;
Ok(config)
}
pub fn ensure_config_exists() -> std::io::Result<ConfigInitResult> {
Self::ensure_config_exists_with_env(&super::super::path_resolver::RealConfigEnvironment)
}
pub fn ensure_config_exists_with_env(
env: &dyn super::super::path_resolver::ConfigEnvironment,
) -> std::io::Result<ConfigInitResult> {
let Some(path) = env.unified_config_path() else {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"Cannot determine config directory (no home directory)",
));
};
Self::ensure_config_exists_at_with_env(&path, env)
}
pub fn ensure_config_exists_at(path: &std::path::Path) -> std::io::Result<ConfigInitResult> {
Self::ensure_config_exists_at_with_env(
path,
&super::super::path_resolver::RealConfigEnvironment,
)
}
pub fn ensure_config_exists_at_with_env(
path: &std::path::Path,
env: &dyn super::super::path_resolver::ConfigEnvironment,
) -> std::io::Result<ConfigInitResult> {
if env.file_exists(path) {
return Ok(ConfigInitResult::AlreadyExists);
}
env.write_file(path, DEFAULT_UNIFIED_CONFIG)?;
Ok(ConfigInitResult::Created)
}
}