renox-cli 1.0.0-rc.6

rnx, the command-line tool for the Renox web framework (like Laravel's artisan).
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
use std::fs;
use std::path::Path;

use anyhow::{Context, Result, bail};

use crate::Database;

/// Files of a new app: (path, contents). `.stub` files are templated.
const STUBS: &[(&str, &str)] = &[
    ("Cargo.toml", include_str!("../stubs/Cargo.toml.stub")),
    ("AGENTS.md", include_str!("../stubs/AGENTS.md.stub")),
    // Claude Code reads CLAUDE.md; it imports AGENTS.md so there's one text.
    ("CLAUDE.md", include_str!("../stubs/CLAUDE.md.stub")),
    (".env", include_str!("../stubs/env.stub")),
    (".env.example", include_str!("../stubs/env.stub")),
    (".gitignore", include_str!("../stubs/gitignore.stub")),
    ("build.rs", include_str!("../stubs/build.rs")),
    ("migrations/.gitkeep", ""),
    ("src/lib.rs", include_str!("../stubs/src/lib.rs")),
    ("src/main.rs", include_str!("../stubs/src/main.rs")),
    ("tests/home.rs", include_str!("../stubs/tests/home.rs")),
    ("src/app/mod.rs", include_str!("../stubs/src/app/mod.rs")),
    (
        "src/app/home/mod.rs",
        include_str!("../stubs/src/app/home/mod.rs"),
    ),
    (
        "resources/views/layouts/app.html",
        include_str!("../stubs/resources/views/layouts/app.html"),
    ),
    (
        "resources/views/home/index.html",
        include_str!("../stubs/resources/views/home/index.html"),
    ),
    (
        "resources/views/errors/default.html",
        include_str!("../stubs/resources/views/errors/default.html"),
    ),
    ("public/app.css", include_str!("../stubs/public/app.css")),
    (
        "resources/lang/en.json",
        include_str!("../stubs/resources/lang/en.json"),
    ),
];

/// `--starter`: the starter kit, files written over the stubs above (same
/// path) or next to them. Sign-up with email verification, roles, the
/// activity log, a dashboard and the users page in the kit's sidebar layout.
const STARTER: &[(&str, &str)] = &[
    ("src/lib.rs", include_str!("../stubs/starter/src/lib.rs")),
    (
        "src/app/mod.rs",
        include_str!("../stubs/starter/src/app/mod.rs"),
    ),
    (
        "src/app/home/mod.rs",
        include_str!("../stubs/starter/src/app/home/mod.rs"),
    ),
    (
        "src/app/dashboard/mod.rs",
        include_str!("../stubs/starter/src/app/dashboard/mod.rs"),
    ),
    (
        "src/app/users/mod.rs",
        include_str!("../stubs/starter/src/app/users/mod.rs"),
    ),
    (
        "src/app/activity/mod.rs",
        include_str!("../stubs/starter/src/app/activity/mod.rs"),
    ),
    (
        "src/app/roles.rs",
        include_str!("../stubs/starter/src/app/roles.rs"),
    ),
    (
        "src/app/seed.rs",
        include_str!("../stubs/starter/src/app/seed.rs"),
    ),
    (
        "tests/home.rs",
        include_str!("../stubs/starter/tests/home.rs"),
    ),
    (
        "resources/views/layouts/app.html",
        include_str!("../stubs/starter/resources/views/layouts/app.html"),
    ),
    (
        "resources/views/home/index.html",
        include_str!("../stubs/starter/resources/views/home/index.html"),
    ),
    (
        "resources/views/dashboard/show.html",
        include_str!("../stubs/starter/resources/views/dashboard/show.html"),
    ),
    (
        "resources/views/users/index.html",
        include_str!("../stubs/starter/resources/views/users/index.html"),
    ),
    (
        "resources/views/activity/index.html",
        include_str!("../stubs/starter/resources/views/activity/index.html"),
    ),
    (
        "resources/lang/en.json",
        include_str!("../stubs/starter/resources/lang/en.json"),
    ),
];

/// `--notifications` on the plain app (the starter kit has them already):
/// `Auth::new().notifications()`, the bell in the layout's bar, and a test.
fn with_notifications(file: &str, contents: &str) -> String {
    let edits: &[(&str, &str)] = match file {
        "src/lib.rs" => &[(
            "        .module(renox::auth::Auth::new().account()) // login, register, /account\n",
            "        // Login, register, /account, and the notification bell (/notifications).\n        \
             .module(renox::auth::Auth::new().account().notifications())\n",
        )],
        "resources/views/layouts/app.html" => &[
            (
                "menu_separator, link_button %}",
                "menu_separator, link_button, notification_bell %}",
            ),
            (
                "    {% if auth.check %}\n",
                "    {% if auth.check %}\n      \
                 {#- In-app notifications: a badge, a panel, new ones live (docs/mail.md). -#}\n      \
                 {{ notification_bell(unread_notifications) }}\n",
            ),
        ],
        "tests/home.rs" => &[("", NOTIFICATIONS_TEST)],
        _ => &[],
    };
    // A checkout with CRLF endings (Git on Windows) compiles the stubs in
    // with them; the edits look for `\n`.
    let mut contents = contents.replace("\r\n", "\n");
    for (old, new) in edits {
        if old.is_empty() {
            contents.push_str(new);
        } else {
            assert!(contents.contains(old), "{file} lost `{old}`");
            contents = contents.replacen(old, new, 1);
        }
    }
    contents
}

/// The test `--notifications` adds to `tests/home.rs`.
const NOTIFICATIONS_TEST: &str = r#"
#[renox::test]
async fn the_bell_shows_notifications() {
    let app = TestApp::new({{crate_name}}::app()).await;
    let user = User::register(app.db(), "Anna", "anna@example.com", "secret123")
        .await
        .unwrap();
    app.acting_as(&user);
    app.get("/").await.assert_ok().assert_see("data-rx-bell");
    app.get("/notifications")
        .await
        .assert_ok()
        .assert_see("No notifications");
}
"#;

/// The files of a new app: the stubs, with the starter kit's over them.
fn files(starter: bool) -> Vec<(&'static str, &'static str)> {
    let kit: &[(&str, &str)] = if starter { STARTER } else { &[] };
    let mut files: Vec<_> = STUBS
        .iter()
        .map(|&(path, text)| {
            let over = kit.iter().find(|(kit_path, _)| *kit_path == path);
            (path, over.map_or(text, |(_, text)| *text))
        })
        .collect();
    files.extend(
        kit.iter()
            .filter(|(path, _)| !STUBS.iter().any(|(stub, _)| stub == path)),
    );
    files
}

const RENOX_GIT: &str = "https://github.com/arif-rachim/renox";

/// Renox from GitHub, pinned to the commit this `rnx` was built from, so
/// `cargo update` doesn't move the app to an API it wasn't written for.
fn git_dependency(rev: Option<&str>) -> String {
    match rev {
        Some(rev) => format!("renox = {{ git = \"{RENOX_GIT}\", rev = \"{rev}\""),
        // Built without git: follow main (move to a `rev` when you can).
        None => format!("renox = {{ git = \"{RENOX_GIT}\", branch = \"main\""),
    }
}

/// The Renox repository at `rev` (or `main`), for links in AGENTS.md.
fn docs_url(rev: Option<&str>) -> String {
    format!("{RENOX_GIT}/blob/{}", rev.unwrap_or("main"))
}

/// AGENTS.md's offline line for an app on a local checkout: everything is there.
fn path_offline(checkout: &str) -> String {
    format!(
        "Offline, everything (the source, the cheat sheet, llms.txt, the guides and the \
         examples) is in the local Renox checkout this app uses: `{checkout}`."
    )
}

/// AGENTS.md's offline line for an app pinned to a Git commit: Cargo's checkout
/// of the repository has everything.
fn git_offline(rev: Option<&str>) -> String {
    let dir = rev.map_or("*", |rev| &rev[..7.min(rev.len())]);
    format!(
        "Offline, everything (the source, the cheat sheet, llms.txt, the guides and the \
         examples) is in the checkout Cargo downloaded: `~/.cargo/git/checkouts/renox-*/{dir}/`."
    )
}

/// AGENTS.md's offline line for an app on crates.io: the downloaded crates
/// hold only the source, so it names the clone of this exact version.
fn registry_offline(version: &str) -> String {
    format!(
        "Offline, Renox's source is in the crates Cargo downloaded: \
         `~/.cargo/registry/src/*/renox-core-{version}/`. For the cheat sheet, llms.txt, the \
         guides and the examples of this version: \
         `git clone --depth 1 --branch v{version} {RENOX_GIT}`."
    )
}

/// Renox from crates.io, at this `rnx`'s own version (`cargo install
/// renox-cli` builds from the registry, without git): a caret requirement,
/// since a minor release doesn't break apps. A pre-release (`1.0.0-rc.1`)
/// is written whole: Cargo never picks one for `"1.0"`.
fn registry_dependency(version: &str) -> String {
    if version.contains('-') {
        return format!("renox = {{ version = \"{version}\"");
    }
    let major_minor: Vec<&str> = version.split('.').take(2).collect();
    format!("renox = {{ version = \"{}\"", major_minor.join("."))
}

/// What `rnx new` makes, besides the name.
#[derive(Clone, Copy)]
pub struct Options {
    pub database: Database,
    pub tailwind: bool,
    pub starter: bool,
    /// The notification bell in the plain app (the starter kit has it).
    pub notifications: bool,
}

pub fn run(name: &str, renox_path: Option<&Path>, options: Options) -> Result<()> {
    run_in(Path::new("."), name, renox_path, options)
}

/// `run`, making the app in `parent` (tests use a temporary directory).
fn run_in(parent: &Path, name: &str, renox_path: Option<&Path>, options: Options) -> Result<()> {
    let Options {
        database,
        tailwind,
        starter,
        notifications,
    } = options;
    validate_name(name)?;
    let root = &parent.join(name);
    if root.exists() {
        bail!("`{name}` already exists");
    }

    let rev = option_env!("RENOX_GIT_REV");
    // Where AGENTS.md sends coding agents: the docs of the Renox this app
    // compiles against, not `main`, which may have APIs it doesn't.
    let (dependency, docs, source) = match renox_path {
        Some(path) => {
            let crate_dir = path.join("crates/renox");
            let crate_dir = crate_dir
                .canonicalize()
                .with_context(|| format!("{} is not a Renox checkout", path.display()))?;
            let checkout = crate_dir
                .parent()
                .and_then(Path::parent)
                .unwrap_or(&crate_dir)
                .display()
                .to_string();
            (
                format!("renox = {{ path = {:?}", crate_dir.display().to_string()),
                docs_url(None),
                path_offline(&checkout),
            )
        }
        None if rev.is_none() && option_env!("RENOX_FROM_CRATES_IO").is_some() => {
            let version = env!("CARGO_PKG_VERSION");
            (
                registry_dependency(version),
                format!("{RENOX_GIT}/blob/v{version}"),
                registry_offline(version),
            )
        }
        None => (git_dependency(rev), docs_url(rev), git_offline(rev)),
    };
    let dependency = match database {
        Database::Sqlite => format!("{dependency} }}"),
        Database::Postgres => format!("{dependency}, features = [\"postgres\"] }}"),
    };
    let crate_name = name.replace('-', "_");
    let postgres = format!("postgres://postgres:postgres@localhost:5432/{crate_name}");
    let (database_url, test_database_url) = match database {
        Database::Sqlite => (
            "sqlite://storage/app.db".to_owned(),
            format!("# TEST_DATABASE_URL={postgres}_test"),
        ),
        Database::Postgres => (
            postgres.clone(),
            format!("TEST_DATABASE_URL={postgres}_test"),
        ),
    };
    let key = crate::generate_key();

    for (file, contents) in files(starter) {
        let contents = if notifications && !starter {
            with_notifications(file, contents)
        } else {
            contents.to_owned()
        };
        let contents = contents
            .replace("{{name}}", name)
            .replace("{{title}}", &title(name))
            .replace("{{renox_dependency}}", &dependency)
            .replace("{{renox_docs}}", &docs)
            .replace("{{renox_offline}}", &source)
            .replace("{{crate_name}}", &crate_name)
            .replace("{{database_url}}", &database_url)
            .replace("{{test_database_url}}", &test_database_url);
        // Only the real .env gets a key; .env.example stays shareable.
        let contents = match file {
            ".env" => contents.replace("{{app_key}}", &key),
            _ => contents.replace("{{app_key}}", ""),
        };
        let path = root.join(file);
        fs::create_dir_all(path.parent().expect("stub paths have a parent"))?;
        fs::write(&path, contents)
            .with_context(|| format!("could not write {}", path.display()))?;
        crate::format::touched(&path);
    }

    if tailwind {
        use_tailwind(root)?;
    }

    match database {
        Database::Sqlite => println!("Created {name}. Next:\n\n    cd {name}\n    rnx serve\n"),
        Database::Postgres => println!(
            "Created {name}. Next: create the `{crate_name}` and `{crate_name}_test` databases \
             (or edit DATABASE_URL and TEST_DATABASE_URL in .env), then\n\n    cd {name}\n    rnx serve\n"
        ),
    }
    if starter {
        println!(
            "Then sign up at /register and make yourself an admin:\n\n    \
             rnx users:admin you@example.com\n\n(or `rnx db:seed` for admin@example.com, password123)\n"
        );
    }
    Ok(())
}

/// `--tailwind`: the app's styles move into Tailwind's input, the layout
/// links the built file, and the CSS is built once if the CLI can be had.
fn use_tailwind(root: &Path) -> Result<()> {
    use_tailwind_with(root, |root| crate::tailwind::build(root, false))
}

/// `use_tailwind` with the CSS built by `build` (tests pass one that needs
/// no download).
fn use_tailwind_with(root: &Path, build: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
    let own = fs::read_to_string(root.join("public/app.css"))?;
    fs::remove_file(root.join("public/app.css"))?;
    let input = root.join(crate::tailwind::INPUT);
    fs::create_dir_all(input.parent().expect("the input has a parent"))?;
    // The app's own rules, without the stub's header comment.
    let rules = own
        .split_once("*/")
        .map_or(own.as_str(), |(_, rest)| rest.trim_start());
    fs::write(
        &input,
        format!(
            "{}
{rules}",
            crate::tailwind::INPUT_STUB
        ),
    )?;

    let layout = root.join("resources/views/layouts/app.html");
    let html = fs::read_to_string(&layout)?.replace(
        "<link rel=\"stylesheet\" href=\"{{ asset('app.css') }}\">",
        "{#- Built by Tailwind from resources/css/app.css (`rnx serve`, `rnx build`). -#}\n  \
         <link rel=\"stylesheet\" href=\"{{ asset('css/app.css') }}\">",
    );
    fs::write(&layout, html)?;
    let home = root.join("resources/views/home/index.html");
    let html = fs::read_to_string(&home)?.replace(
        "    <p class=\"rx-subtitle\">{{ t('home.edit') }}</p>",
        "    <p class=\"rx-subtitle\">{{ t('home.edit') }}</p>\n    \
         <p class=\"mt-2 text-sm font-medium text-emerald-700 dark:text-emerald-400\">\
         Tailwind is on: edit resources/css/app.css, or use its classes in any view.</p>",
    );
    fs::write(&home, html)?;

    if let Err(err) = build(root) {
        eprintln!("rnx: Tailwind isn't built yet ({err:#}); `rnx serve` will try again.");
    }
    Ok(())
}

fn validate_name(name: &str) -> Result<()> {
    let valid = name.starts_with(|c: char| c.is_ascii_lowercase())
        && name
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
    if !valid {
        bail!(
            "`{name}` is not a valid name: use lowercase letters, digits, `-` and `_`, starting with a letter"
        );
    }
    let crate_name = name.replace('-', "_");
    if crate::generate::is_reserved(&crate_name) {
        bail!(
            "`{name}` can't be an app's name: `{crate_name}` is a Rust keyword or a crate the app uses"
        );
    }
    Ok(())
}

/// `coffee-shop` -> `Coffee Shop`
fn title(name: &str) -> String {
    name.split(['-', '_'])
        .filter(|word| !word.is_empty())
        .map(|word| {
            let mut chars = word.chars();
            chars
                .next()
                .map(|first| first.to_ascii_uppercase().to_string() + chars.as_str())
                .unwrap_or_default()
        })
        .collect::<Vec<_>>()
        .join(" ")
}

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

    #[test]
    fn validates_names() {
        assert!(validate_name("shop").is_ok());
        assert!(validate_name("coffee-shop_2").is_ok());
        assert!(validate_name("Shop").is_err());
        assert!(validate_name("2shop").is_err());
        assert!(validate_name("../shop").is_err());
        for reserved in ["renox", "fn", "self", "type"] {
            assert!(validate_name(reserved).is_err(), "{reserved}");
        }
    }

    #[test]
    fn pins_the_git_dependency() {
        assert_eq!(registry_dependency("1.2.3"), "renox = { version = \"1.2\"");
        assert_eq!(
            registry_dependency("1.0.0-rc.1"),
            "renox = { version = \"1.0.0-rc.1\""
        );
        let rev = "0123456789abcdef0123456789abcdef01234567";
        assert!(git_dependency(Some(rev)).ends_with(&format!("rev = \"{rev}\"")));
        assert!(git_dependency(None).ends_with("branch = \"main\""));
        // AGENTS.md links the docs of that same commit.
        assert_eq!(
            docs_url(Some(rev)),
            format!("https://github.com/arif-rachim/renox/blob/{rev}")
        );
        assert!(docs_url(None).ends_with("/blob/main"));
    }

    #[test]
    fn agents_md_says_where_the_docs_are_offline() {
        // crates.io: only the source is downloaded, so the exact clone is named (#221).
        let registry = registry_offline("1.2.3");
        assert!(
            registry.contains(
                "`git clone --depth 1 --branch v1.2.3 https://github.com/arif-rachim/renox`"
            ),
            "{registry}"
        );
        assert!(registry.contains("renox-core-1.2.3/"));
        // Git: the checkout of that commit has everything.
        let git = git_offline(Some("0123456789abcdef"));
        assert!(git.contains("checkouts/renox-*/0123456/"), "{git}");
        assert!(!git.contains("git clone"));
        assert!(git_offline(None).contains("checkouts/renox-*/*/"));
        // A local checkout.
        let path = path_offline("/src/renox");
        assert!(
            path.contains("`/src/renox`") && !path.contains("git clone"),
            "{path}"
        );
    }

    const SQLITE: Options = Options {
        database: Database::Sqlite,
        tailwind: false,
        starter: false,
        notifications: false,
    };

    /// A written file with `\n` line ends (Windows checkouts give the stubs `\r\n`).
    fn read_lf(path: std::path::PathBuf) -> String {
        fs::read_to_string(path).unwrap().replace("\r\n", "\n")
    }

    /// `rnx new --tailwind`'s changes to a new app, with a build that needs no
    /// download: one that works and one that fails (the app is still made,
    /// `rnx serve` builds the CSS later).
    #[test]
    fn tailwind_moves_the_apps_css_and_links_the_built_file() {
        let checkout = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        for works in [true, false] {
            let dir = tempfile::tempdir().unwrap();
            run_in(dir.path(), "inked", Some(&checkout), SQLITE).unwrap();
            let root = dir.path().join("inked");
            let own = read_lf(root.join("public/app.css"));
            let built = std::cell::Cell::new(false);
            use_tailwind_with(&root, |at| {
                built.set(at == root.as_path());
                if works {
                    Ok(())
                } else {
                    Err(anyhow::anyhow!("no Tailwind here"))
                }
            })
            .unwrap();
            assert!(built.get());
            assert!(!root.join("public/app.css").exists());
            let input = read_lf(root.join(crate::tailwind::INPUT));
            assert!(input.starts_with(crate::tailwind::INPUT_STUB), "{input}");
            let rules = own
                .split_once("*/")
                .map_or(own.as_str(), |(_, r)| r.trim_start());
            assert!(input.ends_with(rules), "the app's own rules kept:\n{input}");
            let layout = read_lf(root.join("resources/views/layouts/app.html"));
            assert!(layout.contains("{{ asset('css/app.css') }}"), "{layout}");
            assert!(!layout.contains("{{ asset('app.css') }}"), "{layout}");
            let home = read_lf(root.join("resources/views/home/index.html"));
            assert!(home.contains("Tailwind is on"), "{home}");
        }
    }

    #[test]
    fn makes_an_app_with_every_placeholder_filled() {
        let dir = tempfile::tempdir().unwrap();
        let checkout = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        run_in(dir.path(), "coffee-shop", Some(&checkout), SQLITE).unwrap();
        let root = dir.path().join("coffee-shop");
        for (file, _) in files(false) {
            let text = fs::read_to_string(root.join(file)).unwrap();
            // `{{name}}`-style placeholders (templates' `{{ x }}` has spaces).
            let left = text.split("{{").skip(1).any(|rest| {
                rest.split_once("}}").is_some_and(|(inner, _)| {
                    !inner.is_empty() && inner.chars().all(|c| c.is_ascii_lowercase() || c == '_')
                })
            });
            assert!(!left, "{file} still has a placeholder");
        }
        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
        assert!(cargo.contains("name = \"coffee-shop\""), "{cargo}");
        assert!(cargo.contains("renox = { path = "), "{cargo}");
        // The real .env has a key; the example doesn't.
        let env = read_lf(root.join(".env"));
        assert!(env.contains("APP_KEY=base64:"), "{env}");
        let example = read_lf(root.join(".env.example"));
        assert!(example.contains("APP_KEY=\n"), "{example}");
        assert!(env.contains("DATABASE_URL=sqlite://storage/app.db"));
        // AGENTS.md names the crate in its test example.
        let agents = fs::read_to_string(root.join("AGENTS.md")).unwrap();
        assert!(agents.contains("coffee_shop::app()"));
        // Not twice, and not over a bad name or a checkout that isn't Renox.
        assert!(run_in(dir.path(), "coffee-shop", None, SQLITE).is_err());
        assert!(run_in(dir.path(), "Shop", None, SQLITE).is_err());
        assert!(run_in(dir.path(), "other", Some(dir.path()), SQLITE).is_err());
    }

    #[test]
    fn postgres_apps_point_at_their_databases() {
        let dir = tempfile::tempdir().unwrap();
        run_in(
            dir.path(),
            "kasir",
            None,
            Options {
                database: Database::Postgres,
                ..SQLITE
            },
        )
        .unwrap();
        let root = dir.path().join("kasir");
        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
        assert!(cargo.contains("features = [\"postgres\"]"), "{cargo}");
        let env = read_lf(root.join(".env"));
        assert!(env.contains("DATABASE_URL=postgres://postgres:postgres@localhost:5432/kasir\n"));
        assert!(env.contains(
            "\nTEST_DATABASE_URL=postgres://postgres:postgres@localhost:5432/kasir_test"
        ));
    }

    #[test]
    fn the_starter_kit_writes_over_the_stubs() {
        let dir = tempfile::tempdir().unwrap();
        let starter = Options {
            starter: true,
            ..SQLITE
        };
        run_in(dir.path(), "desk", None, starter).unwrap();
        let root = dir.path().join("desk");
        // Every stub once, the kit's version where it has one, and its own files.
        let files = files(true);
        assert_eq!(files.len(), STUBS.len() + 8);
        for (file, _) in &files {
            assert!(root.join(file).is_file(), "{file}");
        }
        for (file, text) in STARTER {
            let written = read_lf(root.join(file));
            let expected = text
                .replace("\r\n", "\n")
                .replace("{{crate_name}}", "desk")
                .replace("{{title}}", "Desk");
            assert_eq!(written, expected, "{file}");
        }
        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
        assert!(lib.contains(".module(Permissions)"), "{lib}");
        assert!(root.join("src/app/users/mod.rs").is_file());
        let tests = fs::read_to_string(root.join("tests/home.rs")).unwrap();
        assert!(tests.contains("use desk::roles"), "{tests}");
    }

    #[test]
    fn notifications_edit_stubs_checked_out_with_crlf() {
        // Git on Windows checks the stubs out with CRLF endings (#151's
        // edits failed there).
        let lib = "fn app() {\r\n        .module(renox::auth::Auth::new().account()) // login, register, /account\r\n}\r\n";
        let edited = with_notifications("src/lib.rs", lib);
        assert!(
            edited.contains(".module(renox::auth::Auth::new().account().notifications())\n"),
            "{edited}"
        );
    }

    #[test]
    fn notifications_put_the_bell_in_the_plain_app() {
        let dir = tempfile::tempdir().unwrap();
        let bell = Options {
            notifications: true,
            ..SQLITE
        };
        run_in(dir.path(), "relay", None, bell).unwrap();
        let root = dir.path().join("relay");
        let lib = read_lf(root.join("src/lib.rs"));
        assert!(
            lib.contains(".module(renox::auth::Auth::new().account().notifications())\n"),
            "{lib}"
        );
        let layout = read_lf(root.join("resources/views/layouts/app.html"));
        assert!(
            layout.contains("link_button, notification_bell %}")
                && layout.contains("{{ notification_bell(unread_notifications) }}"),
            "{layout}"
        );
        let tests = read_lf(root.join("tests/home.rs"));
        assert!(
            tests.contains("relay::app()") && tests.contains("fn the_bell_shows_notifications"),
            "{tests}"
        );
        // Without the option, none of it; the starter kit has its own bell.
        run_in(dir.path(), "plain", None, SQLITE).unwrap();
        let layout = read_lf(dir.path().join("plain/resources/views/layouts/app.html"));
        assert!(!layout.contains("notification_bell"));
        let kit = Options {
            starter: true,
            ..bell
        };
        run_in(dir.path(), "kit", None, kit).unwrap();
        let layout = read_lf(dir.path().join("kit/resources/views/layouts/app.html"));
        assert_eq!(layout.matches("{{ notification_bell(").count(), 1);
    }

    /// The `.rs` files under `dir`.
    fn rust_files(dir: &Path) -> Vec<std::path::PathBuf> {
        let mut files = Vec::new();
        for entry in fs::read_dir(dir).unwrap().flatten() {
            let path = entry.path();
            if path.is_dir() {
                files.extend(rust_files(&path));
            } else if path.extension().is_some_and(|ext| ext == "rs") {
                files.push(path);
            }
        }
        files
    }

    /// A new app passes `cargo fmt --check` as it is, whatever its name: rustfmt
    /// sorts `use` lines, so a stub's order must not depend on where the name
    /// sorts next to `renox` (#124: `renoxium` failed, `desk` passed).
    #[test]
    fn new_apps_are_formatted_whatever_their_name() {
        if std::process::Command::new("rustfmt")
            .arg("--version")
            .output()
            .is_err()
        {
            eprintln!("rustfmt isn't installed; skipped");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        for (name, starter, notifications) in [
            ("aardvark", false, false),
            ("aardvark-kit", true, false),
            ("aardvark-bell", false, true),
            ("zebra", false, false),
            ("zebra-kit", true, false),
            ("zebra-bell", false, true),
            ("renoxium", true, false),
        ] {
            let options = Options {
                starter,
                notifications,
                ..SQLITE
            };
            run_in(dir.path(), name, None, options).unwrap();
            let files = rust_files(&dir.path().join(name));
            let output = std::process::Command::new("rustfmt")
                .args(["--check", "--edition", "2024"])
                .args(&files)
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "{name}: rustfmt would change the new app:\n{}",
                String::from_utf8_lossy(&output.stdout)
            );
        }
    }

    #[test]
    fn titles_names() {
        assert_eq!(title("coffee-shop_downtown"), "Coffee Shop Downtown");
    }
}