chyabrung-cli 0.2.5

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
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
//! `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::*;

#[model]
pub struct {ty} {{
    pub id: i64,
{cols}    pub created_at: Option<Timestamp>,
    pub updated_at: Option<Timestamp>,
}}
"#,
        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;

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

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::*;

#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct {ty}Request {{
{body}}}
"#,
        ty = n.ty,
    )
}

/// `chy make:request Post [--fields "title,body:text"]`: a validated input type in `src/requests/`.
pub fn request(name: &str, fields: Option<&str>) -> CliResult {
    if !Path::new("Cargo.toml").exists() {
        return Err("no Cargo.toml here: run `chy make:request` inside a Chyabrung app".into());
    }
    let fields = parse_fields(fields)?;
    let base = snake(name);
    let n = Names::new(base.trim_end_matches("_request"));
    if n.ty.is_empty() {
        return Err("give the request a name, e.g. `chy make:request Post`".into());
    }
    let path = PathBuf::from(format!("src/requests/{}.rs", n.file));
    if path.exists() {
        return Err(format!("{} already exists; nothing was created", path.display()));
    }
    write_new(&path, &request_source(&n, &fields))?;
    register_module(Path::new("src/requests"), &n.file, Some(&format!("{}Request", n.ty)))?;
    println!();
    println!("  next: add rules to the fields in {}, then take it in a handler:", path.display());
    println!("      async fn store(input: {}Request) -> Result<Created<{}>> {{ ... }}", n.ty, n.ty);
    Ok(())
}

/// The API resource for a model: how it looks as JSON. `columns` are the
/// model's fields between `id` and the timestamps.
pub fn response_source(n: &Names, columns: &[String]) -> String {
    let mut keys = vec!["id".to_string()];
    keys.extend(columns.iter().filter(|c| !matches!(c.as_str(), "id" | "created_at" | "updated_at")).cloned());
    keys.extend(["created_at".to_string(), "updated_at".to_string()]);
    let width = keys.iter().map(|k| k.len()).max().unwrap_or(0);
    let lines: String = keys
        .iter()
        .map(|k| format!("            \"{k}\": {pad}self.{k},\n", pad = " ".repeat(width - k.len())))
        .collect();
    format!(
        r#"use crate::models::{ty};
use chyabrung::prelude::*;

#[resource({ty})]
pub struct {ty}Resource;

impl JsonResource for {ty}Resource {{
    fn to_array(&self) -> JsonValue {{
        json!({{
{lines}        }})
    }}
}}
"#,
        ty = n.ty,
    )
}

/// The `pub` fields of the model in `src/models/<file>.rs`, leaving out
/// relations, `#[not_column]` fields and fields serde never sends.
pub fn model_columns(source: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut skip = false;
    let mut in_struct = false;
    for line in source.lines() {
        let t = line.trim();
        if t.starts_with("pub struct ") && t.ends_with('{') {
            in_struct = true;
            continue;
        }
        if !in_struct {
            continue;
        }
        if t == "}" {
            break;
        }
        if t.starts_with("#[") {
            let relation = ["has_many", "has_one", "belongs_to", "belongs_to_many", "morph_many", "morph_one", "not_column"]
                .iter()
                .any(|k| t.strip_prefix("#[").is_some_and(|r| r.starts_with(k) && r[k.len()..].starts_with([']', '('])));
            if relation || (t.starts_with("#[serde(") && t.contains("skip")) {
                skip = true;
            }
            continue;
        }
        if let Some(rest) = t.strip_prefix("pub ") {
            if let Some((name, _)) = rest.split_once(':') {
                if !skip {
                    out.push(name.trim().to_string());
                }
            }
            skip = false;
        }
    }
    out
}

