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
//! Keeping apps and the CLI in step: `chy upgrade`, `chy self-update`,
//! the version check `chy dev` runs, and "who holds this port?".

use crate::util::{ok, run, step, CliResult};
use std::process::Command;

/// This CLI's version, e.g. `0.2.0`.
pub const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");

/// `major.minor` of a version (`0.2.3` → `(0, 2)`).
fn series(v: &str) -> Option<(u64, u64)> {
    let mut it = v.trim().trim_start_matches(['^', '~', '=']).split('.');
    Some((it.next()?.parse().ok()?, it.next().and_then(|m| m.parse().ok()).unwrap_or(0)))
}

/// `0.2.1` → `(0, 2, 1)`.
fn triple(v: &str) -> Option<(u64, u64, u64)> {
    let mut it = v.trim().split(['.', '-', '+']);
    Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next().and_then(|p| p.parse().ok()).unwrap_or(0)))
}

/// The version requirement written for `series` (`0.x` → `"0.x"`, `1.x` → `"1"`).
fn requirement(v: &str) -> String {
    match series(v) {
        Some((0, minor)) => format!("0.{minor}"),
        Some((major, _)) => major.to_string(),
        None => v.to_string(),
    }
}

/// The resolved `chyabrung` version in `Cargo.lock`, if any.
pub fn locked_version(lock: &str) -> Option<String> {
    let mut lines = lock.lines();
    while let Some(l) = lines.next() {
        if l.trim() == "name = \"chyabrung\"" {
            let v = lines.next()?.trim().strip_prefix("version = \"")?.strip_suffix('"')?;
            return Some(v.to_string());
        }
    }
    None
}

/// Rewrite the `chyabrung` / `chyabrung-testing` requirements in a Cargo.toml.
/// Returns the new text and whether anything changed. Path and git
/// dependencies are left alone.
pub fn bump_manifest(manifest: &str, req: &str) -> (String, bool) {
    let mut changed = false;
    let out: Vec<String> = manifest
        .lines()
        .map(|line| {
            let t = line.trim_start();
            let is_dep = ["chyabrung =", "chyabrung=", "chyabrung-testing =", "chyabrung-testing="].iter().any(|p| t.starts_with(p));
            if !is_dep || t.contains("path =") || t.contains("git =") {
                return line.to_string();
            }
            let new = replace_version(line, req);
            changed |= new != line;
            new
        })
        .collect();
    let mut s = out.join("\n");
    if manifest.ends_with('\n') {
        s.push('\n');
    }
    (s, changed)
}

/// `chyabrung = "0.1"` or `chyabrung = { version = "0.1", ... }` → `req`.
fn replace_version(line: &str, req: &str) -> String {
    let (key, rest) = match line.split_once('=') {
        Some(kv) => kv,
        None => return line.to_string(),
    };
    let rest_t = rest.trim_start();
    if rest_t.starts_with('"') {
        return format!("{key}= \"{req}\"");
    }
    if let Some(i) = line.find("version") {
        let after = &line[i..];
        if let (Some(q1), true) = (after.find('"'), after.contains('=')) {
            if let Some(q2) = after[q1 + 1..].find('"') {
                return format!("{}\"{req}\"{}", &line[..i + q1], &after[q1 + 1 + q2 + 1..]);
            }
        }
    }
    line.to_string()
}

/// `chy upgrade`: move the app to the chyabrung version matching this CLI.
pub fn upgrade() -> CliResult {
    let manifest = std::fs::read_to_string("Cargo.toml").map_err(|_| "no Cargo.toml here: run `chy upgrade` in your app's folder".to_string())?;
    let req = requirement(CLI_VERSION);
    let before = std::fs::read_to_string("Cargo.lock").ok().and_then(|l| locked_version(&l));
    let (new, changed) = bump_manifest(&manifest, &req);
    if changed {
        std::fs::write("Cargo.toml", new).map_err(|e| format!("cannot write Cargo.toml: {e}"))?;
        ok(&format!("Cargo.toml now asks for chyabrung \"{req}\""));
    } else if !manifest.contains("chyabrung") {
        return Err("this Cargo.toml does not depend on chyabrung".into());
    }
    step("updating Cargo.lock…");
    let mut cmd = Command::new("cargo");
    cmd.args(["update", "-p", "chyabrung"]);
    if manifest.contains("chyabrung-testing") {
        cmd.args(["-p", "chyabrung-testing"]);
    }
    run(&mut cmd)?;
    let after = std::fs::read_to_string("Cargo.lock").ok().and_then(|l| locked_version(&l));
    match (before, after) {
        (Some(b), Some(a)) if a != b => ok(&format!("chyabrung {b} → {a}")),
        (_, Some(a)) => ok(&format!("chyabrung {a} (already up to date)")),
        _ => {}
    }
    println!("  release notes: https://github.com/Chyabrung/chyabrung/releases");
    println!("  new template features (e.g. `.openapi(...)`) are opt-in; run `cargo build` to check the app");
    Ok(())
}

/// Warn when the app and the CLI are on different release series.
pub fn check_app_version() {
    let Some(app) = std::fs::read_to_string("Cargo.lock").ok().and_then(|l| locked_version(&l)) else { return };
    let (Some(a), Some(c)) = (triple(&app), triple(CLI_VERSION)) else { return };
    if a < c {
        println!("\x1b[33m!\x1b[0m this app uses chyabrung {app}, chy is {CLI_VERSION}: run `chy upgrade` to update the app");
    } else if (a.0, a.1) > (c.0, c.1) {
        println!("\x1b[33m!\x1b[0m this app uses chyabrung {app}, but chy is {CLI_VERSION}: run `chy self-update`");
    }
}

