chyabrung-cli 0.2.4

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! `chy migrate`, `migrate:rollback`, `migrate:status`, `migrate:fresh`, `db:seed`.

use crate::util::{ok, step, CliResult};
use chyabrung_db::Db;
use std::path::Path;

/// The app's database URL, resolved exactly as the app does it
/// (`DATABASE_URL`, then `DB_CONNECTION` + `DB_*` in `.env`).
pub(crate) fn database_url() -> CliResult<String> {
    chyabrung_core::config::database_url()
}

pub(crate) fn runtime() -> CliResult<tokio::runtime::Runtime> {
    tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())
}

pub(crate) async fn connect() -> CliResult<Db> {
    let url = database_url()?;
    Db::connect(&url).await.map_err(|e| e.message().to_string())
}

/// Migrations are compiled into the app (`migrations!()`), so the commands
/// build and start it with `CHY_MIGRATE=<cmd>`: its `migrator().run(&db)`
/// performs the command, prints the result and exits.
fn run_in_app(cmd: &str) -> CliResult {
    let pkg = crate::util::package_name()?;
    step("building the app to run its migrations…");
    let mut c = std::process::Command::new("cargo");
    c.args(["run", "--quiet"]);
    if Path::new("src/main.rs").is_file() {
        c.args(["--bin", &pkg]);
    }
    c.env("CHY_MIGRATE", cmd);
    crate::util::run(&mut c).map_err(|_| "the migration command failed (see the messages above)".to_string())
}

/// Apply pending migrations.
pub fn migrate() -> CliResult {
    run_in_app("run")
}

/// Roll back batches.
pub fn rollback(steps: u32) -> CliResult {
    run_in_app(&format!("rollback:{steps}"))
}

/// Print status.
pub fn status() -> CliResult {
    run_in_app("status")
}

/// Reset and migrate.
pub fn fresh() -> CliResult {
    run_in_app("fresh")
}

/// Run SQL seeds and the optional seed binary.
pub fn seed() -> CliResult {
    runtime()?.block_on(async {
        let db = connect().await?;
        let dir = Path::new("database/seeds");
        if dir.is_dir() {
            let mut files: Vec<_> = std::fs::read_dir(dir)
                .map_err(|e| e.to_string())?
                .flatten()
                .map(|e| e.path())
                .filter(|p| p.extension().map(|e| e == "sql").unwrap_or(false))
                .collect();
            files.sort();
            for f in files {
                let sql = std::fs::read_to_string(&f).map_err(|e| e.to_string())?;
                if sql.lines().all(|l| l.trim().is_empty() || l.trim_start().starts_with("--")) {
                    continue;
                }
                db.execute_script(&sql).await.map_err(|e| format!("{}: {}", f.display(), e.message()))?;
                ok(&format!("seeded {}", f.display()));
            }
        }
        Ok::<_, String>(())
    })?;
    if Path::new("src/bin/seed.rs").is_file() {
        step("running src/bin/seed.rs");
        crate::util::run(std::process::Command::new("cargo").args(["run", "--quiet", "--bin", "seed"]))?;
    }
    Ok(())
}