capy-cli 0.2.0

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

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>,
    },
    /// Start the Rust development server and Vite (when configured).
    Dev,
    /// Build frontend assets and the Rust release application.
    Build,
    /// Run the Rust application only (does not start Vite).
    Serve,
    /// List registered API routes without opening a database connection.
    Routes,
    /// 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 => return process::dev(&find_project(std::env::current_dir()?)?),
        Commands::Build => return process::build(&find_project(std::env::current_dir()?)?),
        Commands::Serve => return process::serve(&find_project(std::env::current_dir()?)?),
        Commands::Routes => "routes",
        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))
}