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::*;
/// The input for creating or changing a {label}.
///
/// Take it as the **last** argument of a handler: `async fn store(input: {ty}Request)`.
/// It is read from the JSON or form body (the query string for `GET`) and
/// checked against the rules below. When a rule fails, the client gets a
/// `422` response with a message for each field, and the handler doesn't run.
///
/// Rules: `required`, `email`, `url`, `min = 3`, `max = 255` (characters for
/// text, the value for numbers), `regex = "^[a-z0-9-]+$"`, `custom = "my_check"`
/// and `message = "Your own message."`. Combine them: `#[validate(required, email)]`.
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct {ty}Request {{
{body}}}
"#,
ty = n.ty,
label = n.file.replace('_', " "),
)
}
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(())
}
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#"//! How a {label} looks in the API.
use crate::models::{ty};
use chyabrung::prelude::*;
/// A {label} as JSON. Add, rename or leave out fields here without changing
/// the `{table}` table. `self` reads the {ty}'s fields.
///
/// Return it from a controller: `{ty}Resource::make({var})` for one
/// (`{{"data": {{...}}}}`), `{ty}Resource::collection(page)` for a list.
#[resource({ty})]
pub struct {ty}Resource;
impl JsonResource for {ty}Resource {{
fn to_array(&self) -> JsonValue {{
json!({{
{lines} }})
}}
}}
"#,
ty = n.ty,
table = n.table,
var = n.file,
label = n.file.replace('_', " "),
)
}
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("#[") {
if t.starts_with("#[model(") || (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
}
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(())
}
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#"//! Create, read, update and delete {table}.
//!
//! The methods have the standard names (`index`, `store`, `show`, `update`,
//! `destroy`), so `route.resource("/{table}", {ty}Controller)` in
//! `src/routes/api.rs` adds them all.
//!
//! - `{var}: {ty}` loads the {label} named in the URL (`/{table}/{{id}}`), or answers `404`.
//! - `input: {ty}Request` is the request body, already checked against its rules.
//! - `{ty}Resource` (in `src/responses/`) decides how a {label} looks as JSON.
//! - To require a logged-in user, add a `user: Auth` argument.
use crate::models::{ty};
use crate::requests::{requests};
use crate::responses::{ty}Resource;
use chyabrung::prelude::*;
pub struct {ty}Controller;
#[controller]
impl {ty}Controller {{
/// List {table}, newest first.
async fn index({index_args}) -> Result<ResourceCollection<{ty}Resource>> {{
Ok({ty}Resource::collection({ty}::query().latest(){page}.await?))
}}
/// Create a {label}.
async fn store(input: {ty}Request) -> Result<Resource<{ty}Resource>> {{
Ok({ty}Resource::make({ty}::create(&input).await?).created())
}}
/// Show one {label}.
async fn show({var}: {ty}) -> Resource<{ty}Resource> {{
{ty}Resource::make({var})
}}
/// Update a {label}.
async fn update(mut {var}: {ty}, input: {ty}Request) -> Result<Resource<{ty}Resource>> {{
{assign} {var}.save().await?;
Ok({ty}Resource::make({var}.refresh().await?))
}}
/// Delete a {label}.
async fn destroy({var}: {ty}) -> Result<NoContent> {{
{var}.delete().await?;
Ok(NoContent)
}}
}}
"#,
table = n.table,
ty = n.ty,
label = 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(\"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));
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["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,
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 line = format!("route.resource(\"/{}\", {}Controller);", n.table, n.ty);
if routes.contains(&line) {
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}{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)
}
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_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)))?;
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,
};
write_new(&PathBuf::from(format!("tests/{}.rs", n.file)), &test_source(&n, &fields, &krate))?;
println!();
if !mounted {
println!(
" add this line to `routes` in src/routes/api.rs:\n route.resource(\"/{}\", {}Controller);\n (or add a `{ROUTES_MARKER}` line there and `make:resource` will do it for you)",
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#[derive(Model)]\npub struct Post {\n pub id: i64,\n pub title: String,\n #[serde(skip_serializing, default)]\n pub secret: String,\n #[model(belongs_to)]\n #[serde(default)]\n pub author: Option<User>,\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_at_marker() {
let n = Names::new("Comment");
let routes = "use crate::controllers::*;\nuse chyabrung::prelude::*;\n\npub fn routes(route: &mut Route) {\n route.resource(\"/posts\", PostController);\n\n // chy:resources (keep this line)\n}\n";
let out = add_route(routes, &n).unwrap();
assert!(out.contains(" route.resource(\"/comments\", CommentController);\n // chy:resources"), "{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::*;\n// chy:resources\n", &n).unwrap();
assert!(out.contains("use crate::controllers::CommentController;\n"));
}
}