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
//! `chy make:*` generators.

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

fn add_mod(dir: &Path, module: &str) -> CliResult {
    let mod_rs = dir.join("mod.rs");
    let mut content = std::fs::read_to_string(&mod_rs).unwrap_or_default();
    let line = format!("pub mod {module};");
    if !content.lines().any(|l| l.trim() == line) {
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(&line);
        content.push('\n');
        std::fs::write(&mod_rs, content).map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// Append `line` to `dir/mod.rs` unless it is already there.
fn add_line(dir: &Path, line: &str) -> CliResult {
    let mod_rs = dir.join("mod.rs");
    let mut content = std::fs::read_to_string(&mod_rs).unwrap_or_default();
    if !content.lines().any(|l| l.trim() == line) {
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(line);
        content.push('\n');
        std::fs::write(&mod_rs, content).map_err(|e| e.to_string())?;
    }
    Ok(())
}

/// Remind the user to declare `mod <folder>;` if neither `src/lib.rs` nor `src/main.rs` does.
fn hint_mod_declared(folder: &str) {
    let declared = ["src/lib.rs", "src/main.rs"].iter().any(|f| {
        std::fs::read_to_string(f)
            .map(|s| s.lines().any(|l| l.trim().trim_start_matches("pub ").starts_with(&format!("mod {folder};"))))
            .unwrap_or(false)
    });
    if !declared {
        println!("  add `pub mod {folder};` to src/lib.rs (or `mod {folder};` to src/main.rs)");
    }
}

/// `chy make:model Comment [--fields "body:text,post_id:int"] [--migration]`:
/// the model, and with `--migration` the migration that creates its table.
pub fn model(name: &str, fields: Option<&str>, with_migration: bool) -> CliResult {
    let n = crate::resource::Names::new(name);
    if n.ty.is_empty() {
        return Err("give the model a name, e.g. `chy make:model Comment`".into());
    }
    let fields = match fields {
        Some(spec) => crate::resource::parse_fields(Some(spec))?,
        None => Vec::new(),
    };
    write_new(&PathBuf::from(format!("src/models/{}.rs", n.file)), &crate::resource::model_source(&n, &fields))?;
    crate::resource::register_module(Path::new("src/models"), &n.file, Some(&n.ty))?;
    hint_mod_declared("models");
    if with_migration {
        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")), &crate::resource::migration_rs(&n, &fields))?;
        crate::resource::rebuild_migrations();
    } else if !fields.is_empty() {
        println!("  add `--migration` to also create the `{}` table", n.table);
    }
    Ok(())
}

/// The shared email layout written to `templates/mail/layout.html`.
pub const MAIL_LAYOUT: &str = include_str!("../assets/mail_layout.html");

pub fn mail_source(ty: &str) -> String {
    format!(
        r#"use chyabrung::prelude::*;

#[derive(Serialize)]
pub struct {ty} {{
    pub name: String,
}}

impl Mailable for {ty} {{
    fn subject(&self) -> String {{
        format!("Hello, {{}}!", self.name)
    }}
}}
"#
    )
}

pub fn mail_view() -> &'static str {
    r##"{% extends "layout.html" %}

{% block content %}
<h1 style="margin:0 0 16px;font-size:22px;">Hello, {{ name }}!</h1>
<p style="margin:0 0 16px;">Write your message here.</p>
<p style="margin:0;"><a href="#" style="display:inline-block;background:#18181b;color:#ffffff;padding:10px 18px;border-radius:6px;text-decoration:none;">Open</a></p>
{% endblock %}
"##
}

pub const MAIL_ENV: &str = r#"MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
"#;

/// `pub mod <folder>;` in `src/lib.rs` (or `mod <folder>;` in `src/main.rs`), unless it is there.
pub fn declare_mod(folder: &str) -> CliResult {
    for (file, line) in [("src/lib.rs", format!("pub mod {folder};")), ("src/main.rs", format!("mod {folder};"))] {
        let Ok(src) = std::fs::read_to_string(file) else { continue };
        if src.lines().any(|l| l.trim().trim_start_matches("pub ").starts_with(&format!("mod {folder};"))) {
            return Ok(());
        }
        let mut lines: Vec<String> = src.lines().map(str::to_owned).collect();
        let at = lines.iter().rposition(|l| l.trim_start().starts_with("pub mod ") || l.trim_start().starts_with("mod ")).map(|i| i + 1).unwrap_or(0);
        lines.insert(at, line.clone());
        let mut out = lines.join("\n");
        out.push('\n');
        std::fs::write(file, out).map_err(|e| format!("{file}: {e}"))?;
        crate::util::ok(&format!("added `{line}` to {file}"));
        return Ok(());
    }
    Ok(())
}

/// What sending mail needs, created when missing: `src/mail/`, the email
/// layout in `templates/mail/` and the `MAIL_*` settings in `.env` files.
pub fn setup_mail() -> CliResult {
    let mod_rs = Path::new("src/mail/mod.rs");
    if !mod_rs.exists() {
        write_new(mod_rs, "")?;
    }
    declare_mod("mail")?;
    let layout = Path::new("templates/mail/layout.html");
    if !layout.exists() {
        write_new(layout, MAIL_LAYOUT)?;
    }
    for env in [".env", ".env.example"] {
        let Ok(src) = std::fs::read_to_string(env) else { continue };
        if src.lines().any(|l| l.trim_start().starts_with("MAIL_MAILER")) {
            continue;
        }
        let sep = if src.is_empty() || src.ends_with("\n\n") {
            ""
        } else if src.ends_with('\n') {
            "\n"
        } else {
            "\n\n"
        };
        std::fs::write(env, format!("{src}{sep}{MAIL_ENV}")).map_err(|e| format!("{env}: {e}"))?;
        crate::util::ok(&format!("added the MAIL_* settings to {env}"));
    }
    Ok(())
}

/// `chy make:mail OrderShipped`: the email in `src/mail/` and its design in `templates/mail/`.
pub fn mail(name: &str) -> CliResult {
    let ty = pascal(name);
    let file = snake(name);
    if ty.is_empty() {
        return Err("give the email a name, e.g. `chy make:mail OrderShipped`".into());
    }
    let view = PathBuf::from(format!("templates/mail/{file}.html"));
    if view.exists() {
        return Err(format!("{} already exists; nothing was created", view.display()));
    }
    if !Path::new("Cargo.toml").exists() {
        return Err("no Cargo.toml here: run `chy make:mail` inside a Chyabrung app".into());
    }
    setup_mail()?;
    write_new(&PathBuf::from(format!("src/mail/{file}.rs")), &mail_source(&ty))?;
    crate::resource::register_module(Path::new("src/mail"), &file, Some(&ty))?;
    write_new(&view, mail_view())?;
    let manifest = std::fs::read_to_string("Cargo.toml").unwrap_or_default();
    if !manifest.contains("\"mail\"") && !manifest.contains("\"full\"") {
        println!("  turn mail on with `chy add mail`");
    }
    println!();
    println!("  send it: Mail::to(&user.email).send({ty} {{ name: user.name.clone() }}).await?;");
    println!("  design:  templates/mail/{file}.html (the struct's fields are its {{{{ variables }}}})");
    Ok(())
}

/// `chy make:controller PostController`
pub fn controller(name: &str) -> CliResult {
    let base = snake(name).trim_end_matches("_controller").to_string();
    let file = format!("{base}_controller");
    let ty = format!("{}Controller", pascal(&base));
    let table = plural(&base);
    let src = format!(
        r#"use chyabrung::prelude::*;

pub struct {ty};

#[controller]
impl {ty} {{
    async fn index(db: Db) -> Result<Json<Vec<serde_json::Value>>> {{
        Ok(Json(db.table("{table}").order_by_desc("id").get().await?))
    }}

    async fn store(db: Db, Json(input): Json<serde_json::Value>) -> Result<Created<serde_json::Value>> {{
        let id = db.table("{table}").insert_get_id(&input).await?;
        Ok(Created(db.table("{table}").find(id).await?))
    }}

    async fn show(db: Db, Path(id): Path<i64>) -> Result<Json<serde_json::Value>> {{
        Ok(Json(db.table("{table}").find(id).await?))
    }}

    async fn update(db: Db, Path(id): Path<i64>, Json(input): Json<serde_json::Value>) -> Result<Json<serde_json::Value>> {{
        db.table("{table}").where_("id", id).update(&input).await?;
        Ok(Json(db.table("{table}").find(id).await?))
    }}

    async fn destroy(db: Db, Path(id): Path<i64>) -> Result<NoContent> {{
        if db.table("{table}").where_("id", id).delete().await? == 0 {{
            return Err(Error::not_found("Not found"));
        }}
        Ok(NoContent)
    }}
}}
"#
    );
    write_new(&PathBuf::from(format!("src/controllers/{file}.rs")), &src)?;
    add_mod(Path::new("src/controllers"), &file)?;
    add_line(Path::new("src/controllers"), &format!("pub use {file}::{ty};"))?;
    hint_mod_declared("controllers");
    println!("  next: add `route.resource(\"/{table}\", {ty});` to `routes` in src/routes/api.rs");
    Ok(())
}

/// `chy make:migration create_posts_table` → returns the base name.
pub fn migration(name: &str) -> CliResult<String> {
    let ts = chrono::Utc::now().format("%Y%m%d%H%M%S");
    let base = format!("{ts}_{}", snake(name));
    write_new(&PathBuf::from(format!("migrations/{base}.rs")), &migration_rs(name))?;
    crate::resource::rebuild_migrations();
    Ok(base)
}

/// A schema-builder migration (`up` / `down`) for a migration name:
/// `create_posts_table`, `add_bio_to_users_table`, or anything else.
pub fn migration_rs(name: &str) -> String {
    let n = snake(name);
    let header = "use chyabrung::db::Schema;\n";
    if let Some(table) = n.strip_prefix("create_").and_then(|s| s.strip_suffix("_table")) {
        return format!(
            r#"{header}
pub fn up(schema: &mut Schema) {{
    schema.create("{table}", |table| {{
        table.id();
        table.string("name");
        table.timestamps();
    }});
}}

pub fn down(schema: &mut Schema) {{
    schema.drop_if_exists("{table}");
}}
"#
        );
    }
    if let Some((cols, table)) = n.strip_prefix("add_").and_then(|s| s.strip_suffix("_table")).and_then(|s| s.rsplit_once("_to_")) {
        let col = cols.split("_and_").next().unwrap_or(cols);
        return format!(
            r#"{header}
pub fn up(schema: &mut Schema) {{
    schema.alter("{table}", |table| {{
        table.string("{col}").nullable();
    }});
}}

pub fn down(schema: &mut Schema) {{
    schema.alter("{table}", |table| {{
        table.drop_column("{col}");
    }});
}}
"#
        );
    }
    format!(
        r#"{header}
pub fn up(schema: &mut Schema) {{
    let _ = schema;
}}

pub fn down(schema: &mut Schema) {{
    let _ = schema;
}}
"#
    )
}

/// `chy make:middleware EnsureAdmin`
pub fn middleware(name: &str) -> CliResult {
    let file = snake(name);
    let src = format!(
        r#"use chyabrung::prelude::*;

pub async fn {file}(req: Request, next: Next) -> Response {{
    let res = next(req).await;
    res
}}
"#
    );
    write_new(&PathBuf::from(format!("src/middleware/{file}.rs")), &src)?;
    add_mod(Path::new("src/middleware"), &file)?;
    hint_mod_declared("middleware");
    Ok(())
}

/// `chy make:job SendWelcomeEmail`
pub fn job(name: &str) -> CliResult {
    let file = snake(name);
    let ty = pascal(name);
    let src = format!(
        r#"use chyabrung::prelude::*;

#[derive(Debug, Serialize, Deserialize)]
pub struct {ty} {{
    pub id: i64,
}}

#[async_trait]
impl Job for {ty} {{
    const NAME: &'static str = "{file}";

    async fn handle(&self, _ctx: &JobContext) -> Result<()> {{
        tracing::info!("running {file} for {{}}", self.id);
        Ok(())
    }}
}}
"#
    );
    write_new(&PathBuf::from(format!("src/jobs/{file}.rs")), &src)?;
    add_mod(Path::new("src/jobs"), &file)?;
    hint_mod_declared("jobs");
    Ok(())
}

/// `chy make:page blog/[slug]`
pub fn page(path: &str) -> CliResult {
    let clean = path.trim_matches('/');
    let dynamic = clean.contains('[');
    let src = if dynamic {
        "use chyabrung::prelude::*;\nuse chyabrung::ui::prelude::*;\n\npub async fn page(cx: PageContext) -> Result<impl IntoView> {\n    let params: serde_json::Value = cx.params()?;\n    Ok(view! { <h1>\"Params: \" {params.to_string()}</h1> })\n}\n".to_string()
    } else {
        format!(
            "use chyabrung::ui::prelude::*;\n\npub fn page(cx: PageContext) -> impl IntoView {{\n    cx.title(\"{clean}\");\n    view! {{ <h1>\"{clean}\"</h1> }}\n}}\n"
        )
    };
    let file = if clean.is_empty() { PathBuf::from("app/page.rs") } else { PathBuf::from(format!("app/{clean}/page.rs")) };
    write_new(&file, &src)?;
    println!("  `file_routes!()` picks it up on the next build (touch src/main.rs if needed)");
    Ok(())
}

/// `chy make:seeder users`
pub fn seeder(name: &str) -> CliResult {
    let n = snake(name);
    write_new(
        &PathBuf::from(format!("database/seeds/{n}.sql")),
        &format!("-- Seed data for {n}\n-- INSERT INTO {n} (name) VALUES ('example');\n"),
    )
}

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

    #[test]
    fn mail_templates() {
        let src = mail_source("OrderShipped");
        assert!(src.contains("pub struct OrderShipped {") && src.contains("impl Mailable for OrderShipped {"), "{src}");
        assert!(src.contains("format!(\"Hello, {}!\", self.name)"), "{src}");
        assert!(mail_view().starts_with("{% extends \"layout.html\" %}"));
        assert!(MAIL_LAYOUT.contains("{% block content %}"));
    }

    #[test]
    fn model_and_migration_templates() {
        let rs = migration_rs("create_blog_posts_table");
        assert!(rs.contains("schema.create(\"blog_posts\", |table| {"));
        assert!(rs.contains("schema.drop_if_exists(\"blog_posts\")"));
        let rs = migration_rs("add_bio_to_users_table");
        assert!(rs.contains("schema.alter(\"users\"") && rs.contains("table.string(\"bio\").nullable()") && rs.contains("table.drop_column(\"bio\")"));
        assert!(migration_rs("tweak_things").contains("pub fn up(schema: &mut Schema)"));
    }
}

