From 0aa0c951f67b9ee8d06510a2cbc62c3ba42a1d03 Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Thu, 29 Jan 2026 15:15:43 +0000 Subject: [PATCH] Add source files: main, lib, cli, error, convert, highlight, validate, typescript --- src/validate.rs | 82 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/validate.rs diff --git a/src/validate.rs b/src/validate.rs new file mode 100644 index 0000000..d815925 --- /dev/null +++ b/src/validate.rs @@ -0,0 +1,82 @@ +use serde_json::Value; +use crate::error::{ConfigForgeError, Result}; + +pub fn validate_config(config_content: &str, config_format: &str, schema: &str, schema_format: &str) -> Result { + let config_format = config_format.parse()?; + let config_value = crate::convert::parse_content(config_content, config_format)?; + + let schema_value: Value = if schema_format == "inline" { + serde_json::from_str(schema)? + } else { + let schema_content = std::fs::read_to_string(schema).map_err(|_| ConfigForgeError::FileNotFound { + path: schema.to_string(), + })?; + serde_json::from_str(&schema_content)? + }; + + let compiled_schema = jsonschema::JSONSchema::compile(&schema_value) + .map_err(|e| ConfigForgeError::SchemaParseError { + details: e.to_string(), + })?; + + let result = compiled_schema.validate(&config_value); + + match result { + Ok(_) => Ok(ValidationResult { + valid: true, + errors: vec![], + }), + Err(errors) => { + let errors: Vec = errors + .map(|e| ValidationError { + path: e.instance_path.to_string(), + message: e.message, + }) + .collect(); + Ok(ValidationResult { + valid: false, + errors, + }) + } + } +} + +#[derive(Debug)] +pub struct ValidationResult { + pub valid: bool, + pub errors: Vec, +} + +#[derive(Debug)] +pub struct ValidationError { + pub path: String, + pub message: String, +} + +pub fn validate_with_schema(config: &Value, schema: &Value) -> Result { + let compiled_schema = jsonschema::JSONSchema::compile(schema) + .map_err(|e| ConfigForgeError::SchemaParseError { + details: e.to_string(), + })?; + + let result = compiled_schema.validate(config); + + match result { + Ok(_) => Ok(ValidationResult { + valid: true, + errors: vec![], + }), + Err(errors) => { + let errors: Vec = errors + .map(|e| ValidationError { + path: e.instance_path.to_string(), + message: e.message, + }) + .collect(); + Ok(ValidationResult { + valid: false, + errors, + }) + } + } +}