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 make:*` generators.

use crate::util::{pascal, plural, snake, write_new, CliResult};
use std::path::{Path, PathBuf};

fn add_mod(dir: &Path, module: &str) -> CliResult {
    let mod_rs = dir.join("mod.rs");
    let mut content = std::fs::read_to_string(&mod_rs).unwrap_or_default();
    let line = format!("pub mod {module};");
    if !content.lines().any(|l| l.trim() == line) {
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(&line);
        content.push('\n');
        std::fs::write(&mod_rs, content).map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// Remind the user to declare `mod <folder>;` if neither `src/lib.rs` nor `src/main.rs` does.
fn hint_mod_declared(folder: &str) {
    let declared = ["src/lib.rs", "src/main.rs"].iter().any(|f| {
        std::fs::read_to_string(f)
            .map(|s| s.lines().any(|l| l.trim().trim_start_matches("pub ").starts_with(&format!("mod {folder};"))))
            .unwrap_or(false)
    });
    if !declared {
        println!("  add `pub mod {folder};` to src/lib.rs (or `mod {folder};` to src/main.rs)");
    }
}

/// The model file content.
pub fn model_source(name: &str) -> String {
    let ty = pascal(name);
    let table = plural(&snake(name));
    format!(
        r#"use chyabrung::prelude::*;

/// The `{table}` table.
#[derive(Debug, Clone, Serialize, Deserialize, Model)]
#[model(table = "{table}", timestamps)]
pub struct {ty} {{
    pub id: i64,
    pub name: String,
    pub created_at: Option<String>,
    pub updated_at: Option<String>,
}}
"#
    )
}

/// `chy make:model Post [--migration]`
pub fn model(name: &str, with_migration: bool) -> CliResult {
    let file = snake(name);
    write_new(&PathBuf::from(format!("src/models/{file}.rs")), &model_source(name))?;
    add_mod(Path::new("src/models"), &file)?;
    hint_mod_declared("models");
    if with_migration {
        migration(&format!("create_{}_table", plural(&file)))?;
    }
    Ok(())
}

/// `chy make:controller PostController`
pub fn controller(name: &str) -> CliResult {
    let base = snake(name).trim_end_matches("_controller").to_string();
    let file = format!("{base}_controller");
    let ty = format!("{}Controller", pascal(&base));
    let table = plural(&base);
    let src = format!(
        r#"use chyabrung::prelude::*;

/// Handlers for `/{table}`. Mount it in `src/routes.rs` with `.mount({ty})`
/// (inside the `/api` group to serve it at `/api/{table}`).
///
/// Every method with a `#[get]`, `#[post]`, ... attribute is a route under
/// the prefix in `#[controller]`. Tip: `chy make:resource` also writes the
/// model, migration, request type and a test.
pub struct {ty};

#[controller("/{table}")]
impl {ty} {{
    /// List {table}.
    #[get("/")]
    async fn index(State(db): State<Db>, Query(q): Query<serde_json::Value>) -> Result<Json<Page<serde_json::Value>>> {{
        let page = q["page"].as_str().and_then(|p| p.parse().ok()).unwrap_or(1);
        Ok(Json(db.table("{table}").order_by_desc("id").paginate(page, 20).await?))
    }}

    /// Create one.
    #[post("/")]
    async fn store(State(db): State<Db>, Json(input): Json<serde_json::Value>) -> Result<(StatusCode, Json<serde_json::Value>)> {{
        let id = db.table("{table}").insert_get_id(&input).await?;
        Ok((StatusCode::CREATED, Json(db.table("{table}").find(id).await?)))
    }}

    /// Show one.
    #[get("/:id")]
    async fn show(State(db): State<Db>, Path(id): Path<i64>) -> Result<Json<serde_json::Value>> {{
        Ok(Json(db.table("{table}").find(id).await?))
    }}

