larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
//! The routes of a collection, as names and addresses.
//!
//! Laravel Rust 0.1 has no named routes, so Larablog keeps a small registry of its own: the five
//! pages of a collection in each language, named `{locale}.{collection}.{index|show|category|tag|
//! feed}` as in PHP, with the address each one has. The addresses are a function of the
//! configuration, so [`Blog::url`](crate::Blog::url) and [`Post::url`](crate::Post::url) work the
//! same in a handler, a command and a test.

use crate::config::CollectionConfig;

/// The five pages of a collection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
    /// The listing.
    Index,
    /// The RSS feed.
    Feed,
    /// A category's listing.
    Category,
    /// A tag's listing.
    Tag,
    /// A post.
    Show,
}

impl Kind {
    /// Every page, in the order PHP registers them.
    pub const ALL: [Kind; 5] = [Kind::Index, Kind::Feed, Kind::Category, Kind::Tag, Kind::Show];

    /// `index`, `feed`, `category`, `tag` or `show`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Index => "index",
            Self::Feed => "feed",
            Self::Category => "category",
            Self::Tag => "tag",
            Self::Show => "show",
        }
    }

    /// The page named `index`, `feed`, `category`, `tag` or `show`.
    pub fn parse(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|kind| kind.as_str() == name)
    }
}

/// One registered route.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Route {
    /// `{locale}.{collection}.{kind}`.
    pub name: String,
    /// Which page it is.
    pub kind: Kind,
    /// The language it serves.
    pub locale: String,
    /// Its address with `{slug}`, `{category}` or `{tag}` placeholders, from the root.
    pub uri: String,
}

/// The name of a route: `en.blog.show`.
pub fn route_name(collection: &str, kind: &str, locale: &str) -> String {
    format!("{locale}.{collection}.{kind}")
}

/// The language's URL prefix: none for the default language of the application, its code for the
/// rest. Laralang, in PHP, replaces this with the prefixes of the whole site.
fn prefix<'a>(locale: &'a str, app_locale: &str) -> &'a str {
    if locale == app_locale { "" } else { locale }
}

/// The address of one page of a collection in one language.
pub fn uri(
    collection: &str,
    kind: Kind,
    locale: &str,
    settings: &CollectionConfig,
    locales: &[String],
    app_locale: &str,
) -> String {
    let path = settings
        .paths
        .get(locale)
        .or_else(|| locales.first().and_then(|first| settings.paths.get(first)))
        .map_or(collection, String::as_str)
        .trim_matches('/');
    let base = [prefix(locale, app_locale), path]
        .iter()
        .filter(|part| !part.is_empty())
        .copied()
        .collect::<Vec<_>>()
        .join("/");

    let category = settings
        .segments
        .category
        .get(locale)
        .map_or("category", String::as_str);
    let tag = settings.segments.tag.get(locale).map_or("tag", String::as_str);

    let rest = match kind {
        Kind::Index => String::new(),
        Kind::Feed => "feed".to_owned(),
        Kind::Category => format!("{category}/{{category}}"),
        Kind::Tag => format!("{tag}/{{tag}}"),
        Kind::Show => "{slug}".to_owned(),
    };

    let joined = [base.as_str(), rest.as_str()]
        .iter()
        .filter(|part| !part.is_empty())
        .copied()
        .collect::<Vec<_>>()
        .join("/");

    format!("/{joined}")
}

/// Every route of a collection: five pages in each language.
pub fn definitions(collection: &str, settings: &CollectionConfig, locales: &[String], app_locale: &str) -> Vec<Route> {
    let mut routes = Vec::new();

    for locale in locales {
        for kind in Kind::ALL {
            routes.push(Route {
                name: route_name(collection, kind.as_str(), locale),
                kind,
                locale: locale.clone(),
                uri: uri(collection, kind, locale, settings, locales, app_locale),
            });
        }
    }

    routes
}

/// Fill the placeholders of an address and put what is left in the query string, the way
/// Laravel's `route()` does.
pub fn fill(uri: &str, parameters: &[(&str, &str)]) -> String {
    let mut path = uri.to_owned();
    let mut query = Vec::new();

    for (key, value) in parameters {
        let placeholder = format!("{{{key}}}");

        if path.contains(&placeholder) {
            path = path.replace(&placeholder, &rawurlencode(value));
        } else {
            query.push(format!("{}={}", rawurlencode(key), rawurlencode(value)));
        }
    }

    if query.is_empty() {
        path
    } else {
        format!("{path}?{}", query.join("&"))
    }
}

/// PHP's `rawurlencode`.
pub fn rawurlencode(text: &str) -> String {
    let mut encoded = String::with_capacity(text.len());

    for byte in text.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
            encoded.push(char::from(byte));
        } else {
            encoded.push_str(&format!("%{byte:02X}"));
        }
    }

    encoded
}