motabhai 0.2.0

A static CMS in the spirit of Lektor: build engine, dev server and admin UI in one binary
//! The `motabhai` command-line interface.

use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};
use motabhai_core::{Database, Error, Project};

mod starter;

/// A static CMS: build engine, dev server and admin UI in one binary.
#[derive(Debug, Parser)]
#[command(name = "motabhai", version, about)]
struct Cli {
    /// Project directory or its `motabhai.toml`. Defaults to searching upward
    /// from the current directory.
    #[arg(short, long, global = true, value_name = "PATH")]
    project: Option<PathBuf>,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Build the site into the output directory.
    Build {
        /// Output directory. Defaults to `public` in the project root.
        #[arg(short, long, value_name = "DIR")]
        output: Option<PathBuf>,
        /// Run every notebook post with Jupyter (`[notebook] jupyter`)
        /// first and publish the fresh outputs. The notebook files are not
        /// changed.
        #[arg(long)]
        execute: bool,
    },
    /// Run the dev server: rebuild on changes, reload the browser and serve
    /// the admin UI.
    Serve {
        /// Port to listen on; 0 picks a free one.
        #[arg(long, default_value_t = 5000)]
        port: u16,
        /// Address to listen on. Only this machine can connect by default.
        #[arg(long, default_value = "127.0.0.1", value_name = "ADDRESS")]
        host: std::net::IpAddr,
        /// Output directory to build into and serve. Defaults to `public` in
        /// the project root.
        #[arg(short, long, value_name = "DIR")]
        output: Option<PathBuf>,
    },
    /// Create a new site from the starter template.
    New {
        /// Directory to create.
        path: PathBuf,
        /// Style the starter site with Tailwind CSS: its own templates and
        /// stylesheet, over the plain theme.
        #[arg(long)]
        tailwind: bool,
        /// The theme the site uses. Every theme is installed in its
        /// `themes/`, to change between later.
        #[arg(
            long,
            value_enum,
            value_name = "THEME",
            default_value_t,
            conflicts_with = "tailwind"
        )]
        theme: starter::Theme,
    },
    /// Build the site, then publish it to a `[deploy.<target>]` of
    /// `motabhai.toml`.
    Deploy {
        /// The target to deploy to. May be left out when the site has only
        /// one.
        target: Option<String>,
        /// Output directory. Defaults to `public` in the project root.
        #[arg(short, long, value_name = "DIR")]
        output: Option<PathBuf>,
    },
    /// Load and validate the project without building it.
    Check,
    /// Remove build output and cached build state.
    Clean {
        /// Output directory. Defaults to `public` in the project root.
        #[arg(short, long, value_name = "DIR")]
        output: Option<PathBuf>,
    },
}

fn main() -> ExitCode {
    install_error_hook();
    let cli = Cli::parse();
    match run(&cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(report) => {
            eprintln!("{report:?}");
            ExitCode::FAILURE
        }
    }
}

fn run(cli: &Cli) -> miette::Result<()> {
    let project = cli.project.as_deref();
    match &cli.command {
        Command::Check => check(project),
        Command::Build { output, execute } => build(project, output.as_deref(), *execute),
        Command::Deploy { target, output } => deploy(project, target.as_deref(), output.as_deref()),
        Command::Serve { port, host, output } => serve(project, *host, *port, output.as_deref()),
        Command::New {
            path,
            tailwind,
            theme,
        } => starter::create(path, *tailwind, *theme),
        Command::Clean { output } => clean(project, output.as_deref()),
    }
}

fn load_project(path: Option<&Path>) -> miette::Result<Project> {
    if let Some(path) = path {
        return Ok(Project::open(path)?);
    }
    let cwd = std::env::current_dir().map_err(|e| Error::io(".", e))?;
    Ok(Project::discover(&cwd)?)
}

fn check(path: Option<&Path>) -> miette::Result<()> {
    let project = load_project(path)?;
    let db = Database::load(&project)?;
    let config = project.config();
    // Each record once, as the primary language has it.
    let primary = || db.records().filter(|r| r.alt() == config.primary().code);
    let attachments: usize = primary().map(|r| r.attachments().len()).sum();
    let hidden = primary().filter(|r| r.is_hidden()).count();
    println!(
        "ok: {} ({})",
        config.project.name,
        project.config_path().display()
    );
    let mut summary = plural(db.models().len(), "model");
    let blocks = db.models().block_count();
    if blocks > 0 {
        let _ = write!(summary, ", {}", plural(blocks, "flow block"));
    }
    let _ = write!(summary, ", {}", plural(primary().count(), "record"));
    if config.is_multilingual() {
        let _ = write!(summary, " in {} languages", config.alternatives.len());
    }
    println!(
        "{summary} ({hidden} hidden), {}",
        plural(attachments, "attachment")
    );
    Ok(())
}

fn build(path: Option<&Path>, output: Option<&Path>, execute: bool) -> miette::Result<()> {
    let project = load_project(path)?;
    let output = output_dir(&project, output)?;
    build_with_hooks(&project, &output, execute)
}

