chyabrung-cli 0.2.3

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
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
//! `chy make:resource Comment`: model + migration + request + controller +
//! route + test, all in one command (like `nest g resource`).

use crate::util::{ok, package_name, pascal, plural, snake, write_new, CliResult};
use std::path::{Path, PathBuf};

/// One column, from `--fields "title:string,body:text,views:int,bio:text?"`.
#[derive(Debug, Clone, PartialEq)]
pub struct FieldSpec {
    pub name: String,
    pub kind: Kind,
    pub optional: bool,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Kind {
    String,
    Text,
    Int,
    Float,
    Bool,
}

impl Kind {
    fn rust(self) -> &'static str {
        match self {
            Kind::String | Kind::Text => "String",
            Kind::Int => "i64",
            Kind::Float => "f64",
            Kind::Bool => "bool",
        }
    }
    /// A sample JSON value for the generated test (`n` varies it).
    fn sample(self, field: &str, n: u32) -> String {
        match self {
            Kind::String | Kind::Text => format!("\"{} {n}\"", field.replace('_', " ")),
            Kind::Int => format!("{n}"),
            Kind::Float => format!("{n}.5"),
            Kind::Bool => (n % 2 == 1).to_string(),
        }
    }
}

/// Parse `--fields`. Default: one `name:string` column.
pub fn parse_fields(spec: Option<&str>) -> CliResult<Vec<FieldSpec>> {
    let Some(spec) = spec.map(str::trim).filter(|s| !s.is_empty()) else {
        return Ok(vec![FieldSpec { name: "name".into(), kind: Kind::String, optional: false }]);
    };
    let mut out: Vec<FieldSpec> = Vec::new();
    for part in spec.split(',').map(str::trim).filter(|p| !p.is_empty()) {
        let (name, ty) = part.split_once(':').unwrap_or((part, "string"));
        let name = snake(name.trim());
        let ty = ty.trim().to_ascii_lowercase();
        let (ty, optional) = match ty.strip_suffix('?') {
            Some(t) => (t.to_string(), true),
            None => (ty, false),
        };
        let kind = match ty.as_str() {
            "string" | "str" | "varchar" => Kind::String,
            "text" => Kind::Text,
            "int" | "integer" | "i64" | "bigint" => Kind::Int,
            "float" | "double" | "f64" | "decimal" | "number" => Kind::Float,
            "bool" | "boolean" => Kind::Bool,
            other => {
                return Err(format!("unknown field type `{other}` for `{name}`; use string, text, int, float or bool (add `?` for optional)"))
            }
        };
        if name.is_empty() || !name.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) {
            return Err(format!("`{part}`: field names must start with a letter"));
        }
        if ["id", "created_at", "updated_at"].contains(&name.as_str()) {
            return Err(format!("`{name}` is added automatically; leave it out of --fields"));
        }
        if out.iter().any(|f| f.name == name) {
            return Err(format!("field `{name}` is listed twice"));
        }
        out.push(FieldSpec { name, kind, optional });
    }
    if out.is_empty() {
        return Err("--fields is empty".into());
    }
    Ok(out)
}

/// Names derived from the resource name.
pub struct Names {
    /// `Comment`
    pub ty: String,
    /// `comment`
    pub file: String,
    /// `comments`
    pub table: String,
}

impl Names {
    pub fn new(name: &str) -> Self {
        let base = snake(name);
        let base = base.trim_end_matches("_controller").to_string();
        Self { ty: pascal(&base), table: plural(&base), file: base }
    }
}

pub fn model_source(n: &Names, fields: &[FieldSpec]) -> String {
    let cols: String = fields.iter().map(|f| format!("    pub {}: {},\n", f.name, rust_ty(f))).collect();
    format!(
        r#"use chyabrung::prelude::*;

/// A row of the `{table}` table (created by the `..._create_{table}_table` migration).
#[derive(Debug, Clone, Serialize, Deserialize, Model)]
#[model(timestamps)]
pub struct {ty} {{
    pub id: i64,
{cols}    pub created_at: Option<String>,
    pub updated_at: Option<String>,
}}
"#,
        table = n.table,
        ty = n.ty,
    )
}

