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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! `ryuk new` and `make:*` file generation from embedded templates.
use crate::names::{pascal, snake};
use include_dir::{Dir, include_dir};
use std::{
    fs,
    io::{self, Write},
    path::{Path, PathBuf},
};

static APP: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/app");
static CLIENT: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/client");
static MAKE: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/make");

fn err(msg: String) -> io::Error {
    io::Error::other(msg)
}

/// Write a new file, refusing to overwrite.
fn write_new(path: &Path, content: &[u8]) -> io::Result<()> {
    if let Some(p) = path.parent() {
        fs::create_dir_all(p)?;
    }
    let mut f = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|e| {
            if e.kind() == io::ErrorKind::AlreadyExists {
                err(format!("{} already exists", path.display()))
            } else {
                e
            }
        })?;
    f.write_all(content)
}

/// Copy an embedded dir; `subst` maps (file name, text) -> text for files that carry placeholders.
fn copy_dir(dir: &Dir, dest: &Path, subst: &dyn Fn(&str, &str) -> String) -> io::Result<()> {
    for f in dir.files() {
        let rel = f.path();
        let name = rel.file_name().and_then(|n| n.to_str()).unwrap_or("");
        if name == ".gitkeep" {
            continue;
        }
        let out = dest.join(rel);
        // Askama templates use `{{ .. }}` themselves; copy them untouched.
        let verbatim = rel.starts_with("templates");
        match f.contents_utf8() {
            Some(t) if verbatim => write_new(&out, t.as_bytes())?,
            Some(t) => write_new(&out, subst(name, t).as_bytes())?,
            None => write_new(&out, f.contents())?,
        }
    }
    for d in dir.dirs() {
        copy_dir(d, dest, subst)?;
    }
    Ok(())
}

/// Database backend of a new app.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Db {
    Sqlite,
    Postgres,
    Mysql,
}

impl Db {
    /// Cargo feature name of both ryuk and sqlx for this backend.
    fn feature(self) -> &'static str {
        match self {
            Db::Sqlite => "sqlite",
            Db::Postgres => "postgres",
            Db::Mysql => "mysql",
        }
    }

    fn url(self, name: &str) -> String {
        match self {
            Db::Sqlite => "sqlite://db.sqlite?mode=rwc".into(),
            Db::Postgres => format!("postgres://ryuk:ryuk@127.0.0.1:5432/{name}"),
            Db::Mysql => format!("mysql://ryuk:ryuk@127.0.0.1:3306/{name}"),
        }
    }

    /// `docker-compose.yml` with a database matching [`Db::url`]; none for sqlite.
    fn compose(self, name: &str) -> Option<String> {
        let (image, env, port, vol, health) = match self {
            Db::Sqlite => return None,
            Db::Postgres => (
                "postgres:16",
                format!(
                    "POSTGRES_USER: ryuk\n      POSTGRES_PASSWORD: ryuk\n      POSTGRES_DB: {name}"
                ),
                "5432",
                "/var/lib/postgresql/data",
                "pg_isready -U ryuk",
            ),
            Db::Mysql => (
                "mysql:8",
                format!(
                    "MYSQL_ROOT_PASSWORD: ryuk\n      MYSQL_USER: ryuk\n      MYSQL_PASSWORD: ryuk\n      MYSQL_DATABASE: {name}"
                ),
                "3306",
                "/var/lib/mysql",
                "mysqladmin ping -h 127.0.0.1 -pryuk",
            ),
        };
        let scheme = self.feature();
        Some(format!(
            "services:\n  db:\n    image: {image}\n    environment:\n      {env}\n    ports:\n      - \"127.0.0.1:{port}:{port}\"\n    volumes:\n      - db-data:{vol}\n    healthcheck:\n      test: [\"CMD-SHELL\", \"{health}\"]\n      interval: 5s\n      retries: 20\n  app:\n    profiles: [\"app\"]\n    build: .\n    ports:\n      - \"127.0.0.1:3000:3000\"\n    environment:\n      DATABASE_URL: {scheme}://ryuk:ryuk@db:{port}/{name}\n      APP_URL: http://localhost:3000\n      # Local try-out only: the image runs with APP_ENV=production, which refuses the log mail driver.\n      # For a real deployment set MAIL_DRIVER=smtp (+ MAIL_HOST, MAIL_FROM, ...) and delete this line.\n      ALLOW_LOG_MAIL: \"true\"\n    depends_on:\n      db:\n        condition: service_healthy\nvolumes:\n  db-data:\n"
        ))
    }
}