/// Builds the site, with its `[hooks]` before and after, warning about
/// notebook posts with unfinished code cells. With `execute`, the notebook
/// posts are run after the `before_build` hooks, as part of the build.
fn build_with_hooks(project: &Project, output: &Path, execute: bool) -> miette::Result<()> {
    let hooks = &project.config().hooks;
    for command in &hooks.before_build {
        eprintln!("running {command}");
        motabhai_build::hooks::run(project, command, output)?;
    }
    let options = motabhai_build::Options::new().with_execute(execute);
    let build = motabhai_build::build_with(project, output, &options)?;
    for unfinished in &build.unfinished {
        eprintln!("warning: {unfinished}");
    }
    println!("{}", summary(&build, &relative(output)));
    for command in &hooks.after_build {
        eprintln!("running {command}");
        motabhai_build::hooks::run(project, command, output)?;
    }
    Ok(())
}

fn deploy(path: Option<&Path>, target: Option<&str>, output: Option<&Path>) -> miette::Result<()> {
    let project = load_project(path)?;
    let config = project.config();
    let names = || {
        config
            .deploy
            .iter()
            .map(|t| t.name.clone())
            .collect::<Vec<_>>()
    };
    let target = match target {
        Some(name) => config
            .deploy_target(name)
            .ok_or_else(|| Error::UnknownDeployTarget {
                name: name.to_owned(),
                help: if config.deploy.is_empty() {
                    "the site has no deploy targets; add a `[deploy.<name>]` table to `motabhai.toml`".to_owned()
                } else {
                    format!("the site's targets are: {}", names().join(", "))
                },
            })?,
        None => match config.deploy.as_slice() {
            [only] => only,
            _ => return Err(Error::NoDeployTarget { names: names() }.into()),
        },
    };
    motabhai_deploy::check(target)?;
    let output = output_dir(&project, output)?;
    build_with_hooks(&project, &output, false)?;
    let deployed = motabhai_deploy::deploy(&project, target, &output)?;
    println!("deployed to {}: {deployed}", target.name);
    Ok(())
}

/// `built 6 pages, 1 attachment and 1 asset into public (2 rebuilt)`, with
/// redirects and thumbnails too if there are any.
fn summary(build: &motabhai_build::Build, output: &Path) -> String {
    let counts = build.counts();
    let mut changes = format!("{} rebuilt", build.rebuilt().count());
    if !build.removed.is_empty() {
        let _ = write!(changes, ", {} removed", build.removed.len());
    }
    let mut kinds = vec![
        plural(counts.pages, "page"),
        plural(counts.attachments, "attachment"),
    ];
    if counts.redirects > 0 {
        kinds.push(plural(counts.redirects, "redirect"));
    }
    if counts.thumbnails > 0 {
        kinds.push(plural(counts.thumbnails, "thumbnail"));
    }
    kinds.push(plural(counts.assets, "asset"));
    let last = kinds.pop().unwrap_or_default();
    format!(
        "built {} and {last} into {} ({changes})",
        kinds.join(", "),
        output.display()
    )
}

fn serve(
    path: Option<&Path>,
    host: std::net::IpAddr,
    port: u16,
    output: Option<&Path>,
) -> miette::Result<()> {
    let project = load_project(path)?;
    let output = output_dir(&project, output)?;
    let options = motabhai_server::Options::new(host, port, output);
    Ok(motabhai_server::serve(&project, &options)?)
}

fn clean(path: Option<&Path>, output: Option<&Path>) -> miette::Result<()> {
    let project = load_project(path)?;
    let output = output_dir(&project, output)?;
    let cleaned = motabhai_build::clean(&project, &output)?;
    if cleaned.output {
        println!("removed {}", relative(&output).display());
    } else if cleaned.state {
        println!("removed the build state");
    } else {
        println!(
            "nothing to clean: {} does not exist",
            relative(&output).display()
        );
    }
    Ok(())
}

/// The output directory: `--output` relative to the current directory, or
/// `public` in the project root.
fn output_dir(project: &Project, output: Option<&Path>) -> miette::Result<PathBuf> {
    match output {
        Some(dir) => Ok(std::path::absolute(dir).map_err(|e| Error::io(dir, e))?),
        None => Ok(project.root().join(motabhai_build::OUTPUT_DIR)),
    }
}

/// `path` relative to the current directory, if it is inside it.
fn relative(path: &Path) -> PathBuf {
    std::env::current_dir()
        .ok()
        .and_then(|cwd| path.strip_prefix(cwd).ok().map(Path::to_path_buf))
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| path.to_path_buf())
}

fn plural(n: usize, noun: &str) -> String {
    if n == 1 {
        format!("1 {noun}")
    } else {
        format!("{n} {noun}s")
    }
}

fn install_error_hook() {
    // Ignore the error: it only fails if a hook is already installed.
    let _ = miette::set_hook(Box::new(|_| {
        Box::new(
            miette::MietteHandlerOpts::new()
                .context_lines(2)
                .tab_width(4)
                .build(),
        )
    }));
}