capy-cli 0.2.0

The command-line interface for the Capy web framework.
Documentation
//! Small process supervisor shared by dev, build, and serve.
use anyhow::{bail, Context, Result};
use capy_cli::{FrontendDriver, ProjectConfig};
use capy_core::AppConfig;
use std::{
    path::{Path, PathBuf},
    process::{Command, ExitCode, ExitStatus, Stdio},
};

pub(crate) fn serve(root: &Path) -> Result<ExitCode> {
    let mut owner = supervisor::Owner::new()?;
    let executable = match compile_backend(root, &mut owner)? {
        Ok(executable) => executable,
        Err(status) => return Ok(exit_code(status)),
    };
    Ok(exit_code(owner.run(
        Command::new(executable).arg("serve").current_dir(root),
    )?))
}

fn compile_backend(
    root: &Path,
    owner: &mut supervisor::Owner,
) -> Result<std::result::Result<PathBuf, ExitStatus>> {
    let metadata = tempfile::tempfile()?;
    let status = owner.run(
        Command::new("cargo")
            .args(["metadata", "--no-deps", "--format-version=1"])
            .current_dir(root)
            .stdout(Stdio::from(metadata.try_clone()?)),
    )?;
    if !status.success() || owner.interrupted() {
        return Ok(Err(status));
    }
    let data: serde_json::Value = read_json(metadata)?;
    let manifest = root.join("Cargo.toml").canonicalize()?;
    let package = data["packages"]
        .as_array()
        .context("Cargo metadata has no packages")?
        .iter()
        .find(|p| {
            p["manifest_path"]
                .as_str()
                .is_some_and(|s| Path::new(s) == manifest)
        })
        .context("Cannot locate application package in Cargo metadata")?;
    let bins: Vec<_> = package["targets"]
        .as_array()
        .context("Cargo metadata has no targets")?
        .iter()
        .filter(|t| {
            t["kind"]
                .as_array()
                .is_some_and(|k| k.iter().any(|k| k == "bin"))
        })
        .filter_map(|t| t["name"].as_str())
        .collect();
    let bin = if let Some(default) = package["default_run"].as_str() {
        default
    } else if bins.len() == 1 {
        bins[0]
    } else {
        bail!("Application has multiple binaries. Set `package.default-run` in Cargo.toml for `capy serve`.");
    };
    let artifacts = tempfile::tempfile()?;
    let status = owner.run(
        Command::new("cargo")
            .args([
                "build",
                "--quiet",
                "--bin",
                bin,
                "--message-format=json-render-diagnostics",
            ])
            .current_dir(root)
            .stdout(Stdio::from(artifacts.try_clone()?)),
    )?;
    if !status.success() || owner.interrupted() {
        return Ok(Err(status));
    }
    use std::io::{BufRead, BufReader, Seek};
    let mut artifacts = artifacts;
    artifacts.rewind()?;
    let mut executable = None;
    for line in BufReader::new(artifacts).lines() {
        let item: serde_json::Value = serde_json::from_str(&line?)?;
        if item["reason"] == "compiler-artifact" && item["target"]["name"] == bin {
            if let Some(path) = item["executable"].as_str() {
                executable = Some(path.to_owned());
            }
        }
    }
    let executable = executable.context("Cargo did not produce an application binary")?;
    Ok(Ok(PathBuf::from(executable)))
}

pub(crate) fn build(root: &Path) -> Result<ExitCode> {
    let driver = ProjectConfig::load(root)?.frontend.driver;
    driver.validate(root)?;
    let mut owner = supervisor::Owner::new()?;
    if let Some(mut command) = driver.install_command(root) {
        println!("Installing frontend dependencies...");
        let status = owner.run(&mut command).context("Could not install frontend dependencies. Install Node.js and pnpm, then run capy build again.")?;
        if !status.success() || owner.interrupted() {
            return Ok(exit_code(status));
        }
    }
    if let Some(mut command) = driver.build_command(root) {
        println!("Building frontend...");
        let status = owner
            .run(&mut command)
            .context("Could not build the frontend. Install Node.js and pnpm.")?;
        if !status.success() || owner.interrupted() {
            return Ok(exit_code(status));
        }
        if !root.join("frontend/dist/index.html").is_file() {
            bail!("Frontend build did not produce frontend/dist/index.html. Check frontend/package.json and vite.config.ts.");
        }
        println!("✓ Frontend built\n");
    }
    println!("Building application...");
    let status = owner.run(
        Command::new("cargo")
            .args(["build", "--release"])
            .current_dir(root),
    )?;
    if !status.success() || owner.interrupted() {
        return Ok(exit_code(status));
    }
    println!("✓ Rust release build complete\n\nBuild complete.");
    Ok(ExitCode::SUCCESS)
}

