use anyhow::{Context, Result};
use larust_convert::codegen::{generate_item, pluralize, to_snake_case, validate_identifier};
use std::path::Path;
const PLAIN_CONTROLLER_TEMPLATE: &str = "pub struct __NAME__;\n\nimpl __NAME__ {}\n";
const RESOURCE_CONTROLLER_TEMPLATE: &str = r#"pub struct __NAME__;
impl __NAME__ {
pub async fn index() -> &'static str {
todo!()
}
pub async fn create() -> &'static str {
todo!()
}
pub async fn store() -> &'static str {
todo!()
}
pub async fn show() -> &'static str {
todo!()
}
pub async fn edit() -> &'static str {
todo!()
}
pub async fn update() -> &'static str {
todo!()
}
pub async fn destroy() -> &'static str {
todo!()
}
}
"#;
const MODEL_TEMPLATE: &str = r#"use larust_support::orm::sqlx;
use larust_support::Model;
#[derive(Model, sqlx::FromRow)]
#[table("__TABLE__")]
pub struct __NAME__ {
#[primary_key]
pub id: i64,
}
"#;
const REQUEST_TEMPLATE: &str = r#"use larust_support::FormRequest;
#[derive(FormRequest)]
pub struct __NAME__ {}
"#;
const MIDDLEWARE_TEMPLATE: &str = r#"use larust_support::axum::extract::Request;
use larust_support::axum::middleware::Next;
use larust_support::axum::response::Response;
pub async fn __NAME__(request: Request, next: Next) -> Response {
next.run(request).await
}
"#;
const COMMAND_TEMPLATE: &str = r#"use larust_support::console::Command;
use larust_support::AppError;
pub struct __NAME__;
impl Command for __NAME__ {
const NAME: &'static str = "__COMMAND_NAME__";
async fn handle(_args: &[String]) -> Result<(), AppError> {
todo!()
}
}
"#;
const MIGRATION_PLACEHOLDER: &str = "-- Write your migration SQL here.\n";
const FACTORY_TEMPLATE: &str = r#"use crate::models::{__NAME__, __NEW_NAME__};
use larust_support::orm::Factory;
pub struct __NAME__Factory;
impl Factory for __NAME__Factory {
type Model = __NAME__;
fn definition(seq: u64) -> __NEW_NAME__ {
let _ = seq;
todo!("build a fake `__NEW_NAME__` value")
}
}
"#;
const POLICY_TEMPLATE: &str = r#"use crate::models::__IMPORTS__;
use larust_support::auth::Policy;
impl Policy<__USER__> for __NAME__ {
fn view_any(_user: &__USER__) -> bool {
false
}
fn view(&self, _user: &__USER__) -> bool {
false
}
fn create(_user: &__USER__) -> bool {
false
}
fn update(&self, _user: &__USER__) -> bool {
false
}
fn delete(&self, _user: &__USER__) -> bool {
false
}
}
"#;
pub fn make_controller(name: &str, resource: bool) -> Result<()> {
let template = if resource {
RESOURCE_CONTROLLER_TEMPLATE
} else {
PLAIN_CONTROLLER_TEMPLATE
};
generate_item(
name,
Path::new("app/Http/Controllers"),
"controller",
template,
&[],
)
}
pub fn make_model(name: &str, migration: bool) -> Result<()> {
validate_identifier(name)?;
let table = pluralize(&to_snake_case(name));
generate_item(
name,
Path::new("app/Models"),
"model",
MODEL_TEMPLATE,
&[("__TABLE__", &table)],
)?;
if migration {
let migration_name = format!("create_{table}_table");
let content =
format!("CREATE TABLE {table} (\n id INTEGER PRIMARY KEY AUTOINCREMENT\n);\n");
make_migration_with_content(&migration_name, &content)?;
}
Ok(())
}
pub fn make_request(name: &str) -> Result<()> {
generate_item(
name,
Path::new("app/Http/Requests"),
"request",
REQUEST_TEMPLATE,
&[],
)
}
pub fn make_middleware(name: &str) -> Result<()> {
validate_identifier(name)?;
let fn_name = to_snake_case(name);
larust_convert::codegen::generate_file(
Path::new("app/Http/Middleware"),
&fn_name,
"middleware",
&MIDDLEWARE_TEMPLATE.replace("__NAME__", &fn_name),
Some(&fn_name),
)
}
pub fn make_command(name: &str) -> Result<()> {
validate_identifier(name)?;
let command_name = to_snake_case(name).replace('_', ":");
generate_item(
name,
Path::new("app/Console/Commands"),
"command",
COMMAND_TEMPLATE,
&[("__COMMAND_NAME__", &command_name)],
)
}
pub fn make_migration(name: &str) -> Result<()> {
make_migration_with_content(name, MIGRATION_PLACEHOLDER)
}
fn make_migration_with_content(name: &str, content: &str) -> Result<()> {
let dir = Path::new("database/migrations");
anyhow::ensure!(
dir.is_dir(),
"no database/migrations directory found here (run this from a Larust app's root)"
);
let next = next_migration_number(dir)?;
let slug: String = name
.to_lowercase()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
let path = dir.join(format!("{next:04}_{slug}.sql"));
std::fs::write(&path, content).with_context(|| format!("writing {}", path.display()))?;
println!("Created migration: {}", path.display());
Ok(())
}
pub fn make_policy(name: &str, user: &str) -> Result<()> {
validate_identifier(name)?;
validate_identifier(user)?;
let mod_name = format!("{}_policy", to_snake_case(name));
larust_convert::codegen::generate_file(
Path::new("app/Policies"),
&mod_name,
"policy",
&policy_content(name, user),
None,
)
}
fn policy_content(name: &str, user: &str) -> String {
let imports = if name == user {
name.to_string()
} else {
format!("{{{name}, {user}}}")
};
POLICY_TEMPLATE
.replace("__IMPORTS__", &imports)
.replace("__USER__", user)
.replace("__NAME__", name)
}
pub fn make_factory(name: &str) -> Result<()> {
validate_identifier(name)?;
let mod_name = format!("{}_factory", to_snake_case(name));
larust_convert::codegen::generate_file(
Path::new("database/factories"),
&mod_name,
"factory",
&factory_content(name),
Some(&format!("{name}Factory")),
)
}
fn factory_content(name: &str) -> String {
FACTORY_TEMPLATE
.replace("__NAME__", name)
.replace("__NEW_NAME__", &format!("New{name}"))
}
fn next_migration_number(dir: &Path) -> Result<u32> {
let mut max = 0u32;
for entry in std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
let entry = entry?;
let name = entry.file_name();
if let Some(prefix) = name.to_string_lossy().split('_').next() {
if let Ok(n) = prefix.parse::<u32>() {
max = max.max(n);
}
}
}
Ok(max + 1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn policy_content_imports_both_types_when_name_and_user_differ() {
let content = policy_content("Post", "User");
assert!(content.contains("use crate::models::{Post, User};"));
assert!(content.contains("impl Policy<User> for Post {"));
assert!(!content.contains("__NAME__"));
assert!(!content.contains("__USER__"));
assert!(!content.contains("__IMPORTS__"));
}
#[test]
fn policy_content_dedupes_the_import_when_name_equals_user() {
let content = policy_content("User", "User");
assert!(content.contains("use crate::models::User;"));
assert!(!content.contains("User, User"));
assert!(content.contains("impl Policy<User> for User {"));
}
#[test]
fn factory_content_fills_in_the_model_and_its_new_struct() {
let content = factory_content("Post");
assert!(content.contains("use crate::models::{Post, NewPost};"));
assert!(content.contains("pub struct PostFactory;"));
assert!(content.contains("impl Factory for PostFactory {"));
assert!(content.contains("type Model = Post;"));
assert!(content.contains("fn definition(seq: u64) -> NewPost {"));
assert!(!content.contains("__NAME__"));
assert!(!content.contains("__NEW_NAME__"));
}
}