mod names;
mod scaffold;
use clap::{Parser, Subcommand};
use std::{
path::Path,
process::{Child, Command, ExitCode},
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
#[derive(Parser)]
#[command(
name = "ryuk",
version,
about = "Laravel-style full-stack Rust framework"
)]
struct Cli {
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
New {
name: String,
#[arg(long, value_enum, default_value = "sqlite")]
db: scaffold::Db,
},
Serve,
#[command(name = "migrate")]
Migrate,
#[command(name = "migrate:rollback")]
MigrateRollback,
#[command(name = "migrate:fresh")]
MigrateFresh,
#[command(name = "make:model")]
MakeModel { name: String },
#[command(name = "make:api")]
MakeApi { name: String },
#[command(name = "make:controller")]
MakeController { name: String },
#[command(name = "make:migration")]
MakeMigration { name: String },
#[command(name = "make:job")]
MakeJob { name: String },
#[command(name = "make:mail")]
MakeMail {
name: String,
#[arg(long)]
template: bool,
},
#[command(name = "make:event")]
MakeEvent { name: String },
#[command(name = "make:notification")]
MakeNotification { name: String },
#[command(name = "make:policy")]
MakePolicy { name: String },
#[command(name = "make:seeder")]
MakeSeeder { name: String },
#[command(name = "make:middleware")]
MakeMiddleware { name: String },
#[command(name = "make:mcp-tool")]
MakeMcpTool { name: String },
#[command(name = "db:seed")]
DbSeed,
#[command(
name = "oauth:client",
trailing_var_arg = true,
allow_hyphen_values = true
)]
OauthClient { args: Vec<String> },
#[command(
name = "apikey:create",
trailing_var_arg = true,
allow_hyphen_values = true
)]
ApikeyCreate { args: Vec<String> },
#[command(
name = "apikey:list",
trailing_var_arg = true,
allow_hyphen_values = true
)]
ApikeyList { args: Vec<String> },
#[command(
name = "apikey:revoke",
trailing_var_arg = true,
allow_hyphen_values = true
)]
ApikeyRevoke { args: Vec<String> },
#[command(
name = "push:test",
trailing_var_arg = true,
allow_hyphen_values = true
)]
PushTest { args: Vec<String> },
#[command(
name = "device:list",
trailing_var_arg = true,
allow_hyphen_values = true
)]
DeviceList { args: Vec<String> },
#[command(name = "queue:work")]
QueueWork,
Doctor,
Routes,
}
fn main() -> ExitCode {
let cmd = Cli::parse().cmd;
let cwd = Path::new(".");
let res = match cmd {
Cmd::New { name, db } => {
scaffold::new_app(cwd, &name, std::env::var("RYUK_PATH").ok().as_deref(), db).map(
|root| {
println!(
"Created {}\n\n cd {name} && (cd client && npm install) && ryuk serve",
root.display()
);
0
},
)
}
Cmd::Serve => serve(),
Cmd::Migrate => app_cmd("migrate", &[]),
Cmd::MigrateRollback => app_cmd("migrate:rollback", &[]),
Cmd::MigrateFresh => app_cmd("migrate:fresh", &[]),
Cmd::QueueWork => app_cmd("queue:work", &[]),
Cmd::Routes => app_cmd("routes", &[]),
Cmd::Doctor => Ok(doctor()),
Cmd::MakeMigration { name } => scaffold::make_migration(cwd, &name).map(|f| report(&[f])),
Cmd::MakeModel { name } => scaffold::make(cwd, "model", &name).map(|f| report(&f)),
Cmd::MakeController { name } => {
scaffold::make(cwd, "controller", &name).map(|f| report(&f))
}
Cmd::MakeApi { name } => scaffold::make(cwd, "api", &name).map(|f| report(&f)),
Cmd::OauthClient { args } => app_cmd("oauth:client", &args),
Cmd::ApikeyCreate { args } => app_cmd("apikey:create", &args),
Cmd::ApikeyList { args } => app_cmd("apikey:list", &args),
Cmd::ApikeyRevoke { args } => app_cmd("apikey:revoke", &args),
Cmd::PushTest { args } => app_cmd("push:test", &args),
Cmd::DeviceList { args } => app_cmd("device:list", &args),
Cmd::MakeJob { name } => scaffold::make(cwd, "job", &name).map(|f| report(&f)),
Cmd::MakeEvent { name } => scaffold::make(cwd, "event", &name).map(|f| report(&f)),
Cmd::MakeNotification { name } => {
scaffold::make(cwd, "notification", &name).map(|f| report(&f))
}
Cmd::MakePolicy { name } => scaffold::make(cwd, "policy", &name).map(|f| report(&f)),
Cmd::MakeSeeder { name } => scaffold::make(cwd, "seeder", &name).map(|f| report(&f)),
Cmd::MakeMiddleware { name } => {
scaffold::make(cwd, "middleware", &name).map(|f| report(&f))
}
Cmd::MakeMcpTool { name } => scaffold::make(cwd, "mcp-tool", &name).map(|f| report(&f)),
Cmd::DbSeed => app_cmd("db:seed", &[]),
Cmd::MakeMail { name, template } => {
scaffold::make(cwd, if template { "mail-template" } else { "mail" }, &name)
.map(|f| report(&f))
}
};
match res {
Ok(0) => ExitCode::SUCCESS,
Ok(c) => ExitCode::from(c as u8),
Err(e) => {
eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
fn watch_args(has_templates: bool) -> Vec<&'static str> {
let mut a = vec!["watch", "-w", "src", "-w", "Cargo.toml"];
if has_templates {
a.extend(["-w", "templates"]);
}
a.extend(["-x", "run"]);
a
}
fn report(files: &[std::path::PathBuf]) -> i32 {
for f in files {
println!("Created {}", f.display());
}
0
}
fn app_cmd(cmd: &str, extra: &[String]) -> std::io::Result<i32> {
let st = Command::new("cargo")
.args(["run", "-q", "--", cmd])
.args(extra)
.status()?;
Ok(st.code().unwrap_or(1))
}
static STOP: AtomicBool = AtomicBool::new(false);
fn spawn(program: &str, args: &[&str], dir: Option<&str>) -> std::io::Result<Child> {
let mut c = Command::new(program);
c.args(args);
if let Some(d) = dir {
c.current_dir(d);
}
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut c, 0); c.spawn()
}
fn kill(child: &mut Child) {
#[cfg(unix)]
{
let _ = Command::new("kill")
.args(["-TERM", "--", &format!("-{}", child.id())])
.stderr(std::process::Stdio::null())
.status();
}
let _ = child.kill();
let _ = child.wait();
}
fn serve() -> std::io::Result<i32> {
let mut children: Vec<(&str, Child)> = vec![];
if Path::new("client/package.json").exists() {
if !Path::new("client/node_modules").exists() {
eprintln!("client/node_modules missing: running `npm install` first");
let ok = Command::new("npm")
.arg("install")
.current_dir("client")
.status()
.is_ok_and(|s| s.success());
if !ok {
eprintln!("`npm install` failed in client/; fix it and run `ryuk serve` again");
return Ok(1);
}
}
children.push(("vite", spawn("npm", &["run", "dev"], Some("client"))?));
} else {
eprintln!("client/package.json not found, skipping vite");
}
let watch = Command::new("cargo")
.args(["watch", "--version"])
.output()
.map(|o| o.status.success())
.unwrap_or(false);
children.push((
"cargo",
if watch {
spawn(
"cargo",
&watch_args(std::path::Path::new("templates").is_dir()),
None,
)?
} else {
spawn("cargo", &["run"], None)?
},
));
ctrlc::set_handler(|| STOP.store(true, Ordering::SeqCst)).map_err(std::io::Error::other)?;
let mut code = 0;
'wait: loop {
if STOP.load(Ordering::SeqCst) {
break;
}
for (name, c) in children.iter_mut() {
if let Ok(Some(st)) = c.try_wait() {
code = st.code().unwrap_or(1);
if code != 0 {
eprintln!("{name} exited with status {code}; stopping the other process");
}
break 'wait;
}
}
std::thread::sleep(Duration::from_millis(200));
}
children.iter_mut().for_each(|(_, c)| kill(c));
Ok(code)
}
fn version(prog: &str) -> Option<String> {
let o = Command::new(prog)
.arg("--version")
.output()
.ok()
.filter(|o| o.status.success())?;
Some(
String::from_utf8_lossy(&o.stdout)
.lines()
.next()?
.trim()
.to_string(),
)
}
fn doctor() -> i32 {
let mut bad = false;
for (prog, needed) in [
("rustc", true),
("node", false),
("pnpm", false),
("docker", false),
] {
match version(prog) {
Some(v) => println!("ok {prog}: {v}"),
None => {
println!(
"{} {prog}: not found",
if needed { "MISSING " } else { "missing " }
);
bad |= needed;
}
}
}
let url = std::env::var("DATABASE_URL").ok().or_else(|| {
let env = std::fs::read_to_string(".env").ok()?;
env.lines()
.find_map(|l| l.strip_prefix("DATABASE_URL="))
.map(|v| v.trim().to_string())
});
match url {
None => println!("missing DATABASE_URL: not set (env or .env)"),
Some(u) => {
let (ok, what) = db_reachable(&u);
println!(
"{} database: {what}",
if ok { "ok " } else { "MISSING " }
);
bad |= !ok;
}
}
bad as i32
}
fn db_reachable(url: &str) -> (bool, String) {
use std::net::{TcpStream, ToSocketAddrs};
let Some((scheme, rest)) = url.split_once("://") else {
return (false, format!("unparseable URL `{url}`"));
};
if scheme == "sqlite" {
let file = rest.split('?').next().unwrap_or("");
let dir = Path::new(file)
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
return (dir.is_dir(), format!("sqlite file {file}"));
}
let hp = rest
.rsplit('@')
.next()
.unwrap_or("")
.split('/')
.next()
.unwrap_or("");
let hp = if hp.contains(':') {
hp.to_string()
} else {
format!(
"{hp}:{}",
if scheme.starts_with("mysql") {
3306
} else {
5432
}
)
};
let ok = hp
.to_socket_addrs()
.ok()
.and_then(|mut a| a.next())
.is_some_and(|a| TcpStream::connect_timeout(&a, Duration::from_secs(2)).is_ok());
(
ok,
format!(
"{scheme} {hp} {}",
if ok { "reachable" } else { "unreachable" }
),
)
}
#[cfg(test)]
mod tests {
use super::watch_args;
#[test]
fn serve_rebuilds_when_an_email_template_changes() {
let with = watch_args(true);
assert!(
with.windows(2).any(|w| w == ["-w", "templates"]),
"{with:?}"
);
assert!(with.windows(2).any(|w| w == ["-w", "src"]) && with.ends_with(&["-x", "run"]));
assert!(!watch_args(false).contains(&"templates"));
}
}