use crate::util::{ok, package_name, pascal, plural, snake, write_new, CliResult};
use std::path::{Path, PathBuf};
#[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",
}
}
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(),
}
}
}
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)
}
pub struct Names {
pub ty: String,
pub file: String,
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,
)
}
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
)
}
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));
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()
}
}
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()))
}
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
}
pub const ROUTES_MARKER: &str = "// chy:resources";
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)
}
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"));
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();
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)?;
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,
};
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());
}
}