/// Write `src/responses/<file>_resource.rs` and list it in `src/responses/mod.rs`.
fn write_response(n: &Names, columns: &[String]) -> CliResult {
    write_new(&PathBuf::from(format!("src/responses/{}_resource.rs", n.file)), &response_source(n, columns))?;
    register_module(Path::new("src/responses"), &format!("{}_resource", n.file), Some(&format!("{}Resource", n.ty)))?;
    let declared = ["src/lib.rs", "src/main.rs"]
        .iter()
        .any(|f| std::fs::read_to_string(f).is_ok_and(|s| s.lines().any(|l| l.trim().trim_start_matches("pub ") == "mod responses;")));
    if !declared {
        println!("  add `pub mod responses;` to src/lib.rs");
    }
    Ok(())
}

/// `chy make:response Post`: how the `Post` model looks as JSON, in `src/responses/`.
pub fn response(name: &str) -> CliResult {
    if !Path::new("Cargo.toml").exists() {
        return Err("no Cargo.toml here: run `chy make:response` inside a Chyabrung app".into());
    }
    let base = snake(name);
    let base = base.trim_end_matches("_resource").trim_end_matches("_response");
    let n = Names::new(base);
    if n.ty.is_empty() {
        return Err("give the model a name, e.g. `chy make:response Post`".into());
    }
    let path = PathBuf::from(format!("src/responses/{}_resource.rs", n.file));
    if path.exists() {
        return Err(format!("{} already exists; nothing was created", path.display()));
    }
    let model = format!("src/models/{}.rs", n.file);
    let columns = match std::fs::read_to_string(&model) {
        Ok(src) => model_columns(&src),
        Err(_) => {
            println!("  {model} not found: the resource lists `id` and the timestamps; add the other fields by hand");
            Vec::new()
        }
    };
    write_response(&n, &columns)?;
    println!();
    println!("  next: return it from a controller:");
    println!("      async fn show({}: {}) -> Resource<{}Resource> {{ {}Resource::make({}) }}", n.file, n.ty, n.ty, n.ty, n.file);
    Ok(())
}

