markupwright 0.1.3

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

use crate::domain::registry::{self, ConfiguredDomain};

use super::{Error, ErrorKind, Metadata, RawConfig, Render, value};

pub(super) fn validate(raw: &RawConfig) -> Result<(), Error> {
    if raw.version != 1 {
        return Err(Error {
            kind: ErrorKind::UnsupportedVersion(raw.version),
        });
    }

    validate_render(&raw.render)?;

    if raw.documents.is_empty() {
        return Err(Error::semantic(
            "documents",
            "must contain at least one rule",
        ));
    }

    for (index, document) in raw.documents.iter().enumerate() {
        value::validate_path(&document.template).map_err(|error| {
            Error::semantic(format!("documents[{index}].template"), error.to_string())
        })?;

        if document
            .include
            .iter()
            .any(|pattern| !pattern.ends_with(raw.render.source_suffix.as_ref()))
        {
            return Err(Error::semantic(
                format!("documents[{index}].include"),
                format!(
                    "every pattern must end with render.source-suffix {:?}",
                    raw.render.source_suffix
                ),
            ));
        }
    }

    for path in raw.directories.keys() {
        value::validate_path(path)
            .map_err(|error| Error::semantic(format!("directories.{path:?}"), error.to_string()))?;
    }

    Ok(())
}

fn validate_render(render: &Render) -> Result<(), Error> {
    value::validate_path(&render.header)
        .map_err(|error| Error::semantic("render.header", error.to_string()))?;

    if render.source_suffix.is_empty()
        || !render.source_suffix.starts_with('.')
        || !render
            .source_suffix
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || ".-_".contains(character))
    {
        return Err(Error::semantic(
            "render.source-suffix",
            "must be a filename suffix beginning with a dot",
        ));
    }

    value::validate_filename(&render.navigation)
        .map_err(|error| Error::semantic("render.navigation", error.to_string()))?;

    Ok(())
}

pub(super) fn configure_domains(
    configured: BTreeMap<String, toml::Value>,
) -> Result<Vec<ConfiguredDomain>, Error> {
    let registrations = registry::registrations().collect::<Vec<_>>();
    let mut names = BTreeSet::new();

    for registration in &registrations {
        if !names.insert(registration.name) {
            return Err(Error {
                kind: ErrorKind::DuplicateDomain(registration.name),
            });
        }
    }

    configured
        .into_iter()
        .map(|(name, value)| {
            let registration = registrations
                .iter()
                .find(|registration| registration.name == name)
                .copied()
                .ok_or_else(|| Error {
                    kind: ErrorKind::UnknownDomain(name.clone().into_boxed_str()),
                })?;

            ConfiguredDomain::parse(registration, value).map_err(|source| Error {
                kind: ErrorKind::Domain {
                    name: name.into_boxed_str(),
                    source,
                },
            })
        })
        .collect()
}

pub(super) fn validate_namespaces(domains: &[ConfiguredDomain]) -> Result<(), Error> {
    const CORE: [&str; 7] = [
        "children",
        "description",
        "kind",
        "markupwright",
        "name",
        "nav",
        "version",
    ];

    let mut owners = BTreeMap::<Box<str>, &'static str>::new();

    for domain in domains {
        for namespace in domain.namespaces() {
            if namespace.is_empty() {
                return Err(Error::semantic(
                    format!("domains.{}", domain.name()),
                    "context namespaces must not be empty",
                ));
            }

            if CORE.contains(&namespace.as_ref()) {
                return Err(Error::semantic(
                    format!("domains.{}", domain.name()),
                    format!("context namespace {namespace:?} conflicts with a core value"),
                ));
            }

            if let Some(previous) = owners.insert(namespace.clone(), domain.name()) {
                return Err(Error::semantic(
                    format!("domains.{}", domain.name()),
                    format!(
                        "context namespace {namespace:?} is also provided by domain {previous:?}"
                    ),
                ));
            }
        }
    }

    Ok(())
}

pub(super) fn validate_metadata_domains(
    workspace: &Metadata,
    directories: &BTreeMap<String, Metadata>,
    domains: &[ConfiguredDomain],
) -> Result<(), Error> {
    let configured = |name: &str| domains.iter().any(|domain| domain.name() == name);

    if let Some(domain) = workspace.domain.as_deref()
        && !configured(domain)
    {
        return Err(Error::semantic(
            "workspace.domain",
            unconfigured_domain(domain),
        ));
    }

    for (path, metadata) in directories {
        if let Some(domain) = metadata.domain.as_deref()
            && !configured(domain)
        {
            return Err(Error::semantic(
                format!("directories.{path:?}.domain"),
                unconfigured_domain(domain),
            ));
        }
    }

    Ok(())
}

pub(super) fn unconfigured_domain(domain: &str) -> String {
    format!("references unconfigured domain {domain:?}")
}