//! `ryuk new` and `make:*` file generation from embedded templates.
use crate::names::{pascal, snake};
use include_dir::{Dir, include_dir};
use std::{
fs,
io::{self, Write},
path::{Path, PathBuf},
};
static APP: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/app");
static CLIENT: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/client");
static MAKE: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/make");
fn err(msg: String) -> io::Error {
io::Error::other(msg)
}
/// Write a new file, refusing to overwrite.
fn write_new(path: &Path, content: &[u8]) -> io::Result<()> {
if let Some(p) = path.parent() {
fs::create_dir_all(p)?;
}
let mut f = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|e| {
if e.kind() == io::ErrorKind::AlreadyExists {
err(format!("{} already exists", path.display()))
} else {
e
}
})?;
f.write_all(content)
}
/// Copy an embedded dir; `subst` maps (file name, text) -> text for files that carry placeholders.
fn copy_dir(dir: &Dir, dest: &Path, subst: &dyn Fn(&str, &str) -> String) -> io::Result<()> {
for f in dir.files() {
let rel = f.path();
let name = rel.file_name().and_then(|n| n.to_str()).unwrap_or("");
if name == ".gitkeep" {
continue;
}
let out = dest.join(rel);
// Askama templates use `{{ .. }}` themselves; copy them untouched.
let verbatim = rel.starts_with("templates");
match f.contents_utf8() {
Some(t) if verbatim => write_new(&out, t.as_bytes())?,
Some(t) => write_new(&out, subst(name, t).as_bytes())?,
None => write_new(&out, f.contents())?,
}
}
for d in dir.dirs() {
copy_dir(d, dest, subst)?;
}
Ok(())
}
/// Database backend of a new app.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Db {
Sqlite,
Postgres,
Mysql,
}
impl Db {
/// Cargo feature name of both ryuk and sqlx for this backend.
fn feature(self) -> &'static str {
match self {
Db::Sqlite => "sqlite",
Db::Postgres => "postgres",
Db::Mysql => "mysql",
}
}
fn url(self, name: &str) -> String {
match self {
Db::Sqlite => "sqlite://db.sqlite?mode=rwc".into(),
Db::Postgres => format!("postgres://ryuk:ryuk@127.0.0.1:5432/{name}"),
Db::Mysql => format!("mysql://ryuk:ryuk@127.0.0.1:3306/{name}"),
}
}
/// `docker-compose.yml` with a database matching [`Db::url`]; none for sqlite.
fn compose(self, name: &str) -> Option<String> {
let (image, env, port, vol, health) = match self {
Db::Sqlite => return None,
Db::Postgres => (
"postgres:16",
format!(
"POSTGRES_USER: ryuk\n POSTGRES_PASSWORD: ryuk\n POSTGRES_DB: {name}"
),
"5432",
"/var/lib/postgresql/data",
"pg_isready -U ryuk",
),
Db::Mysql => (
"mysql:8",
format!(
"MYSQL_ROOT_PASSWORD: ryuk\n MYSQL_USER: ryuk\n MYSQL_PASSWORD: ryuk\n MYSQL_DATABASE: {name}"
),
"3306",
"/var/lib/mysql",
"mysqladmin ping -h 127.0.0.1 -pryuk",
),
};
let scheme = self.feature();
Some(format!(
"services:\n db:\n image: {image}\n environment:\n {env}\n ports:\n - \"127.0.0.1:{port}:{port}\"\n volumes:\n - db-data:{vol}\n healthcheck:\n test: [\"CMD-SHELL\", \"{health}\"]\n interval: 5s\n retries: 20\n app:\n profiles: [\"app\"]\n build: .\n ports:\n - \"127.0.0.1:3000:3000\"\n environment:\n DATABASE_URL: {scheme}://ryuk:ryuk@db:{port}/{name}\n APP_URL: http://localhost:3000\n # Local try-out only: the image runs with APP_ENV=production, which refuses the log mail driver.\n # For a real deployment set MAIL_DRIVER=smtp (+ MAIL_HOST, MAIL_FROM, ...) and delete this line.\n ALLOW_LOG_MAIL: \"true\"\n depends_on:\n db:\n condition: service_healthy\nvolumes:\n db-data:\n"
))
}
}
/// Scaffold a new app at `parent/name`. `ryuk_path` is the local ryuk crate (RYUK_PATH), else crates.io.
pub fn new_app(parent: &Path, name: &str, ryuk_path: Option<&str>, db: Db) -> io::Result<PathBuf> {
if name.is_empty()
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return Err(err(format!(
"invalid app name '{name}' (use letters, digits, - and _)"
)));
}
let root = parent.join(name);
if root.exists() {
return Err(err(format!("{} already exists", root.display())));
}
let src = match ryuk_path {
Some(p) => {
let abs = fs::canonicalize(p).unwrap_or_else(|_| PathBuf::from(p));
format!("path = \"{}\"", abs.display())
}
None => "version = \"0.1\"".to_string(),
};
let dep = format!(
"ryuk = {{ {src}, default-features = false, features = [\"inertia\", \"auth\", \"validation\", \"openapi\", \"queue\", \"mail\", \"csrf\", \"safety\", \"session-db\", \"api\", \"apikeys\", \"oauth-server\", \"social\", \"passkey\", \"push\", \"mail-templates\", \"storage\", \"s3\", \"mcp\", \"http\", \"cache\", \"events\", \"schedule\", \"gate\", \"crypt\", \"notifications\", \"lang\", \"tenancy\", \"{}\"] }}",
db.feature()
);
let (sqlx, url) = (format!("sqlx-{}", db.feature()), db.url(name));
fs::create_dir_all(&root)?;
copy_dir(&APP, &root, &|_, t| {
t.replace("{{name}}", name)
.replace("{{ryuk_dep}}", &dep)
.replace("{{sqlx}}", &sqlx)
.replace("{{database_url}}", &url)
})?;
if let Some(c) = db.compose(name) {
write_new(&root.join("docker-compose.yml"), c.as_bytes())?;
}
// These cannot keep their real names inside this crate's source tree.
for (from, to) in [
("Cargo.toml.tmpl", "Cargo.toml"),
("gitignore", ".gitignore"),
("env", ".env"),
] {
fs::rename(root.join(from), root.join(to))?;
}
// client/ is owned by the frontend template: opaque, except these two known files.
copy_dir(&CLIENT, &root.join("client"), &|file, t| {
if file == "package.json" || file == "index.html" {
t.replace("{{name}}", name)
} else {
t.to_string()
}
})?;
Ok(root)
}
fn render(tmpl: &str, name: &str) -> String {
let t = MAKE
.get_file(tmpl)
.expect("embedded template")
.contents_utf8()
.expect("utf8 template");
t.replace("{{Name}}", &pascal(name))
.replace("{{snake}}", &snake(name))
}
/// Append `line` to `dir/mod.rs` (creating it).
fn register_mod(dir: &Path, line: &str) -> io::Result<()> {
let mut f = fs::OpenOptions::new()
.append(true)
.create(true)
.open(dir.join("mod.rs"))?;
writeln!(f, "{line}")
}
fn check_root(root: &Path) -> io::Result<()> {
if root.join("Cargo.toml").exists() && root.join("src").is_dir() {
Ok(())
} else {
Err(err(
"run this from a ryuk app root (Cargo.toml + src/)".into()
))
}
}
/// Add the module's `index` route to `src/<file>` at its `marker`, with a fully qualified path (the
/// routes files only import the controllers they were generated with). Returns false and leaves the
/// file alone when the marker is gone, so the caller can say what to add by hand.
fn wire_route(root: &Path, file: &str, marker: &str, path: &str) -> io::Result<bool> {
let p = root.join("src").join(file);
let Ok(src) = fs::read_to_string(&p) else {
return Ok(false);
};
if !src.contains(marker) {
return Ok(false);
}
let line = format!(".routes(routes!(crate::controllers::{path}::index))");
fs::write(
&p,
src.replacen(marker, &format!("{line}\n {marker}"), 1),
)?;
Ok(true)
}
/// Kinds handled by the simple "one file + mod line" generator.
pub fn make(root: &Path, kind: &str, name: &str) -> io::Result<Vec<PathBuf>> {
check_root(root)?;
check_name(name)?;
let s = snake(name);
let (dir, tmpl) = match kind {
"model" => ("models", "model.rs.tmpl"),
"tenant-model" => ("models", "model_tenant.rs.tmpl"),
"controller" => ("controllers", "controller.rs.tmpl"),
"api" => ("controllers/api", "api.rs.tmpl"),
"job" => ("jobs", "job.rs.tmpl"),
"mail" => ("mails", "mail.rs.tmpl"),
"mail-template" => ("mails", "mail_template.rs.tmpl"),
"event" => ("events", "event.rs.tmpl"),
"notification" => ("notifications", "notification.rs.tmpl"),
"policy" => ("policies", "policy.rs.tmpl"),
"seeder" => ("seeders", "seeder.rs.tmpl"),
"middleware" => ("middleware", "middleware.rs.tmpl"),
"mcp-tool" => ("mcp", "mcp_tool.rs.tmpl"),
_ => return Err(err(format!("unknown generator '{kind}'"))),
};
let d = root.join("src").join(dir);
let file = d.join(format!("{s}.rs"));
write_new(&file, render(tmpl, name).as_bytes())?;
register_mod(&d, &format!("pub mod {s};"))?;
let wired = match kind {
"controller" => Some(("routes.rs", "// ryuk:routes", s.clone())),
"api" => Some(("api.rs", "// ryuk:api-routes", format!("api::{s}"))),
_ => None,
};
if let Some((f, marker, path)) = wired {
if wire_route(root, f, marker, &path)? {
println!("Registered the route in src/{f}");
} else {
println!(
"src/{f} has no `{marker}` marker: add `.routes(routes!(crate::controllers::{path}::index))` yourself"
);
}
}
if kind == "seeder" {
// Seeders run in creation order; the marker keeps `db:seed` a plain list of calls.
let modrs = d.join("mod.rs");
let src = fs::read_to_string(&modrs)?;
if src.contains("// ryuk:seeders") {
let call = format!("{s}::run(_db).await?;");
fs::write(
&modrs,
src.replacen(
"// ryuk:seeders",
&format!("{call}\n // ryuk:seeders"),
1,
),
)?;
} else {
println!(
"src/seeders/mod.rs has no `// ryuk:seeders` marker: call `{s}::run(db).await?` yourself"
);
}
}
match kind {
"api" => println!(
"Next: the stub requires the scope `{s}:read`. Add it to SCOPES in src/controllers/api_keys.rs and to the OAuth scope list in src/lib.rs, otherwise no key or token can reach this route."
),
"model" => println!(
"Next: if rows belong to a user, delete them in `delete_user` (src/account.rs), or account deletion leaves this table's data behind."
),
"tenant-model" => println!(
"Next: filter EVERY query on this table by `org_id` from `ryuk::tenancy::Member` (see src/controllers/projects.rs), and delete its rows in `delete_org` (src/account.rs), or deleting an organization leaves them behind."
),
_ => {}
}
let mut made = vec![file];
if kind == "mail-template" {
for (ext, tmpl) in [
("html", "mail_template.html.tmpl"),
("txt", "mail_template.txt.tmpl"),
] {
let path = root.join("templates/mail").join(format!("{s}.{ext}"));
write_new(&path, render(tmpl, name).as_bytes())?;
made.push(path);
}
}
if let Some(tmpl) = match kind {
"model" => Some("model_migration.rs.tmpl"),
"tenant-model" => Some("model_migration_tenant.rs.tmpl"),
_ => None,
} {
made.push(migration(root, &format!("create_{s}s_table"), tmpl, name)?);
}
Ok(made)
}
/// A generator name becomes a file name, a `mod` line and a Rust identifier, so it must be plain: a letter first,
/// then letters, digits, spaces, `-` and `_`, and not a Rust keyword. `../x` would write outside the project and
/// `x;include_str!(..);` would splice code into `mod.rs`.
fn check_name(name: &str) -> io::Result<()> {
const KEYWORDS: &[&str] = &[
"as", "async", "await", "box", "break", "const", "continue", "crate", "dyn", "else",
"enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
"move", "mut", "pub", "ref", "return", "self", "static", "struct", "super", "trait",
"true", "type", "unsafe", "use", "where", "while",
];
let mut chars = name.chars();
let plain = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || "-_ ".contains(c));
if !plain || name.len() > 64 {
return Err(err(format!(
"invalid name '{name}' (a letter first, then letters, digits, spaces, - and _; at most 64 characters)"
)));
}
if KEYWORDS.contains(&snake(name).as_str()) {
return Err(err(format!(
"'{name}' is a Rust keyword; pick another name"
)));
}
Ok(())
}
/// `make:migration`: file `m<timestamp>_<name>.rs`, registered in `src/migrations/mod.rs`.
pub fn make_migration(root: &Path, name: &str) -> io::Result<PathBuf> {
check_root(root)?;
check_name(name)?;
migration(root, name, "migration.rs.tmpl", name)
}
fn migration(root: &Path, file_name: &str, tmpl: &str, tmpl_name: &str) -> io::Result<PathBuf> {
let d = root.join("src/migrations");
let modrs = d.join("mod.rs");
let src =
fs::read_to_string(&modrs).map_err(|_| err("src/migrations/mod.rs not found".into()))?;
if !src.contains("// ryuk:mods") || !src.contains("// ryuk:list") {
return Err(err(
"src/migrations/mod.rs lost its `// ryuk:mods` / `// ryuk:list` markers".into(),
));
}
let m = format!(
"m{}_{}",
chrono::Utc::now().format("%Y%m%d_%H%M%S"),
snake(file_name)
);
let file = d.join(format!("{m}.rs"));
write_new(&file, render(tmpl, tmpl_name).as_bytes())?;
let out = src
.replace("// ryuk:mods", &format!("mod {m};\n// ryuk:mods"))
.replace(
"// ryuk:list",
&format!("Box::new({m}::Migration),\n // ryuk:list"),
);
fs::write(modrs, out)?;
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn askama_templates_are_copied_byte_for_byte() {
let tmp = tempfile::tempdir().unwrap();
let root = new_app(tmp.path(), "demo", Some("/nonexistent/ryuk"), Db::Sqlite).unwrap();
let mut seen = 0;
for f in APP
.get_dir("templates/mail")
.expect("embedded mail templates")
.files()
{
let name = f.path().file_name().unwrap();
let got = fs::read(root.join("templates/mail").join(name)).unwrap();
assert_eq!(got, f.contents(), "{name:?} was altered while generating");
seen += 1;
}
assert!(
seen >= 8,
"layout + macros + 3 emails x 2 parts, saw {seen}"
);
let html = fs::read_to_string(root.join("templates/mail/verify_email.html")).unwrap();
assert!(
html.contains("{{ name }}") && html.contains("{{ m::button(link,"),
"{html}"
);
// Spaces inside `{{ }}` also keep these away from the generator's own `{{name}}` placeholders.
let txt = fs::read_to_string(root.join("templates/mail/verify_email.txt")).unwrap();
assert!(
txt.contains("{{ link }}") && txt.contains("{{ life }}"),
"{txt}"
);
}
#[test]
fn new_scaffolds_app_for_every_db() {
let tmp = tempfile::tempdir().unwrap();
for (db, feat, url, compose) in [
(
Db::Sqlite,
"sqlite",
"DATABASE_URL=sqlite://db.sqlite?mode=rwc",
false,
),
(
Db::Postgres,
"postgres",
"DATABASE_URL=postgres://ryuk:ryuk@127.0.0.1:5432/demo",
true,
),
(
Db::Mysql,
"mysql",
"DATABASE_URL=mysql://ryuk:ryuk@127.0.0.1:3306/demo",
true,
),
] {
let parent = tmp.path().join(feat);
let root = new_app(&parent, "demo", Some("/nonexistent/ryuk"), db).unwrap();
for f in [
"Cargo.toml",
".env",
".gitignore",
"src/main.rs",
"src/routes.rs",
"src/controllers/auth.rs",
"src/models/user.rs",
"src/migrations/mod.rs",
] {
assert!(root.join(f).exists(), "missing {f}");
}
let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
assert!(
cargo.contains("name = \"demo\"") && cargo.contains("path = \"/nonexistent/ryuk\"")
);
assert!(
cargo.contains("default-features = false")
&& cargo.contains(&format!("\"{feat}\"] }}")),
"{cargo}"
);
assert!(cargo.contains(&format!("sqlx-{feat}")));
assert!(fs::read_to_string(root.join(".env")).unwrap().contains(url));
assert_eq!(root.join("docker-compose.yml").exists(), compose);
for f in ["Cargo.toml", ".env", "src/main.rs"] {
assert!(
!fs::read_to_string(root.join(f)).unwrap().contains("{{"),
"{f}"
);
}
if compose {
let c = fs::read_to_string(root.join("docker-compose.yml")).unwrap();
assert!(c.contains("ryuk") && c.contains("demo"));
assert!(
c.contains("profiles: [\"app\"]")
&& c.contains(&format!("{feat}://ryuk:ryuk@db:")),
"{c}"
);
// The production image refuses the log mail driver; the local compose says so and opts in.
assert!(c.contains("ALLOW_LOG_MAIL: \"true\""), "{c}");
}
for f in [
"src/lib.rs",
"tests/flows.rs",
"Dockerfile",
".dockerignore",
".env.example",
"README.md",
] {
assert!(root.join(f).exists(), "missing {f}");
assert!(
!fs::read_to_string(root.join(f)).unwrap().contains("{{"),
"{f}"
);
}
assert!(
fs::read_to_string(root.join("Dockerfile"))
.unwrap()
.contains("/usr/local/bin/demo")
);
}
let r = tmp.path().join("again");
new_app(&r, "demo", None, Db::Sqlite).unwrap();
assert!(
new_app(&r, "demo", None, Db::Sqlite).is_err(),
"must not overwrite"
);
let d2 = new_app(&r, "d2", None, Db::Sqlite).unwrap();
assert!(
fs::read_to_string(d2.join("Cargo.toml"))
.unwrap()
.contains("version = \"0.1\"")
);
assert!(new_app(&r, "bad name", None, Db::Sqlite).is_err());
}
#[test]
fn make_generates_and_refuses_overwrite() {
let tmp = tempfile::tempdir().unwrap();
let root = new_app(tmp.path(), "demo", None, Db::Sqlite).unwrap();
make(&root, "model", "BlogPost").unwrap();
let model = fs::read_to_string(root.join("src/models/blog_post.rs")).unwrap();
assert!(model.contains("blog_posts"));
assert!(
fs::read_to_string(root.join("src/models/mod.rs"))
.unwrap()
.contains("pub mod blog_post;")
);
let mig = fs::read_to_string(root.join("src/migrations/mod.rs")).unwrap();
assert!(mig.contains("create_blog_posts_table::Migration"));
assert!(make(&root, "model", "BlogPost").is_err());
// Names become files, `mod` lines and identifiers: nothing that escapes or injects is accepted.
for bad in [
"../../escape",
"a/b",
"x;include_str!(\"/etc/passwd\");",
"foo;bar",
"x{}",
"",
"1abc",
"type",
"Mod",
".hidden",
] {
for kind in ["job", "controller", "seeder", "model"] {
assert!(make(&root, kind, bad).is_err(), "{kind} {bad:?}");
}
assert!(make_migration(&root, bad).is_err(), "migration {bad:?}");
}
assert!(!root.join("src").join("escape.rs").exists());
// Passkeys need a real domain as the relying party id, so the generated app must not default to a bare IP.
let env = fs::read_to_string(root.join(".env")).unwrap();
assert!(env.contains("APP_URL=http://localhost:3000"), "{env}");
make(&root, "tenant-model", "Invoice").unwrap();
let t = fs::read_to_string(root.join("src/models/invoice.rs")).unwrap();
assert!(t.contains("pub org_id: i64") && t.contains("invoices"));
let mig = fs::read_dir(root.join("src/migrations"))
.unwrap()
.map(|e| e.unwrap().path())
.find(|p| p.to_string_lossy().ends_with("create_invoices_table.rs"))
.expect("tenant migration");
let mig = fs::read_to_string(mig).unwrap();
assert!(
mig.contains("Orgs::Table")
&& mig.contains("ForeignKeyAction::Cascade")
&& mig.contains("idx_invoices_org_id"),
"FK to orgs and an org_id index"
);
make(&root, "controller", "Invoice").unwrap();
let routes = fs::read_to_string(root.join("src/routes.rs")).unwrap();
assert!(routes.contains("routes!(crate::controllers::invoice::index)"));
assert!(
routes.contains("// ryuk:routes"),
"marker stays for the next controller"
);
assert!(
fs::read_to_string(root.join("src/controllers/mod.rs"))
.unwrap()
.contains("pub mod invoice;")
);
make(&root, "controller", "Order").unwrap();
let routes = fs::read_to_string(root.join("src/routes.rs")).unwrap();
assert!(
routes.contains("controllers::invoice::index")
&& routes.contains("controllers::order::index")
);
make(&root, "api", "Widget").unwrap();
let api = fs::read_to_string(root.join("src/api.rs")).unwrap();
assert!(
api.contains("routes!(crate::controllers::api::widget::index)")
&& api.contains("// ryuk:api-routes")
);
let w = fs::read_to_string(root.join("src/controllers/api/widget.rs")).unwrap();
assert!(w.contains("ApiAuth") && w.contains("path = \"/widget\"") && !w.contains("{{"));
assert!(
fs::read_to_string(root.join("src/controllers/api/mod.rs"))
.unwrap()
.contains("pub mod widget;")
);
assert!(make(&root, "api", "Widget").is_err());
make(&root, "job", "SendEmail").unwrap();
assert!(
fs::read_to_string(root.join("src/jobs/send_email.rs"))
.unwrap()
.contains("struct SendEmail")
);
make(&root, "mail-template", "Invoice Paid").unwrap();
let rs = fs::read_to_string(root.join("src/mails/invoice_paid.rs")).unwrap();
assert!(
rs.contains("path = \"mail/invoice_paid.html\", askama = ryuk::mail::askama"),
"{rs}"
);
assert!(
rs.contains("pub fn invoice_paid(name: &str, to: &str) -> Result<Mail, MailError>"),
"{rs}"
);
let html = fs::read_to_string(root.join("templates/mail/invoice_paid.html")).unwrap();
assert!(
html.contains("{{ name }}") && html.contains("InvoicePaid"),
"{html}"
);
assert!(
fs::read_to_string(root.join("templates/mail/invoice_paid.txt"))
.unwrap()
.contains("Hi {{ name }},")
);
assert!(
make(&root, "mail-template", "Invoice Paid").is_err(),
"never overwrites"
);
for (kind, name, file) in [
("event", "UserRegistered", "events/user_registered.rs"),
("notification", "Welcome", "notifications/welcome.rs"),
("policy", "Post", "policies/post.rs"),
("middleware", "Audit", "middleware/audit.rs"),
("mcp-tool", "Weather", "mcp/weather.rs"),
] {
make(&root, kind, name).unwrap();
assert!(root.join("src").join(file).exists(), "{kind}");
}
make(&root, "seeder", "Users").unwrap();
let seeders = fs::read_to_string(root.join("src/seeders/mod.rs")).unwrap();
assert!(seeders.contains("users::run(_db).await?;"), "{seeders}");
assert!(seeders.contains("pub mod users;"));
}
}