/// Scaffold a new app at `parent/name`. `ryuk_path` is the local ryuk crate (RYUK_PATH), else crates.io.
pub fn new_app(parent: &Path, name: &str, ryuk_path: Option<&str>, db: Db) -> io::Result<PathBuf> {
    if name.is_empty()
        || !name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Err(err(format!(
            "invalid app name '{name}' (use letters, digits, - and _)"
        )));
    }
    let root = parent.join(name);
    if root.exists() {
        return Err(err(format!("{} already exists", root.display())));
    }
    let src = match ryuk_path {
        Some(p) => {
            let abs = fs::canonicalize(p).unwrap_or_else(|_| PathBuf::from(p));
            format!("path = \"{}\"", abs.display())
        }
        None => "version = \"0.1\"".to_string(),
    };
    let dep = format!(
        "ryuk = {{ {src}, default-features = false, features = [\"inertia\", \"auth\", \"validation\", \"openapi\", \"queue\", \"mail\", \"csrf\", \"safety\", \"session-db\", \"api\", \"apikeys\", \"oauth-server\", \"social\", \"passkey\", \"push\", \"mail-templates\", \"storage\", \"s3\", \"mcp\", \"http\", \"cache\", \"events\", \"schedule\", \"gate\", \"crypt\", \"notifications\", \"lang\", \"tenancy\", \"{}\"] }}",
        db.feature()
    );
    let (sqlx, url) = (format!("sqlx-{}", db.feature()), db.url(name));
    fs::create_dir_all(&root)?;
    copy_dir(&APP, &root, &|_, t| {
        t.replace("{{name}}", name)
            .replace("{{ryuk_dep}}", &dep)
            .replace("{{sqlx}}", &sqlx)
            .replace("{{database_url}}", &url)
    })?;
    if let Some(c) = db.compose(name) {
        write_new(&root.join("docker-compose.yml"), c.as_bytes())?;
    }
    // These cannot keep their real names inside this crate's source tree.
    for (from, to) in [
        ("Cargo.toml.tmpl", "Cargo.toml"),
        ("gitignore", ".gitignore"),
        ("env", ".env"),
    ] {
        fs::rename(root.join(from), root.join(to))?;
    }
    // client/ is owned by the frontend template: opaque, except these two known files.
    copy_dir(&CLIENT, &root.join("client"), &|file, t| {
        if file == "package.json" || file == "index.html" {
            t.replace("{{name}}", name)
        } else {
            t.to_string()
        }
    })?;
    Ok(root)
}

fn render(tmpl: &str, name: &str) -> String {
    let t = MAKE
        .get_file(tmpl)
        .expect("embedded template")
        .contents_utf8()
        .expect("utf8 template");
    t.replace("{{Name}}", &pascal(name))
        .replace("{{snake}}", &snake(name))
}

/// Append `line` to `dir/mod.rs` (creating it).
fn register_mod(dir: &Path, line: &str) -> io::Result<()> {
    let mut f = fs::OpenOptions::new()
        .append(true)
        .create(true)
        .open(dir.join("mod.rs"))?;
    writeln!(f, "{line}")
}

fn check_root(root: &Path) -> io::Result<()> {
    if root.join("Cargo.toml").exists() && root.join("src").is_dir() {
        Ok(())
    } else {
        Err(err(
            "run this from a ryuk app root (Cargo.toml + src/)".into()
        ))
    }
}

/// Add the module's `index` route to `src/<file>` at its `marker`, with a fully qualified path (the
/// routes files only import the controllers they were generated with). Returns false and leaves the
/// file alone when the marker is gone, so the caller can say what to add by hand.
fn wire_route(root: &Path, file: &str, marker: &str, path: &str) -> io::Result<bool> {
    let p = root.join("src").join(file);
    let Ok(src) = fs::read_to_string(&p) else {
        return Ok(false);
    };
    if !src.contains(marker) {
        return Ok(false);
    }
    let line = format!(".routes(routes!(crate::controllers::{path}::index))");
    fs::write(
        &p,
        src.replacen(marker, &format!("{line}\n        {marker}"), 1),
    )?;
    Ok(true)
}

