Skip to content

Commit

Permalink
Add Util crate to get version
Browse files Browse the repository at this point in the history
  • Loading branch information
theory committed Sep 6, 2024
1 parent 9180f9e commit ca9c5d5
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 33 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ assert!(validator.validate(&meta).is_ok());
*/

mod util;
mod valid;
pub use valid::{ValidationError, Validator};
mod meta;
Expand Down
16 changes: 3 additions & 13 deletions src/meta/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{collections::HashMap, error::Error, fs::File, path::PathBuf};

use crate::util;
use relative_path::RelativePathBuf;
use semver::Version;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -297,18 +298,6 @@ impl TryFrom<Value> for Meta {
}
}

fn version_from(meta: &Value) -> Option<u8> {
let v = meta.get("meta-spec")?.get("version")?.as_str()?;
if v.len() < 2 {
return None;
}
match &v[0..2] {
"1." => Some(1),
"2." => Some(2),
_ => None,
}
}

impl TryFrom<&[Value]> for Meta {
type Error = Box<dyn Error>;
fn try_from(meta: &[Value]) -> Result<Self, Self::Error> {
Expand All @@ -317,7 +306,8 @@ impl TryFrom<&[Value]> for Meta {
}

// Find the version of the first doc.
let version = version_from(&meta[0]).ok_or("no spec version found in first meta value")?;
let version =
util::get_version(&meta[0]).ok_or("no spec version found in first meta value")?;

// Convert the first doc to v2 if necessary.
let mut v2 = match version {
Expand Down
23 changes: 3 additions & 20 deletions src/valid/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use std::{error::Error, fmt};
use boon::{Compiler, Schemas};
use serde_json::Value;

use crate::util;

// Export compiler publicly only for tests.
#[cfg(test)]
pub mod compiler;
Expand Down Expand Up @@ -64,26 +66,7 @@ impl Validator {
/// for validation. Returns a the Meta spec version on success and a
/// validation error on failure.
pub fn validate<'a>(&'a mut self, meta: &'a Value) -> Result<u8, Box<dyn Error + '_>> {
let map = meta.as_object().ok_or(ValidationError::UnknownSpec)?;
let version = map
.get("meta-spec")
.ok_or(ValidationError::UnknownSpec)?
.as_object()
.ok_or(ValidationError::UnknownSpec)?
.get("version")
.ok_or(ValidationError::UnknownSpec)?
.as_str()
.ok_or(ValidationError::UnknownSpec)?;

if version.len() < 2 {
return Err(Box::new(ValidationError::UnknownSpec));
}

let v = match &version[0..2] {
"1." => 1,
"2." => 2,
_ => return Err(Box::new(ValidationError::UnknownSpec)),
};
let v = util::get_version(meta).ok_or(ValidationError::UnknownSpec)?;
let id = format!("{SCHEMA_BASE}{v}/distribution.schema.json");

let compiler = &mut self.compiler;
Expand Down

0 comments on commit ca9c5d5

Please sign in to comment.