rustio-admin-cli 0.19.0

Command-line tools for rustio-admin: project scaffolding, migrations, user management.
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
//! `rustio startproject <name>` — generate a fresh project skeleton
//! at `./<name>/`.
//!
//! Templates are baked into the binary via `include_str!` so the CLI
//! stays single-binary. Each template carries a `{{name}}` placeholder
//! that we substitute for the project name; everything else is
//! verbatim.

use std::fs;
use std::path::Path;

/// `(relative_target_path, template_body)` pairs. `target_path` is
/// relative to the new project's root and creates parent directories
/// on demand.
const PROJECT_TEMPLATES: &[(&str, &str)] = &[
    (
        "Cargo.toml",
        include_str!("../templates/project/Cargo.toml.tmpl"),
    ),
    (
        ".env.example",
        include_str!("../templates/project/.env.example"),
    ),
    (
        ".gitignore",
        include_str!("../templates/project/.gitignore"),
    ),
    (
        "README.md",
        include_str!("../templates/project/README.md.tmpl"),
    ),
    (
        "src/main.rs",
        include_str!("../templates/project/src/main.rs.tmpl"),
    ),
    (
        "src/post.rs",
        include_str!("../templates/project/src/post.rs.tmpl"),
    ),
    (
        "migrations/0001_create_posts.sql",
        include_str!("../templates/project/migrations/0001_create_posts.sql"),
    ),
];

/// `blog` preset — layered on top of `PROJECT_TEMPLATES`. The
/// `src/main.rs` and (later) any other shared file is replaced
/// wholesale by writing the preset version *after* the minimal
/// pass (`fs::write` overwrites unconditionally), so the ordering
/// `PROJECT_TEMPLATES` → `BLOG_OVERRIDES` matters: keep
/// preset-owned filenames in the overrides slice and any new-only
/// files separate from them. New-only files (`src/comment.rs`,
/// `migrations/0002_create_comments.sql`) are listed in
/// `BLOG_EXTRAS` to keep the rebuilt mental model from the
/// minimal scaffold honest.
const BLOG_OVERRIDES: &[(&str, &str)] = &[(
    "src/main.rs",
    include_str!("../templates/project_blog/src/main.rs.tmpl"),
)];

const BLOG_EXTRAS: &[(&str, &str)] = &[
    (
        "src/comment.rs",
        include_str!("../templates/project_blog/src/comment.rs.tmpl"),
    ),
    (
        "migrations/0002_create_comments.sql",
        include_str!("../templates/project_blog/migrations/0002_create_comments.sql"),
    ),
];

/// Valid preset names, surfaced verbatim in the error path so
/// `--preset foo` reports the closed list of choices.
const VALID_PRESETS: &[&str] = &["minimal", "blog"];

pub fn project(name: &str, preset: &str) -> Result<(), String> {
    project_in(Path::new("."), name, preset)
}

