markupwright 0.1.3

Template-driven workspace documentation generator
Documentation
use std::{collections::BTreeMap, path::Path};

use serde::{Deserialize, de::DeserializeOwned};

use crate::domain::{
    ContextEntry,
    collection::{Scope, matching_files},
};

#[derive(Debug)]
pub(crate) struct Domain;

#[derive(Debug, Deserialize)]
#[serde(transparent)]
pub(crate) struct Config(BTreeMap<String, Collection>);

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Collection {
    include: crate::config::Patterns,
    fields: Box<[Box<str>]>,
    #[serde(default, rename = "sort-by")]
    sort_by: Option<Box<str>>,
    #[serde(default)]
    scope: Scope,
}

#[derive(Debug, thiserror::Error)]
enum ParseError {
    #[error("missing opening delimiter")]
    MissingOpening,
    #[error("missing closing delimiter")]
    MissingClosing,
    #[error("invalid frontmatter boundary")]
    InvalidBoundary,
    #[error("invalid YAML: {0}")]
    Yaml(#[from] serde_norway::Error),
}

impl crate::domain::registry::Domain for Domain {
    type Config = Config;
    type State = ();

    const NAME: &'static str = "frontmatter";

    fn initialize(
        config: &Self::Config,
        _root: &Path,
        _files: &crate::domain::IndexedFiles,
    ) -> Result<Self::State, crate::domain::Error> {
        for (namespace, collection) in &config.0 {
            if namespace.is_empty() || collection.include.is_empty() || collection.fields.is_empty()
            {
                return Err(crate::domain::Error::message(
                    crate::layout::CONFIG,
                    Self::NAME,
                    "namespaces, include patterns, and fields must not be empty",
                ));
            }

            if let Some(sort_by) = &collection.sort_by
                && !collection
                    .fields
                    .iter()
                    .any(|field| field.as_ref() == sort_by.as_ref())
            {
                return Err(crate::domain::Error::message(
                    crate::layout::CONFIG,
                    Self::NAME,
                    format!("{namespace}: sort-by field {sort_by:?} is not selected"),
                ));
            }
        }

        Ok(())
    }

    fn context(
        config: &Self::Config,
        _state: &Self::State,
        context: &crate::RenderCtx<'_>,
    ) -> Result<Vec<ContextEntry>, crate::domain::Error> {
        let mut output = Vec::new();

        for (namespace, collection) in &config.0 {
            let Some(base) = collection.scope.base(context) else {
                continue;
            };
            let mut entries = Vec::new();

            for path in matching_files(context, base, &collection.include) {
                let source = context.workspace.contents(path).ok_or_else(|| {
                    crate::domain::Error::message(path, Self::NAME, "source is not UTF-8 text")
                })?;
                let document = parse::<serde_norway::Value>(source).map_err(|error| {
                    crate::domain::Error::parse(path, "YAML frontmatter", error)
                })?;
                let mapping = document.as_mapping().ok_or_else(|| {
                    crate::domain::Error::message(
                        path,
                        "YAML frontmatter",
                        "frontmatter must be a mapping",
                    )
                })?;
                let mut entry = BTreeMap::new();

                for field in &collection.fields {
                    let key = serde_norway::Value::String(field.to_string());
                    let value = mapping.get(&key).ok_or_else(|| {
                        crate::domain::Error::message(
                            path,
                            "YAML frontmatter",
                            format!("missing configured field {field:?}"),
                        )
                    })?;

                    entry.insert(field.clone(), value.clone());
                }

                entries.push((path, entry));
            }

            if let Some(field) = &collection.sort_by {
                entries.sort_by(|(left_path, left), (right_path, right)| {
                    sortable_value(left.get(field.as_ref()))
                        .cmp(sortable_value(right.get(field.as_ref())))
                        .then_with(|| left_path.cmp(right_path))
                });
            }

            if !entries.is_empty() {
                let values = entries
                    .into_iter()
                    .map(|(_, entry)| entry)
                    .collect::<Vec<_>>();

                output.push((
                    namespace.clone().into_boxed_str(),
                    crate::domain::to_value(&values),
                ));
            }
        }

        Ok(output)
    }

    fn is_source_input(
        config: &Self::Config,
        _state: &Self::State,
        root: &Path,
        path: &Path,
    ) -> bool {
        config.0.values().any(|collection| {
            crate::domain::collection::pattern_matches(
                root,
                collection.scope,
                &collection.include,
                path,
            )
        })
    }

    fn namespaces(config: &Self::Config) -> Vec<Box<str>> {
        config
            .0
            .keys()
            .map(|namespace| namespace.clone().into_boxed_str())
            .collect()
    }
}

fn sortable_value(value: Option<&serde_norway::Value>) -> &str {
    value.and_then(serde_norway::Value::as_str).unwrap_or("")
}

fn parse<T>(source: &str) -> Result<T, ParseError>
where
    T: DeserializeOwned,
{
    let source = source
        .strip_prefix("---\n")
        .or_else(|| source.strip_prefix("---\r\n"))
        .ok_or(ParseError::MissingOpening)?;
    let end = source
        .match_indices("\n---")
        .find_map(|(index, _)| {
            let remainder = source.get(index + "\n---".len()..)?;

            (remainder.is_empty() || remainder.starts_with('\n') || remainder.starts_with("\r\n"))
                .then_some(index)
        })
        .ok_or(ParseError::MissingClosing)?;
    let yaml = source.get(..end).ok_or(ParseError::InvalidBoundary)?;

    serde_norway::from_str(yaml).map_err(ParseError::from)
}

crate::domain::registry::register_domain!(Domain);

#[cfg(test)]
mod tests {
    use googletest::prelude::*;

    use super::*;

    #[gtest]
    fn parses_arbitrary_frontmatter() -> Result<()> {
        let frontmatter = parse::<BTreeMap<String, String>>(
            "---\nname: rust-quality\ndescription: Rust checks.\n---\n# Document\n",
        )
        .or_fail()?;

        verify_eq!(
            frontmatter.get("name").map(String::as_str),
            Some("rust-quality")
        )?;
        verify_eq!(
            frontmatter.get("description").map(String::as_str),
            Some("Rust checks.")
        )
    }
}