use std::fs;
use std::path::{Path, PathBuf};
use laravel::console::{Console, command};
use crate::registry;
use crate::support::{pascal, snake};
const ACTION_STUB: &str = include_str!("stubs/action.stub");
const MODEL_ACTION_STUB: &str = include_str!("stubs/model-action.stub");
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Generated {
pub path: PathBuf,
pub class: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GenerateError {
EmptyName,
Exists(PathBuf),
Io(String),
}
pub fn generate(base: &Path, name: &str, model: Option<&str>) -> Result<Generated, GenerateError> {
let segments: Vec<&str> = name
.split(['/', '\\'])
.flat_map(|segment| segment.split("::"))
.filter(|segment| !segment.is_empty())
.collect();
let Some((last, folders)) = segments.split_last() else {
return Err(GenerateError::EmptyName);
};
let class = pascal(last);
let file = snake(last);
let (stub, directories) = match model {
Some(model) => {
let model = model.trim_matches('\\').trim_matches(':');
let name = model
.rsplit("::")
.next()
.unwrap_or(model)
.rsplit('\\')
.next()
.unwrap_or(model);
let path = if model.contains("::") || model.contains('\\') {
model.replace('\\', "::")
} else {
format!("crate::models::{model}")
};
let stub = MODEL_ACTION_STUB
.replace("{{ class }}", &class)
.replace("{{ modelFullName }}", &path)
.replace("{{ modelName }}", name)
.replace("{{ modelVariable }}", &snake(name));
(stub, vec![snake(name)])
}
None => (
ACTION_STUB.replace("{{ class }}", &class),
folders.iter().map(|folder| snake(folder)).collect(),
),
};
let mut relative = PathBuf::from("src/actions");
for directory in &directories {
relative.push(directory);
}
let directory = base.join(&relative);
let path = directory.join(format!("{file}.rs"));
if path.exists() {
return Err(GenerateError::Exists(relative.join(format!("{file}.rs"))));
}
let io = |error: std::io::Error| GenerateError::Io(error.to_string());
fs::create_dir_all(&directory).map_err(io)?;
fs::write(&path, stub).map_err(io)?;
declare(&base.join("src/actions"), &directories, &file).map_err(io)?;
Ok(Generated {
path: relative.join(format!("{file}.rs")),
class,
})
}
fn declare(root: &Path, directories: &[String], file: &str) -> std::io::Result<()> {
let mut chain: Vec<(PathBuf, String)> = Vec::new();
let mut directory = root.to_path_buf();
for name in directories {
chain.push((directory.clone(), name.clone()));
directory.push(name);
}
chain.push((directory, file.to_owned()));
for (directory, module) in chain {
let mod_file = directory.join("mod.rs");
let line = format!("pub mod {module};");
let current = fs::read_to_string(&mod_file).unwrap_or_default();
if current.lines().any(|existing| existing.trim() == line) {
continue;
}
fs::create_dir_all(&directory)?;
let mut next = current;
if !next.is_empty() && !next.ends_with('\n') {
next.push('\n');
}
next.push_str(&line);
next.push('\n');
fs::write(mod_file, next)?;
}
Ok(())
}
#[command("make:action")]
pub async fn make_action(
name: String,
#[arg(long)]
model: Option<String>,
console: &mut Console,
) -> laravel::Result<u8> {
let base = laravel::config().app.base_path.clone();
match generate(&base, &name, model.as_deref()) {
Ok(generated) => {
console.success(format!("Action [{}] created successfully.", generated.path.display()));
let declared = fs::read_to_string(base.join("src/lib.rs"))
.map(|lib| lib.contains("mod actions"))
.unwrap_or(true);
if !declared {
console.line("Declare the module in src/lib.rs: pub mod actions;");
}
Ok(0)
}
Err(GenerateError::Exists(path)) => {
console.error(format!("Action already exists. [{}]", path.display()));
Ok(1)
}
Err(GenerateError::EmptyName) => {
console.error("The action needs a name.");
Ok(1)
}
Err(GenerateError::Io(error)) => {
console.error(format!("Could not write the action: {error}"));
Ok(1)
}
}
}
#[command("list:actions")]
pub async fn list_actions(console: &mut Console) -> laravel::Result<()> {
let actions = registry::all();
if actions.is_empty() {
console.warn("No action files found.");
return Ok(());
}
console.info("Available Actions:");
for registration in actions {
console.line(format!("- {}", registration.name()));
}
Ok(())
}