/// Workdir-parameterised variant — `project()` calls this with
/// `Path::new(".")`. Pulled out so unit tests can scaffold under
/// a tempdir without changing the process working directory.
fn project_in(parent: &Path, name: &str, preset: &str) -> Result<(), String> {
    validate_name(name)?;
    if !VALID_PRESETS.contains(&preset) {
        return Err(format!(
            "unknown preset `{preset}`. Valid: {}",
            VALID_PRESETS.join(", ")
        ));
    }

    let dir = parent.join(name);
    let dir = dir.as_path();
    if dir.exists() {
        return Err(format!(
            "`{name}` already exists in the current directory. Pick a fresh name or remove it first."
        ));
    }

    let mut written = 0usize;
    for (rel, body) in PROJECT_TEMPLATES {
        let target = dir.join(rel);
        if let Some(parent) = target.parent() {
            fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
        }
        let body = body.replace("{{name}}", name);
        fs::write(&target, body).map_err(|e| format!("write {}: {e}", target.display()))?;
        written += 1;
    }

    if preset == "blog" {
        for (rel, body) in BLOG_OVERRIDES.iter().chain(BLOG_EXTRAS.iter()) {
            let target = dir.join(rel);
            if let Some(parent) = target.parent() {
                fs::create_dir_all(parent)
                    .map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
            }
            let body = body.replace("{{name}}", name);
            fs::write(&target, body).map_err(|e| format!("write {}: {e}", target.display()))?;
            // Overrides reuse a slot the minimal scaffold already
            // wrote — don't double-count those. Extras are net-new
            // files; bump the counter for them.
            if BLOG_EXTRAS.iter().any(|(p, _)| *p == *rel) {
                written += 1;
            }
        }
    }

    println!("Created `{name}/` ({preset} preset) with {written} files.");
    println!();
    println!("Next steps:");
    println!("  cd {name}");
    println!("  cp .env.example .env       # safe local defaults; edit before production");
    println!(
        "  rustio migrate apply       # creates the posts table{}",
        if preset == "blog" {
            " + comments table"
        } else {
            ""
        }
    );
    println!("  rustio user create --email admin@{name}.local --role administrator");
    println!("  cargo run                  # boots http://127.0.0.1:8000/admin");
    Ok(())
}

/// A project name must be a valid Rust crate identifier: ASCII
/// letters / digits / `-` / `_`, not starting with a digit, not
/// empty. The Cargo.toml template uses the name verbatim, so any
/// character cargo would reject here would just shift the failure
/// downstream.
fn validate_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("project name is required".into());
    }
    if name.starts_with(|c: char| c.is_ascii_digit()) {
        return Err("project name may not start with a digit".into());
    }
    let valid = name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if !valid {
        return Err("project name may only contain ASCII letters, digits, '-', and '_'".into());
    }
    Ok(())
}

// ---- startapp -----------------------------------------------------------

const APP_MODEL_TEMPLATE: &str = include_str!("../templates/app/model.rs.tmpl");
const APP_MIGRATION_TEMPLATE: &str = include_str!("../templates/app/migration.sql.tmpl");

pub fn app(name: &str) -> Result<(), String> {
    validate_app_name(name)?;
    ensure_in_project_root()?;

    let singular = camel_case(name);
    let table = format!("{name}s");

    let model_path = Path::new("src").join(format!("{name}.rs"));
    if model_path.exists() {
        return Err(format!(
            "{} already exists; pick a different name or remove the file first.",
            model_path.display()
        ));
    }

    let next_version = next_migration_version()?;
    let migration_path =
        Path::new("migrations").join(format!("{next_version:04}_create_{table}.sql"));
    fs::create_dir_all("migrations").map_err(|e| format!("mkdir migrations: {e}"))?;

    let model_body = APP_MODEL_TEMPLATE
        .replace("{{Singular}}", &singular)
        .replace("{{name}}", name)
        .replace("{{table}}", &table);
    let migration_body = APP_MIGRATION_TEMPLATE
        .replace("{{name}}", name)
        .replace("{{table}}", &table);

    fs::write(&model_path, model_body)
        .map_err(|e| format!("write {}: {e}", model_path.display()))?;
    fs::write(&migration_path, migration_body)
        .map_err(|e| format!("write {}: {e}", migration_path.display()))?;

    println!("Created {}", model_path.display());
    println!("Created {}", migration_path.display());
    println!();
    println!("Next steps:");
    println!("  1. Edit `src/main.rs` and add the lines:");
    println!();
    println!("       mod {name};");
    println!("       use {name}::{singular};");
    println!();
    println!("     Then chain it onto the Admin builder:");
    println!();
    println!("       Admin::new()");
    println!("           // … other models …");
    println!("           .model::<{singular}>()");
    println!();
    println!("  2. Apply the migration:");
    println!();
    println!("       rustio migrate apply");
    println!();
    println!("  3. Reboot the server. The `{singular}` admin pages land at /admin/{table}.");
    Ok(())
}

