laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
use laravel::console::{Console, command, escape_markup};
use laravel::container::Inject;

use crate::generator::CardGenerator;
use crate::sources::CardSources;

/// Generate social cards and blog covers from SVG or image templates.
///
/// One command for all content types: what used to be a command per kind of content is now a card
/// source per kind of content.
#[command("cards:generate")]
pub async fn generate_cards(
    /// Only these sources (defaults to all registered).
    #[arg(long)]
    source: Vec<String>,
    /// Only cards whose key matches one of these.
    #[arg(long)]
    only: Vec<String>,
    /// Regenerate even when nothing changed.
    #[arg(long)]
    force: bool,
    /// List what would be generated, write nothing.
    #[arg(long)]
    dry_run: bool,
    console: &mut Console,
    generator: Inject<CardGenerator>,
    registered: Inject<CardSources>,
) -> laravel::Result<u8> {
    if !generator.renderer().available() {
        // Image templates are drawn without a renderer, so a missing one only stops the run when an SVG
        // template needs it.
        let mut needs_renderer = false;

        for template in laravel::config().section::<crate::LaracardsConfig>().templates.keys() {
            needs_renderer = needs_renderer || !generator.uses_image(template)?;
        }

        if needs_renderer {
            console.error("The configured renderer is not available. Install one, or use image templates.");

            return Ok(1);
        }
    }

    let sources: Vec<_> = registered
        .all()
        .into_iter()
        .filter(|(name, _)| source.is_empty() || source.contains(name))
        .collect();

    if sources.is_empty() {
        console.warn("No card sources registered. Add one with LaracardsServiceProvider::source.");

        return Ok(0);
    }

    let (mut generated, mut skipped, mut failed) = (0, 0, 0);

    for (name, source) in sources {
        console.markup(format!("<fg=cyan>{}</>", escape_markup(&name)));

        for card in source.cards().await? {
            if !only.is_empty() && !only.iter().any(|key| key == card.key()) {
                continue;
            }

            let key = escape_markup(card.key());

            if dry_run {
                console.markup(format!("  <fg=gray>[DRY]</>   {key}"));

                continue;
            }

            let path = match generator.generate(&card, force).await {
                Ok(path) => path,
                Err(error) => {
                    console.markup(format!(
                        "  <fg=red>[FAIL]</>  {key} - {}",
                        escape_markup(error.to_string())
                    ));
                    failed += 1;

                    continue;
                }
            };

            let Some(path) = path else {
                console.markup(format!("  <fg=gray>[SKIP]</>  {key} (up to date)"));
                skipped += 1;

                continue;
            };

            let size = std::fs::metadata(&path).map_or(0.0, |metadata| metadata.len() as f64 / 1024.0);

            console.markup(format!("  <fg=green>[OK]</>    {key} - {size:.1} KB"));
            generated += 1;
        }
    }

    if !dry_run {
        generator.manifest().save()?;
    }

    console.new_line();
    console.line(format!("Generated {generated}, skipped {skipped}, failed {failed}."));

    Ok(u8::from(failed > 0))
}

// The PHP package does this with `vendor:publish --tag=laracards-templates`, which Laravel Rust 0.1 lacks.
/// Write the example template, post.svg, into the templates directory.
#[command("laracards:publish")]
pub async fn publish(
    /// Overwrite the file when it already exists.
    #[arg(long)]
    force: bool,
    console: &mut Console,
) -> laravel::Result<u8> {
    let config = crate::LaracardsConfig::current();
    let directory = crate::LaracardsConfig::resolve(&crate::LaracardsConfig::base(), &config.paths.templates);
    let target = directory.join("post.svg");

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

        return Ok(1);
    }

    std::fs::create_dir_all(&directory)?;
    std::fs::write(&target, crate::templates::POST)?;

    console.info(format!("Wrote {}.", target.display()));

    Ok(0)
}