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
//! Shared CLI helpers.

use base64::Engine;
use rand::RngCore;
use std::path::Path;
use std::process::Command;

/// CLI result type (errors are human-readable strings).
pub type CliResult<T = ()> = Result<T, String>;

/// Print a step.
pub fn step(msg: &str) {
    println!("\x1b[35m🥁\x1b[0m {msg}");
}

/// Print a success line.
pub fn ok(msg: &str) {
    println!("\x1b[32m✓\x1b[0m {msg}");
}

/// Run a command, inheriting stdio.
pub fn run(cmd: &mut Command) -> CliResult {
    let shown = format!("{cmd:?}");
    let status = cmd.status().map_err(|e| format!("failed to run {shown}: {e}"))?;
    if status.success() {
        Ok(())
    } else {
        Err(format!("{shown} exited with {status}"))
    }
}

/// Whether a program is on PATH.
pub fn which(program: &str) -> bool {
    let exts: &[&str] = if cfg!(windows) { &["", ".exe", ".cmd"] } else { &[""] };
    std::env::var_os("PATH")
        .map(|p| std::env::split_paths(&p).any(|d| exts.iter().any(|e| d.join(format!("{program}{e}")).is_file())))
        .unwrap_or(false)
}

/// The `[package] name` of the crate in the current directory.
pub fn package_name() -> CliResult<String> {
    let s = std::fs::read_to_string("Cargo.toml").map_err(|_| "no Cargo.toml here — run inside a Chyabrung app".to_string())?;
    let v: toml::Table = s.parse().map_err(|e| format!("Cargo.toml: {e}"))?;
    v.get("package")
        .and_then(|p| p.get("name"))
        .and_then(|n| n.as_str())
        .map(str::to_owned)
        .ok_or_else(|| "Cargo.toml has no [package] name".into())
}

/// Read `chyabrung.toml` as a table (empty if missing).
pub fn config() -> toml::Table {
    std::fs::read_to_string("chyabrung.toml").ok().and_then(|s| s.parse().ok()).unwrap_or_default()
}

/// Write a file, refusing to overwrite.
pub fn write_new(path: &Path, content: &str) -> CliResult {
    if path.exists() {
        return Err(format!("{} already exists", path.display()));
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    std::fs::write(path, content).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
    ok(&format!("created {}", path.display().to_string().replace('\\', "/")));
    Ok(())
}

/// `PostComment` / `post-comment` / `post comment` → `post_comment`.
pub fn snake(s: &str) -> String {
    let mut out = String::new();
    let mut prev_lower = false;
    for c in s.chars() {
        if c.is_uppercase() {
            if prev_lower {
                out.push('_');
            }
            out.extend(c.to_lowercase());
            prev_lower = false;
        } else if c == '-' || c == ' ' || c == '_' {
            if !out.ends_with('_') && !out.is_empty() {
                out.push('_');
            }
            prev_lower = false;
        } else {
            out.push(c);
            prev_lower = c.is_lowercase() || c.is_ascii_digit();
        }
    }
    out
}

/// `post_comment` → `PostComment`.
pub fn pascal(s: &str) -> String {
    snake(s)
        .split('_')
        .filter(|p| !p.is_empty())
        .map(|p| {
            let mut c = p.chars();
            c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
        })
        .collect()
}

/// Naive English plural for table names.
pub fn plural(s: &str) -> String {
    if s.ends_with('y') && !s.ends_with("ay") && !s.ends_with("ey") && !s.ends_with("oy") {
        format!("{}ies", &s[..s.len() - 1])
    } else if s.ends_with('s') || s.ends_with('x') || s.ends_with("ch") || s.ends_with("sh") {
        format!("{s}es")
    } else {
        format!("{s}s")
    }
}

/// Generate a random `base64:` key.
pub fn new_key() -> String {
    let mut b = [0u8; 32];
    rand::thread_rng().fill_bytes(&mut b);
    format!("base64:{}", base64::engine::general_purpose::STANDARD.encode(b))
}

/// Set (or replace) `KEY=value` in an env file.
pub fn set_env_var(path: &Path, key: &str, value: &str) -> CliResult {
    let content = std::fs::read_to_string(path).unwrap_or_default();
    let mut found = false;
    let mut lines: Vec<String> = content
        .lines()
        .map(|l| {
            if l.trim_start().starts_with(&format!("{key}=")) {
                found = true;
                format!("{key}={value}")
            } else {
                l.to_string()
            }
        })
        .collect();
    if !found {
        lines.push(format!("{key}={value}"));
    }
    std::fs::write(path, lines.join("\n") + "\n").map_err(|e| e.to_string())
}

/// `chy key:generate`
pub fn key_generate(show: bool) -> CliResult {
    let key = new_key();
    if show {
        println!("{key}");
        return Ok(());
    }
    set_env_var(Path::new(".env"), "APP_KEY", &key)?;
    ok("APP_KEY written to .env");
    Ok(())
}

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

    #[test]
    fn names() {
        assert_eq!(snake("PostComment"), "post_comment");
        assert_eq!(snake("send-welcome email"), "send_welcome_email");
        assert_eq!(snake("HTTPServer2"), "httpserver2");
        assert_eq!(pascal("post_comment"), "PostComment");
        assert_eq!(pascal("PostController"), "PostController");
        assert_eq!(plural("category"), "categories");
        assert_eq!(plural("post"), "posts");
        assert_eq!(plural("box"), "boxes");
    }

    #[test]
    fn env_file() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join(".env");
        std::fs::write(&p, "A=1\nAPP_KEY=old\n").unwrap();
        set_env_var(&p, "APP_KEY", "new").unwrap();
        set_env_var(&p, "B", "2").unwrap();
        assert_eq!(std::fs::read_to_string(&p).unwrap(), "A=1\nAPP_KEY=new\nB=2\n");
        assert!(new_key().starts_with("base64:"));
    }
}