capy-cli 0.5.0

The command-line interface for the Capy web framework.
Documentation
//! Capy command line interface.

mod contracts;
mod dev;
mod doctor;
mod process;

use anyhow::{Context, Result};
use capy_cli::{find_project, generate, new_project_with_frontend, FrontendDriver, Generator};
use clap::{Parser, Subcommand};
use std::{
    path::PathBuf,
    process::{Command, ExitCode},
};

#[derive(Parser)]
#[command(
    name = "capy",
    version,
    about = "Capy — A calmer way to build web apps in Rust."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a ready-to-run Capy application.
    New {
        name: String,
        /// Create a backend-only application.
        #[arg(long, conflicts_with = "frontend")]
        api: bool,
        /// Frontend stack (defaults to react).
        #[arg(long, value_enum)]
        frontend: Option<FrontendDriver>,
    },
    /// Watch Rust sources and run the development dashboard (plain output in CI/non-TTY terminals).
    Dev(dev::Options),
    /// Build frontend assets and the Rust release application.
    Build,
    /// Run the Rust application only (does not start Vite).
    Serve,
    /// Diagnose tools, project configuration and database connectivity without installing anything.
    Doctor,
    /// Validate production configuration, assets and migration registration offline; do not start HTTP.
    Check,
    /// List registered API routes without opening a database connection.
    Routes {
        /// Include stable operation identifiers and response contract types.
        #[arg(long)]
        api: bool,
    },
    /// Generate generated/openapi.json without opening a database connection.
    Openapi {
        /// Fail on drift without changing generated files.
        #[arg(long)]
        check: bool,
    },
    /// Generate OpenAPI and frontend/src/generated/api-types.ts from Rust DTOs.
    Types {
        /// Fail on drift without changing generated files (for CI).
        #[arg(long)]
        check: bool,
    },
    /// Create and register a controller.
    #[command(name = "make:controller")]
    MakeController { name: String },
    /// Create and register a SeaORM entity.
    #[command(name = "make:model")]
    MakeModel { name: String },
    /// Create and register a validated JSON request.
    #[command(name = "make:request")]
    MakeRequest { name: String },
    /// Create and register a SeaORM migration.
    #[command(name = "make:migration")]
    MakeMigration { name: String },
    /// Apply pending migrations.
    Migrate,
    /// Revert the most recently applied migration.
    #[command(name = "migrate:rollback")]
    MigrateRollback,
    /// Show pending and applied migrations.
    #[command(name = "migrate:status")]
    MigrateStatus,
    /// Run application tests; pass Cargo test arguments after --.
    Test {
        #[arg(last = true)]
        args: Vec<String>,
    },
}

fn main() -> ExitCode {
    match execute(Cli::parse()) {
        Ok(code) => code,
        Err(error) => {
            eprintln!("Capy could not complete the command.\n\n{error:#}");
            ExitCode::FAILURE
        }
    }
}

fn execute(cli: Cli) -> Result<ExitCode> {
    let command = match cli.command {
        Commands::New {
            name,
            api,
            frontend,
        } => {
            let frontend = if api {
                FrontendDriver::None
            } else {
                frontend.unwrap_or(FrontendDriver::React)
            };
            new_project_with_frontend(&PathBuf::from(&name), &name, frontend)?;
            println!("Created {name}.\n\n  cd {name}\n  capy dev\n\nSQLite is ready for local development. Set DATABASE_URL to use PostgreSQL.");
            return Ok(ExitCode::SUCCESS);
        }
        Commands::MakeController { name } => return make(Generator::Controller, &name),
        Commands::MakeModel { name } => return make(Generator::Model, &name),
        Commands::MakeRequest { name } => return make(Generator::Request, &name),
        Commands::MakeMigration { name } => return make(Generator::Migration, &name),
        Commands::Test { args } => return cargo(&[vec!["test".into()], args].concat()),
        Commands::Dev(options) => {
            return dev::run(&find_project(std::env::current_dir()?)?, options)
        }
        Commands::Build => return process::build(&find_project(std::env::current_dir()?)?),
        Commands::Serve => return process::serve(&find_project(std::env::current_dir()?)?),
        Commands::Doctor => return doctor::run(&find_project(std::env::current_dir()?)?),
        Commands::Check => {
            let root = find_project(std::env::current_dir()?)?;
            doctor::check(&root)?;
            let status = cargo(&[
                "run".into(),
                "--offline".into(),
                "--quiet".into(),
                "--".into(),
                "check".into(),
            ])?;
            if status != ExitCode::SUCCESS {
                return Ok(status);
            }
            let types =
                capy_cli::ProjectConfig::load(&root)?.frontend.driver == FrontendDriver::React;
            return contracts::run(&root, types, true, true);
        }
        Commands::Routes { api } => {
            if api {
                "routes:api"
            } else {
                "routes"
            }
        }
        Commands::Openapi { check } => {
            return contracts::run(
                &find_project(std::env::current_dir()?)?,
                false,
                check,
                false,
            )
        }
        Commands::Types { check } => {
            return contracts::run(&find_project(std::env::current_dir()?)?, true, check, false)
        }
        Commands::Migrate => "migrate",
        Commands::MigrateRollback => "migrate:rollback",
        Commands::MigrateStatus => "migrate:status",
    };
    cargo(&["run".into(), "--quiet".into(), "--".into(), command.into()])
}

fn make(kind: Generator, name: &str) -> Result<ExitCode> {
    let root = find_project(std::env::current_dir()?)?;
    let path = generate(&root, kind, name)?;
    println!(
        "Created {}",
        path.strip_prefix(&root).unwrap_or(&path).display()
    );
    Ok(ExitCode::SUCCESS)
}

fn cargo(args: &[String]) -> Result<ExitCode> {
    let root = find_project(std::env::current_dir()?)?;
    let status = Command::new("cargo")
        .args(args)
        .current_dir(root)
        .status()
        .context("Could not start Cargo. Install the stable Rust toolchain.")?;
    Ok(process::exit_code(status))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn dev_cli_flags_validate_conflicts() {
        for args in [
            vec!["capy", "dev"],
            vec!["capy", "dev", "--inline"],
            vec!["capy", "dev", "--tui"],
            vec!["capy", "dev", "--stream"],
            vec!["capy", "dev", "--tui", "--stream"],
        ] {
            assert!(Cli::try_parse_from(args).is_ok());
        }
        for flag in ["--tui", "--stream"] {
            assert!(Cli::try_parse_from(["capy", "dev", "--inline", flag]).is_err());
        }
    }
}