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 doctor`: check that the project is ready to run.

use crate::util::{which, CliResult};
use base64::Engine;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Level {
    Ok,
    Warn,
    Fail,
    Skip,
}

struct Report {
    fails: usize,
    warns: usize,
}

impl Report {
    fn line(&mut self, level: Level, what: &str, detail: impl AsRef<str>) {
        let (icon, color) = match level {
            Level::Ok => ("✓", "\x1b[32m"),
            Level::Warn => {
                self.warns += 1;
                ("!", "\x1b[33m")
            }
            Level::Fail => {
                self.fails += 1;
                ("✗", "\x1b[31m")
            }
            Level::Skip => ("-", "\x1b[2m"),
        };
        let detail = detail.as_ref();
        if detail.is_empty() {
            println!("  {color}{icon}\x1b[0m {what}");
        } else {
            println!("  {color}{icon}\x1b[0m {what} \x1b[2m— {detail}\x1b[0m");
        }
    }

    fn section(&self, title: &str) {
        println!("\n\x1b[1m{title}\x1b[0m");
    }
}

/// `chy doctor`
pub fn run() -> CliResult {
    let mut r = Report { fails: 0, warns: 0 };
    chyabrung_core::config::load_dotenv();
    let production = chyabrung_core::config::is_production();
    let cargo_toml = std::fs::read_to_string("Cargo.toml").ok();

    r.section("Project");
    project(&mut r, cargo_toml.as_deref());

    r.section("Environment");
    env_file(&mut r);
    app_key(&mut r, std::env::var("APP_KEY").ok().as_deref(), production);

    r.section("Server");
    port(&mut r);

    r.section("Database");
    database(&mut r, cargo_toml.as_deref());

    r.section("Tools");
    tools(&mut r);

    println!();
    match (r.fails, r.warns) {
        (0, 0) => {
            println!("\x1b[32mAll checks passed.\x1b[0m");
            Ok(())
        }
        (0, w) => {
            println!("\x1b[33m{w} warning{}, no problems.\x1b[0m", plural(w));
            Ok(())
        }
        (f, _) => Err(format!("{f} problem{} found", plural(f))),
    }
}

fn plural(n: usize) -> &'static str {
    if n == 1 {
        ""
    } else {
        "s"
    }
}

fn project(r: &mut Report, cargo_toml: Option<&str>) {
    match cargo_toml {
        None => r.line(Level::Fail, "Cargo.toml", "not found; run `chy doctor` inside a Chyabrung app"),
        Some(s) if s.contains("chyabrung") => match crate::util::package_name() {
            Ok(n) => r.line(Level::Ok, "Chyabrung app", n),
            Err(e) => r.line(Level::Fail, "Cargo.toml", e),
        },
        Some(_) => r.line(Level::Warn, "Cargo.toml", "does not depend on chyabrung"),
    }
    if Path::new("chyabrung.toml").is_file() {
        match std::fs::read_to_string("chyabrung.toml").map(|s| s.parse::<toml::Table>()) {
            Ok(Ok(_)) => r.line(Level::Ok, "chyabrung.toml", ""),
            Ok(Err(e)) => r.line(Level::Fail, "chyabrung.toml", format!("invalid TOML: {}", e.message())),
            Err(e) => r.line(Level::Fail, "chyabrung.toml", e.to_string()),
        }
    } else {
        r.line(Level::Skip, "chyabrung.toml", "not present (defaults are used)");
    }
}

fn env_file(r: &mut Report) {
    if Path::new(".env").is_file() {
        r.line(Level::Ok, ".env", "");
    } else if Path::new(".env.example").is_file() || Path::new("env.example").is_file() {
        r.line(Level::Warn, ".env", "missing; copy .env.example to .env");
    } else {
        r.line(Level::Skip, ".env", "not present");
    }
}

/// Same rules as `chyabrung_auth::Key::from_env`.
fn check_app_key(value: Option<&str>, production: bool) -> (Level, String) {
    let Some(v) = value.filter(|v| !v.trim().is_empty()) else {
        return if production {
            (Level::Fail, "not set; required in production (run `chy key:generate`)".into())
        } else {
            (Level::Warn, "not set; a random key is used, so sessions reset on restart (run `chy key:generate`)".into())
        };
    };
    let bytes = match v.strip_prefix("base64:") {
        Some(b64) => match base64::engine::general_purpose::STANDARD.decode(b64.trim()) {
            Ok(b) => b.len(),
            Err(_) => return (Level::Fail, "invalid base64 value (run `chy key:generate`)".into()),
        },
        None => v.len(),
    };
    if bytes < 16 {
        (Level::Fail, format!("only {bytes} bytes; at least 16 needed (run `chy key:generate`)"))
    } else if bytes < 32 {
        (Level::Warn, format!("{bytes} bytes; 32+ recommended"))
    } else {
        (Level::Ok, format!("{bytes} bytes"))
    }
}

fn app_key(r: &mut Report, value: Option<&str>, production: bool) {
    let (level, detail) = check_app_key(value, production);
    r.line(level, "APP_KEY", detail);
}

fn port(r: &mut Report) {
    let cfg = match chyabrung_core::Config::load() {
        Ok(c) => c,
        Err(e) => {
            r.line(Level::Fail, "configuration", e.message());
            return;
        }
    };
    let host: String = cfg.get_or("app.host", "127.0.0.1".to_string());
    let port: u16 = cfg.get_or("app.port", 2007);
    let addr = format!("{host}:{port}");
    match std::net::TcpListener::bind(&addr) {
        Ok(_) => r.line(Level::Ok, &format!("port {port} is free"), &addr),
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
            r.line(Level::Fail, &format!("port {port}"), format!("{addr} is in use (is the app already running?)"))
        }
        Err(e) => r.line(Level::Fail, &format!("port {port}"), format!("cannot bind {addr}: {e}")),
    }
}

fn database(r: &mut Report, cargo_toml: Option<&str>) {
    let url = match crate::db::database_url() {
        Ok(u) => u,
        Err(e) => {
            let uses_db = cargo_toml.is_some_and(|s| ["sqlite", "postgres", "mysql"].iter().any(|d| s.contains(d)))
                || Path::new("migrations").is_dir();
            if uses_db {
                // Not fatal: the app may fall back to a default URL in code.
                r.line(Level::Warn, "DATABASE_URL", format!("{e}; skipped connection and migration checks"));
            } else {
                r.line(Level::Skip, "database", "not configured");
            }
            return;
        }
    };
    let rt = match crate::db::runtime() {
        Ok(rt) => rt,
        Err(e) => return r.line(Level::Fail, "database", e),
    };
    rt.block_on(async {
        let db = match tokio::time::timeout(Duration::from_secs(5), crate::db::connect()).await {
            Ok(Ok(db)) => {
                r.line(Level::Ok, "database reachable", redact(&url));
                db
            }
            Ok(Err(e)) => return r.line(Level::Fail, "database", format!("{}: {e}", redact(&url))),
            Err(_) => return r.line(Level::Fail, "database", format!("{}: no answer within 5s", redact(&url))),
        };
        if !Path::new("migrations").is_dir() {
            return r.line(Level::Skip, "migrations", "no migrations/ directory");
        }
        let status = match crate::db::migrator() {
            Ok(m) => m.status(&db).await.map_err(|e| e.message().to_string()),
            Err(e) => Err(e),
        };
        match status {
            Ok(st) => {
                let pending: Vec<_> = st.iter().filter(|s| s.batch.is_none()).map(|s| s.name.as_str()).collect();
                if pending.is_empty() {
                    r.line(Level::Ok, "migrations", format!("{} applied, none pending", st.len()));
                } else {
                    r.line(
                        Level::Warn,
                        &format!("{} pending migration{}", pending.len(), plural(pending.len())),
                        format!("{} (run `chy migrate`)", pending.join(", ")),
                    );
                }
            }
            Err(e) => r.line(Level::Fail, "migrations", e),
        }
    });
}

/// Hide the password in `scheme://user:pass@host/db`.
fn redact(url: &str) -> String {
    if let Some((scheme, rest)) = url.split_once("://") {
        if let Some((creds, host)) = rest.rsplit_once('@') {
            let user = creds.split(':').next().unwrap_or("");
            let masked = if creds.contains(':') { format!("{user}:***") } else { user.to_string() };
            return format!("{scheme}://{masked}@{host}");
        }
    }
    url.to_string()
}

