codeint-config 0.10.2

Configuration and CLI argument parsing for codeint
Documentation
use serde_json::{Map, Value};

use crate::config_error::{ConfigFileKind, ConfigurationFileError, JsonType, KeyPath, KeySegment};

#[cfg(test)]
mod tests;

const DEFINITION_PREFIX: &str = "#/$defs/";

pub(super) fn check_shape(
    value: &Value,
    root_schema: &Value,
) -> Result<(), ConfigurationFileError> {
    Shape { root_schema }.check(value, root_schema, &KeyPath::default())
}

struct Shape<'schema> {
    root_schema: &'schema Value,
}

impl<'schema> Shape<'schema> {
    fn check(
        &self,
        value: &Value,
        schema: &'schema Value,
        key: &KeyPath,
    ) -> Result<(), ConfigurationFileError> {
        let schema = self.resolve(schema);
        if let Some(variants) = schema.get("anyOf").and_then(Value::as_array) {
            return self.check_any_of(value, variants, key);
        }
        self.check_type(value, schema, key)?;
        check_range(value, schema, key)?;
        check_allowed_values(value, schema, key)?;
        match value {
            Value::Object(members) => self.check_members(members, schema, key),
            Value::Array(items) => self.check_items(items, schema, key),
            _ => Ok(()),
        }
    }

    fn check_any_of(
        &self,
        value: &Value,
        variants: &'schema [Value],
        key: &KeyPath,
    ) -> Result<(), ConfigurationFileError> {
        let mut matched_type_error: Option<ConfigurationFileError> = None;
        let mut allowed_types = Vec::new();
        for variant in variants {
            let resolved = self.resolve(variant);
            let variant_types = self.expected_types(resolved);
            for ty in &variant_types {
                if !allowed_types.contains(ty) {
                    allowed_types.push(*ty);
                }
            }
            match self.check(value, resolved, key) {
                Ok(()) => return Ok(()),
                Err(error) => {
                    if matched_type_error.is_none()
                        && variant_types.iter().any(|ty| ty.accepts(value))
                    {
                        matched_type_error = Some(error);
                    }
                }
            }
        }
        if let Some(error) = matched_type_error {
            return Err(error);
        }
        Err(ConfigurationFileError::WrongType {
            file: ConfigFileKind::Json,
            key: key.clone(),
            expected: allowed_types,
            found: JsonType::of(value),
        })
    }

    fn expected_types(&self, schema: &'schema Value) -> Vec<JsonType> {
        let resolved = self.resolve(schema);
        if let Some(variants) = resolved.get("anyOf").and_then(Value::as_array) {
            let mut types = Vec::new();
            for variant in variants {
                for ty in self.expected_types(variant) {
                    if !types.contains(&ty) {
                        types.push(ty);
                    }
                }
            }
            return types;
        }
        match resolved.get("type") {
            Some(Value::String(name)) => JsonType::from_schema_name(name).into_iter().collect(),
            Some(Value::Array(names)) => names
                .iter()
                .filter_map(Value::as_str)
                .filter_map(JsonType::from_schema_name)
                .collect(),
            _ => Vec::new(),
        }
    }

    fn resolve(&self, schema: &'schema Value) -> &'schema Value {
        let definition = schema
            .get("$ref")
            .and_then(Value::as_str)
            .and_then(|reference| reference.strip_prefix(DEFINITION_PREFIX))
            .and_then(|name| self.root_schema.get("$defs")?.get(name));
        definition.map_or(schema, |definition| self.resolve(definition))
    }

    fn check_type(
        &self,
        value: &Value,
        schema: &'schema Value,
        key: &KeyPath,
    ) -> Result<(), ConfigurationFileError> {
        let expected = self.expected_types(schema);
        if expected.is_empty() || expected.iter().any(|json_type| json_type.accepts(value)) {
            Ok(())
        } else {
            Err(ConfigurationFileError::WrongType {
                file: ConfigFileKind::Json,
                key: key.clone(),
                expected,
                found: JsonType::of(value),
            })
        }
    }

    fn check_members(
        &self,
        members: &Map<String, Value>,
        schema: &'schema Value,
        key: &KeyPath,
    ) -> Result<(), ConfigurationFileError> {
        let properties = schema.get("properties").and_then(Value::as_object);
        let additional = schema.get("additionalProperties");
        for (name, member) in members {
            let member_key = key.child(KeySegment::Key(name.clone()));
            match properties.and_then(|properties| properties.get(name)) {
                Some(member_schema) => self.check(member, member_schema, &member_key)?,
                None => match additional {
                    Some(Value::Bool(false)) => {
                        return Err(ConfigurationFileError::UnknownKey {
                            file: ConfigFileKind::Json,
                            key: member_key,
                            allowed: properties
                                .map(|properties| properties.keys().cloned().collect())
                                .unwrap_or_default(),
                        });
                    }
                    Some(additional_schema) if additional_schema.is_object() => {
                        self.check(member, additional_schema, &member_key)?;
                    }
                    _ => {}
                },
            }
        }
        let missing = schema
            .get("required")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(Value::as_str)
            .find(|name| !members.contains_key(*name));
        match missing {
            Some(name) => Err(ConfigurationFileError::MissingKey {
                file: ConfigFileKind::Json,
                key: key.clone(),
                missing: name.to_owned(),
            }),
            None => Ok(()),
        }
    }

    fn check_items(
        &self,
        items: &[Value],
        schema: &'schema Value,
        key: &KeyPath,
    ) -> Result<(), ConfigurationFileError> {
        let Some(item_schema) = schema.get("items") else {
            return Ok(());
        };
        items.iter().enumerate().try_for_each(|(index, item)| {
            self.check(item, item_schema, &key.child(KeySegment::Index(index)))
        })
    }
}

fn check_range(value: &Value, schema: &Value, key: &KeyPath) -> Result<(), ConfigurationFileError> {
    let Some(found) = value.as_f64() else {
        return Ok(());
    };
    if let (Some(exclusive_minimum), Some(maximum)) = (
        schema.get("exclusiveMinimum").and_then(Value::as_f64),
        schema.get("maximum").and_then(Value::as_f64),
    ) {
        return if found > exclusive_minimum && found <= maximum {
            Ok(())
        } else {
            Err(ConfigurationFileError::OutOfExclusiveMinRange {
                file: ConfigFileKind::Json,
                key: key.clone(),
                exclusive_minimum,
                maximum,
                found,
            })
        };
    }
    let (Some(minimum), Some(maximum)) = (
        schema.get("minimum").and_then(Value::as_f64),
        schema.get("maximum").and_then(Value::as_f64),
    ) else {
        return Ok(());
    };
    if (minimum..=maximum).contains(&found) {
        Ok(())
    } else {
        Err(ConfigurationFileError::OutOfRange {
            file: ConfigFileKind::Json,
            key: key.clone(),
            minimum,
            maximum,
            found,
        })
    }
}

fn check_allowed_values(
    value: &Value,
    schema: &Value,
    key: &KeyPath,
) -> Result<(), ConfigurationFileError> {
    let Some(allowed) = schema.get("enum").and_then(Value::as_array) else {
        return Ok(());
    };
    if allowed.contains(value) {
        return Ok(());
    }
    Err(ConfigurationFileError::NotOneOf {
        file: ConfigFileKind::Json,
        key: key.clone(),
        allowed: allowed
            .iter()
            .map(|allowed| match allowed {
                Value::String(name) => name.clone(),
                other => other.to_string(),
            })
            .collect(),
        found: Box::new(value.clone()),
    })
}