chyabrung-cli 0.2.5

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! `chy build`: release binary + minified CSS + WASM islands + optional static export.

use crate::util::{ok, run as exec, step, which, CliResult};
use std::path::Path;
use std::process::Command;

pub(crate) fn supports_hydration() -> bool {
    std::fs::read_to_string("Cargo.toml")
        .map(|s| s.contains("cdylib") && s.contains("hydrate"))
        .unwrap_or(false)
}

fn build_css() -> CliResult {
    if !Path::new("style/app.css").exists() {
        return Ok(());
    }
    step("building CSS (Tailwind, minified)");
    let (exe, mut args): (String, Vec<String>) = if which("tailwindcss") {
        ("tailwindcss".into(), vec![])
    } else if Path::new("bin/tailwindcss").exists() || Path::new("bin/tailwindcss.exe").exists() {
        ((if cfg!(windows) { "bin/tailwindcss.exe" } else { "bin/tailwindcss" }).into(), vec![])
    } else if which("npx") && Path::new("node_modules/tailwindcss").is_dir() {
        ((if cfg!(windows) { "npx.cmd" } else { "npx" }).into(), vec!["@tailwindcss/cli".into()])
    } else {
        eprintln!("  skipped: Tailwind CLI not found. Download the standalone binary from https://github.com/tailwindlabs/tailwindcss/releases to ./bin/tailwindcss (or `npm i -D tailwindcss @tailwindcss/cli`)");
        return Ok(());
    };
    args.extend(["-i", "style/app.css", "-o", "public/app.css", "--minify"].map(String::from));
    match exec(Command::new(exe).args(args)) {
        Ok(()) => ok("public/app.css"),
        Err(e) => eprintln!("  warning: CSS build failed ({e}); continuing without fresh CSS"),
    }
    Ok(())
}

fn lib_name() -> CliResult<String> {
    let s = std::fs::read_to_string("Cargo.toml").map_err(|e| e.to_string())?;
    let t: toml::Table = s.parse().map_err(|e| format!("Cargo.toml: {e}"))?;
    let name = t
        .get("lib")
        .and_then(|l| l.get("name"))
        .and_then(|n| n.as_str())
        .map(str::to_owned)
        .unwrap_or(crate::util::package_name()?);
    Ok(name.replace('-', "_"))
}

/// Cargo's target directory (handles workspaces and `CARGO_TARGET_DIR`).
fn target_dir() -> String {
    Command::new("cargo")
        .args(["metadata", "--format-version", "1", "--no-deps"])
        .output()
        .ok()
        .and_then(|o| serde_json::from_slice::<serde_json::Value>(&o.stdout).ok())
        .and_then(|v| v["target_directory"].as_str().map(|s| s.replace('\\', "/")))
        .unwrap_or_else(|| "target".into())
}

fn build_wasm() -> CliResult {
    step("building WASM islands (wasm32-unknown-unknown, feature `hydrate`)");
    if !which("wasm-bindgen") {
        return Err("wasm-bindgen CLI not found: `cargo install wasm-bindgen-cli` (and `rustup target add wasm32-unknown-unknown`)".into());
    }
    exec(Command::new("cargo").args([
        "build",
        "--lib",
        "--release",
        "--target",
        "wasm32-unknown-unknown",
        "--no-default-features",
        "--features",
        "hydrate",
    ]))?;
    let wasm = format!("{}/wasm32-unknown-unknown/release/{}.wasm", target_dir(), lib_name()?);
    exec(Command::new("wasm-bindgen").args([&wasm, "--target", "web", "--out-dir", "dist/pkg", "--out-name", "app", "--no-typescript"]))?;
    if which("wasm-opt") {
        let _ = exec(Command::new("wasm-opt").args(["-Oz", "dist/pkg/app_bg.wasm", "-o", "dist/pkg/app_bg.wasm"]));
    }
    ok("dist/pkg/app.js + app_bg.wasm");
    Ok(())
}

/// `chy build`
pub fn run_build(static_site: bool, wasm: bool) -> CliResult {
    build_css()?;
    if wasm && supports_hydration() {
        build_wasm()?;
    }
    step("building release binary");
    let exe = crate::dev::cargo_build(true, None)?;
    ok(&format!("{}", exe.display()));
    if static_site {
        step("exporting static site to dist/site");
        exec(Command::new(&exe).args(["--export", "dist/site"]).env("APP_ENV", "production"))?;
        if Path::new("public").is_dir() {
            copy_dir(Path::new("public"), &Path::new("dist/site").join("assets"))?;
        }
        if Path::new("dist/pkg").is_dir() {
            copy_dir(Path::new("dist/pkg"), &Path::new("dist/site").join("pkg"))?;
        }
        ok("dist/site");
    }
    Ok(())
}

/// Entry point.
pub fn run(static_site: bool, wasm: bool) -> CliResult {
    crate::util::package_name()?;
    run_build(static_site, wasm)
}

fn copy_dir(from: &Path, to: &Path) -> CliResult {
    std::fs::create_dir_all(to).map_err(|e| e.to_string())?;
    for e in std::fs::read_dir(from).map_err(|e| e.to_string())?.flatten() {
        let p = e.path();
        let dest = to.join(e.file_name());
        if p.is_dir() {
            copy_dir(&p, &dest)?;
        } else {
            std::fs::copy(&p, &dest).map_err(|e| e.to_string())?;
        }
    }
    Ok(())
}