    /// Update one.
    #[put("/:id")]
    async fn update(State(db): State<Db>, Path(id): Path<i64>, Json(input): Json<serde_json::Value>) -> Result<Json<serde_json::Value>> {{
        db.table("{table}").where_("id", id).update(&input).await?;
        Ok(Json(db.table("{table}").find(id).await?))
    }}

    /// Delete one.
    #[delete("/:id")]
    async fn destroy(State(db): State<Db>, Path(id): Path<i64>) -> Result<StatusCode> {{
        let n = db.table("{table}").where_("id", id).delete().await?;
        if n == 0 {{
            return Err(Error::not_found("Not found"));
        }}
        Ok(StatusCode::NO_CONTENT)
    }}
}}
"#
    );
    write_new(&PathBuf::from(format!("src/controllers/{file}.rs")), &src)?;
    add_mod(Path::new("src/controllers"), &file)?;
    hint_mod_declared("controllers");
    println!("  next: mount it in src/routes.rs with `.mount(crate::controllers::{file}::{ty})`");
    Ok(())
}

/// SQL for a migration name.
pub fn migration_sql(name: &str) -> (String, String) {
    let n = snake(name);
    if let Some(table) = n.strip_prefix("create_").and_then(|s| s.strip_suffix("_table")) {
        let up = format!(
            "CREATE TABLE {table} (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    name VARCHAR(255) NOT NULL,\n    created_at VARCHAR(40) NULL,\n    updated_at VARCHAR(40) NULL\n);\n"
        );
        return (up, format!("DROP TABLE {table};\n"));
    }
    ("-- Write your migration here\n".into(), "-- Reverse the migration here\n".into())
}

/// `chy make:migration create_posts_table` → returns the base name.
pub fn migration(name: &str) -> CliResult<String> {
    let ts = chrono::Utc::now().format("%Y%m%d%H%M%S");
    let base = format!("{ts}_{}", snake(name));
    let (up, down) = migration_sql(name);
    write_new(&PathBuf::from(format!("migrations/{base}.up.sql")), &up)?;
    write_new(&PathBuf::from(format!("migrations/{base}.down.sql")), &down)?;
    Ok(base)
}

/// `chy make:middleware EnsureAdmin`
pub fn middleware(name: &str) -> CliResult {
    let file = snake(name);
    let src = format!(
        r#"use chyabrung::prelude::*;

/// Middleware `{file}`. Register with `.middleware({file}::{file})`.
pub async fn {file}(req: Request, next: Next) -> Response {{
    // before the handler
    let res = next(req).await;
    // after the handler
    res
}}
"#
    );
    write_new(&PathBuf::from(format!("src/middleware/{file}.rs")), &src)?;
    add_mod(Path::new("src/middleware"), &file)?;
    hint_mod_declared("middleware");
    Ok(())
}

/// `chy make:job SendWelcomeEmail`
pub fn job(name: &str) -> CliResult {
    let file = snake(name);
    let ty = pascal(name);
    let src = format!(
        r#"use chyabrung::prelude::*;

/// Background job `{file}`. Dispatch with `queue.dispatch({ty} {{ .. }}).await?` and
/// register on the worker with `.register::<{ty}>()`.
#[derive(Debug, Serialize, Deserialize)]
pub struct {ty} {{
    pub id: i64,
}}

#[async_trait]
impl Job for {ty} {{
    const NAME: &'static str = "{file}";

    async fn handle(&self, _ctx: &JobContext) -> Result<()> {{
        tracing::info!("running {file} for {{}}", self.id);
        Ok(())
    }}
}}
"#
    );
    write_new(&PathBuf::from(format!("src/jobs/{file}.rs")), &src)?;
    add_mod(Path::new("src/jobs"), &file)?;
    hint_mod_declared("jobs");
    Ok(())
}

