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 {
New {
name: String,
#[arg(long, conflicts_with = "frontend")]
api: bool,
#[arg(long, value_enum)]
frontend: Option<FrontendDriver>,
},
Dev(dev::Options),
Build,
Serve,
Doctor,
Check,
Routes {
#[arg(long)]
api: bool,
},
Openapi {
#[arg(long)]
check: bool,
#[arg(long)]
strict: bool,
},
Types {
#[arg(long)]
check: bool,
#[arg(long)]
strict: bool,
},
#[command(name = "make:controller")]
MakeController { name: String },
#[command(name = "make:model")]
MakeModel { name: String },
#[command(name = "make:request")]
MakeRequest { name: String },
#[command(name = "make:migration")]
MakeMigration { name: String },
#[command(name = "make:resource")]
MakeResource {
name: String,
fields: Vec<String>,
#[arg(long)]
frontend: bool,
},
#[command(name = "make:auth")]
MakeAuth {
#[arg(long)]
frontend: bool,
},
#[command(name = "auth:prune")]
AuthPrune,
#[command(name = "make:mail")]
MakeMail { name: String },
#[command(name = "make:notification")]
MakeNotification { name: String },
Mail {
#[command(subcommand)]
command: Option<MailCommand>,
},
#[command(name = "make:job")]
MakeJob { name: String },
#[command(name = "queue:work")]
QueueWork {
#[arg(long = "queue")]
queues: Vec<String>,
#[arg(long)]
concurrency: Option<usize>,
},
#[command(name = "queue:failed")]
QueueFailed,
#[command(name = "queue:retry")]
QueueRetry { id: String },
#[command(name = "queue:forget")]
QueueForget { id: String },
#[command(alias = "db:migrate")]
Migrate,
#[command(name = "db:seed")]
Seed,
#[command(name = "migrate:rollback", alias = "db:rollback")]
MigrateRollback,
#[command(name = "migrate:status", alias = "db:status")]
MigrateStatus,
Test {
#[arg(last = true)]
args: Vec<String>,
},
}
#[derive(Subcommand)]
enum MailCommand {
List,
Show { id: String },
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::MakeResource {
name,
fields,
frontend,
} => {
let root = find_project(std::env::current_dir()?)?;
let paths = capy_cli::make_resource(&root, &name, &fields, frontend)?;
println!("Created resource and updated {} files. Run capy db:migrate, capy types, and capy test.", paths.len());
return Ok(ExitCode::SUCCESS);
}
Commands::MakeAuth { frontend } => {
let root = find_project(std::env::current_dir()?)?;
let paths = capy_cli::make_auth_with_frontend(&root, frontend)?;
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, strict } => {
return contracts::run_with_strict(
&find_project(std::env::current_dir()?)?,
false,
check,
false,
strict,
)
}
Commands::Types { check, strict } => {
return contracts::run_with_strict(
&find_project(std::env::current_dir()?)?,
true,
check,
false,
strict,
)
}
Commands::Migrate => "migrate",
Commands::Seed => "db:seed",
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()
);
if matches!(kind, Generator::Controller) {
println!("Routing is explicit. Add this declaration to the Routes chain in routes/api.rs (mounted under /api), choosing an unused path:\n {}", capy_cli::controller_route(name)?);
}
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());
}
}
}