use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use regex::Regex;
use serde_json::Value;
use crate::audit::balanced;
use crate::manifest::controller;
use crate::route_parity::{ignored, php_auth};
use crate::feasibility;
const RESERVED: &[&str] = &[
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "gen",
"if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super",
"trait", "true", "try", "type", "unsafe", "use", "where", "while", "abstract", "become", "box", "do", "final", "macro",
"override", "priv", "typeof", "unsized", "virtual", "yield",
];
pub fn run(inventory: &Path, rust: &Path) -> Result<(), String> {
let mut inv = feasibility::load(inventory)?;
feasibility::score_all(&mut inv);
let php = PathBuf::from(inv["app"]["path"].as_str().ok_or("inventory has no app.path")?);
if !rust.join("Cargo.toml").is_file() || !rust.join("src").is_dir() {
return Err(format!("{} isn't a Laravel Rust app (no Cargo.toml + src/); create one with `laravel new <name> --rust`", rust.display()));
}
if let (Ok(p), Ok(r)) = (fs::canonicalize(&php), fs::canonicalize(rust)) {
if r.starts_with(&p) {
return Err("the Rust app is inside the PHP app; put it somewhere else (hard rule 2)".into());
}
}
let models = Models::new(&inv, &php);
let mut files: Vec<(String, String)> = models.files();
let (handler_files, wiring, names) = handlers(&inv, &models);
files.extend(handler_files);
files.extend(views(&inv, &php, &names));
let (mut written, mut skipped, mut skipped_notes, mut todos) = (Vec::new(), Vec::new(), Vec::new(), 0);
for (rel, text) in &files {
let path = rust.join(rel);
if path.exists() {
skipped_notes.push(match missing_fields(&path, text) {
Some(m) => format!("- `{rel}`: lacks {m}; add them, or the relations to this model won't compile"),
None => format!("- `{rel}`"),
});
skipped.push(rel.clone());
continue;
}
fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?;
fs::write(&path, text).map_err(|e| format!("{rel}: {e}"))?;
let n = text.lines().skip(1).filter(|l| l.contains("PORT-TODO")).count();
todos += n;
written.push(format!("- `{rel}` ({n} PORT-TODO)"));
}
let mut report = format!(
"# larakiln codegen\n\nGenerated from `{}`. {} files written, {} skipped because they already exist, {todos} `PORT-TODO` markers.\n\n\
Nothing here is wired up yet, and nothing existing was changed. Do the wiring below, run `cargo build`, then work through the `PORT-TODO` markers item by item with `/port-next`.\n\n",
php.display(),
written.len(),
skipped.len()
);
report += &format!("## Wiring\n\n{wiring}{}\n", models.wiring(&skipped));
report += &format!("## Written ({})\n\n{}\n\n", written.len(), written.join("\n"));
if !skipped.is_empty() {
report += &format!(
"## Skipped: already exist ({})\n\nCompare these by hand with what codegen would have written (delete the file and re-run to see it).\n\n{}\n",
skipped.len(),
skipped_notes.join("\n")
);
}
fs::write(rust.join("larakiln-codegen.md"), report).map_err(|e| e.to_string())?;
println!("Wrote {} files ({todos} PORT-TODO), skipped {} existing. Next: follow {}/larakiln-codegen.md", written.len(), skipped.len(), rust.display());
Ok(())
}
fn snake(s: &str) -> String {
let mut out = String::new();
for (i, ch) in s.chars().enumerate() {
if ch.is_uppercase() {
if i > 0 && !out.ends_with('_') {
out.push('_');
}
out.extend(ch.to_lowercase());
} else if ch == '-' || ch == ' ' || ch == '.' {
out.push('_');
} else {
out.push(ch);
}
}
out
}
fn studly(s: &str) -> String {
s.split(['_', '-']).map(|w| {
let mut c = w.chars();
c.next().map(|f| f.to_uppercase().chain(c).collect::<String>()).unwrap_or_default()
}).collect()
}
fn plural(s: &str) -> String {
let consonant_y = s.ends_with('y') && !s.ends_with("ay") && !s.ends_with("ey") && !s.ends_with("oy") && !s.ends_with("uy");
if consonant_y {
format!("{}ies", &s[..s.len() - 1])
} else if ["s", "x", "ch", "sh"].iter().any(|e| s.ends_with(e)) {
format!("{s}es")
} else {
format!("{s}s")
}
}
fn ident(s: &str) -> String {
let s = snake(s);
if RESERVED.contains(&s.as_str()) { format!("{s}_") } else { s }
}
fn missing_fields(existing: &Path, generated: &str) -> Option<String> {
let have = fs::read_to_string(existing).ok()?;
let field = Regex::new(r"(?m)^\s*pub (\w+):").unwrap();
let have: Vec<String> = field.captures_iter(&have).map(|c| c[1].to_string()).collect();
let missing: Vec<String> = field.captures_iter(generated).map(|c| c[1].to_string()).filter(|f| !have.contains(f)).map(|f| format!("`{f}`")).collect();
(!missing.is_empty()).then(|| missing.join(", "))
}
fn class_basename(s: &str) -> &str {
s.rsplit('\\').next().unwrap_or(s)
}
#[derive(Clone)]
struct Column {
name: String,
ty: String,
nullable: bool,
note: Option<String>,
}
struct Models {
list: Vec<(String, Value, String)>,
tables: HashMap<String, Vec<Column>>,
}
impl Models {
fn new(inv: &Value, php: &Path) -> Self {
let list = inv["models"].as_array().into_iter().flatten().map(|m| {
let name = m["id"].as_str().unwrap_or("").trim_start_matches("model:").to_string();
let table = m["table"].as_str().map(String::from).unwrap_or_else(|| plural(&snake(&name)));
(name, m.clone(), table)
}).collect();
let mut models = Models { list, tables: migrations(php) };
models.match_key_types();
models
}
fn match_key_types(&mut self) {
let id_ty = |tables: &HashMap<String, Vec<Column>>, table: &str| -> Option<String> {
tables.get(table)?.iter().find(|c| c.name == "id").map(|c| c.ty.clone())
};
let mut fixes = Vec::new(); for (name, m, table) in &self.list {
for r in m["relations"].as_array().into_iter().flatten() {
let related = r["related"].as_str().unwrap_or("");
let Some((_, _, rtable)) = self.list.iter().find(|(n, _, _)| n == related) else { continue };
match r["type"].as_str() {
Some("belongsTo") => {
let fk = format!("{}_id", snake(r["name"].as_str().unwrap_or("")));
if let Some(t) = id_ty(&self.tables, rtable) {
fixes.push((table.clone(), fk, t));
}
}
Some("hasMany" | "hasOne") => {
if let Some(t) = id_ty(&self.tables, table) {
fixes.push((rtable.clone(), format!("{}_id", snake(name)), t));
}
}
_ => {}
}
}
}
for (table, col, ty) in fixes {
if let Some(c) = self.tables.get_mut(&table).and_then(|cols| cols.iter_mut().find(|c| c.name == col)) {
c.ty = ty;
}
}
}
fn has(&self, name: &str) -> bool {
self.list.iter().any(|(n, _, _)| n == name)
}
fn by_table(&self, table: &str) -> Option<&str> {
self.list.iter().find(|(_, _, t)| t == table).map(|(n, _, _)| n.as_str())
}
fn files(&self) -> Vec<(String, String)> {
self.list.iter().map(|(name, m, table)| (format!("src/models/{}.rs", snake(name)), self.model(name, m, table))).collect()
}
fn wiring(&self, skipped: &[String]) -> String {
let mods: String = self
.list
.iter()
.filter(|(n, _, _)| !skipped.contains(&format!("src/models/{}.rs", snake(n))))
.map(|(n, _, _)| format!("mod {};\npub use {}::{n};\n", snake(n), snake(n)))
.collect();
format!("**`src/models/mod.rs`**: add\n\n```rust\n{mods}```\n\nModels need their migrations too: the PHP app keeps owning the schema while both apps run, so the Rust app reads the same tables. Port migrations only when the Rust app takes the schema over.\n\n")
}
fn model(&self, name: &str, m: &Value, table: &str) -> String {
let mut uses: BTreeSet<&str> = ["model"].into();
let mut extra_uses: BTreeSet<String> = BTreeSet::new();
let mut body = String::new();
let casts = &m["casts"];
let columns = self.tables.get(table);
match columns {
None => body += &format!(" pub id: i64,\n // PORT-TODO: no `Schema::create('{table}')` found in database/migrations; add the columns by hand (`php artisan db:table {table} --json`).\n"),
Some(cols) => {
for c in cols {
let mut ty = c.ty.clone();
let mut serde_skip = false;
let mut note = c.note.clone();
let cast = casts[c.name.as_str()].as_str();
match cast.map(|s| s.split(':').next().unwrap_or(s)) {
Some("hashed") => (ty, serde_skip) = ("PasswordHash".into(), true),
Some("encrypted") if cast == Some("encrypted") => ty = "Encrypted<String>".into(),
Some("encrypted") => {
ty = "Encrypted<serde_json::Value>".into();
note = Some(format!("PORT-TODO: `{}` cast; pick the Rust type", cast.unwrap_or("")));
}
Some("boolean" | "bool") => ty = "bool".into(),
Some("integer" | "int") => ty = "i64".into(),
Some("float" | "double") => ty = "f64".into(),
Some("datetime" | "immutable_datetime" | "timestamp") => ty = "Timestamp".into(),
Some("date" | "immutable_date") => ty = "civil::Date".into(),
Some("array" | "json" | "collection" | "object") => ty = "serde_json::Value".into(),
Some(other) if ty == "String" && !["string"].contains(&other) => note = Some(format!("PORT-TODO: `{other}` cast")),
_ => {}
}
if c.name == "password" && ty == "String" {
(ty, serde_skip) = ("PasswordHash".into(), true);
}
if ty == "RememberToken" {
serde_skip = true;
}
for (needle, path) in [
("Timestamp", "laravel::time::Timestamp"),
("civil::", "laravel::time::civil"),
("PasswordHash", "laravel::hash::PasswordHash"),
("Encrypted", "laravel::crypt::Encrypted"),
("RememberToken", "laravel::auth::RememberToken"),
("Decimal", "laravel::numeric::Decimal"),
] {
if ty.contains(needle) {
extra_uses.insert(path.into());
}
}
if let Some(n) = note {
body += &format!(" // {n}\n");
}
if serde_skip {
body += " #[serde(skip)]\n";
}
let field = ident(&c.name);
if field != c.name {
body += &format!(" #[column(\"{}\")]\n", c.name);
}
let ty = if c.nullable { format!("Option<{ty}>") } else { ty };
body += &format!(" pub {field}: {ty},\n");
}
}
}
for r in m["relations"].as_array().into_iter().flatten() {
let (rname, related, kind) = (r["name"].as_str().unwrap_or("?"), r["related"].as_str().unwrap_or("?"), r["type"].as_str().unwrap_or("?"));
let field = ident(rname);
let attr = match kind {
"belongsTo" => Some(("belongs_to", "BelongsTo")),
"hasMany" => Some(("has_many", "HasMany")),
"hasOne" => Some(("has_one", "HasOne")),
_ => None,
};
match attr {
Some((a, w)) if self.has(related) => {
uses.insert(w);
extra_uses.insert(format!("crate::models::{related}"));
let fk_nullable = columns.is_some_and(|cols| cols.iter().any(|c| c.name == format!("{}_id", snake(rname)) && c.nullable));
let target = if (kind == "belongsTo" && fk_nullable) || kind == "hasOne" { format!("Option<{related}>") } else { related.to_string() };
body += &format!(" #[{a}]\n pub {field}: {w}<{target}>,\n");
}
_ => body += &format!(" // PORT-TODO: `{rname}` is a `{kind}` relation to `{related}`; map it by hand (model-relationships.md).\n"),
}
}
let mut head = format!("// Generated by larakiln codegen from {} and the PHP migrations. Search for PORT-TODO.\n// larakiln: {}\n", m["file"].as_str().unwrap_or("?"), m["id"].as_str().unwrap_or("?"));
head += &format!("use laravel::model::{{{}}};\n", uses.iter().copied().collect::<Vec<_>>().join(", "));
for u in extra_uses.iter().filter(|u| !u.starts_with("crate::")) {
head += &format!("use {u};\n");
}
let crate_uses: Vec<&String> = extra_uses.iter().filter(|u| u.starts_with("crate::")).filter(|u| !u.ends_with(&format!("::{name}"))).collect();
if !crate_uses.is_empty() {
head += "\n";
for u in crate_uses {
head += &format!("use {u};\n");
}
}
let table_attr = if *table == plural(&snake(name)) { "#[model]".to_string() } else { format!("#[model(table = \"{table}\")]") };
format!("{head}\n{table_attr}\npub struct {name} {{\n{body}}}\n")
}
}
fn migrations(php: &Path) -> HashMap<String, Vec<Column>> {
let mut tables: HashMap<String, Vec<Column>> = HashMap::new();
let Ok(dir) = fs::read_dir(php.join("database/migrations")) else { return tables };
let mut files: Vec<PathBuf> = dir.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|e| e == "php")).collect();
files.sort();
let open = Regex::new(r#"Schema::(create|table)\(\s*['"]([^'"]+)['"]"#).unwrap();
for f in files {
let Ok(src) = fs::read_to_string(&f) else { continue };
let src = src.split("function down").next().unwrap_or(&src);
for c in open.captures_iter(src) {
let rest = &src[c.get(0).unwrap().end()..];
let Some(brace) = rest.find('{') else { continue };
let Some(body) = balanced(&rest[brace..], '{', '}') else { continue };
let cols = tables.entry(c[2].to_string()).or_default();
for stmt in body.trim_start_matches('{').split(';') {
apply(cols, stmt.trim());
}
}
}
tables
}
fn apply(cols: &mut Vec<Column>, stmt: &str) {
let call = Regex::new(r#"^\$table->(\w+)\(([^)]*)\)"#).unwrap();
let Some(c) = call.captures(stmt) else { return };
let (method, args) = (&c[1], &c[2]);
let quoted = Regex::new(r#"['"]([^'"]+)['"]"#).unwrap();
let names: Vec<String> = quoted.captures_iter(args).map(|q| q[1].to_string()).collect();
let nullable = stmt.contains("->nullable(");
let col = |name: &str, ty: &str, nullable: bool| Column { name: name.into(), ty: ty.into(), nullable, note: None };
let first = names.first().cloned();
let ty = match method {
"id" | "bigIncrements" | "foreignId" | "unsignedBigInteger" | "bigInteger" => "i64",
"increments" | "integer" | "unsignedInteger" | "mediumInteger" | "smallInteger" | "tinyInteger" | "unsignedSmallInteger" | "unsignedTinyInteger" | "unsignedMediumInteger" | "year" => "i32",
"string" | "char" | "text" | "mediumText" | "longText" | "tinyText" | "uuid" | "ulid" | "enum" | "ipAddress" | "macAddress" | "set" => "String",
"boolean" => "bool",
"decimal" | "unsignedDecimal" => "Decimal",
"float" | "double" => "f64",
"date" => "civil::Date",
"time" | "timeTz" => "civil::Time",
"dateTime" | "dateTimeTz" | "timestamp" | "timestampTz" => "Timestamp",
"json" | "jsonb" => "serde_json::Value",
"binary" => "Vec<u8>",
"foreignIdFor" => {
let class = args.split("::class").next().unwrap_or("").trim();
let name = first.clone().unwrap_or_else(|| format!("{}_id", snake(class_basename(class))));
cols.push(col(&name, "i64", nullable));
return;
}
"timestamps" | "timestampsTz" | "nullableTimestamps" => {
let n = method == "nullableTimestamps";
cols.push(col("created_at", "Timestamp", n));
cols.push(col("updated_at", "Timestamp", n));
return;
}
"softDeletes" | "softDeletesTz" => {
let mut c = col(first.as_deref().unwrap_or("deleted_at"), "Timestamp", true);
c.note = Some("PORT-TODO: soft deletes; check how Laravel Rust handles them before relying on this column".into());
cols.push(c);
return;
}
"rememberToken" => {
cols.push(col("remember_token", "RememberToken", true));
return;
}
"morphs" | "nullableMorphs" | "uuidMorphs" | "ulidMorphs" => {
let base = first.unwrap_or_default();
let n = method == "nullableMorphs";
cols.push(col(&format!("{base}_type"), "String", n));
cols.push(col(&format!("{base}_id"), if method == "morphs" || n { "i64" } else { "String" }, n));
return;
}
"dropColumn" => {
cols.retain(|c| !names.contains(&c.name));
return;
}
"renameColumn" => {
if let [from, to] = names.as_slice() {
if let Some(c) = cols.iter_mut().find(|c| &c.name == from) {
c.name = to.clone();
}
}
return;
}
"index" | "unique" | "primary" | "foreign" | "dropForeign" | "dropIndex" | "dropUnique" | "dropPrimary" | "engine" | "charset"
| "collation" | "comment" | "fullText" | "spatialIndex" | "dropTimestamps" | "dropSoftDeletes" | "dropRememberToken" | "dropMorphs" => return,
other => {
let mut c = col(first.as_deref().unwrap_or(other), "String", nullable);
c.note = Some(format!("PORT-TODO: unmapped column type `$table->{other}(...)`"));
cols.push(c);
return;
}
};
let name = first.unwrap_or_else(|| "id".into());
let nullable = nullable && method != "id";
if let Some(existing) = cols.iter_mut().find(|c| c.name == name) {
*existing = col(&name, ty, nullable); } else {
cols.push(col(&name, ty, nullable));
}
}
fn input_struct(name: &str, req: &Value, auth: &str, models: &Models) -> String {
let id = req["id"].as_str().unwrap_or("?");
let Some(rules) = req["rules"].as_object() else {
return format!("// PORT-TODO: {id} builds its rules at runtime; write `{name}` by hand (validation.md).\n\n");
};
let mut fields = String::new();
for (field, rs) in rules {
let rs: Vec<&str> = rs.as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if field.contains('.') || field.contains('*') {
fields += &format!(" // PORT-TODO: nested field `{field}`: {}\n", rs.join("|"));
continue;
}
let numeric = rs.iter().any(|r| ["integer", "numeric", "decimal"].contains(&r.split(':').next().unwrap_or(r)));
let mut ty = if rs.contains(&"boolean") || rs.contains(&"accepted") {
"bool"
} else if rs.contains(&"integer") {
"i64"
} else if numeric {
"f64"
} else {
"String"
}
.to_string();
let (mut out, mut todo) = (Vec::new(), Vec::new());
for r in &rs {
let (rule, arg) = r.split_once(':').map_or((*r, ""), |(a, b)| (a, b));
let args: Vec<&str> = arg.split(',').filter(|a| !a.is_empty()).collect();
let quoted = || args.iter().map(|a| format!("\"{a}\"")).collect::<Vec<_>>().join(", ");
match rule {
"string" | "integer" | "numeric" | "boolean" => {}
"nullable" => ty = format!("Option<{ty}>"),
"sometimes" => ty = format!("Sometimes<{ty}>"),
"required" | "email" | "url" | "uuid" | "ulid" | "ip" | "ipv4" | "ipv6" | "json" | "alpha" | "alpha_num" | "alpha_dash"
| "ascii" | "lowercase" | "uppercase" | "confirmed" | "accepted" | "declined" | "filled" | "present" | "date" | "timezone"
| "mac_address" | "hex_color" | "bail" => out.push(rule.to_string()),
"max" if numeric => out.push(format!("max_value({arg})")),
"min" if numeric => out.push(format!("min_value({arg})")),
"max" => out.push(format!("max_length({arg})")),
"min" => out.push(format!("min_length({arg})")),
"between" if numeric => out.push(format!("between({arg})")),
"between" if args.len() == 2 => out.extend([format!("min_length({})", args[0]), format!("max_length({})", args[1])]),
"in" => out.push(format!("one_of({})", quoted())),
"not_in" => out.push(format!("not_one_of({})", quoted())),
"digits" | "digits_between" | "same" | "different" | "gt" | "gte" | "lt" | "lte" | "decimal" | "multiple_of" => {
out.push(format!("{rule}({arg})"))
}
"starts_with" | "ends_with" | "doesnt_start_with" | "doesnt_end_with" => out.push(format!("{rule}({})", quoted())),
"after" | "before" | "after_or_equal" | "before_or_equal" if arg == "today" => {
out.push(match rule { "after" => "after_today", "before" => "before_today", "after_or_equal" => "today_or_after", _ => "today_or_before" }.into())
}
"after" | "before" | "after_or_equal" | "before_or_equal" => out.push(format!("{rule}({arg})")),
"unique" if !args.is_empty() => match models.by_table(args[0]) {
Some(model) => out.push(format!("unique({model}::{})", args.get(1).copied().unwrap_or(field.as_str()))),
None => todo.push(r.to_string()),
},
_ => todo.push(r.to_string()),
}
}
if !todo.is_empty() {
fields += &format!(" // PORT-TODO: no verified mapping for {}\n", todo.join(", "));
}
if !out.is_empty() {
fields += &format!(" #[validate({})]\n", out.join(", "));
}
fields += &format!(" pub {}: {ty},\n", ident(field));
}
let authorize = match req["authorize"].as_str() {
Some(a) if a != "true" => format!("// PORT-TODO: the FormRequest's authorize() is `{a}`; use #[validate(authorize(Policy::method, route(\"..\")))]\n"),
_ => String::new(),
};
format!("/// larakiln: {id}\n{authorize}#[laravel::input]\n#[validate({auth})]\npub struct {name} {{\n{fields}}}\n\n")
}
type Modules<'a> = BTreeMap<String, (String, Vec<(&'a Value, String)>)>;
struct Handler {
module: String,
func: String,
method: String,
uri: String,
auth: bool,
api: bool,
}
fn handlers(inv: &Value, models: &Models) -> (Vec<(String, String)>, String, HashMap<String, String>) {
let inertia = inv["app"]["frontend"].as_str().unwrap_or("").starts_with("inertia");
let routes: Vec<&Value> = inv["routes"].as_array().into_iter().flatten().filter(|r| ignored(r, &[]).is_none()).collect();
let mut by_module: Modules = BTreeMap::new();
let mut names = HashMap::new();
let mut table: Vec<Handler> = Vec::new();
for r in &routes {
let class = controller(r);
let action = r["action"].as_str().unwrap_or("Closure");
let method = r["method"].as_str().unwrap_or("GET").to_string();
let uri = r["uri"].as_str().unwrap_or("/").to_string();
let (module, func) = if class == "Closure" {
let slug = uri.trim_matches('/').replace(['/', '-', '.'], "_").replace(['{', '}', '?'], "");
("closures".to_string(), ident(&format!("{}_{}", method.to_lowercase(), if slug.is_empty() { "root".into() } else { slug })))
} else {
let base = class.trim_end_matches("Controller");
let func = action.split_once('@').map_or("handle".to_string(), |(_, m)| if m == "__invoke" { "handle".into() } else { ident(m) });
let module = snake(if base.is_empty() { &class } else { base });
(if module.ends_with('s') { module } else { plural(&module) }, func)
};
if let Some(n) = r["name"].as_str() {
names.insert(n.to_string(), format!("{module}::{func}"));
}
let api = r["middleware"].as_array().into_iter().flatten().any(|m| m == "api");
table.push(Handler { module: module.clone(), func: func.clone(), method, uri, auth: php_auth(r), api });
let entry = by_module.entry(module).or_insert_with(|| (action.split('@').next().unwrap_or(action).to_string(), Vec::new()));
if !entry.1.iter().any(|(_, f)| *f == func) {
entry.1.push((r, func));
}
}
let requests: Vec<&Value> = inv["requests"].as_array().into_iter().flatten().collect();
let mut files = Vec::new();
let param_re = Regex::new(r"\{(\w+)\??\}").unwrap();
for (module, (class, funcs)) in &by_module {
let controller_file = funcs.first().and_then(|(r, _)| r["action"].as_str()).map(|a| class_basename(a.split('@').next().unwrap_or(a)).to_string());
let mut body = String::new();
let mut uses: BTreeSet<String> = BTreeSet::new();
let any_auth = funcs.iter().all(|(r, _)| php_auth(r));
let mut n = 0;
for req in &requests {
let file = req["file"].as_str().unwrap_or("");
let id = req["id"].as_str().unwrap_or("");
let from_controller = controller_file.as_deref().is_some_and(|c| file.ends_with(&format!("/{c}.php")) && id.contains('#'));
let form_request = !id.contains('#') && controller_uses(inv, class, class_basename(id.trim_start_matches("request:")));
if from_controller || form_request {
n += 1;
let name = if form_request {
class_basename(id.trim_start_matches("request:")).trim_end_matches("Request").to_string()
} else {
format!("{}Input{n}", studly(module))
};
body += &input_struct(&name, req, if any_auth { "authenticated" } else { "anyone" }, models);
if req["rules"].as_object().is_some_and(|r| r.values().filter_map(Value::as_array).flatten().any(|v| v.as_str().is_some_and(|s| s.starts_with("unique:")))) {
for (m, _, _) in &models.list {
if body.contains(&format!("unique({m}::")) {
uses.insert(format!("crate::models::{m}"));
}
}
}
if body.contains("Sometimes<") {
uses.insert("laravel::validation::Sometimes".into());
}
}
}
if n > 0 {
body = format!("// PORT-TODO: rename each input struct and take it as the handler's last argument: `Valid(input): Valid<Name>`.\n\n{body}");
}
for (r, func) in funcs {
let method = r["method"].as_str().unwrap_or("GET");
let mut args = Vec::new();
let params: Vec<String> = param_re.captures_iter(r["uri"].as_str().unwrap_or("")).map(|c| c[1].to_string()).collect();
if php_auth(r) {
let me = if params.iter().any(|p| ident(p) == "user") { "_auth_user" } else { "_user" };
args.push(format!("Authenticated({me}): Authenticated<User>"));
uses.insert("crate::models::User".into());
}
let model_params: Vec<(String, String)> = params.iter().map(|p| (p.clone(), studly(p))).collect();
if !params.is_empty() && model_params.iter().all(|(_, m)| models.has(m)) {
for (p, m) in &model_params {
args.push(format!("_{}: {m}", ident(p)));
uses.insert(format!("crate::models::{m}"));
}
} else if params.len() == 1 {
args.push(format!("Params(_{}): Params<String>", ident(¶ms[0])));
} else if !params.is_empty() {
let pats = params.iter().map(|p| format!("_{}", ident(p))).collect::<Vec<_>>().join(", ");
let tys = vec!["String"; params.len()].join(", ");
args.push(format!("Params(({pats})): Params<({tys})>"));
}
let ret = if method != "GET" {
"laravel::Result<Redirect>"
} else if inertia {
uses.insert("laravel::inertia::Page".into());
"laravel::Result<Page>"
} else {
uses.insert("laravel::view::View".into());
"laravel::Result<View>"
};
let action = r["action"].as_str().unwrap_or("Closure");
body += &format!(
"/// larakiln: {} ({})\npub async fn {func}({}) -> {ret} {{\n todo!(\"PORT-TODO: port {}\")\n}}\n\n",
r["id"].as_str().unwrap_or("?"),
class_basename(action),
args.join(", "),
if action == "Closure" { format!("the closure for {method} {}", r["uri"].as_str().unwrap_or("")) } else { action.replace('\\', "\\\\").replace('"', "\\\"") }
);
}
let source = if class == "Closure" { "the PHP closure routes".to_string() } else { class.clone() };
let mut head = format!("// Generated by larakiln codegen from {source}. Search for PORT-TODO.\n#![allow(unused_imports)] // PORT-TODO: remove once every handler is ported\nuse laravel::prelude::*;\n");
for u in uses.iter().filter(|u| !u.starts_with("crate::")) {
head += &format!("use {u};\n");
}
let crate_uses: Vec<String> = uses.iter().filter_map(|u| u.strip_prefix("crate::models::")).map(String::from).collect();
if !crate_uses.is_empty() {
head += &format!("\nuse crate::models::{{{}}};\n", crate_uses.join(", "));
}
files.push((format!("src/http/handlers/{module}.rs"), format!("{head}\n{}", body.trim_end().to_string() + "\n")));
}
let mut wiring = String::new();
let mods: String = by_module.keys().map(|m| format!("pub mod {m};\n")).collect();
wiring += &format!("**`src/http/handlers/mod.rs`**: add\n\n```rust\n{mods}```\n\n");
for (file, api) in [("ported", false), ("ported_api", true)] {
let list: Vec<&Handler> = table.iter().filter(|h| h.api == api).collect();
if list.is_empty() {
continue;
}
let modules: BTreeSet<&str> = list.iter().map(|h| h.module.as_str()).collect();
let line = |h: &Handler| {
let uri = if api { h.uri.strip_prefix("/api").filter(|u| !u.is_empty()).unwrap_or("/").to_string() } else { h.uri.clone() };
let uri = uri.replace('?', "");
format!("route.{}(\"{uri}\", {}::{});", h.method.to_lowercase(), h.module, h.func)
};
let open: Vec<String> = list.iter().filter(|h| !h.auth).map(|h| format!(" {}", line(h))).collect();
let authed: Vec<String> = list.iter().filter(|h| h.auth).map(|h| format!(" {}", line(h))).collect();
let mut text = format!(
"// Generated by larakiln codegen from the PHP route list. Routes behind `auth` in PHP are behind `Authenticate` here.\n{}use laravel::prelude::*;\n\nuse crate::http::handlers::{{{}}};\n\npub fn routes(route: &mut Router) {{\n",
if authed.is_empty() { "" } else { "use laravel::auth::Authenticate;\n" },
modules.iter().copied().collect::<Vec<_>>().join(", ")
);
for l in &open {
text += &format!("{l}\n");
}
if !authed.is_empty() {
text += &format!("\n route.middleware(Authenticate).group(|route| {{\n{}\n }});\n", authed.join("\n"));
}
text += "}\n";
files.push((format!("src/routes/{file}.rs"), text));
let target = if api { "api" } else { "web" };
wiring += &format!(
"**`src/routes/mod.rs`**: add `pub mod {file};`. **`src/routes/{target}.rs`**: call `crate::routes::{file}::routes(route);` at the top of `routes`, before any fallback route, and delete the skeleton's own routes for the same URIs (for example `/` and `/login`), or keep them and remove the generated ones.{}\n\n",
if api { " Laravel Rust already prefixes API routes with `/api`, so the generated URIs don't repeat it." } else { "" }
);
}
(files, wiring, names)
}
fn controller_uses(inv: &Value, class: &str, request: &str) -> bool {
let php = Path::new(inv["app"]["path"].as_str().unwrap_or(""));
let rel = class.trim_start_matches("App\\").replace('\\', "/");
fs::read_to_string(php.join("app").join(format!("{rel}.php"))).is_ok_and(|s| s.contains(request))
}
fn views(inv: &Value, php: &Path, names: &HashMap<String, String>) -> Vec<(String, String)> {
inv["views"].as_array().into_iter().flatten().filter_map(|v| {
let file = v["file"].as_str()?;
let name = v["id"].as_str()?.trim_start_matches("view:");
let src = fs::read_to_string(php.join(file)).ok()?;
let out = format!("{{# Generated by larakiln codegen from {file}. Search for PORT-TODO. #}}\n{{# larakiln: view:{name} #}}\n{}", blade_to_jinja(&src, names));
Some((format!("resources/views/{}.html", name.replace('.', "/")), out))
}).collect()
}
fn unquote(s: &str) -> String {
s.trim().trim_matches(['\'', '"']).to_string()
}
fn split_args(s: &str) -> Vec<String> {
let (mut out, mut cur, mut depth, mut quote) = (Vec::new(), String::new(), 0, None);
for ch in s.chars() {
match (quote, ch) {
(Some(q), c) if c == q => quote = None,
(Some(_), _) => {}
(None, '\'' | '"') => quote = Some(ch),
(None, '(' | '[') => depth += 1,
(None, ')' | ']') => depth -= 1,
(None, ',') if depth == 0 => {
out.push(cur.trim().to_string());
cur.clear();
continue;
}
_ => {}
}
cur.push(ch);
}
if !cur.trim().is_empty() {
out.push(cur.trim().to_string());
}
out
}
fn expr(e: &str, names: &HashMap<String, String>) -> (String, bool) {
let mut s = e.trim().to_string();
let route = Regex::new(r#"route\(\s*'([^']+)'"#).unwrap();
let mut unknown_route = false;
s = route.replace_all(&s, |c: ®ex::Captures| match names.get(&c[1]) {
Some(h) => format!("route(\"{h}\""),
None => {
unknown_route = true;
format!("route(\"{}\"", &c[1])
}
}).into_owned();
let format = Regex::new(r"->format\(([^)]*)\)").unwrap();
let php_date_format = format.is_match(&s); s = format.replace_all(&s, "|date($1)").into_owned();
s = s.replace("->diffForHumans()", "|for_humans");
s = Regex::new(r"count\(\s*\$(\w+)\s*\)").unwrap().replace_all(&s, "$1|length").into_owned();
s = s.replace("->", ".").replace("===", "==").replace("!==", "!=").replace("&&", " and ").replace("||", " or ");
s = Regex::new(r"!([^=])").unwrap().replace_all(&s, "not $1").into_owned();
s = Regex::new(r"\bnull\b").unwrap().replace_all(&s, "none").into_owned();
s = Regex::new(r"\$(\w+)").unwrap().replace_all(&s, "$1").into_owned();
s = Regex::new(r"'([^'\x22]*)'").unwrap().replace_all(&s, "\"$1\"").into_owned();
s = Regex::new(r"\s+").unwrap().replace_all(&s, " ").trim().to_string();
let allowed = ["route", "old", "url", "csrf_field", "vite", "session", "error", "asset", "date"];
let code = Regex::new(r#""[^"]*""#).unwrap().replace_all(&s, "\"\"").into_owned(); let calls_ok = Regex::new(r"(\w+)\(").unwrap().captures_iter(&code).all(|c| allowed.contains(&&c[1]));
let todo = unknown_route || php_date_format || code.contains("::") || code.contains("this.") || !calls_ok;
(s, todo)
}
fn blade_to_jinja(src: &str, names: &HashMap<String, String>) -> String {
let mut s = Regex::new(r"(?s)\{\{--(.*?)--\}\}").unwrap().replace_all(src, "{#$1#}").into_owned();
s = Regex::new(r#"(?s)@error\(\s*['"]([^'"]+)['"]\s*\)(.*?)@enderror"#).unwrap().replace_all(&s, |c: ®ex::Captures| {
format!("@error('{}'){}@enderror", &c[1], c[2].replace("$message", &format!("error('{}')", &c[1])))
}).into_owned();
s = Regex::new(r"(?s)(^|[^@])\{\{(.*?)\}\}").unwrap().replace_all(&s, |c: ®ex::Captures| {
let (e, todo) = expr(&c[2], names);
format!("{}{{{{ {e} }}}}{}", &c[1], if todo { " {# PORT-TODO: check expression #}" } else { "" })
}).into_owned();
s = Regex::new(r"(?s)\{!!(.*?)!!\}").unwrap().replace_all(&s, |c: ®ex::Captures| {
let (e, todo) = expr(&c[1], names);
format!("{{{{ {e}|safe }}}}{}", if todo { " {# PORT-TODO: check expression #}" } else { "" })
}).into_owned();
let at = Regex::new(r"(^|[\s>])@(\w+)").unwrap();
let loop_re = Regex::new(r"^(.*)\s+as\s+(?:\$(\w+)\s*=>\s*)?\$(\w+)$").unwrap();
let mut out = String::new();
let mut rest = s.as_str();
let mut stack: Vec<String> = Vec::new();
while let Some(c) = at.captures(rest) {
let m = c.get(0).unwrap();
let name = c[2].to_string();
out += &rest[..m.start()];
out += &c[1];
let mut after = &rest[m.end()..];
let mut arg: Option<String> = None;
let trimmed = after.trim_start_matches([' ', '\t']);
if trimmed.starts_with('(') {
if let Some(b) = balanced(trimmed, '(', ')') {
arg = Some(b[1..b.len() - 1].to_string());
after = &trimmed[b.len()..];
}
}
let a = arg.clone().unwrap_or_default();
let ex = |e: &str| {
let (x, todo) = expr(e, names);
(x, if todo { " {# PORT-TODO: check expression #}" } else { "" })
};
let text: String = match name.as_str() {
"extends" => format!("{{% extends \"{}\" %}}", unquote(&split_args(&a)[0])),
"section" => {
let args = split_args(&a);
if args.len() > 1 {
let (v, t) = ex(&args[1]);
format!("{{% block {} %}}{{{{ {v} }}}}{{% endblock %}}{t}", unquote(&args[0]))
} else {
format!("{{% block {} %}}", unquote(&a))
}
}
"endsection" | "stop" | "show" => "{% endblock %}".into(),
"yield" => {
let args = split_args(&a);
let default = args.get(1).map(|d| unquote(d)).unwrap_or_default();
format!("{{% block {} %}}{default}{{% endblock %}}", unquote(&args[0]))
}
"include" => {
let args = split_args(&a);
format!("{{% include \"{}\" %}}{}", unquote(&args[0]), if args.len() > 1 { " {# PORT-TODO: pass the include's data #}" } else { "" })
}
"foreach" | "forelse" => {
stack.push(name.clone());
match loop_re.captures(a.trim()) {
Some(f) => {
let (list, t) = ex(&f[1]);
match f.get(2) {
Some(k) => format!("{{% for {}, {} in {list}|items %}}{t}", k.as_str(), &f[3]),
None => format!("{{% for {} in {list} %}}{t}", &f[3]),
}
}
None => format!("{{# PORT-TODO: @{name}({a}) #}}"),
}
}
"empty" if stack.last().is_some_and(|t| t == "forelse") && arg.is_none() => "{% else %}".into(),
"endforeach" | "endforelse" => {
stack.pop();
"{% endfor %}".into()
}
"if" => {
let (x, t) = ex(&a);
format!("{{% if {x} %}}{t}")
}
"elseif" => {
let (x, t) = ex(&a);
format!("{{% elif {x} %}}{t}")
}
"else" => "{% else %}".into(),
"unless" => {
let (x, t) = ex(&a);
format!("{{% if not ({x}) %}}{t}")
}
"isset" => {
let (x, t) = ex(&a);
format!("{{% if {x} is defined and {x} is not none %}}{t}")
}
"empty" => {
let (x, t) = ex(&a);
format!("{{% if not {x} %}}{t}")
}
"endif" | "endunless" | "endisset" | "endempty" => "{% endif %}".into(),
"csrf" => "{{ csrf_field() }}".into(),
"method" => format!("<input type=\"hidden\" name=\"_method\" value=\"{}\">", unquote(&a).to_uppercase()),
"error" => format!("{{% if error(\"{}\") %}}", unquote(&split_args(&a)[0])),
"enderror" => "{% endif %}".into(),
"vite" => {
let inner = a.trim().trim_start_matches('[').trim_end_matches(']');
split_args(inner).iter().map(|f| format!("{{{{ vite(\"{}\") }}}}", unquote(f))).collect()
}
"json" => {
let (x, t) = ex(&split_args(&a)[0]);
format!("{{{{ {x}|tojson }}}}{t}")
}
"inertia" => "{{ inertia }}".into(),
"inertiaHead" => "{{ inertia_head }}".into(),
_ if name.chars().next().is_some_and(char::is_lowercase) => {
format!("{{# PORT-TODO: @{name}{} has no verified Jinja mapping #}}", arg.map(|a| format!("({a})")).unwrap_or_default())
}
_ => format!("@{name}"),
};
out += &text;
rest = after;
}
out += rest;
let components = Regex::new(r"<(x-[\w.\-:]+|livewire:[\w.\-]+)").unwrap();
components.replace_all(&out, "{# PORT-TODO: Blade component <$1> #}<$1").into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn migrations_become_columns() {
let mut cols = Vec::new();
for s in [
"{\n $table->id()".trim_start_matches('{').trim(),
"$table->foreignId('user_id')->constrained()->cascadeOnDelete()",
"$table->string('message')",
"$table->timestamp('seen_at')->nullable()",
"$table->unique('message')",
"$table->timestamps()",
"$table->rememberToken()",
] {
apply(&mut cols, s);
}
let got: Vec<(String, String, bool)> = cols.into_iter().map(|c| (c.name, c.ty, c.nullable)).collect();
let want = [("id", "i64", false), ("user_id", "i64", false), ("message", "String", false), ("seen_at", "Timestamp", true), ("created_at", "Timestamp", false), ("updated_at", "Timestamp", false), ("remember_token", "RememberToken", true)];
assert_eq!(got, want.map(|(a, b, c)| (a.to_string(), b.to_string(), c)));
}
#[test]
fn rules_become_validate_attributes() {
let models = Models { list: vec![("User".into(), json!({}), "users".into())], tables: HashMap::new() };
let req = json!({"id": "request:X#1", "rules": {
"message": ["required", "string", "max:255"],
"age": ["nullable", "integer", "min:18"],
"email": ["required", "email", "unique:users,email"],
"role": ["in:admin,editor"],
"photo": ["image"]
}});
let s = input_struct("NewChirp", &req, "authenticated", &models);
assert!(s.contains("#[validate(authenticated)]\npub struct NewChirp"), "{s}");
assert!(s.contains("#[validate(required, max_length(255))]\n pub message: String,"), "{s}");
assert!(s.contains("#[validate(min_value(18))]\n pub age: Option<i64>,"), "{s}");
assert!(s.contains("#[validate(required, email, unique(User::email))]"), "{s}");
assert!(s.contains("one_of(\"admin\", \"editor\")"), "{s}");
assert!(s.contains("PORT-TODO: no verified mapping for image"), "{s}");
}
#[test]
fn blade_becomes_jinja() {
let names: HashMap<String, String> = [("chirps.store".to_string(), "chirps::store".to_string()), ("chirps.edit".to_string(), "chirps::edit".to_string())].into();
let blade = "@extends('layout')\n@section('content')\n<form action=\"{{ route('chirps.store') }}\">\n@csrf\n@method('delete')\n@error('message')\n<p>{{ $message }}</p>\n@enderror\n@foreach ($chirps as $chirp)\n<a href=\"{{ route('chirps.edit', $chirp) }}\">{{ $chirp->user->name }}</a>\n@if ($chirp->user->is(auth()->user()))\nx\n@endif\n@endforeach\n@endsection\nmail@example.com\n";
let j = blade_to_jinja(blade, &names);
for want in [
"{% extends \"layout\" %}",
"{% block content %}",
"{{ route(\"chirps::store\") }}",
"{{ csrf_field() }}",
"value=\"DELETE\"",
"{% if error(\"message\") %}\n<p>{{ error(\"message\") }}</p>\n{% endif %}",
"{% for chirp in chirps %}",
"{{ route(\"chirps::edit\", chirp) }}",
"{{ chirp.user.name }}",
"{% if chirp.user.is(auth().user()) %} {# PORT-TODO: check expression #}",
"action=\"{{ route(\"chirps::store\") }}\">",
"{% endfor %}\n{% endblock %}",
"mail@example.com",
] {
assert!(j.contains(want), "missing {want:?} in:\n{j}");
}
}
#[test]
fn foreign_keys_take_their_keys_type() {
let col = |name: &str, ty: &str| Column { name: name.into(), ty: ty.into(), nullable: false, note: None };
let mut models = Models {
list: vec![
("Account".into(), json!({"relations": [{"name": "contacts", "related": "Contact", "type": "hasMany"}]}), "accounts".into()),
("Contact".into(), json!({"relations": [{"name": "organization", "related": "Organization", "type": "belongsTo"}]}), "contacts".into()),
("Organization".into(), json!({}), "organizations".into()),
],
tables: HashMap::from([
("accounts".into(), vec![col("id", "i32")]),
("contacts".into(), vec![col("id", "i64"), col("account_id", "i64"), col("organization_id", "i64")]),
("organizations".into(), vec![col("id", "i32")]),
]),
};
models.match_key_types();
let ty = |c: &str| models.tables["contacts"].iter().find(|x| x.name == c).unwrap().ty.clone();
assert_eq!((ty("account_id"), ty("organization_id"), ty("id")), ("i32".into(), "i32".into(), "i64".into()));
}
}