renox-cli 1.0.0-rc.3

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
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"),
    ),
];

/// 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"))
}

/// 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,
}

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,
    } = 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),
                format!("the local Renox checkout this app uses: `{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}"),
                format!(
                    "the crates Cargo downloaded: `~/.cargo/registry/src/*/renox-core-{version}/`"
                ),
            )
        }
        None => (
            git_dependency(rev),
            docs_url(rev),
            match rev {
                Some(rev) => format!(
                    "the checkout Cargo downloaded: `~/.cargo/git/checkouts/renox-*/{}/`",
                    &rev[..7.min(rev.len())]
                ),
                None => "the checkout Cargo downloaded: `~/.cargo/git/checkouts/renox-*/*/`".into(),
            },
        ),
    };
    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 = contents
            .replace("{{name}}", name)
            .replace("{{title}}", &title(name))
            .replace("{{renox_dependency}}", &dependency)
            .replace("{{renox_docs}}", &docs)
            .replace("{{renox_source}}", &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<()> {
    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) = crate::tailwind::build(root, false) {
        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"));
    }

    const SQLITE: Options = Options {
        database: Database::Sqlite,
        tailwind: false,
        starter: 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")
    }

    #[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}");
    }

    /// 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) in [
            ("aardvark", false),
            ("aardvark-kit", true),
            ("zebra", false),
            ("zebra-kit", true),
            ("renoxium", true),
        ] {
            let options = Options { starter, ..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");
    }
}