/// `chy make:page blog/[slug]`
pub fn page(path: &str) -> CliResult {
    let clean = path.trim_matches('/');
    let dynamic = clean.contains('[');
    let src = if dynamic {
        "use chyabrung::prelude::*;\nuse chyabrung::ui::prelude::*;\n\npub async fn page(cx: PageContext) -> Result<impl IntoView> {\n    let params: serde_json::Value = cx.params()?;\n    Ok(view! { <h1>\"Params: \" {params.to_string()}</h1> })\n}\n".to_string()
    } else {
        format!(
            "use chyabrung::ui::prelude::*;\n\npub fn page(cx: PageContext) -> impl IntoView {{\n    cx.title(\"{clean}\");\n    view! {{ <h1>\"{clean}\"</h1> }}\n}}\n"
        )
    };
    let file = if clean.is_empty() { PathBuf::from("app/page.rs") } else { PathBuf::from(format!("app/{clean}/page.rs")) };
    write_new(&file, &src)?;
    println!("  `file_routes!()` picks it up on the next build (touch src/main.rs if needed)");
    Ok(())
}

/// `chy make:seeder users`
pub fn seeder(name: &str) -> CliResult {
    let n = snake(name);
    write_new(
        &PathBuf::from(format!("database/seeds/{n}.sql")),
        &format!("-- Seed data for {n}\n-- INSERT INTO {n} (name) VALUES ('example');\n"),
    )
}

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

    #[test]
    fn model_and_migration_templates() {
        let m = model_source("BlogPost");
        assert!(m.contains("pub struct BlogPost"));
        assert!(m.contains("table = \"blog_posts\""));
        let (up, down) = migration_sql("create_posts_table");
        assert!(up.starts_with("CREATE TABLE posts"));
        assert_eq!(down, "DROP TABLE posts;\n");
        let (up, _) = migration_sql("add_bio_to_users");
        assert!(up.starts_with("--"));
    }
}

/// Up/down SQL for a full-text search index on `table` in `dialect`.
pub fn search_sql(dialect: chyabrung_db::Dialect, table: &str, columns: &[&str]) -> CliResult<(String, String)> {
    use chyabrung_db::search;
    let up = search::index_statements(dialect, table, "id", columns)?;
    let down = search::drop_index_statements(dialect, table);
    let join = |v: Vec<String>| v.into_iter().map(|s| format!("{s};\n")).collect::<String>();
    Ok((join(up), join(down)))
}

/// `chy make:search posts --columns title,body`: a migration that creates the
/// full-text search index for the database in `DATABASE_URL`.
pub fn search(table: &str, columns: &str) -> CliResult {
    let table = snake(table);
    let cols: Vec<&str> = columns.split(',').map(str::trim).filter(|c| !c.is_empty()).collect();
    let dialect = match crate::db::database_url() {
        Ok(url) => chyabrung_db::Dialect::from_url(&url).ok_or_else(|| format!("unknown database in DATABASE_URL: {url}"))?,
        Err(_) => {
            println!("  DATABASE_URL is not set; writing SQLite SQL");
            chyabrung_db::Dialect::Sqlite
        }
    };
    let (up, down) = search_sql(dialect, &table, &cols)?;
    let ts = chrono::Utc::now().format("%Y%m%d%H%M%S");
    let base = format!("{ts}_add_search_to_{table}");
    write_new(&PathBuf::from(format!("migrations/{base}.up.sql")), &up)?;
    write_new(&PathBuf::from(format!("migrations/{base}.down.sql")), &down)?;
    println!("  next: add `searchable = \"{}\"` to the model's #[model(...)] and run `chy migrate`", cols.join(", "));
    Ok(())
}

#[cfg(test)]
mod search_tests {
    #[test]
    fn search_migration_sql() {
        let (up, down) = super::search_sql(chyabrung_db::Dialect::Postgres, "posts", &["title", "body"]).unwrap();
        assert!(up.starts_with("CREATE INDEX \"posts_search_idx\" ON \"posts\" USING GIN"));
        assert_eq!(down, "DROP INDEX IF EXISTS \"posts_search_idx\";\n");
        assert!(super::search_sql(chyabrung_db::Dialect::Sqlite, "posts", &[]).is_err());
    }
}