Add source files: main, lib, cli, error, convert, highlight, validate, typescript
This commit is contained in:
82
src/validate.rs
Normal file
82
src/validate.rs
Normal file
@@ -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<ValidationResult> {
|
||||||
|
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<ValidationError> = 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<ValidationError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ValidationError {
|
||||||
|
pub path: String,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate_with_schema(config: &Value, schema: &Value) -> Result<ValidationResult> {
|
||||||
|
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<ValidationError> = errors
|
||||||
|
.map(|e| ValidationError {
|
||||||
|
path: e.instance_path.to_string(),
|
||||||
|
message: e.message,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(ValidationResult {
|
||||||
|
valid: false,
|
||||||
|
errors,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user