motabhai 0.2.0

A static CMS in the spirit of Lektor: build engine, dev server and admin UI in one binary
//! `motabhai new`: the starter site and the themes motabhai ships with,
//! embedded in the binary.

use std::fmt::Write as _;
use std::path::Path;

use motabhai_core::Error;

/// The files of a directory beside `src/`, as (path there, contents).
macro_rules! files {
    ($dir:literal: $($path:literal),* $(,)?) => {
        &[$(($path, include_str!(concat!("../", $dir, "/", $path)))),*]
    };
}

/// The site's own files as (path in the new site, contents): its config,
/// models, content and menu. They live in `crates/motabhai/starter/`;
/// `gitignore` and `github/` are stored without their dots so they do not
/// apply to this repository.
const FILES: &[(&str, &str)] = &[
    (".gitignore", include_str!("../starter/gitignore")),
    (
        ".github/workflows/deploy.yml",
        include_str!("../starter/github/workflows/deploy.yml"),
    ),
    ("motabhai.toml", include_str!("../starter/motabhai.toml")),
    (
        "models/page.toml",
        include_str!("../starter/models/page.toml"),
    ),
    (
        "models/blog.toml",
        include_str!("../starter/models/blog.toml"),
    ),
    (
        "models/blog-post.toml",
        include_str!("../starter/models/blog-post.toml"),
    ),
    (
        "models/projects.toml",
        include_str!("../starter/models/projects.toml"),
    ),
    (
        "models/project.toml",
        include_str!("../starter/models/project.toml"),
    ),
    (
        "content/index.md",
        include_str!("../starter/content/index.md"),
    ),
    (
        "content/about/index.md",
        include_str!("../starter/content/about/index.md"),
    ),
    (
        "content/blog/index.md",
        include_str!("../starter/content/blog/index.md"),
    ),
    (
        "content/blog/hello-world/index.md",
        include_str!("../starter/content/blog/hello-world/index.md"),
    ),
    (
        "content/projects/index.md",
        include_str!("../starter/content/projects/index.md"),
    ),
    (
        "content/projects/example-project/index.md",
        include_str!("../starter/content/projects/example-project/index.md"),
    ),
    (
        "databags/menu.toml",
        include_str!("../starter/databags/menu.toml"),
    ),
];

/// The files `--tailwind` adds to the site, replacing those in [`FILES`]
/// with the same path. Its templates and stylesheet are the site's own, so
/// they replace the plain theme's. They live in
/// `crates/motabhai/starter-tailwind/`.
const TAILWIND_FILES: &[(&str, &str)] = files!("starter-tailwind":
    "motabhai.toml",
    "assets/css/main.css",
    "templates/layout.html",
    "templates/blog-post.html",
);

/// A theme motabhai ships with. Every new site has all of them installed
/// in `themes/`, and uses the one `--theme` names.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum Theme {
    /// One column of text with the menu on top.
    #[default]
    Plain,
    /// A sidebar beside the content, post cards and the latest posts on
    /// the home page, in coral, navy and cream.
    EngineeringFantasy,
}

impl Theme {
    /// Every theme motabhai ships with.
    const ALL: [Self; 2] = [Self::Plain, Self::EngineeringFantasy];

    /// The theme's name: its directory in `themes/`.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Plain => "plain",
            Self::EngineeringFantasy => "engineering-fantasy",
        }
    }

    /// The theme's files, as (path in the theme, contents). They live in
    /// `crates/motabhai/themes/<name>/`.
    fn files(self) -> &'static [(&'static str, &'static str)] {
        match self {
            Self::Plain => files!("themes/plain":
                "assets/css/main.css",
                "templates/layout.html",
                "templates/page.html",
                "templates/blog.html",
                "templates/blog-post.html",
                "templates/tag.html",
                "templates/projects.html",
                "templates/project.html",
            ),
            Self::EngineeringFantasy => files!("themes/engineering-fantasy":
                "assets/css/main.css",
                "templates/layout.html",
                "templates/page.html",
                "templates/blog.html",
                "templates/blog-post.html",
                "templates/card.html",
                "templates/tag.html",
                "templates/projects.html",
                "templates/project.html",
            ),
        }
    }
}

