chyabrung-cli 0.2.0

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! `chy new <app> --template <api|blog|saas>`

use crate::util::{ok, step, CliResult};
use include_dir::{include_dir, Dir};
use std::path::{Path, PathBuf};

static TEMPLATES: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates");

/// Template names.
pub fn templates() -> Vec<String> {
    TEMPLATES.dirs().map(|d| d.path().to_string_lossy().into_owned()).collect()
}

/// Root of a local Chyabrung checkout (explicit, or the one this CLI was built from).
fn local_root(explicit: Option<&str>) -> Option<PathBuf> {
    let candidate = match explicit {
        Some(p) => PathBuf::from(p),
        None => Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."),
    };
    let candidate = std::fs::canonicalize(&candidate).unwrap_or(candidate);
    candidate.join("crates/framework/Cargo.toml").is_file().then_some(candidate)
}

fn norm(p: &Path) -> String {
    let s = p.to_string_lossy().replace('\\', "/");
    s.strip_prefix("//?/").map(str::to_owned).unwrap_or(s)
}

/// `(chyabrung dependency line, chyabrung-testing dependency line)`.
fn dependencies(explicit: Option<&str>, features: &str, testing_features: &str) -> (String, String) {
    match local_root(explicit) {
        Some(root) => (
            format!("chyabrung = {{ path = \"{}\", features = [{features}] }}", norm(&root.join("crates/framework"))),
            format!("chyabrung-testing = {{ path = \"{}\", features = [{testing_features}] }}", norm(&root.join("crates/testing"))),
        ),
        None => (
            format!("chyabrung = {{ version = \"0.2\", features = [{features}] }}"),
            format!("chyabrung-testing = {{ version = \"0.2\", features = [{testing_features}] }}"),
        ),
    }
}

/// Render placeholders.
pub fn render(content: &str, name: &str, dep: &str, testing_dep: &str, key: &str) -> String {
    content
        .replace("{{app_name}}", name)
        .replace("{{crate_name}}", &name.replace('-', "_"))
        .replace("{{chyabrung_dep}}", dep)
        .replace("{{testing_dep}}", testing_dep)
        .replace("{{app_key}}", key)
}

fn extract(dir: &Dir<'_>, base: &Path, out: &Path, vars: &dyn Fn(&str) -> String) -> CliResult {
    for f in dir.files() {
        let rel = f.path().strip_prefix(base).map_err(|e| e.to_string())?;
        let mut target = out.join(rel);
        let fname = target.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
        if let Some(stripped) = fname.strip_suffix(".tmpl") {
            target.set_file_name(stripped);
        }
        if fname == "env.example" {
            target.set_file_name(".env");
        }
        if fname == "gitignore" {
            target.set_file_name(".gitignore");
        }
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
        }
        match f.contents_utf8() {
            Some(text) => std::fs::write(&target, vars(text)),
            None => std::fs::write(&target, f.contents()),
        }
        .map_err(|e| format!("cannot write {}: {e}", target.display()))?;
    }
    for d in dir.dirs() {
        extract(d, base, out, vars)?;
    }
    Ok(())
}

fn features_for(template: &str) -> &'static str {
    match template {
        "api" => "\"sqlite\", \"auth\", \"storage\"",
        "blog" => "\"sqlite\", \"auth\", \"ui\"",
        "saas" => "\"sqlite\", \"auth\", \"tenancy\", \"jobs-db\", \"mail\"",
        _ => "\"sqlite\"",
    }
}

/// Create a new project.
pub fn run(name: &str, template: &str, chyabrung_path: Option<&str>) -> CliResult {
    if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
        return Err("app names may only contain letters, digits, `-` and `_`".into());
    }
    let out = Path::new(name);
    if out.exists() {
        return Err(format!("directory `{name}` already exists"));
    }
    let tdir = TEMPLATES
        .get_dir(template)
        .ok_or_else(|| format!("unknown template `{template}`; available: {}", templates().join(", ")))?;
    step(&format!("creating `{name}` from the `{template}` template"));
    let (dep, testing_dep) = dependencies(chyabrung_path, features_for(template), "\"db\", \"auth\"");
    let key = crate::util::new_key();
    extract(tdir, tdir.path(), out, &|text| render(text, name, &dep, &testing_dep, &key))?;
    ok(&format!("created {name}/"));
    println!(
        "\n  Next steps:\n\n    cd {name}\n    chy migrate\n    chy dev\n\n  Then open http://127.0.0.1:2007 🥁\n"
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn templates_are_embedded() {
        let t = templates();
        for name in ["api", "blog", "saas"] {
            assert!(t.contains(&name.to_string()), "missing template {name}: {t:?}");
        }
    }

    #[test]
    fn renders_placeholders() {
        let s = render("name={{app_name}} crate={{crate_name}} {{chyabrung_dep}}", "my-app", "dep", "t", "k");
        assert_eq!(s, "name=my-app crate=my_app dep");
    }

    #[test]
    fn scaffolds_every_template() {
        let d = tempfile::tempdir().unwrap();
        for t in ["api", "blog", "saas"] {
            let tdir = TEMPLATES.get_dir(t).unwrap();
            let out = d.path().join(t);
            extract(tdir, tdir.path(), &out, &|text| render(text, "demo", "chyabrung = \"0.1\"", "chyabrung-testing = \"0.1\"", "k")).unwrap();
            assert!(out.join("Cargo.toml").is_file(), "{t}: Cargo.toml");
            assert!(out.join(".env").is_file(), "{t}: .env");
            assert!(out.join("src/main.rs").is_file(), "{t}: main.rs");
            let cargo = std::fs::read_to_string(out.join("Cargo.toml")).unwrap();
            assert!(cargo.contains("name = \"demo\""));
            assert!(!cargo.contains("{{"));
        }
    }
}