use std::collections::HashMap;
use anyhow::{Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use serde::Deserialize;
use crate::Root;
#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
pub struct ConfigFile {
pub stems: HashMap<String, ConfigStem>,
pub schema_directory: Option<Utf8PathBuf>,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[serde(try_from = "Utf8PathBuf")]
struct _Root(Root);
impl TryFrom<Utf8PathBuf> for _Root {
type Error = <Root as TryFrom<Utf8PathBuf>>::Error;
fn try_from(value: Utf8PathBuf) -> std::result::Result<Self, Self::Error> {
Root::try_from(value).map(_Root)
}
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ConfigStem {
root: _Root,
schema: Utf8PathBuf,
}
impl ConfigStem {
pub fn root(&self) -> &Root {
&self.root.0
}
pub fn schema(&self) -> &Utf8Path {
&self.schema
}
}
impl ConfigFile {
pub fn load(path: impl AsRef<Utf8Path>) -> Result<Self> {
let path = path.as_ref();
let config_context = || format!("Reading config file {path:?}");
let config_data = std::fs::read_to_string(path).with_context(config_context)?;
config_data.as_str().try_into()
}
}
impl TryFrom<&str> for ConfigFile {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Ok(toml::from_str(value)?)
}
}