sal/src/cmd/herodo.rs
2025-04-04 18:38:53 +02:00

117 lines
3.6 KiB
Rust

//! Herodo - A Rhai script executor for SAL
//!
//! This binary loads the Rhai engine, registers all SAL modules,
//! and executes Rhai scripts from a specified directory in sorted order.
// Removed unused imports
use rhai::Engine;
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use std::process;
/// Run the herodo script executor with the given script path
///
/// # Arguments
///
/// * `script_path` - Path to a Rhai script file or directory containing Rhai scripts
///
/// # Returns
///
/// Result indicating success or failure
pub fn run(script_path: &str) -> Result<(), Box<dyn Error>> {
let path = Path::new(script_path);
// Check if the path exists
if !path.exists() {
eprintln!("Error: '{}' does not exist", script_path);
process::exit(1);
}
// Create a new Rhai engine
let mut engine = Engine::new();
// Register println function for output
engine.register_fn("println", |s: &str| println!("{}", s));
// Register all SAL modules with the engine
crate::rhai::register(&mut engine)?;
// Determine if the path is a file or directory
let script_files: Vec<PathBuf> = if path.is_file() {
// Check if it's a .rhai file
if path.extension().map_or(false, |ext| ext == "rhai") {
vec![path.to_path_buf()]
} else {
eprintln!("Error: '{}' is not a Rhai script file", script_path);
process::exit(1);
}
} else if path.is_dir() {
// Find all .rhai files in the directory recursively
let mut files: Vec<PathBuf> = Vec::new();
// Helper function to recursively find .rhai files
fn find_rhai_files(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
find_rhai_files(&path, files)?;
} else if path.is_file() &&
path.extension().map_or(false, |ext| ext == "rhai") {
files.push(path);
}
}
}
Ok(())
}
// Find all .rhai files recursively
find_rhai_files(path, &mut files)?;
// Sort the script files by name
files.sort();
if files.is_empty() {
println!("No Rhai scripts found in '{}'", script_path);
return Ok(());
}
files
} else {
eprintln!("Error: '{}' is neither a file nor a directory", script_path);
process::exit(1);
};
println!("Found {} Rhai script{} to execute:",
script_files.len(),
if script_files.len() == 1 { "" } else { "s" });
// Execute each script in sorted order
for script_file in script_files {
println!("\nExecuting: {}", script_file.display());
// Read the script content
let script = fs::read_to_string(&script_file)?;
// Execute the script
match engine.eval::<rhai::Dynamic>(&script) {
Ok(result) => {
println!("Script executed successfully");
if !result.is_unit() {
println!("Result: {}", result);
}
},
Err(err) => {
eprintln!("Error executing script: {}", err);
// Exit with error code when a script fails
process::exit(1);
}
}
}
println!("\nAll scripts executed");
Ok(())
}