/// The placeholder in `motabhai.toml` replaced by the quoted site name.
const NAME_PLACEHOLDER: &str = "__SITE_NAME__";

/// The placeholder in the Tailwind `motabhai.toml` replaced by
/// [`TAILWIND_VERSION`].
const VERSION_PLACEHOLDER: &str = "__TAILWIND_VERSION__";

/// The placeholder in the GitHub Actions workflow replaced by this
/// motabhai's version, the release it installs.
const MOTABHAI_VERSION_PLACEHOLDER: &str = "__MOTABHAI_VERSION__";

/// The Tailwind CSS version new sites pin: the latest release when this
/// version of motabhai was made.
pub const TAILWIND_VERSION: &str = "4.3.5";

/// The placeholder in `motabhai.toml` replaced by the quoted name of the
/// theme in use.
const THEME_PLACEHOLDER: &str = "__THEME__";

/// Writes the starter site to `dir`, which must not exist or be empty. The
/// site is named after the directory, has every theme motabhai ships with
/// in `themes/`, and uses `theme`. With `tailwind`, it is styled with
/// Tailwind CSS instead: its own templates and stylesheet, over the plain
/// theme.
pub fn create(dir: &Path, tailwind: bool, theme: Theme) -> miette::Result<()> {
    let not_empty = dir.exists()
        && (!dir.is_dir()
            || std::fs::read_dir(dir)
                .map_err(|e| Error::io(dir, e))?
                .next()
                .is_some());
    if not_empty {
        return Err(Error::NotEmpty {
            dir: dir.to_path_buf(),
        }
        .into());
    }
    let absolute = std::path::absolute(dir).map_err(|e| Error::io(dir, e))?;
    let name = absolute
        .file_name()
        .map_or_else(|| "My site".into(), |n| n.to_string_lossy());
    let replacements: &[(&str, &str)] = if tailwind { TAILWIND_FILES } else { &[] };
    let added = replacements
        .iter()
        .filter(|(path, _)| FILES.iter().all(|(p, _)| p != path));
    for (path, text) in FILES.iter().chain(added) {
        let text = replacements
            .iter()
            .find(|(p, _)| p == path)
            .map_or(*text, |(_, t)| t);
        let text = text
            .replace(NAME_PLACEHOLDER, &toml_string(&name))
            .replace(THEME_PLACEHOLDER, &toml_string(theme.name()))
            .replace(VERSION_PLACEHOLDER, TAILWIND_VERSION)
            .replace(MOTABHAI_VERSION_PLACEHOLDER, env!("CARGO_PKG_VERSION"));
        write(&dir.join(path), &text)?;
    }
    for shipped in Theme::ALL {
        let theme_dir = dir.join(motabhai_core::THEMES_DIR).join(shipped.name());
        for (path, text) in shipped.files() {
            write(&theme_dir.join(path), text)?;
        }
    }
    println!("created {}", dir.display());
    println!("next: cd {} && motabhai build", dir.display());
    Ok(())
}

/// Writes one file of the new site, making its directory.
fn write(path: &Path, text: &str) -> miette::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
    }
    Ok(std::fs::write(path, text).map_err(|e| Error::io(path, e))?)
}

/// A TOML basic string.
fn toml_string(text: &str) -> String {
    let mut quoted = String::with_capacity(text.len() + 2);
    quoted.push('"');
    for c in text.chars() {
        match c {
            '"' => quoted.push_str("\\\""),
            '\\' => quoted.push_str("\\\\"),
            c if c.is_control() => {
                // Writing to a String cannot fail.
                let _ = write!(quoted, "\\u{:04X}", u32::from(c));
            }
            c => quoted.push(c),
        }
    }
    quoted.push('"');
    quoted
}