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(())
}
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(())
}
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)");
}
}
pub fn model_source(name: &str) -> String {
let ty = pascal(name);
let table = plural(&snake(name));
format!(
r#"use chyabrung::prelude::*;
/// The `{table}` table.
#[derive(Debug, Clone, Serialize, Deserialize, Model)]
#[model(table = "{table}", timestamps)]
pub struct {ty} {{
pub id: i64,
pub name: String,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}}
"#
)
}
pub fn model(name: &str, with_migration: bool) -> CliResult {
let file = snake(name);
write_new(&PathBuf::from(format!("src/models/{file}.rs")), &model_source(name))?;
add_mod(Path::new("src/models"), &file)?;
add_line(Path::new("src/models"), &format!("pub use {file}::{};", pascal(name)))?;
hint_mod_declared("models");
if with_migration {
migration(&format!("create_{}_table", plural(&file)))?;
}
Ok(())
}
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::*;
/// Handlers for `{table}`. Add them all in `src/routes/api.rs` with
/// `route.resource("/{table}", {ty});` (served at `/api/{table}`), or one at a
/// time: `route.get("/{table}", {ty}::index);`.
///
/// These handlers work on the `{table}` table directly. With a model and a
/// request type they get simpler (`async fn show(post: Post) -> Post`):
/// `chy make:resource` writes all of that, plus a test.
pub struct {ty};
#[controller]
impl {ty} {{
/// List {table}.
async fn index(db: Db) -> Result<Json<Vec<serde_json::Value>>> {{
Ok(Json(db.table("{table}").order_by_desc("id").get().await?))
}}
/// Create one.
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?))
}}
/// Show one.
async fn show(db: Db, Path(id): Path<i64>) -> Result<Json<serde_json::Value>> {{
Ok(Json(db.table("{table}").find(id).await?))
}}
/// Update one.
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?))
}}
/// Delete one.
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(())
}
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)
}
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}
/// Run the migration: create the `{table}` table.
pub fn up(schema: &mut Schema) {{
schema.create("{table}", |table| {{
table.id();
table.string("name");
table.timestamps();
}});
}}
/// Reverse the migration.
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}
/// Run the migration: add columns to `{table}`.
pub fn up(schema: &mut Schema) {{
schema.alter("{table}", |table| {{
table.string("{col}").nullable();
}});
}}
/// Reverse the migration.
pub fn down(schema: &mut Schema) {{
schema.alter("{table}", |table| {{
table.drop_column("{col}");
}});
}}
"#
);
}
format!(
r#"{header}
/// Run the migration.
pub fn up(schema: &mut Schema) {{
// schema.create("table", |table| {{ table.id(); ... }});
// schema.alter("table", |table| {{ table.string("column").nullable(); }});
let _ = schema;
}}
/// Reverse the migration.
pub fn down(schema: &mut Schema) {{
let _ = schema;
}}
"#
)
}
pub fn middleware(name: &str) -> CliResult {
let file = snake(name);
let src = format!(
r#"use chyabrung::prelude::*;
/// Middleware `{file}`. Register with `.middleware({file}::{file})`.
pub async fn {file}(req: Request, next: Next) -> Response {{
// before the handler
let res = next(req).await;
// after the handler
res
}}
"#
);
write_new(&PathBuf::from(format!("src/middleware/{file}.rs")), &src)?;
add_mod(Path::new("src/middleware"), &file)?;
hint_mod_declared("middleware");
Ok(())
}
pub fn job(name: &str) -> CliResult {
let file = snake(name);
let ty = pascal(name);
let src = format!(
r#"use chyabrung::prelude::*;
/// Background job `{file}`. Dispatch with `queue.dispatch({ty} {{ .. }}).await?` and
/// register on the worker with `.register::<{ty}>()`.
#[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(())
}
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(())
}
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 model_and_migration_templates() {
let m = model_source("BlogPost");
assert!(m.contains("pub struct BlogPost"));
assert!(m.contains("table = \"blog_posts\""));
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)"));
}
}
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;
/// Run the migration: full-text search over `{table}` ({cols_plain}).
pub fn up(schema: &mut Schema) {{
schema.search_index("{table}", &[{cols}]);
}}
/// Reverse the migration.
pub fn down(schema: &mut Schema) {{
schema.drop_search_index("{table}");
}}
"#,
cols_plain = columns.join(", ")
))
}
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());
}
}