/// Kinds handled by the simple "one file + mod line" generator.
pub fn make(root: &Path, kind: &str, name: &str) -> io::Result<Vec<PathBuf>> {
    check_root(root)?;
    check_name(name)?;
    let s = snake(name);
    let (dir, tmpl) = match kind {
        "model" => ("models", "model.rs.tmpl"),
        "tenant-model" => ("models", "model_tenant.rs.tmpl"),
        "controller" => ("controllers", "controller.rs.tmpl"),
        "api" => ("controllers/api", "api.rs.tmpl"),
        "job" => ("jobs", "job.rs.tmpl"),
        "mail" => ("mails", "mail.rs.tmpl"),
        "mail-template" => ("mails", "mail_template.rs.tmpl"),
        "event" => ("events", "event.rs.tmpl"),
        "notification" => ("notifications", "notification.rs.tmpl"),
        "policy" => ("policies", "policy.rs.tmpl"),
        "seeder" => ("seeders", "seeder.rs.tmpl"),
        "middleware" => ("middleware", "middleware.rs.tmpl"),
        "mcp-tool" => ("mcp", "mcp_tool.rs.tmpl"),
        _ => return Err(err(format!("unknown generator '{kind}'"))),
    };
    let d = root.join("src").join(dir);
    let file = d.join(format!("{s}.rs"));
    write_new(&file, render(tmpl, name).as_bytes())?;
    register_mod(&d, &format!("pub mod {s};"))?;
    let wired = match kind {
        "controller" => Some(("routes.rs", "// ryuk:routes", s.clone())),
        "api" => Some(("api.rs", "// ryuk:api-routes", format!("api::{s}"))),
        _ => None,
    };
    if let Some((f, marker, path)) = wired {
        if wire_route(root, f, marker, &path)? {
            println!("Registered the route in src/{f}");
        } else {
            println!(
                "src/{f} has no `{marker}` marker: add `.routes(routes!(crate::controllers::{path}::index))` yourself"
            );
        }
    }
    if kind == "seeder" {
        // Seeders run in creation order; the marker keeps `db:seed` a plain list of calls.
        let modrs = d.join("mod.rs");
        let src = fs::read_to_string(&modrs)?;
        if src.contains("// ryuk:seeders") {
            let call = format!("{s}::run(_db).await?;");
            fs::write(
                &modrs,
                src.replacen(
                    "// ryuk:seeders",
                    &format!("{call}\n    // ryuk:seeders"),
                    1,
                ),
            )?;
        } else {
            println!(
                "src/seeders/mod.rs has no `// ryuk:seeders` marker: call `{s}::run(db).await?` yourself"
            );
        }
    }
    match kind {
        "api" => println!(
            "Next: the stub requires the scope `{s}:read`. Add it to SCOPES in src/controllers/api_keys.rs and to the OAuth scope list in src/lib.rs, otherwise no key or token can reach this route."
        ),
        "model" => println!(
            "Next: if rows belong to a user, delete them in `delete_user` (src/account.rs), or account deletion leaves this table's data behind."
        ),
        "tenant-model" => println!(
            "Next: filter EVERY query on this table by `org_id` from `ryuk::tenancy::Member` (see src/controllers/projects.rs), and delete its rows in `delete_org` (src/account.rs), or deleting an organization leaves them behind."
        ),
        _ => {}
    }
    let mut made = vec![file];
    if kind == "mail-template" {
        for (ext, tmpl) in [
            ("html", "mail_template.html.tmpl"),
            ("txt", "mail_template.txt.tmpl"),
        ] {
            let path = root.join("templates/mail").join(format!("{s}.{ext}"));
            write_new(&path, render(tmpl, name).as_bytes())?;
            made.push(path);
        }
    }
    if let Some(tmpl) = match kind {
        "model" => Some("model_migration.rs.tmpl"),
        "tenant-model" => Some("model_migration_tenant.rs.tmpl"),
        _ => None,
    } {
        made.push(migration(root, &format!("create_{s}s_table"), tmpl, name)?);
    }
    Ok(made)
}

