@@ -38,7 +38,7 @@ use syntect::{
3838 parsing:: SyntaxSet ,
3939 util:: { as_24_bit_terminal_escaped, LinesWithEndings }
4040} ;
41- use tracing:: { Level , debug, error} ;
41+ use tracing:: { Level , debug, error, trace } ;
4242use tracing_subscriber:: { filter:: EnvFilter , layer:: SubscriberExt , Layer } ;
4343
4444pub const EXIT_SUCCESS : i32 = 0 ;
@@ -302,6 +302,43 @@ pub fn enable_tracing(trace_level: &TraceLevel, trace_format: &TraceFormat) {
302302 }
303303}
304304
305+ /// Validate the JSON against the schema.
306+ ///
307+ /// # Arguments
308+ ///
309+ /// * `source` - The source of the JSON
310+ /// * `schema` - The schema to validate against
311+ /// * `json` - The JSON to validate
312+ ///
313+ /// # Returns
314+ ///
315+ /// Nothing on success.
316+ ///
317+ /// # Errors
318+ ///
319+ /// * `DscError` - The JSON is invalid
320+ pub fn validate_json ( source : & str , schema : & Value , json : & Value ) -> Result < ( ) , DscError > {
321+ debug ! ( "Validating {source} against schema" ) ;
322+ trace ! ( "JSON: {json}" ) ;
323+ trace ! ( "Schema: {schema}" ) ;
324+ let compiled_schema = match JSONSchema :: compile ( schema) {
325+ Ok ( compiled_schema) => compiled_schema,
326+ Err ( err) => {
327+ return Err ( DscError :: Validation ( format ! ( "JSON Schema Compilation Error: {err}" ) ) ) ;
328+ }
329+ } ;
330+
331+ if let Err ( err) = compiled_schema. validate ( json) {
332+ let mut error = format ! ( "'{source}' failed validation: " ) ;
333+ for e in err {
334+ error. push_str ( & format ! ( "\n {e} " ) ) ;
335+ }
336+ return Err ( DscError :: Validation ( error) ) ;
337+ } ;
338+
339+ Ok ( ( ) )
340+ }
341+
305342pub fn parse_input_to_json ( value : & str ) -> String {
306343 match serde_json:: from_str ( value) {
307344 Ok ( json) => json,
0 commit comments