larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
//! YAML into plain `serde_json` values, so the rest of the crate handles frontmatter and the two
//! shared files like PHP handles the arrays Symfony's parser returns.
//!
//! The parser is `saphyr`: YAML 1.2, safe Rust, maintained. A mapping keeps no order in a
//! `serde_json::Value`, so [`parse_entries`] returns the top level as pairs, which is what
//! `_categories.yml` and `_authors.yml` need.

use saphyr::{LoadableYamlNode, Scalar, Yaml};
use serde_json::{Map, Number, Value};

/// A YAML mapping at the top of a document, in file order.
pub type Entries = Vec<(String, Value)>;

/// Parse a document into a value. An empty document is `Null`.
///
/// # Errors
///
/// Fails with the parser's message when the text is not valid YAML.
pub fn parse(source: &str) -> Result<Value, String> {
    let documents = Yaml::load_from_str(source).map_err(|error| error.to_string())?;

    Ok(documents.first().map_or(Value::Null, convert))
}

/// Parse a document whose top level is a mapping, keeping the order of its keys. A document that
/// is not a mapping gives no entries, as the PHP package treats a file that is not an array.
///
/// # Errors
///
/// Fails with the parser's message when the text is not valid YAML.
pub fn parse_entries(source: &str) -> Result<Entries, String> {
    let documents = Yaml::load_from_str(source).map_err(|error| error.to_string())?;

    Ok(match documents.first().and_then(Yaml::as_mapping) {
        Some(mapping) => mapping
            .iter()
            .map(|(key, value)| (key_of(key), convert(value)))
            .collect(),
        None => Vec::new(),
    })
}

fn convert(node: &Yaml<'_>) -> Value {
    match node {
        Yaml::Value(scalar) => scalar_value(scalar),
        Yaml::Representation(text, ..) => Value::String(text.to_string()),
        Yaml::Sequence(items) => Value::Array(items.iter().map(convert).collect()),
        Yaml::Mapping(mapping) => {
            let mut map = Map::new();

            for (key, value) in mapping {
                map.insert(key_of(key), convert(value));
            }

            Value::Object(map)
        }
        Yaml::Tagged(_, inner) => convert(inner),
        Yaml::Alias(_) | Yaml::BadValue => Value::Null,
    }
}

fn scalar_value(scalar: &Scalar<'_>) -> Value {
    match scalar {
        Scalar::Null => Value::Null,
        Scalar::Boolean(value) => Value::Bool(*value),
        Scalar::Integer(value) => Value::Number((*value).into()),
        Scalar::FloatingPoint(value) => Number::from_f64(value.0).map_or(Value::Null, Value::Number),
        Scalar::String(value) => Value::String(value.to_string()),
    }
}

fn key_of(key: &Yaml<'_>) -> String {
    match convert(key) {
        Value::String(text) => text,
        Value::Null => String::new(),
        other => other.to_string(),
    }
}