systemprompt_config/services/
schema_validation.rs1use std::path::Path;
4
5use schemars::JsonSchema;
6use serde::de::DeserializeOwned;
7use thiserror::Error;
8
9#[derive(Debug, Error)]
10#[non_exhaustive]
11pub enum ConfigValidationError {
12 #[error("Failed to read config file: {0}")]
13 Read(#[from] std::io::Error),
14
15 #[error("Failed to parse YAML config: {0}")]
16 Parse(#[from] serde_yaml::Error),
17
18 #[error("Schema validation failed: {0}")]
19 Schema(String),
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> {
31 let schema = schemars::schema_for!(T);
32 serde_json::to_value(schema)
33}
34
35pub fn validate_yaml_str<T: DeserializeOwned>(yaml: &str) -> Result<T, ConfigValidationError> {
36 let config: T = serde_yaml::from_str(yaml)?;
37 Ok(config)
38}
39
40pub fn validate_yaml_file(
41 path: impl AsRef<Path>,
42) -> Result<serde_yaml::Value, ConfigValidationError> {
43 let content = std::fs::read_to_string(path)?;
44 let value: serde_yaml::Value = serde_yaml::from_str(&content)?;
45 Ok(value)
46}