/// A generator name becomes a file name, a `mod` line and a Rust identifier, so it must be plain: a letter first,
/// then letters, digits, spaces, `-` and `_`, and not a Rust keyword. `../x` would write outside the project and
/// `x;include_str!(..);` would splice code into `mod.rs`.
fn check_name(name: &str) -> io::Result<()> {
    const KEYWORDS: &[&str] = &[
        "as", "async", "await", "box", "break", "const", "continue", "crate", "dyn", "else",
        "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
        "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super", "trait",
        "true", "type", "unsafe", "use", "where", "while",
    ];
    let mut chars = name.chars();
    let plain = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || "-_ ".contains(c));
    if !plain || name.len() > 64 {
        return Err(err(format!(
            "invalid name '{name}' (a letter first, then letters, digits, spaces, - and _; at most 64 characters)"
        )));
    }
    if KEYWORDS.contains(&snake(name).as_str()) {
        return Err(err(format!(
            "'{name}' is a Rust keyword; pick another name"
        )));
    }
    Ok(())
}

/// `make:migration`: file `m<timestamp>_<name>.rs`, registered in `src/migrations/mod.rs`.
pub fn make_migration(root: &Path, name: &str) -> io::Result<PathBuf> {
    check_root(root)?;
    check_name(name)?;
    migration(root, name, "migration.rs.tmpl", name)
}