/// `chy self-update`: install the latest CLI, even while another `chy` runs.
pub fn self_update() -> CliResult {
    let exe = std::env::current_exe().map_err(|e| e.to_string())?;
    // Windows cannot overwrite a running .exe, but it can rename it.
    let old = exe.with_extension("old.exe");
    let moved = cfg!(windows) && {
        let _ = std::fs::remove_file(&old);
        std::fs::rename(&exe, &old).is_ok()
    };
    step(&format!("installing the latest chyabrung-cli (now {CLI_VERSION})…"));
    let result = run(Command::new("cargo").args(["install", "chyabrung-cli", "--locked", "--force"]));
    if result.is_err() && moved && !exe.exists() {
        let _ = std::fs::rename(&old, &exe); // put the working one back
    }
    result?;
    ok("chy is up to date; in each app run `chy upgrade` to use the new version");
    Ok(())
}

/// Remove the `chy.old.exe` left by a previous self-update (best effort).
pub fn cleanup_old_exe() {
    if let Ok(exe) = std::env::current_exe() {
        let old = exe.with_extension("old.exe");
        if old.exists() {
            let _ = std::fs::remove_file(old);
        }
    }
}

/// Which process listens on `port`, as "name (PID n)", when it can be found.
pub fn port_owner(port: u16) -> Option<String> {
    if cfg!(windows) {
        let out = Command::new("netstat").args(["-ano", "-p", "TCP"]).output().ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        let pid = text.lines().find_map(|l| {
            let cols: Vec<&str> = l.split_whitespace().collect();
            (cols.len() >= 5 && cols[1].ends_with(&format!(":{port}")) && cols[3].eq_ignore_ascii_case("LISTENING")).then(|| cols[4].to_string())
        })?;
        let out = Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"]).output().ok()?;
        let name = String::from_utf8_lossy(&out.stdout).split(',').next().map(|s| s.trim().trim_matches('"').to_string()).filter(|s| !s.is_empty());
        Some(match name {
            Some(n) => format!("{n} (PID {pid})"),
            None => format!("PID {pid}"),
        })
    } else {
        let out = Command::new("lsof").args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-Fpc"]).output().ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        let pid = text.lines().find_map(|l| l.strip_prefix('p'))?.to_string();
        let name = text.lines().find_map(|l| l.strip_prefix('c')).unwrap_or("process");
        Some(format!("{name} (PID {pid})"))
    }
}

/// The command that stops a process, for the hint.
pub fn stop_hint(owner: &str) -> String {
    let pid = owner.rsplit("PID ").next().unwrap_or("").trim_end_matches(')');
    if cfg!(windows) {
        format!("Stop-Process -Id {pid}")
    } else {
        format!("kill {pid}")
    }
}

/// The port the app will listen on (`APP_PORT`, `[app] port`, default 2007).
pub fn app_port() -> u16 {
    let _ = dotenvy::dotenv();
    if let Some(p) = std::env::var("APP_PORT").ok().and_then(|p| p.parse().ok()) {
        return p;
    }
    crate::util::config()
        .get("app")
        .and_then(|a| a.get("port"))
        .and_then(|p| match p {
            toml::Value::Integer(i) => u16::try_from(*i).ok(),
            toml::Value::String(s) => chyabrung_core::config::interpolate(s).parse().ok(),
            _ => None,
        })
        .unwrap_or(2007)
}

/// Before starting: is the port free? If not, say who has it and how to stop it.
pub fn check_port(port: u16) -> CliResult {
    // Windows lets a test bind succeed next to some existing listeners, so
    // also ask the OS who is listening.
    let owner = port_owner(port);
    let bind_ok = std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() && std::net::TcpListener::bind(("0.0.0.0", port)).is_ok();
    if bind_ok && owner.is_none() {
        return Ok(());
    }
    let mut msg = format!("port {port} is already in use");
    match owner {
        Some(owner) => {
            msg.push_str(&format!(" by {owner}.\n  Probably another `chy dev` is still running in another terminal: press Ctrl-C there, or run `{}`.", stop_hint(&owner)));
        }
        None => msg.push_str(".\n  Probably another `chy dev` is still running in another terminal: press Ctrl-C there."),
    }
    msg.push_str("\n  To run this app next to it, use another port: set APP_PORT=2008 in .env");
    Err(msg)
}

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

    #[test]
    fn versions() {
        assert_eq!(requirement("0.2.0"), "0.2");
        assert_eq!(requirement("1.4.2"), "1");
        assert_eq!(series("^0.1"), Some((0, 1)));
        let lock = "[[package]]\nname = \"chyabrung\"\nversion = \"0.1.0\"\nsource = \"x\"\n";
        assert_eq!(locked_version(lock).as_deref(), Some("0.1.0"));
    }

    #[test]
    fn bumps_manifest() {
        let m = "[dependencies]\nchyabrung = { version = \"0.1\", features = [\"sqlite\"] }\nchyabrung-core = \"0.1\"\nserde = \"1\"\n\n[dev-dependencies]\nchyabrung-testing = \"0.1\"\nlocal = { path = \"x\" }\n";
        let (out, changed) = bump_manifest(m, "0.2");
        assert!(changed);
        assert!(out.contains("chyabrung = { version = \"0.2\", features = [\"sqlite\"] }"));
        assert!(out.contains("chyabrung-testing = \"0.2\""));
        assert!(out.contains("chyabrung-core = \"0.1\""), "only the facade and testing crates are touched");
        let (_, again) = bump_manifest(&out, "0.2");
        assert!(!again);
        let (_, path) = bump_manifest("chyabrung = { path = \"../chyabrung\" }\n", "0.2");
        assert!(!path);
    }
}