capy-cli 0.7.2

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 },
    /// Install conventional browser authentication.
    #[command(name = "make:auth")]
    MakeAuth,
    /// Delete expired sessions and password-reset records.
    #[command(name = "auth:prune")]
    AuthPrune,
    /// Generate a typed mailable and compiled text/HTML templates.
    #[command(name = "make:mail")]
    MakeMail { name: String },
    /// Generate a mail notification and compiled templates.
    #[command(name = "make:notification")]
    MakeNotification { name: String },
    /// Inspect the private local development inbox (requires the mail feature).
    Mail {
        #[command(subcommand)]
        command: Option<MailCommand>,
    },
    /// Create and register a durable job; installs jobs on first use.
    #[command(name = "make:job")]
    MakeJob { name: String },
    /// Run the application worker with bounded concurrency.
    #[command(name = "queue:work")]
    QueueWork {
        #[arg(long = "queue")]
        queues: Vec<String>,
        #[arg(long)]
        concurrency: Option<usize>,
    },
    /// Inspect failed jobs without dumping payloads.
    #[command(name = "queue:failed")]
    QueueFailed,
    /// Return a failed job to its original queue.
    #[command(name = "queue:retry")]
    QueueRetry { id: String },
    /// Permanently delete one failed job.
    #[command(name = "queue:forget")]
    QueueForget { id: 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>,
    },
}

#[derive(Subcommand)]
enum MailCommand {
    /// List captured message IDs, timestamps, recipients and subjects.
    List,
    /// Inspect text, HTML source, sender and custom headers in your terminal.
    Show { id: String },
    /// Remove all messages from the configured development inbox.
    Clear,
}

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::MakeMail { ref name } | Commands::MakeNotification { ref name } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = if matches!(cli.command, Commands::MakeMail { .. }) {
                capy_cli::make_mail(&root, name)?
            } else {
                capy_cli::make_notification(&root, name)?
            };
            println!("Created outbound communication and updated {} files. Development logs metadata only; configure SMTP to deliver.", paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::Mail { command } => {
            let args = match command.unwrap_or(MailCommand::List) {
                MailCommand::List => vec!["mail:list".into()],
                MailCommand::Show { id } => vec!["mail:show".into(), id],
                MailCommand::Clear => vec!["mail:clear".into()],
            };
            return process::application_command(&find_project(std::env::current_dir()?)?, &args);
        }
        Commands::MakeJob { name } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::make_job(&root, &name)?;
            println!(
                "Created job and updated {} files. Run capy migrate, then capy queue:work.",
                paths.len()
            );
            return Ok(ExitCode::SUCCESS);
        }
        Commands::QueueWork {
            queues,
            concurrency,
        } => {
            let mut args = vec!["queue:work".to_owned()];
            for queue in queues {
                args.extend(["--queue".into(), queue]);
            }
            if let Some(concurrency) = concurrency {
                args.extend(["--concurrency".into(), concurrency.to_string()]);
            }
            return process::application_command(&find_project(std::env::current_dir()?)?, &args);
        }
        Commands::QueueFailed => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["queue:failed".into()],
            )
        }
        Commands::QueueRetry { id } => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["queue:retry".into(), id],
            )
        }
        Commands::QueueForget { id } => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["queue:forget".into(), id],
            )
        }
        Commands::MakeAuth => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::make_auth(&root)?;
            println!("Installed conventional auth ({} files).\nRun capy migrate, then capy types (React) or capy openapi (--api).\nReplace app/auth.rs reset delivery before production.", paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::AuthPrune => "auth:prune",
        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());
        }
    }
}