ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! `ryuk` command line: scaffold apps, generate files, run dev servers, proxy app commands.
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 {
    /// Scaffold a new app in ./<name>
    New {
        name: String,
        /// Database backend
        #[arg(long, value_enum, default_value = "sqlite")]
        db: scaffold::Db,
    },
    /// Run vite dev + cargo (watch) together
    Serve,
    /// Run pending migrations
    #[command(name = "migrate")]
    Migrate,
    /// Roll back the last migration
    #[command(name = "migrate:rollback")]
    MigrateRollback,
    /// Drop everything and re-run all migrations
    #[command(name = "migrate:fresh")]
    MigrateFresh,
    /// Generate a SeaORM entity (plus its create-table migration)
    #[command(name = "make:model")]
    MakeModel {
        name: String,
        /// Tenant-owned: adds an `org_id` column (foreign key to `orgs`, indexed); see the tenancy guide
        #[arg(long)]
        tenant: bool,
    },
    /// Generate a JSON api controller (src/controllers/api, route in src/api.rs)
    #[command(name = "make:api")]
    MakeApi { name: String },
    /// Generate a controller
    #[command(name = "make:controller")]
    MakeController { name: String },
    /// Generate an empty migration
    #[command(name = "make:migration")]
    MakeMigration { name: String },
    /// Generate a queue job
    #[command(name = "make:job")]
    MakeJob { name: String },
    /// Generate a mail builder
    #[command(name = "make:mail")]
    MakeMail {
        name: String,
        /// Render the body from templates/mail/<name>.html and .txt (Askama) instead of inline strings
        #[arg(long)]
        template: bool,
    },
    /// Generate an event
    #[command(name = "make:event")]
    MakeEvent { name: String },
    /// Generate a notification
    #[command(name = "make:notification")]
    MakeNotification { name: String },
    /// Generate a policy for an existing model
    #[command(name = "make:policy")]
    MakePolicy { name: String },
    /// Generate a database seeder
    #[command(name = "make:seeder")]
    MakeSeeder { name: String },
    /// Generate an axum middleware
    #[command(name = "make:middleware")]
    MakeMiddleware { name: String },
    /// Generate an MCP tool
    #[command(name = "make:mcp-tool")]
    MakeMcpTool { name: String },
    /// Run the database seeders (src/seeders)
    #[command(name = "db:seed")]
    DbSeed,
    /// Register an OAuth client: --name <n> --redirect <uri>... --scope <s>... [--public] [--first-party] (scopes: profile posts:read posts:write devices account)
    #[command(
        name = "oauth:client",
        trailing_var_arg = true,
        allow_hyphen_values = true
    )]
    OauthClient { args: Vec<String> },
    /// Issue an API key: --user <id> | --system, --name <n>, --scope <s>... [--expires-days <n>]
    #[command(
        name = "apikey:create",
        trailing_var_arg = true,
        allow_hyphen_values = true
    )]
    ApikeyCreate { args: Vec<String> },
    /// List a user's API keys: --user <id>
    #[command(
        name = "apikey:list",
        trailing_var_arg = true,
        allow_hyphen_values = true
    )]
    ApikeyList { args: Vec<String> },
    /// Revoke an API key: --user <id> <key_id>
    #[command(
        name = "apikey:revoke",
        trailing_var_arg = true,
        allow_hyphen_values = true
    )]
    ApikeyRevoke { args: Vec<String> },
    /// Send a push now: --user <id> --title <t> --body <b> [--data k=v]... (log driver unless configured)
    #[command(
        name = "push:test",
        trailing_var_arg = true,
        allow_hyphen_values = true
    )]
    PushTest { args: Vec<String> },
    /// List a user's push devices: --user <id>
    #[command(
        name = "device:list",
        trailing_var_arg = true,
        allow_hyphen_values = true
    )]
    DeviceList { args: Vec<String> },
    /// Run the queue worker
    #[command(name = "queue:work")]
    QueueWork,
    /// Check rust, node, pnpm, docker and the database
    Doctor,
    /// Print the OpenAPI paths
    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, tenant } => {
            scaffold::make(cwd, if tenant { "tenant-model" } else { "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
        }
    }
}

/// `cargo watch` arguments. Only src/, Cargo.toml and templates/: watching everything restarts the server
/// on every write to client/node_modules/.vite or db.sqlite (outside a git repo .gitignore is not honored).
/// templates/ holds the Askama email templates, which are compiled in: without watching it, editing an
/// email would silently not rebuild.
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
}

/// The generated app binary doubles as its own artisan: forward to `cargo run -- <cmd>`.
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); // own group so we can kill npm's children too
    c.spawn()
}

fn kill(child: &mut Child) {
    #[cfg(unix)]
    {
        // shortcut: shells out to kill(1) for the group to avoid a libc dependency.
        // The group may already be gone (the child exited on its own): keep that quiet.
        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)
}

/// First line of `prog --version`, or None when it is not installed.
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(),
    )
}

/// `ryuk doctor`: exit 1 when rust or the database is missing (node/pnpm/docker are optional).
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
}

/// sqlite: the file's directory exists; others: a TCP connection to host:port succeeds.
/// shortcut: no login or query, only reachability; run `ryuk migrate` for a real check.
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"]));
        // An app generated before templates/ existed must still start: cargo watch rejects a missing path.
        assert!(!watch_args(false).contains(&"templates"));
    }
}