larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
use laravel::console::{Console, command, escape_markup};

use crate::support;

/// The views the crate ships, which `larablog:publish` writes into the application.
pub const VIEWS: [(&str, &str); 2] = [
    ("index.html", include_str!("../resources/views/index.html")),
    ("show.html", include_str!("../resources/views/show.html")),
];

/// Check the blog posts: titles, slugs per language, categories, authors, missing translations.
///
/// Errors are posts that are not published at all (no title, a slug used twice in one language), a
/// `post:` link to a folder that does not exist, in any post, scheduled ones included, and a
/// condition with no closing `:::`. A link to a post that is not out yet is not an error. Warnings
/// are posts missing in a language the collection is written in. It exits 1 on errors, for CI.
#[command("larablog:check")]
pub async fn check(
    /// Only this collection.
    collection: Option<String>,
    /// Also list links to posts that are not out yet.
    #[arg(long)]
    pending: bool,
    console: &mut Console,
) -> laravel::Result<u8> {
    let mut failed = false;

    for (name, blog) in crate::collections() {
        if collection.as_deref().is_some_and(|only| only != name) {
            continue;
        }

        blog.rebuild_index()?;
        console.markup(format!("<fg=green>{}</>", escape_markup(&name)));

        for error in blog.errors() {
            console.markup(format!(
                "  <fg=red>โœ—</> {}: {}",
                escape_markup(&error.file),
                escape_markup(&error.message)
            ));
            failed = true;
        }

        let mut by_id: Vec<(String, Vec<String>)> = Vec::new();
        let all = blog.all();

        for post in &all {
            match by_id.iter_mut().find(|(id, _)| *id == post.id) {
                Some((_, locales)) => locales.push(post.locale.clone()),
                None => by_id.push((post.id.clone(), vec![post.locale.clone()])),
            }

            for condition in post.conditions() {
                if !condition.closed {
                    console.markup(format!(
                        "  <fg=red>โœ—</> {}/{}: if-published post:{} is missing its closing :::.",
                        escape_markup(&post.id),
                        post.locale,
                        escape_markup(&condition.post)
                    ));
                    failed = true;
                }
            }

            // Scheduled posts too: a link written today to a folder that does not exist would
            // otherwise only be found the day the post goes live.
            for id in blog.broken_links(post) {
                console.markup(format!(
                    "  <fg=red>โœ—</> {}/{}: links to post:{}, which does not exist.",
                    escape_markup(&post.id),
                    post.locale,
                    escape_markup(&id)
                ));
                failed = true;
            }

            // Not an error: the link is plain text until its post is out.
            if pending {
                for (id, date) in blog.pending_links(post) {
                    let when = date.map_or_else(
                        || "when it stops being a draft".to_owned(),
                        |date| format!("on {}", support::date_string(date)),
                    );

                    console.markup(format!(
                        "  <fg=yellow>ยท</> {}/{}: post:{} becomes a link {when}.",
                        escape_markup(&post.id),
                        post.locale,
                        escape_markup(&id)
                    ));
                }
            }
        }

        let locales = blog.locales();

        for (id, present) in &by_id {
            let missing: Vec<&str> = locales
                .iter()
                .filter(|locale| !present.contains(locale))
                .map(String::as_str)
                .collect();

            if !missing.is_empty() {
                console.markup(format!(
                    "  <fg=yellow>!</> {}: no {} version.",
                    escape_markup(id),
                    missing.join(", ")
                ));
            }
        }

        console.line(format!(
            "  {} files, {} posts, {}.",
            all.len(),
            by_id.len(),
            locales.join("/")
        ));
    }

    Ok(u8::from(failed))
}

/// Rebuild the blog indexes without waiting for the next request.
///
/// Optional: a request builds a missing index by itself, and `larablog:check` refreshes it before
/// validating.
#[command("larablog:cache")]
pub async fn cache(
    /// Only this collection.
    collection: Option<String>,
    console: &mut Console,
) -> laravel::Result<u8> {
    let collections = crate::collections();

    if let Some(only) = &collection
        && !collections.iter().any(|(name, _)| name == only)
    {
        console.error(format!("Unknown collection: {only}."));

        return Ok(1);
    }

    let caching = laravel::config().section::<crate::LarablogConfig>().cache.enabled;

    for (name, blog) in collections {
        if collection.as_deref().is_some_and(|only| only != name) {
            continue;
        }

        let count = blog.rebuild_index()?;

        console.line(format!(
            "{name}: {count} files indexed.{}",
            if caching { "" } else { " Caching is disabled." }
        ));
    }

    Ok(0)
}

// The PHP package has no views of its own to publish: the site writes them. This crate ships a
// plain pair so a blog works the moment its provider is added, and publishing them is how a site
// starts from them, since Laravel Rust 0.1 has no `vendor:publish`.
/// Write the views the crate ships into `resources/views/vendor/larablog`, where they override the
/// packaged ones.
#[command("larablog:publish")]
pub async fn publish(
    /// Overwrite the files when they already exist.
    #[arg(long)]
    force: bool,
    console: &mut Console,
) -> laravel::Result<u8> {
    let directory = laravel::config().app.resource_path("views/vendor/larablog");
    let mut failed = false;

    std::fs::create_dir_all(&directory)?;

    for (file, contents) in VIEWS {
        let target = directory.join(file);

        if target.exists() && !force {
            console.warn(format!(
                "{} already exists. Pass --force to overwrite it.",
                target.display()
            ));
            failed = true;

            continue;
        }

        std::fs::write(&target, contents)?;
        console.info(format!("Wrote {}.", target.display()));
    }

    Ok(u8::from(failed))
}