use console::style;
use std::fs;
use std::path::Path;
use crate::templates;
pub fn run(name: String) {
let struct_name = to_pascal_case(&name);
let struct_name = if struct_name.ends_with("Action") {
struct_name
} else {
format!("{struct_name}Action")
};
let file_name = to_snake_case(&struct_name);
if !is_valid_identifier(&file_name) {
eprintln!(
"{} '{}' is not a valid action name",
style("Error:").red().bold(),
name
);
std::process::exit(1);
}
let actions_dir = Path::new("src/actions");
let action_file = actions_dir.join(format!("{file_name}.rs"));
let mod_file = actions_dir.join("mod.rs");
if !actions_dir.exists() {
eprintln!(
"{} Actions directory not found at src/actions",
style("Error:").red().bold()
);
eprintln!(
"{}",
style("Make sure you're in a Ferro project root directory.").dim()
);
eprintln!(
"{}",
style("You can create the directory with: mkdir -p src/actions").dim()
);
std::process::exit(1);
}
if action_file.exists() {
eprintln!(
"{} Action '{}' already exists at {}",
style("Info:").yellow().bold(),
struct_name,
action_file.display()
);
std::process::exit(0);
}
if mod_file.exists() {
let mod_content = fs::read_to_string(&mod_file).unwrap_or_default();
let mod_decl = format!("mod {file_name};");
let pub_mod_decl = format!("pub mod {file_name};");
if mod_content.contains(&mod_decl) || mod_content.contains(&pub_mod_decl) {
eprintln!(
"{} Module '{}' is already declared in src/actions/mod.rs",
style("Info:").yellow().bold(),
file_name
);
std::process::exit(0);
}
}
let action_content = templates::action_template(&file_name, &struct_name);
if let Err(e) = fs::write(&action_file, action_content) {
eprintln!(
"{} Failed to write action file: {}",
style("Error:").red().bold(),
e
);
std::process::exit(1);
}
println!("{} Created {}", style("✓").green(), action_file.display());
if mod_file.exists() {
if let Err(e) = update_mod_file(&mod_file, &file_name) {
eprintln!(
"{} Failed to update mod.rs: {}",
style("Error:").red().bold(),
e
);
std::process::exit(1);
}
println!("{} Updated src/actions/mod.rs", style("✓").green());
} else {
let mod_content = format!("pub mod {file_name};\n");
if let Err(e) = fs::write(&mod_file, mod_content) {
eprintln!(
"{} Failed to create mod.rs: {}",
style("Error:").red().bold(),
e
);
std::process::exit(1);
}
println!("{} Created src/actions/mod.rs", style("✓").green());
}
println!();
println!(
"Action {} created successfully!",
style(&struct_name).cyan().bold()
);
println!();
println!("Usage:");
println!(
" {} Resolve from container in your controller:",
style("1.").dim()
);
println!(" let action: {struct_name} = App::get().unwrap();");
println!(" action.execute();");
println!();
}
fn is_valid_identifier(name: &str) -> bool {
if name.is_empty() {
return false;
}
let mut chars = name.chars();
match chars.next() {
Some(c) if c.is_alphabetic() || c == '_' => {}
_ => return false,
}
chars.all(|c| c.is_alphanumeric() || c == '_')
}
fn to_snake_case(s: &str) -> String {
let mut result = String::new();
for (i, c) in s.chars().enumerate() {
if c.is_uppercase() {
if i > 0 {
result.push('_');
}
result.push(c.to_lowercase().next().unwrap());
} else {
result.push(c);
}
}
result
}
fn to_pascal_case(s: &str) -> String {
let mut result = String::new();
let mut capitalize_next = true;
for c in s.chars() {
if c == '_' || c == '-' || c == ' ' {
capitalize_next = true;
} else if capitalize_next {
result.push(c.to_uppercase().next().unwrap());
capitalize_next = false;
} else {
result.push(c);
}
}
result
}
fn update_mod_file(mod_file: &Path, file_name: &str) -> Result<(), String> {
let content =
fs::read_to_string(mod_file).map_err(|e| format!("Failed to read mod.rs: {e}"))?;
let pub_mod_decl = format!("pub mod {file_name};");
let mut lines: Vec<&str> = content.lines().collect();
let mut last_pub_mod_idx = None;
for (i, line) in lines.iter().enumerate() {
if line.trim().starts_with("pub mod ") {
last_pub_mod_idx = Some(i);
}
}
let insert_idx = match last_pub_mod_idx {
Some(idx) => idx + 1,
None => {
let mut insert_idx = 0;
for (i, line) in lines.iter().enumerate() {
if line.starts_with("//!") || line.is_empty() {
insert_idx = i + 1;
} else {
break;
}
}
insert_idx
}
};
lines.insert(insert_idx, &pub_mod_decl);
let new_content = lines.join("\n");
fs::write(mod_file, new_content).map_err(|e| format!("Failed to write mod.rs: {e}"))?;
Ok(())
}