/// The migration for a full-text search index (the schema builder writes the
/// right index for whichever database runs it).
pub fn search_migration_rs(table: &str, columns: &[&str]) -> CliResult<String> {
    if columns.is_empty() {
        return Err("give the columns to search: `chy make:search posts --columns title,body`".into());
    }
    if let Some(bad) = columns.iter().find(|c| !c.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_')) {
        return Err(format!("`{bad}` is not a column name"));
    }
    let cols = columns.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");
    Ok(format!(
        r#"use chyabrung::db::Schema;

pub fn up(schema: &mut Schema) {{
    schema.search_index("{table}", &[{cols}]);
}}

pub fn down(schema: &mut Schema) {{
    schema.drop_search_index("{table}");
}}
"#
    ))
}

/// `chy make:search posts --columns title,body`: a migration that creates the
/// full-text search index.
pub fn search(table: &str, columns: &str) -> CliResult {
    let table = snake(table);
    let cols: Vec<&str> = columns.split(',').map(str::trim).filter(|c| !c.is_empty()).collect();
    let src = search_migration_rs(&table, &cols)?;
    let ts = chrono::Utc::now().format("%Y%m%d%H%M%S");
    write_new(&PathBuf::from(format!("migrations/{ts}_add_search_to_{table}.rs")), &src)?;
    crate::resource::rebuild_migrations();
    println!("  next: add `searchable = \"{}\"` to the model's #[model(...)] and run `chy migrate`", cols.join(", "));
    Ok(())
}

#[cfg(test)]
mod search_tests {
    #[test]
    fn search_migration() {
        let rs = super::search_migration_rs("posts", &["title", "body"]).unwrap();
        assert!(rs.contains("schema.search_index(\"posts\", &[\"title\", \"body\"]);"));
        assert!(rs.contains("schema.drop_search_index(\"posts\");"));
        assert!(super::search_migration_rs("posts", &[]).is_err());
        assert!(super::search_migration_rs("posts", &["title; DROP"]).is_err());
    }
}