capy-cli 0.10.0

The command-line interface for the Capy web framework.
Documentation
use anyhow::{bail, Result};
use capy_cli::{FrontendDriver, ProjectConfig};
use capy_core::AppConfig;
use std::{
    path::Path,
    process::{Command, ExitCode, Stdio},
    time::Duration,
};

pub(crate) fn check(root: &Path) -> Result<()> {
    AppConfig::load_from(root)?;
    let driver = ProjectConfig::load(root)?.frontend.driver;
    driver.validate(root)?;
    if driver == FrontendDriver::React
        && std::fs::File::open(root.join("frontend/dist/index.html")).is_err()
    {
        bail!("Production frontend build missing. Run capy build before capy check.");
    }
    Ok(())
}

pub(crate) fn run(root: &Path) -> Result<ExitCode> {
    tokio::runtime::Runtime::new()?.block_on(diagnose(root))
}

fn report(ok: bool, message: &str, failures: &mut usize) {
    println!("  {} {message}", if ok { "✓" } else { "✗" });
    if !ok {
        *failures += 1;
    }
}

async fn version(command: Command) -> Option<String> {
    let mut command = tokio::process::Command::from(command);
    command
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .kill_on_drop(true);
    let output = tokio::time::timeout(Duration::from_secs(5), command.output())
        .await
        .ok()?
        .ok()?;
    output
        .status
        .success()
        .then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned())
}

fn at_least(version: &str, minimum: (u32, u32, u32)) -> bool {
    let Some(number) = version
        .split_whitespace()
        .find(|part| part.starts_with(|c: char| c.is_ascii_digit() || c == 'v'))
    else {
        return false;
    };
    let parts: Vec<u32> = number
        .trim_start_matches('v')
        .split('.')
        .take(3)
        .filter_map(|part| part.parse().ok())
        .collect();
    parts.len() == 3 && (parts[0], parts[1], parts[2]) >= minimum
}