pub fn controller_source(n: &Names, fields: &[FieldSpec], page_query: bool) -> String {
    let var = &n.file;
    let assign: String = fields.iter().map(|f| format!("        {var}.{0} = input.{0};\n", f.name)).collect();
    let (index_args, page) = if page_query {
        ("q: 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#"use crate::models::{ty};
use crate::requests::{requests};
use crate::responses::{ty}Resource;
use chyabrung::prelude::*;

pub struct {ty}Controller;

#[controller]
impl {ty}Controller {{
    async fn index({index_args}) -> Result<ResourceCollection<{ty}Resource>> {{
        Ok({ty}Resource::collection({ty}::query().latest(){page}.await?))
    }}

    async fn store(input: {ty}Request) -> Result<Resource<{ty}Resource>> {{
        Ok({ty}Resource::make({ty}::create(&input).await?).created())
    }}

    async fn show({var}: {ty}) -> Resource<{ty}Resource> {{
        {ty}Resource::make({var})
    }}

    async fn update(mut {var}: {ty}, input: {ty}Request) -> Result<Resource<{ty}Resource>> {{
{assign}        {var}.save().await?;
        Ok({ty}Resource::make({var}.refresh().await?))
    }}

    async fn destroy({var}: {ty}) -> Result<NoContent> {{
        {var}.delete().await?;
        Ok(NoContent)
    }}
}}
"#,
        ty = n.ty,
    )
}

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(\"data.{}\", {})", first.name, first.kind.sample(&first.name, 1));
    let check_updated = format!("assert_json_path(\"data.{}\", {})", 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#"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["data"]["id"].as_i64().unwrap();

    c.get("/api/{table}").send().await.assert_ok().assert_json_path("meta.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,
        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`.
pub 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
}

/// Add `route.resource("/comments", CommentController);` to `pub fn routes` in
/// `src/routes/api.rs`: after its last `route.resource(...)` line, or at the
/// end of the function. Returns `None` (and changes nothing) when there is no
/// `pub fn routes`.
pub fn add_route(routes: &str, n: &Names) -> Option<String> {
    let line = format!("route.resource(\"/{}\", {}Controller);", n.table, n.ty);
    if routes.contains(&line) {
        return Some(routes.to_string());
    }
    let mut lines: Vec<String> = routes.lines().map(str::to_owned).collect();
    let start = lines.iter().position(|l| l.trim_start().starts_with("pub fn routes("))?;
    let end = start + lines[start..].iter().position(|l| l.trim_end() == "}")?;
    let at = match lines[start..end].iter().rposition(|l| l.trim_start().starts_with("route.resource(")) {
        Some(i) => start + i + 1,
        None => end,
    };
    lines.insert(at, format!("    {line}"));
    if !lines.iter().any(|l| l.trim() == "use crate::controllers::*;") {
        let import = format!("use crate::controllers::{}Controller;", 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_response(&n, &fields.iter().map(|f| f.name.clone()).collect::<Vec<_>>())?;
    write_new(&controller_file, &controller_source(&n, &fields, page_query))?;
    register_module(Path::new("src/controllers"), &format!("{}_controller", n.file), Some(&format!("{}Controller", n.ty)))?;

    // 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!("added route.resource(\"/{}\", {}Controller) to src/routes/api.rs", n.table, n.ty));
            }
            true
        }
        None => false,
    };

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

    println!();
    if !mounted {
        println!(
            "  add this line to `pub fn routes` in src/routes/api.rs:\n      route.resource(\"/{}\", {}Controller);",
            n.table, 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|PATCH|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]\nimpl BlogPostController"));
        assert!(!c.contains("#[get"), "no route attributes");
        assert!(c.contains("blog_post.draft = input.draft;"));
        assert!(c.contains("async fn show(blog_post: BlogPost) -> Resource<BlogPostResource>"));
        assert!(!c.contains("Valid"), "no old extractor wrappers");
        assert!(test_source(&n, &f, "app").contains("assert_invalid(\"title\")"));
    }

    #[test]
    fn writes_responses_from_model_fields() {
        let model = "use chyabrung::prelude::*;\n\n#[model]\npub struct Post {\n    pub id: i64,\n    pub title: String,\n    #[serde(skip_serializing, default)]\n    pub secret: String,\n    #[belongs_to]\n    pub author: Option<User>,\n    #[has_many(foreign_key = \"post_id\")]\n    pub comments: Vec<Comment>,\n    #[not_column]\n    pub score: Option<i64>,\n    pub created_at: Option<String>,\n}\n";
        assert_eq!(model_columns(model), vec!["id", "title", "created_at"]);
        let src = response_source(&Names::new("BlogPost"), &["title".into(), "draft".into()]);
        assert!(src.contains("#[resource(BlogPost)]\npub struct BlogPostResource;"));
        assert!(src.contains("\"title\":      self.title,"), "{src}");
        assert!(src.contains("\"updated_at\": self.updated_at,"));
        let c = controller_source(&Names::new("BlogPost"), &parse_fields(Some("title")).unwrap(), false);
        assert!(c.contains("BlogPostResource::collection("));
        assert!(c.contains("BlogPostResource::make(BlogPost::create(&input).await?).created()"));
    }

    #[test]
    fn adds_resource_to_routes() {
        let n = Names::new("Comment");
        let routes = "use crate::controllers::*;
use chyabrung::prelude::*;

pub fn routes(route: &mut Route) {
    route.get(\"/me\", me);

    route.resource(\"/posts\", PostController);

    route.get(\"/stats\", stats);
}
";
        let out = add_route(routes, &n).unwrap();
        assert!(out.contains("    route.resource(\"/posts\", PostController);
    route.resource(\"/comments\", CommentController);
"), "{out}");
        assert!(!out.contains("use crate::controllers::CommentController;"), "the glob import covers it");
        assert_eq!(add_route(&out, &n).unwrap(), out, "running twice changes nothing");
        assert!(add_route("fn r() {}", &n).is_none());
        let out = add_route("use chyabrung::prelude::*;

pub fn routes(route: &mut Route) {
}
", &n).unwrap();
        assert!(out.contains("use crate::controllers::CommentController;
"));
        assert!(out.contains("    route.resource(\"/comments\", CommentController);
}"), "{out}");
    }

}