/// App names follow Rust module rules: ASCII lowercase letters /
/// digits / `_`, not starting with a digit. We deliberately reject
/// `-` here because it can't appear in a Rust module path without
/// `r#`-escapes. Stricter than `validate_name` on purpose.
fn validate_app_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("app name is required".into());
    }
    if name.starts_with(|c: char| c.is_ascii_digit()) {
        return Err("app name may not start with a digit".into());
    }
    let valid = name
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
    if !valid {
        return Err(
            "app name may only contain lowercase ASCII letters, digits, and '_' \
             (e.g. `post`, `course`, `book_review`)"
                .into(),
        );
    }
    Ok(())
}

/// Refuse to scaffold an app outside a project. We recognise a
/// project root by the combo of `Cargo.toml` and `src/main.rs`,
/// which `rustio startproject` always lays down — and which
/// `cargo new --bin` produces too.
fn ensure_in_project_root() -> Result<(), String> {
    if !Path::new("Cargo.toml").exists() {
        return Err(
            "no Cargo.toml in the current directory. Run `rustio startapp` from the \
             project root, or scaffold a fresh project with `rustio startproject <name>` \
             first."
                .into(),
        );
    }
    if !Path::new("src").join("main.rs").exists() {
        return Err(
            "no src/main.rs in the current directory. The CLI scaffolds models for \
             binary projects."
                .into(),
        );
    }
    Ok(())
}

/// snake_case → CamelCase. `book_review` → `BookReview`. Single-word
/// inputs hit the Title Case path, which is the same shape.
fn camel_case(snake: &str) -> String {
    let mut out = String::with_capacity(snake.len());
    let mut next_upper = true;
    for c in snake.chars() {
        if c == '_' {
            next_upper = true;
        } else if next_upper {
            out.extend(c.to_uppercase());
            next_upper = false;
        } else {
            out.push(c);
        }
    }
    out
}