async fn diagnose(root: &Path) -> Result<ExitCode> {
    println!("Capy Doctor\n\nRust");
    let mut failures = 0;
    let mut database_available = false;
    let mut rustc = Command::new("rustc");
    rustc.arg("--version");
    let rust = version(rustc).await;
    let supported = rust.as_deref().is_some_and(|v| at_least(v, (1, 88, 0)));
    report(
        supported,
        &match rust {
            Some(version) if supported => version,
            Some(version) => format!("{version}; upgrade to Rust 1.88 or newer."),
            None => "rustc unavailable; install Rust 1.88 or newer.".into(),
        },
        &mut failures,
    );
    let mut cargo = Command::new("cargo");
    cargo.arg("--version");
    let cargo = version(cargo).await;
    report(
        cargo.is_some(),
        &cargo.unwrap_or_else(|| "cargo unavailable; install the Rust toolchain.".into()),
        &mut failures,
    );
    println!("\nProject");
    let project = ProjectConfig::load(root);
    report(
        project.is_ok(),
        if project.is_ok() {
            "capy.toml valid (or legacy API-only project)"
        } else {
            "Invalid capy.toml; set [frontend] driver to react or none."
        },
        &mut failures,
    );
    if let Ok(project) = project {
        let driver = project.frontend.driver;
        println!("\nFrontend");
        if driver == FrontendDriver::None {
            println!("  ✓ API-only project; Node.js and pnpm are not required.");
        } else {
            let mut node = Command::new("node");
            node.arg("--version");
            let node = version(node).await;
            // Vite 7 supports Node 20.19+ or 22.12+; exclude unsupported Node 21.
            let supported = node.as_deref().is_some_and(|v| {
                at_least(v, (22, 12, 0)) || (v.starts_with("v20.") && at_least(v, (20, 19, 0)))
            });
            report(
                supported,
                &match node {
                    Some(version) if supported => version,
                    Some(version) => format!("Node {version}; install Node 20.19+, 22.12+ or 24 LTS (Node 21 is unsupported)."),
                    None => "Node.js unavailable; install Node 22.12+ or 24 LTS.".into(),
                },
                &mut failures,
            );
            let pnpm = version(driver.version_command(root).expect("React package manager")).await;
            report(
                pnpm.is_some(),
                &pnpm.map(|v| format!("pnpm {v}")).unwrap_or_else(|| {
                    "pnpm unavailable; install pnpm and run pnpm install in frontend/.".into()
                }),
                &mut failures,
            );
            report(
                driver.validate(root).is_ok(),
                "frontend/package.json must exist for React projects.",
                &mut failures,
            );
            report(
                driver.dependencies_installed(root),
                "frontend dependencies: run pnpm install in frontend/ if missing.",
                &mut failures,
            );
        }
    }
    println!("\nDatabase and application configuration");
    match AppConfig::load_from(root) {
        Err(error) => report(false, &error.to_string(), &mut failures),
        Ok(config) => {
            report(
                true,
                "Configuration valid; database URL configured (redacted).",
                &mut failures,
            );
            match database(root, &config.database.url).await {
                Ok(()) => {
                    database_available = true;
                    report(true, "Database reachable (read-only probe).", &mut failures);
                }
                Err(message) => report(false, message, &mut failures),
            }
        }
    }
    if database_available && root.join("app/jobs/mod.rs").is_file() {
        println!("\nJobs");
        let status = tokio::process::Command::new("cargo")
            .args(["run", "--offline", "--quiet", "--", "queue:check"])
            .current_dir(root)
            .kill_on_drop(true)
            .status();
        let ok = matches!(tokio::time::timeout(Duration::from_secs(120), status).await, Ok(Ok(status)) if status.success());
        report(
            ok,
            "Queue tables and worker configuration (read-only; no running worker required).",
            &mut failures,
        );
    }
    if root.join("config/mail.toml").is_file() {
        println!("\nMail");
        let status = tokio::process::Command::new("cargo")
            .args(["run", "--offline", "--quiet", "--", "mail:check"])
            .current_dir(root)
            .kill_on_drop(true)
            .status();
        let ok = matches!(tokio::time::timeout(Duration::from_secs(120), status).await, Ok(Ok(status)) if status.success());
        report(
            ok,
            "Mail configuration/templates (offline; no SMTP connection or credentials sent).",
            &mut failures,
        );
    }
    if failures == 0 {
        println!("\nEverything looks good.");
        Ok(ExitCode::SUCCESS)
    } else {
        println!("\n{failures} check(s) need attention. No dependencies were installed or migrations applied.");
        Ok(ExitCode::FAILURE)
    }
}

async fn database(root: &Path, url: &str) -> Result<(), &'static str> {
    let url = if url.starts_with("sqlite:") && !url.contains(":memory:") {
        let path = url
            .strip_prefix("sqlite://")
            .or_else(|| url.strip_prefix("sqlite:"))
            .unwrap()
            .split('?')
            .next()
            .unwrap();
        // Never open a missing SQLite file with mode=rwc: doctor must not create it.
        let path = root.join(path);
        if !path.is_file() {
            return Err("SQLite file missing; run capy migrate to initialize the database.");
        }
        format!("sqlite://{}?mode=ro", path.display())
    } else {
        url.to_owned()
    };
    let mut options = sea_orm::ConnectOptions::new(url);
    options
        .max_connections(1)
        .min_connections(0)
        .acquire_timeout(Duration::from_secs(3))
        .sqlx_logging(false);
    let probe = async {
        let db = sea_orm::Database::connect(options).await?;
        let result = db.ping().await;
        let _ = db.close().await;
        result
    };
    match tokio::time::timeout(Duration::from_secs(5), probe).await {
        Ok(Ok(())) => Ok(()),
        _ => Err("Database unavailable; check DATABASE_URL, credentials, network access and database service (5-second probe bound)."),
    }
}