/// The migration that creates the resource's table.
pub fn migration_rs(n: &Names, fields: &[FieldSpec]) -> String {
    let cols: String = fields
        .iter()
        .map(|f| {
            let mut c = match f.kind {
                Kind::String => format!("table.string(\"{}\")", f.name),
                Kind::Text => format!("table.text(\"{}\")", f.name),
                Kind::Int => format!("table.big_integer(\"{}\")", f.name),
                Kind::Float => format!("table.float(\"{}\")", f.name),
                Kind::Bool => format!("table.boolean(\"{}\")", f.name),
            };
            if f.optional {
                c.push_str(".nullable()");
            } else if f.kind == Kind::Bool {
                c.push_str(".default(false)");
            }
            if f.kind == Kind::Int && f.name.ends_with("_id") {
                c.push_str(".index()");
            }
            format!("        {c};\n")
        })
        .collect();
    format!(
        r#"use chyabrung::db::Schema;

/// Run the migration: create the `{table}` table.
pub fn up(schema: &mut Schema) {{
    schema.create("{table}", |table| {{
        table.id();
{cols}        table.timestamps();
    }});
}}

/// Reverse the migration.
pub fn down(schema: &mut Schema) {{
    schema.drop_if_exists("{table}");
}}
"#,
        table = n.table
    )
}

/// `migrations!()` reads the folder when the crate compiles: mark the crate
/// root as changed so a newly added migration is included in the next build.
pub fn rebuild_migrations() {
    for f in ["src/lib.rs", "src/main.rs"] {
        if let Ok(s) = std::fs::read(f) {
            let _ = std::fs::write(f, s);
            return;
        }
    }
}

pub fn request_source(n: &Names, fields: &[FieldSpec]) -> String {
    let mut body = String::new();
    for f in fields {
        let rule = match (f.kind, f.optional) {
            (Kind::String, false) => Some("#[validate(required, max = 255)]"),
            (Kind::String, true) => Some("#[validate(max = 255)]"),
            (Kind::Text, false) => Some("#[validate(required)]"),
            (Kind::Bool, false) => Some("#[serde(default)]"),
            _ => None,
        };
        if let Some(r) = rule {
            body.push_str(&format!("    {r}\n"));
        }
        body.push_str(&format!("    pub {}: {},\n", f.name, rust_ty(f)));
    }
    format!(
        r#"use chyabrung::prelude::*;

/// `POST /api/{table}` and `PUT /api/{table}/:id`
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct {ty}Request {{
{body}}}
"#,
        table = n.table,
        ty = n.ty,
    )
}

pub fn controller_source(n: &Names, fields: &[FieldSpec], page_query: bool) -> String {
    let assign: String = fields.iter().map(|f| format!("        item.{0} = input.{0};\n", f.name)).collect();
    let (index_args, page) = if page_query {
        (
            "Valid(Query(q)): Valid<Query<PageQuery>>",
            ".paginate(q.page.unwrap_or(1), q.per_page.unwrap_or(20))",
        )
    } else {
        ("", ".paginate(1, 20)")
    };
    let requests = if page_query { format!("{{PageQuery, {}Request}}", n.ty) } else { format!("{}Request", n.ty) };
    format!(
        r#"//! Create, read, update and delete {table}.
//!
//! Every method with a `#[get]`, `#[post]`, ... attribute is a route under
//! the controller's prefix. The controller is mounted in `src/routes/api.rs`.
//! To require a logged-in user, add an `Auth(user): Auth` argument.

use crate::models::{ty};
use crate::requests::{requests};
use chyabrung::prelude::*;

pub struct {ty}Controller;

#[controller("/{table}")]
impl {ty}Controller {{
    /// List {table}, newest first.
    #[get("/")]
    async fn index({index_args}) -> Result<Json<Page<{ty}>>> {{
        Ok(Json({ty}::query().latest(){page}.await?))
    }}

    /// Create a {file}.
    #[post("/")]
    async fn store(Valid(Json(input)): Valid<Json<{ty}Request>>) -> Result<(StatusCode, Json<{ty}>)> {{
        let item = {ty}::create(&input).await?;
        Ok((StatusCode::CREATED, Json(item)))
    }}

    /// Show one {file} (`404` if it does not exist).
    #[get("/:id", name = "{table}.show")]
    async fn show(Path(id): Path<i64>) -> Result<Json<{ty}>> {{
        Ok(Json({ty}::find(id).await?))
    }}

    /// Update a {file}.
    #[put("/:id")]
    async fn update(Path(id): Path<i64>, Valid(Json(input)): Valid<Json<{ty}Request>>) -> Result<Json<{ty}>> {{
        let mut item = {ty}::find(id).await?;
{assign}        item.save().await?;
        Ok(Json(item.refresh().await?))
    }}

    /// Delete a {file}.
    #[delete("/:id")]
    async fn destroy(Path(id): Path<i64>) -> Result<StatusCode> {{
        {ty}::find(id).await?.delete().await?;
        Ok(StatusCode::NO_CONTENT)
    }}
}}
"#,
        table = n.table,
        ty = n.ty,
        file = n.file.replace('_', " "),
    )
}