/// Walk `migrations/` and return the next available `NNNN` prefix.
/// Picks `1` for an empty / missing directory; otherwise `max + 1`
/// across every parseable filename.
fn next_migration_version() -> Result<i64, String> {
    let dir = Path::new("migrations");
    if !dir.exists() {
        return Ok(1);
    }
    let mut highest: i64 = 0;
    for entry in fs::read_dir(dir).map_err(|e| format!("read_dir migrations: {e}"))? {
        let entry = entry.map_err(|e| format!("dir entry: {e}"))?;
        let path = entry.path();
        if path.extension().and_then(|s| s.to_str()) != Some("sql") {
            continue;
        }
        let stem = match path.file_stem().and_then(|s| s.to_str()) {
            Some(s) => s,
            None => continue,
        };
        let prefix = stem.split_once('_').map(|(p, _)| p).unwrap_or(stem);
        if let Ok(n) = prefix.parse::<i64>() {
            if n > highest {
                highest = n;
            }
        }
    }
    Ok(highest + 1)
}

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

    #[test]
    fn valid_names_accepted() {
        for name in &["my-app", "my_app", "MyApp", "app1", "a-b_c-1"] {
            assert!(validate_name(name).is_ok(), "should accept {name}");
        }
    }

    #[test]
    fn invalid_names_rejected() {
        for name in &["", "1app", "my app", "my/app", "my.app", "my\u{1F600}app"] {
            assert!(validate_name(name).is_err(), "should reject {name:?}");
        }
    }

    // `const_is_empty` correctly notes the standalone-const checks
    // below are compile-time constants — but that's the point.
    // Catches a regression where a templates file gets emptied or
    // include_str! points at the wrong path.
    #[allow(clippy::const_is_empty)]
    #[test]
    fn every_template_carries_at_least_one_placeholder_or_fixed_content() {
        // Sanity check that the static slice is wired correctly.
        // Empty templates are also a regression — `include_str!` would
        // happily load a zero-byte file but the scaffold would write
        // empty files into the new project.
        for (rel, body) in PROJECT_TEMPLATES {
            assert!(!body.is_empty(), "template {rel} is empty");
        }
        assert!(
            !APP_MODEL_TEMPLATE.is_empty(),
            "app model template is empty"
        );
        assert!(
            !APP_MIGRATION_TEMPLATE.is_empty(),
            "app migration template is empty"
        );
    }

    #[test]
    fn camel_case_handles_single_word_and_snake() {
        assert_eq!(camel_case("post"), "Post");
        assert_eq!(camel_case("book_review"), "BookReview");
        assert_eq!(camel_case("a_b_c"), "ABC");
        assert_eq!(camel_case(""), "");
    }

    #[test]
    fn validate_app_name_accepts_typical_names() {
        for name in &["post", "course", "book_review", "user2", "v1"] {
            assert!(validate_app_name(name).is_ok(), "should accept {name}");
        }
    }

    #[test]
    fn validate_app_name_rejects_capitals_and_dashes() {
        for name in &["Post", "BOOK", "book-review", "1book", "", "book.review"] {
            assert!(validate_app_name(name).is_err(), "should reject {name:?}");
        }
    }

    // ---- project presets ----

    #[allow(clippy::const_is_empty)]
    #[test]
    fn blog_preset_templates_are_non_empty() {
        for (rel, body) in BLOG_OVERRIDES.iter().chain(BLOG_EXTRAS.iter()) {
            assert!(!body.is_empty(), "blog template {rel} is empty");
        }
    }

    #[test]
    fn project_rejects_unknown_preset_with_valid_list_in_message() {
        let dir = unique_tempdir();
        let err = project_in(&dir, "proj", "definitely-not-a-preset").expect_err("must error");
        assert!(err.contains("unknown preset"), "got: {err}");
        assert!(err.contains("minimal"), "must list minimal: {err}");
        assert!(err.contains("blog"), "must list blog: {err}");
    }

    #[test]
    fn project_minimal_writes_post_but_not_comment_or_blog_main() {
        let dir = unique_tempdir();
        project_in(&dir, "proj", "minimal").expect("minimal should scaffold");
        let root = dir.join("proj");
        assert!(root.join("src/post.rs").exists(), "post.rs missing");
        assert!(!root.join("src/comment.rs").exists(), "comment.rs leaked");
        assert!(
            !root.join("migrations/0002_create_comments.sql").exists(),
            "0002 migration leaked"
        );
        // main.rs ships the single-model registration.
        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
        assert!(main.contains(".model::<Post>()"), "Post must be registered");
        assert!(
            !main.contains("Comment"),
            "minimal main.rs must not mention Comment"
        );
    }

    #[test]
    fn project_blog_layers_comment_model_and_two_model_main_over_minimal() {
        let dir = unique_tempdir();
        project_in(&dir, "blog", "blog").expect("blog should scaffold");
        let root = dir.join("blog");
        assert!(root.join("src/post.rs").exists(), "post.rs missing");
        assert!(root.join("src/comment.rs").exists(), "comment.rs missing");
        assert!(
            root.join("migrations/0001_create_posts.sql").exists(),
            "0001 migration missing"
        );
        assert!(
            root.join("migrations/0002_create_comments.sql").exists(),
            "0002 migration missing"
        );
        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
        assert!(main.contains(".model::<Post>()"), "Post must be registered");
        assert!(
            main.contains(".model::<Comment>()"),
            "Comment must be registered"
        );
    }

    /// Stdlib-only tempdir for scaffold tests — no `tempfile` dep
    /// just for the scaffold suite.
    fn unique_tempdir() -> std::path::PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let pid = std::process::id();
        let dir = std::env::temp_dir().join(format!("rustio-scaffold-{pid}-{n}"));
        fs::create_dir_all(&dir).unwrap();
        dir
    }
}