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
//! `chy routes`: build the app, ask it for its route table and print it.
//!
//! The app is started with `CHY_ROUTES=1`; `App::listen` then prints the
//! table as one JSON line (prefixed with `CHY_ROUTES_JSON:`) and exits
//! before binding a port.

use crate::util::{step, CliResult};
use chyabrung_core::app::ROUTES_MARKER;
use chyabrung_core::RouteInfo;
use std::io::Read;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

const TIMEOUT: Duration = Duration::from_secs(60);

/// `chy routes`
pub fn run(features: Option<&str>, json: bool) -> CliResult {
    crate::util::package_name()?;
    step("building the app to read its routes");
    let exe = crate::dev::cargo_build(false, features)?;
    let routes = collect(&exe)?;
    if json {
        println!("{}", serde_json::to_string_pretty(&routes).map_err(|e| e.to_string())?);
    } else {
        print!("{}", table(&routes));
    }
    Ok(())
}

fn collect(exe: &std::path::Path) -> CliResult<Vec<RouteInfo>> {
    let mut child = Command::new(exe)
        .env("CHY_ROUTES", "1")
        .env("APP_ENV", std::env::var("APP_ENV").unwrap_or_else(|_| "development".into()))
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .map_err(|e| format!("failed to start {}: {e}", exe.display()))?;
    // Read stdout on a thread so a chatty app can't block on a full pipe.
    let mut stdout = child.stdout.take().expect("piped stdout");
    let reader = std::thread::spawn(move || {
        let mut s = String::new();
        let _ = stdout.read_to_string(&mut s);
        s
    });
    let start = Instant::now();
    let status = loop {
        if let Some(st) = child.try_wait().map_err(|e| e.to_string())? {
            break st;
        }
        if start.elapsed() > TIMEOUT {
            let _ = child.kill();
            let _ = child.wait();
            return Err(format!(
                "the app did not report its routes within {}s. `chy routes` needs main() to reach `App::listen`/`serve`",
                TIMEOUT.as_secs()
            ));
        }
        std::thread::sleep(Duration::from_millis(50));
    };
    let out = reader.join().unwrap_or_default();
    parse(&out).ok_or_else(|| {
        if status.success() {
            "the app exited without printing its routes. `chy routes` needs main() to reach `App::listen`/`serve`".to_string()
        } else {
            format!("the app exited with {status} before reaching `App::listen` (see the output above)")
        }
    })
}

fn parse(out: &str) -> Option<Vec<RouteInfo>> {
    out.lines().find_map(|l| l.strip_prefix(ROUTES_MARKER)).and_then(|j| serde_json::from_str(j).ok())
}

fn method_color(m: &str) -> &'static str {
    match m {
        "GET" | "HEAD" => "\x1b[32m",
        "POST" => "\x1b[33m",
        "PUT" | "PATCH" => "\x1b[34m",
        "DELETE" => "\x1b[31m",
        _ => "\x1b[36m",
    }
}

/// Middleware every route starts with (the app's global middleware).
fn common_prefix(routes: &[RouteInfo]) -> &[String] {
    let Some(first) = routes.first() else { return &[] };
    let mut n = first.middleware.len();
    for r in &routes[1..] {
        n = n.min(first.middleware.iter().zip(&r.middleware).take_while(|(a, b)| a == b).count());
    }
    &first.middleware[..n]
}

fn table(routes: &[RouteInfo]) -> String {
    let headers = ["METHOD", "PATH", "NAME", "MIDDLEWARE"];
    // Only factor out shared middleware when there is more than one route.
    let global = if routes.len() > 1 { common_prefix(routes) } else { &[] };
    let rows: Vec<[String; 4]> = routes
        .iter()
        .map(|r| {
            let own = &r.middleware[global.len()..];
            [
                r.method.clone(),
                r.path.clone(),
                r.name.clone().unwrap_or_else(|| "-".into()),
                if own.is_empty() { "-".into() } else { own.join(", ") },
            ]
        })
        .collect();
    let mut w = headers.map(str::len);
    for r in &rows {
        for (i, c) in r.iter().enumerate() {
            w[i] = w[i].max(c.chars().count());
        }
    }
    let mut out = String::new();
    if !global.is_empty() {
        out.push_str(&format!("\x1b[2mglobal middleware (every route):\x1b[0m {}\n\n", global.join(", ")));
    }
    out.push_str(&format!(
        "\x1b[1m{:<w0$}  {:<w1$}  {:<w2$}  {}\x1b[0m\n",
        headers[0],
        headers[1],
        headers[2],
        headers[3],
        w0 = w[0],
        w1 = w[1],
        w2 = w[2]
    ));
    for r in &rows {
        out.push_str(&format!(
            "{}{:<w0$}\x1b[0m  {:<w1$}  \x1b[2m{:<w2$}\x1b[0m  {}\n",
            method_color(&r[0]),
            r[0],
            r[1],
            r[2],
            r[3],
            w0 = w[0],
            w1 = w[1],
            w2 = w[2]
        ));
    }
    out.push_str(&format!("\n{} route{}\n", rows.len(), if rows.len() == 1 { "" } else { "s" }));
    out
}

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

    #[test]
    fn parses_marker_line_among_logs() {
        let out = "2026-01-01 INFO starting\nCHY_ROUTES_JSON:[{\"method\":\"GET\",\"path\":\"/\",\"name\":\"home\",\"middleware\":[\"logger\"]}]\n";
        let r = parse(out).unwrap();
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].name.as_deref(), Some("home"));
        assert!(parse("no marker").is_none());
    }

    #[test]
    fn renders_table() {
        let t = table(&[RouteInfo { method: "POST".into(), path: "/posts".into(), name: None, middleware: vec![] }]);
        assert!(t.contains("/posts"));
        assert!(t.contains("1 route\n"));
    }

    #[test]
    fn factors_out_global_middleware() {
        let mw = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        let rows = [
            RouteInfo { method: "GET".into(), path: "/".into(), name: None, middleware: mw(&["logger", "cors"]) },
            RouteInfo { method: "POST".into(), path: "/login".into(), name: None, middleware: mw(&["logger", "cors", "rate_limit"]) },
        ];
        assert_eq!(common_prefix(&rows), mw(&["logger", "cors"]).as_slice());
        let t = table(&rows);
        assert!(t.contains("global middleware (every route):\x1b[0m logger, cors"));
        assert!(t.contains("rate_limit"));
    }
}