systemprompt_config/services/
schema_validation.rs1use std::path::Path;
7
8use schemars::JsonSchema;
9use serde::de::DeserializeOwned;
10use thiserror::Error;
11
12#[derive(Debug, Error)]
13#[non_exhaustive]
14pub enum ConfigValidationError {
15 #[error("Failed to read config file: {0}")]
16 Read(#[from] std::io::Error),
17
18 #[error("Failed to parse YAML config: {0}")]
19 Parse(#[from] serde_yaml::Error),
20}
21
22pub fn validate_config<T: DeserializeOwned + JsonSchema>(
23 yaml_path: impl AsRef<Path>,
24) -> Result<T, ConfigValidationError> {
25 let content = std::fs::read_to_string(yaml_path)?;
26 let config: T = serde_yaml::from_str(&content)?;
27 Ok(config)
28}
29
30pub fn generate_schema<T: JsonSchema>() -> Result<serde_json::Value, serde_json::Error> {
32 let schema = schemars::schema_for!(T);
33 serde_json::to_value(schema)
34}
35
36pub fn validate_yaml_str<T: DeserializeOwned>(yaml: &str) -> Result<T, ConfigValidationError> {
37 let config: T = serde_yaml::from_str(yaml)?;
38 Ok(config)
39}
40
41pub fn validate_yaml_file(
42 path: impl AsRef<Path>,
43) -> Result<serde_yaml::Value, ConfigValidationError> {
44 let content = std::fs::read_to_string(path)?;
45 let value: serde_yaml::Value = serde_yaml::from_str(&content)?;
46 Ok(value)
47}