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 #[error("Schema validation failed: {0}")]
22 Schema(String),
23}
24
25pub fn validate_config<T: DeserializeOwned + JsonSchema>(
26 yaml_path: impl AsRef<Path>,
27) -> Result<T, ConfigValidationError> {
28 let content = std::fs::read_to_string(yaml_path)?;
29 let config: T = serde_yaml::from_str(&content)?;
30 Ok(config)
31}
32
33pub fn generate_schema<T: JsonSchema>() -> Result<serde_json::Value, serde_json::Error> {
34 let schema = schemars::schema_for!(T);
35 serde_json::to_value(schema)
36}
37
38pub fn validate_yaml_str<T: DeserializeOwned>(yaml: &str) -> Result<T, ConfigValidationError> {
39 let config: T = serde_yaml::from_str(yaml)?;
40 Ok(config)
41}
42
43pub fn validate_yaml_file(
44 path: impl AsRef<Path>,
45) -> Result<serde_yaml::Value, ConfigValidationError> {
46 let content = std::fs::read_to_string(path)?;
47 let value: serde_yaml::Value = serde_yaml::from_str(&content)?;
48 Ok(value)
49}