fn migration(root: &Path, file_name: &str, tmpl: &str, tmpl_name: &str) -> io::Result<PathBuf> {
    let d = root.join("src/migrations");
    let modrs = d.join("mod.rs");
    let src =
        fs::read_to_string(&modrs).map_err(|_| err("src/migrations/mod.rs not found".into()))?;
    if !src.contains("// ryuk:mods") || !src.contains("// ryuk:list") {
        return Err(err(
            "src/migrations/mod.rs lost its `// ryuk:mods` / `// ryuk:list` markers".into(),
        ));
    }
    let m = format!(
        "m{}_{}",
        chrono::Utc::now().format("%Y%m%d_%H%M%S"),
        snake(file_name)
    );
    let file = d.join(format!("{m}.rs"));
    write_new(&file, render(tmpl, tmpl_name).as_bytes())?;
    let out = src
        .replace("// ryuk:mods", &format!("mod {m};\n// ryuk:mods"))
        .replace(
            "// ryuk:list",
            &format!("Box::new({m}::Migration),\n            // ryuk:list"),
        );
    fs::write(modrs, out)?;
    Ok(file)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn askama_templates_are_copied_byte_for_byte() {
        let tmp = tempfile::tempdir().unwrap();
        let root = new_app(tmp.path(), "demo", Some("/nonexistent/ryuk"), Db::Sqlite).unwrap();
        let mut seen = 0;
        for f in APP
            .get_dir("templates/mail")
            .expect("embedded mail templates")
            .files()
        {
            let name = f.path().file_name().unwrap();
            let got = fs::read(root.join("templates/mail").join(name)).unwrap();
            assert_eq!(got, f.contents(), "{name:?} was altered while generating");
            seen += 1;
        }
        assert!(
            seen >= 8,
            "layout + macros + 3 emails x 2 parts, saw {seen}"
        );
        let html = fs::read_to_string(root.join("templates/mail/verify_email.html")).unwrap();
        assert!(
            html.contains("{{ name }}") && html.contains("{{ m::button(link,"),
            "{html}"
        );
        // Spaces inside `{{ }}` also keep these away from the generator's own `{{name}}` placeholders.
        let txt = fs::read_to_string(root.join("templates/mail/verify_email.txt")).unwrap();
        assert!(
            txt.contains("{{ link }}") && txt.contains("{{ life }}"),
            "{txt}"
        );
    }

    #[test]
    fn new_scaffolds_app_for_every_db() {
        let tmp = tempfile::tempdir().unwrap();
        for (db, feat, url, compose) in [
            (
                Db::Sqlite,
                "sqlite",
                "DATABASE_URL=sqlite://db.sqlite?mode=rwc",
                false,
            ),
            (
                Db::Postgres,
                "postgres",
                "DATABASE_URL=postgres://ryuk:ryuk@127.0.0.1:5432/demo",
                true,
            ),
            (
                Db::Mysql,
                "mysql",
                "DATABASE_URL=mysql://ryuk:ryuk@127.0.0.1:3306/demo",
                true,
            ),
        ] {
            let parent = tmp.path().join(feat);
            let root = new_app(&parent, "demo", Some("/nonexistent/ryuk"), db).unwrap();
            for f in [
                "Cargo.toml",
                ".env",
                ".gitignore",
                "src/main.rs",
                "src/routes.rs",
                "src/controllers/auth.rs",
                "src/models/user.rs",
                "src/migrations/mod.rs",
            ] {
                assert!(root.join(f).exists(), "missing {f}");
            }
            let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
            assert!(
                cargo.contains("name = \"demo\"") && cargo.contains("path = \"/nonexistent/ryuk\"")
            );
            assert!(
                cargo.contains("default-features = false")
                    && cargo.contains(&format!("\"{feat}\"] }}")),
                "{cargo}"
            );
            assert!(cargo.contains(&format!("sqlx-{feat}")));
            assert!(fs::read_to_string(root.join(".env")).unwrap().contains(url));
            assert_eq!(root.join("docker-compose.yml").exists(), compose);
            for f in ["Cargo.toml", ".env", "src/main.rs"] {
                assert!(
                    !fs::read_to_string(root.join(f)).unwrap().contains("{{"),
                    "{f}"
                );
            }
            if compose {
                let c = fs::read_to_string(root.join("docker-compose.yml")).unwrap();
                assert!(c.contains("ryuk") && c.contains("demo"));
                assert!(
                    c.contains("profiles: [\"app\"]")
                        && c.contains(&format!("{feat}://ryuk:ryuk@db:")),
                    "{c}"
                );
                // The production image refuses the log mail driver; the local compose says so and opts in.
                assert!(c.contains("ALLOW_LOG_MAIL: \"true\""), "{c}");
            }
            for f in [
                "src/lib.rs",
                "tests/flows.rs",
                "Dockerfile",
                ".dockerignore",
                ".env.example",
                "README.md",
            ] {
                assert!(root.join(f).exists(), "missing {f}");
                assert!(
                    !fs::read_to_string(root.join(f)).unwrap().contains("{{"),
                    "{f}"
                );
            }
            assert!(
                fs::read_to_string(root.join("Dockerfile"))
                    .unwrap()
                    .contains("/usr/local/bin/demo")
            );
        }
        let r = tmp.path().join("again");
        new_app(&r, "demo", None, Db::Sqlite).unwrap();
        assert!(
            new_app(&r, "demo", None, Db::Sqlite).is_err(),
            "must not overwrite"
        );
        let d2 = new_app(&r, "d2", None, Db::Sqlite).unwrap();
        assert!(
            fs::read_to_string(d2.join("Cargo.toml"))
                .unwrap()
                .contains("version = \"0.1\"")
        );
        assert!(new_app(&r, "bad name", None, Db::Sqlite).is_err());
    }

    #[test]
    fn make_generates_and_refuses_overwrite() {
        let tmp = tempfile::tempdir().unwrap();
        let root = new_app(tmp.path(), "demo", None, Db::Sqlite).unwrap();
        make(&root, "model", "BlogPost").unwrap();
        let model = fs::read_to_string(root.join("src/models/blog_post.rs")).unwrap();
        assert!(model.contains("blog_posts"));
        assert!(
            fs::read_to_string(root.join("src/models/mod.rs"))
                .unwrap()
                .contains("pub mod blog_post;")
        );
        let mig = fs::read_to_string(root.join("src/migrations/mod.rs")).unwrap();
        assert!(mig.contains("create_blog_posts_table::Migration"));
        assert!(make(&root, "model", "BlogPost").is_err());
        // Names become files, `mod` lines and identifiers: nothing that escapes or injects is accepted.
        for bad in [
            "../../escape",
            "a/b",
            "x;include_str!(\"/etc/passwd\");",
            "foo;bar",
            "x{}",
            "",
            "1abc",
            "type",
            "Mod",
            ".hidden",
        ] {
            for kind in ["job", "controller", "seeder", "model"] {
                assert!(make(&root, kind, bad).is_err(), "{kind} {bad:?}");
            }
            assert!(make_migration(&root, bad).is_err(), "migration {bad:?}");
        }
        assert!(!root.join("src").join("escape.rs").exists());
        // Passkeys need a real domain as the relying party id, so the generated app must not default to a bare IP.
        let env = fs::read_to_string(root.join(".env")).unwrap();
        assert!(env.contains("APP_URL=http://localhost:3000"), "{env}");
        make(&root, "tenant-model", "Invoice").unwrap();
        let t = fs::read_to_string(root.join("src/models/invoice.rs")).unwrap();
        assert!(t.contains("pub org_id: i64") && t.contains("invoices"));
        let mig = fs::read_dir(root.join("src/migrations"))
            .unwrap()
            .map(|e| e.unwrap().path())
            .find(|p| p.to_string_lossy().ends_with("create_invoices_table.rs"))
            .expect("tenant migration");
        let mig = fs::read_to_string(mig).unwrap();
        assert!(
            mig.contains("Orgs::Table")
                && mig.contains("ForeignKeyAction::Cascade")
                && mig.contains("idx_invoices_org_id"),
            "FK to orgs and an org_id index"
        );
        make(&root, "controller", "Invoice").unwrap();
        let routes = fs::read_to_string(root.join("src/routes.rs")).unwrap();
        assert!(routes.contains("routes!(crate::controllers::invoice::index)"));
        assert!(
            routes.contains("// ryuk:routes"),
            "marker stays for the next controller"
        );
        assert!(
            fs::read_to_string(root.join("src/controllers/mod.rs"))
                .unwrap()
                .contains("pub mod invoice;")
        );
        make(&root, "controller", "Order").unwrap();
        let routes = fs::read_to_string(root.join("src/routes.rs")).unwrap();
        assert!(
            routes.contains("controllers::invoice::index")
                && routes.contains("controllers::order::index")
        );
        make(&root, "api", "Widget").unwrap();
        let api = fs::read_to_string(root.join("src/api.rs")).unwrap();
        assert!(
            api.contains("routes!(crate::controllers::api::widget::index)")
                && api.contains("// ryuk:api-routes")
        );
        let w = fs::read_to_string(root.join("src/controllers/api/widget.rs")).unwrap();
        assert!(w.contains("ApiAuth") && w.contains("path = \"/widget\"") && !w.contains("{{"));
        assert!(
            fs::read_to_string(root.join("src/controllers/api/mod.rs"))
                .unwrap()
                .contains("pub mod widget;")
        );
        assert!(make(&root, "api", "Widget").is_err());
        make(&root, "job", "SendEmail").unwrap();
        assert!(
            fs::read_to_string(root.join("src/jobs/send_email.rs"))
                .unwrap()
                .contains("struct SendEmail")
        );
        make(&root, "mail-template", "Invoice Paid").unwrap();
        let rs = fs::read_to_string(root.join("src/mails/invoice_paid.rs")).unwrap();
        assert!(
            rs.contains("path = \"mail/invoice_paid.html\", askama = ryuk::mail::askama"),
            "{rs}"
        );
        assert!(
            rs.contains("pub fn invoice_paid(name: &str, to: &str) -> Result<Mail, MailError>"),
            "{rs}"
        );
        let html = fs::read_to_string(root.join("templates/mail/invoice_paid.html")).unwrap();
        assert!(
            html.contains("{{ name }}") && html.contains("InvoicePaid"),
            "{html}"
        );
        assert!(
            fs::read_to_string(root.join("templates/mail/invoice_paid.txt"))
                .unwrap()
                .contains("Hi {{ name }},")
        );
        assert!(
            make(&root, "mail-template", "Invoice Paid").is_err(),
            "never overwrites"
        );
        for (kind, name, file) in [
            ("event", "UserRegistered", "events/user_registered.rs"),
            ("notification", "Welcome", "notifications/welcome.rs"),
            ("policy", "Post", "policies/post.rs"),
            ("middleware", "Audit", "middleware/audit.rs"),
            ("mcp-tool", "Weather", "mcp/weather.rs"),
        ] {
            make(&root, kind, name).unwrap();
            assert!(root.join("src").join(file).exists(), "{kind}");
        }
        make(&root, "seeder", "Users").unwrap();
        let seeders = fs::read_to_string(root.join("src/seeders/mod.rs")).unwrap();
        assert!(seeders.contains("users::run(_db).await?;"), "{seeders}");
        assert!(seeders.contains("pub mod users;"));
    }
}