pub(crate) fn dev(root: &Path) -> Result<ExitCode> {
    let driver = ProjectConfig::load(root)?.frontend.driver;
    driver.validate(root)?;
    let config = AppConfig::load_from(root)?;
    if config.app.port == 0 {
        bail!("capy dev requires a fixed APP_PORT so the frontend can reach the backend. Set a port in config/app.toml, .env, or APP_PORT.");
    }
    let host = match config.app.host.as_str() {
        "0.0.0.0" => "127.0.0.1",
        "::" => "::1",
        host => host,
    };
    let origin = if host.contains(':') {
        format!("http://[{host}]:{}", config.app.port)
    } else {
        format!("http://{host}:{}", config.app.port)
    };
    let frontend_port = if driver == FrontendDriver::React {
        let port: u16 = std::env::var("CAPY_FRONTEND_PORT")
            .unwrap_or_else(|_| "5173".into())
            .parse()
            .context("CAPY_FRONTEND_PORT must be a TCP port between 1 and 65535.")?;
        if port == 0 {
            bail!("CAPY_FRONTEND_PORT must be a TCP port between 1 and 65535.");
        }
        if port == config.app.port {
            bail!("The frontend and backend must use different ports.");
        }
        // Check before spawning, so another server cannot be reported as ours.
        std::net::TcpListener::bind(("127.0.0.1", port)).with_context(|| {
            format!("Frontend port {port} is unavailable. Set CAPY_FRONTEND_PORT to another port.")
        })?;
        port
    } else {
        5173
    };
    let mut owner = supervisor::Owner::new()?;
    if let Some(mut command) = driver.install_command(root) {
        println!("Installing frontend dependencies...");
        let status = owner.run(&mut command).context("Could not install frontend dependencies. Install Node.js and pnpm, then run capy dev again.")?;
        if !status.success() || owner.interrupted() {
            return Ok(exit_code(status));
        }
    }
    let executable = match compile_backend(root, &mut owner)? {
        Ok(executable) => executable,
        Err(status) => return Ok(exit_code(status)),
    };
    println!("Capy\n\nBackend\n  {origin}");
    if driver != FrontendDriver::None {
        println!("\nFrontend\n  http://127.0.0.1:{frontend_port}");
    }
    println!("\nEnvironment\n  development\n");
    let backend = owner.spawn(
        Command::new(executable)
            .arg("serve")
            .current_dir(root)
            .env("CAPY_DEV", "1")
            .env("APP_ENVIRONMENT", "development")
            .env("APP_HOST", &config.app.host)
            .env("APP_PORT", config.app.port.to_string()),
    )?;
    let frontend = if let Some(mut command) = driver.dev_command(root, &origin, frontend_port) {
        Some(
            owner
                .spawn(&mut command)
                .context("Could not start Vite. Install Node.js and pnpm.")?,
        )
    } else {
        None
    };
    owner.supervise(backend, frontend.map(|id| (id, frontend_port)))
}

fn read_json(mut file: std::fs::File) -> Result<serde_json::Value> {
    use std::io::Seek;
    file.rewind()?;
    Ok(serde_json::from_reader(file)?)
}

pub(crate) fn exit_code(status: ExitStatus) -> ExitCode {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        ExitCode::from(
            status
                .code()
                .unwrap_or_else(|| 128 + status.signal().unwrap_or(1)) as u8,
        )
    }
    #[cfg(not(unix))]
    ExitCode::from(u8::try_from(status.code().unwrap_or(1)).unwrap_or(1))
}

#[path = "supervisor.rs"]
mod supervisor;