fn tool_version(program: &str, args: &[&str]) -> Option<String> {
    let out = Command::new(program).args(args).output().ok()?;
    let s = String::from_utf8_lossy(&out.stdout);
    s.lines().next().map(|l| l.trim().to_string()).filter(|l| !l.is_empty())
}

fn tools(r: &mut Report) {
    for (tool, hint) in [("cargo", "install Rust from https://rustup.rs"), ("rustc", "install Rust from https://rustup.rs")] {
        match tool_version(tool, &["--version"]) {
            Some(v) => r.line(Level::Ok, tool, v),
            None => r.line(Level::Fail, tool, format!("not found; {hint}")),
        }
    }

    if Path::new("style/app.css").exists() {
        let local = Path::new("bin/tailwindcss").exists() || Path::new("bin/tailwindcss.exe").exists();
        if which("tailwindcss") || local || (which("npx") && Path::new("node_modules/tailwindcss").is_dir()) {
            r.line(Level::Ok, "tailwindcss", "");
        } else {
            r.line(Level::Warn, "tailwindcss", "not found; CSS won't be rebuilt (put the standalone binary in ./bin/tailwindcss)");
        }
    }

    if crate::build::supports_hydration() {
        let has_target = Command::new("rustup")
            .args(["target", "list", "--installed"])
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).contains("wasm32-unknown-unknown"))
            .unwrap_or(false);
        if has_target {
            r.line(Level::Ok, "wasm32-unknown-unknown target", "");
        } else {
            r.line(Level::Warn, "wasm32-unknown-unknown target", "missing; run `rustup target add wasm32-unknown-unknown`");
        }
        if which("wasm-bindgen") {
            r.line(Level::Ok, "wasm-bindgen", "");
        } else {
            r.line(Level::Warn, "wasm-bindgen", "missing; run `cargo install wasm-bindgen-cli`");
        }
        if !which("wasm-opt") {
            r.line(Level::Skip, "wasm-opt", "not found (optional; shrinks WASM bundles)");
        }
    }

    if crate::util::config().contains_key("deploy") {
        for tool in ["ssh", "scp"] {
            if which(tool) {
                r.line(Level::Ok, tool, "");
            } else {
                r.line(Level::Warn, tool, "missing; `chy deploy` needs OpenSSH");
            }
        }
    }
}

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

    #[test]
    fn app_key_rules() {
        assert_eq!(check_app_key(None, false).0, Level::Warn);
        assert_eq!(check_app_key(Some(""), true).0, Level::Fail);
        assert_eq!(check_app_key(Some("base64:!!"), false).0, Level::Fail);
        assert_eq!(check_app_key(Some("short"), false).0, Level::Fail);
        assert_eq!(check_app_key(Some("0123456789abcdef"), false).0, Level::Warn);
        assert_eq!(check_app_key(Some(&crate::util::new_key()), true).0, Level::Ok);
    }

    #[test]
    fn redacts_passwords() {
        assert_eq!(redact("postgres://app:secret@localhost/db"), "postgres://app:***@localhost/db");
        assert_eq!(redact("sqlite://app.db"), "sqlite://app.db");
    }
}