pub fn test_source(n: &Names, fields: &[FieldSpec], krate: &str) -> String {
    let obj = |k: u32| -> String {
        let pairs: Vec<String> = fields.iter().map(|f| format!("\"{}\": {}", f.name, f.kind.sample(&f.name, k))).collect();
        format!("json!({{{}}})", pairs.join(", "))
    };
    let first = &fields[0];
    let (created, updated) = (obj(1), obj(2));
    let check_created = format!("assert_json_path(\"{}\", {})", first.name, first.kind.sample(&first.name, 1));
    let check_updated = format!("assert_json_path(\"{}\", {})", first.name, first.kind.sample(&first.name, 2));
    // A complete body with one required text field left empty: parsed fine, then rejected by the rules.
    let invalid = fields
        .iter()
        .find(|f| !f.optional && matches!(f.kind, Kind::String | Kind::Text))
        .map(|bad| {
            let pairs: Vec<String> = fields
                .iter()
                .map(|f| {
                    let v = if f.name == bad.name { "\"\"".to_string() } else { f.kind.sample(&f.name, 1) };
                    format!("\"{}\": {v}", f.name)
                })
                .collect();
            format!(
                "
    c.post(\"/api/{t}\").json(&json!({{{}}})).send().await.assert_invalid(\"{}\");",
                pairs.join(", "),
                bad.name,
                t = n.table
            )
        })
        .unwrap_or_default();
    format!(
        r#"//! Tests for `/api/{table}` (generated by `chy make:resource {ty}`).

use chyabrung::prelude::*;
use chyabrung::storage::Storage;
use chyabrung_testing::{{test_db_with, TestClient}};

async fn client() -> (TestClient, tempfile::TempDir) {{
    let db = test_db_with(&{krate}::migrator().expect("read migrations")).await;
    let jwt = Jwt::new(b"test-secret-test-secret-test-secret".to_vec()).unwrap();
    let dir = tempfile::tempdir().unwrap();
    let storage = Storage::local(dir.path(), "/storage");
    (TestClient::new({krate}::app(db, jwt, Cache::memory(), storage)), dir)
}}

#[tokio::test]
async fn {file}_crud() {{
    let (c, _d) = client().await;
{invalid}
    let item: serde_json::Value = c.post("/api/{table}").json(&{created}).send().await.assert_status(201).json();
    let id = item["id"].as_i64().unwrap();

    c.get("/api/{table}").send().await.assert_ok().assert_json_path("total", 1);
    c.get(&format!("/api/{table}/{{id}}")).send().await.assert_ok().{check_created};
    c.put(&format!("/api/{table}/{{id}}")).json(&{updated}).send().await.assert_ok().{check_updated};
    c.delete(&format!("/api/{table}/{{id}}")).send().await.assert_status(204);
    c.get(&format!("/api/{table}/{{id}}")).send().await.assert_not_found();
}}
"#,
        table = n.table,
        ty = n.ty,
        file = n.file,
    )
}

fn rust_ty(f: &FieldSpec) -> String {
    if f.optional {
        format!("Option<{}>", f.kind.rust())
    } else {
        f.kind.rust().to_string()
    }
}

/// Add `pub mod x;` and (optionally) `pub use x::Item;` to a folder's `mod.rs`.
fn register_module(dir: &Path, module: &str, reexport: Option<&str>) -> CliResult {
    let mod_rs = dir.join("mod.rs");
    let mut content = std::fs::read_to_string(&mod_rs).unwrap_or_default();
    let mod_line = format!("pub mod {module};");
    if !content.lines().any(|l| l.trim() == mod_line) {
        content = insert_after_last(&content, "pub mod ", &mod_line);
    }
    if let Some(item) = reexport {
        let use_line = format!("pub use {module}::{item};");
        if !content.lines().any(|l| l.trim() == use_line) {
            content = insert_after_last(&content, "pub use ", &use_line);
        }
    }
    std::fs::write(&mod_rs, content).map_err(|e| format!("cannot write {}: {e}", mod_rs.display()))
}

/// Insert `line` after the last line starting with `prefix` (or at the end).
fn insert_after_last(content: &str, prefix: &str, line: &str) -> String {
    let mut lines: Vec<String> = content.lines().map(str::to_owned).collect();
    match lines.iter().rposition(|l| l.starts_with(prefix)) {
        Some(i) => lines.insert(i + 1, line.to_string()),
        None => {
            if lines.last().is_some_and(|l| !l.trim().is_empty()) {
                lines.push(String::new());
            }
            lines.push(line.to_string());
        }
    }
    let mut out = lines.join("\n");
    out.push('\n');
    out
}

/// The marker line in `src/routes/api.rs` where new controllers are mounted.
pub const ROUTES_MARKER: &str = "// chy:resources";

/// Mount the controller in `src/routes/api.rs`, at the `// chy:resources` marker.
/// Returns false (and changes nothing) when there is no marker.
pub fn add_route(routes: &str, n: &Names) -> Option<String> {
    let mount = format!(".mount({}Controller)", n.ty);
    if routes.contains(&mount) {
        return Some(routes.to_string());
    }
    let idx = routes.lines().position(|l| l.trim_start().starts_with(ROUTES_MARKER))?;
    let mut lines: Vec<String> = routes.lines().map(str::to_owned).collect();
    let indent: String = lines[idx].chars().take_while(|c| c.is_whitespace()).collect();
    lines.insert(idx, format!("{indent}{mount}"));
    let import = format!("use crate::controllers::{}_controller::{}Controller;", n.file, n.ty);
    if !lines.iter().any(|l| l.trim() == import) {
        let at = lines.iter().rposition(|l| l.starts_with("use ")).map(|i| i + 1).unwrap_or(0);
        lines.insert(at, import);
    }
    let mut out = lines.join("\n");
    out.push('\n');
    Some(out)
}

/// `chy make:resource Comment [--fields "body:text,post_id:int"]`
pub fn run(name: &str, fields: Option<&str>) -> CliResult {
    if !Path::new("Cargo.toml").exists() {
        return Err("no Cargo.toml here: run `chy make:resource` inside a Chyabrung app".into());
    }
    let fields = parse_fields(fields)?;
    let n = Names::new(name);
    if n.ty.is_empty() {
        return Err("give the resource a name, e.g. `chy make:resource Comment`".into());
    }
    let krate = package_name()?.replace('-', "_");
    let controller_file = PathBuf::from(format!("src/controllers/{}_controller.rs", n.file));
    for p in [
        PathBuf::from(format!("src/models/{}.rs", n.file)),
        PathBuf::from(format!("src/requests/{}.rs", n.file)),
        controller_file.clone(),
        PathBuf::from(format!("tests/{}.rs", n.file)),
    ] {
        if p.exists() {
            return Err(format!("{} already exists; nothing was created", p.display()));
        }
    }
    let page_query = std::fs::read_to_string("src/requests/mod.rs").is_ok_and(|s| s.contains("PageQuery"));

    // model + migration
    write_new(&PathBuf::from(format!("src/models/{}.rs", n.file)), &model_source(&n, &fields))?;
    register_module(Path::new("src/models"), &n.file, Some(&n.ty))?;
    let ts = chrono::Utc::now().format("%Y%m%d%H%M%S");
    let base = format!("{ts}_create_{}_table", n.table);
    write_new(&PathBuf::from(format!("migrations/{base}.rs")), &migration_rs(&n, &fields))?;
    rebuild_migrations();

    // request + controller
    write_new(&PathBuf::from(format!("src/requests/{}.rs", n.file)), &request_source(&n, &fields))?;
    register_module(Path::new("src/requests"), &n.file, Some(&format!("{}Request", n.ty)))?;
    write_new(&controller_file, &controller_source(&n, &fields, page_query))?;
    register_module(Path::new("src/controllers"), &format!("{}_controller", n.file), None)?;

    // route
    let routes_path = Path::new("src/routes/api.rs");
    let routes = std::fs::read_to_string(routes_path).unwrap_or_default();
    let mounted = match add_route(&routes, &n) {
        Some(updated) => {
            if updated != routes {
                std::fs::write(routes_path, updated).map_err(|e| e.to_string())?;
                ok(&format!("mounted {}Controller in src/routes/api.rs (/api/{})", n.ty, n.table));
            }
            true
        }
        None => false,
    };

    // test
    write_new(&PathBuf::from(format!("tests/{}.rs", n.file)), &test_source(&n, &fields, &krate))?;

    println!();
    if !mounted {
        println!(
            "  add the routes in src/routes/api.rs, inside the `/api` group:\n      .mount(crate::controllers::{}_controller::{}Controller)\n  (or add a `{ROUTES_MARKER}` line there and `make:resource` will do it for you)",
            n.file, n.ty
        );
    }
    println!("  next: `chy migrate` to create the `{}` table, then `cargo test`", n.table);
    println!("  docs: GET /api/{0}, POST /api/{0}, GET|PUT|DELETE /api/{0}/:id (see /docs)", n.table);
    Ok(())
}

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

    #[test]
    fn parses_fields() {
        let f = parse_fields(Some("title:string, body:text, views:int, bio:text?, published:bool")).unwrap();
        assert_eq!(f.len(), 5);
        assert_eq!(f[2], FieldSpec { name: "views".into(), kind: Kind::Int, optional: false });
        assert!(f[3].optional);
        assert_eq!(parse_fields(None).unwrap()[0].name, "name");
        assert!(parse_fields(Some("x:blob")).is_err());
        assert!(parse_fields(Some("id:int")).is_err());
        assert!(parse_fields(Some("a,a")).is_err());
    }

    #[test]
    fn generates_sources() {
        let n = Names::new("BlogPost");
        assert_eq!((n.ty.as_str(), n.file.as_str(), n.table.as_str()), ("BlogPost", "blog_post", "blog_posts"));
        let f = parse_fields(Some("title,body:text?,draft:bool")).unwrap();
        assert!(model_source(&n, &f).contains("pub body: Option<String>,"));
        let rs = migration_rs(&n, &parse_fields(Some("title,body:text?,draft:bool,user_id:int")).unwrap());
        assert!(rs.contains("schema.create(\"blog_posts\", |table| {"));
        assert!(rs.contains("table.string(\"title\");"));
        assert!(rs.contains("table.text(\"body\").nullable();"));
        assert!(rs.contains("table.boolean(\"draft\").default(false);"));
        assert!(rs.contains("table.big_integer(\"user_id\").index();"));
        assert!(rs.contains("schema.drop_if_exists(\"blog_posts\")"));
        assert!(request_source(&n, &f).contains("#[validate(required, max = 255)]\n    pub title: String,"));
        let c = controller_source(&n, &f, true);
        assert!(c.contains("#[controller(\"/blog_posts\")]"));
        assert!(c.contains("item.draft = input.draft;"));
        assert!(test_source(&n, &f, "app").contains("assert_invalid(\"title\")"));
    }

    #[test]
    fn mounts_at_marker() {
        let n = Names::new("Comment");
        let routes = "use crate::controllers::post_controller::PostController;\nuse chyabrung::prelude::*;\n\nfn r() {\n    x.group(\"/api\", |r| {\n        r.mount(PostController)\n            // chy:resources (keep this line)\n    })\n}\n";
        let out = add_route(routes, &n).unwrap();
        assert!(out.contains("            .mount(CommentController)\n            // chy:resources"));
        assert!(out.contains("use crate::controllers::comment_controller::CommentController;\n"));
        assert_eq!(add_route(&out, &n).unwrap(), out, "running twice changes nothing");
        assert!(add_route("fn r() {}", &n).is_none());
    }
}