use crate::{error::Error, util};
use boon::{Compiler, Schemas};
use log::debug;
use serde_json::Value;
#[cfg(test)]
pub mod compiler;
#[cfg(not(test))]
mod compiler;
pub struct Validator {
compiler: Compiler,
schemas: Schemas,
}
const SCHEMA_BASE: &str = "https://pgxn.org/meta/v";
impl Default for Validator {
fn default() -> Self {
Self::new()
}
}
impl Validator {
pub fn new() -> Validator {
Validator {
compiler: compiler::new(),
schemas: Schemas::new(),
}
}
pub fn validate(&mut self, meta: &Value) -> Result<u8, Error> {
self.validate_schema(meta, "distribution.schema.json")
}
pub fn validate_release(&mut self, meta: &Value) -> Result<u8, Error> {
self.validate_schema(meta, "release.schema.json")
}
pub fn validate_payload(&mut self, meta: &Value) -> Result<(), Error> {
self.validate_version_schema(meta, 2, "payload.schema.json")
}
fn validate_schema(&mut self, meta: &Value, schema: &str) -> Result<u8, Error> {
let v = util::get_version(meta).ok_or(Error::UnknownSpec)?;
self.validate_version_schema(meta, v, schema).map(|()| v)
}
fn validate_version_schema(&mut self, meta: &Value, v: u8, schema: &str) -> Result<(), Error> {
let id = format!("{SCHEMA_BASE}{v}/{schema}");
debug!(schema:display=id;"validate");
let compiler = &mut self.compiler;
let schemas = &mut self.schemas;
let idx = compiler.compile(&id, schemas)?;
schemas.validate(meta, idx)?;
Ok(())
}
}
#[cfg(test)]
mod tests;