sal/src/cmd/herodo.rs
2025-04-04 18:21:16 +02:00

84 lines
2.4 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 the directory containing Rhai scripts
///
/// # Returns
///
/// Result indicating success or failure
pub fn run(script_path: &str) -> Result<(), Box<dyn Error>> {
let script_dir = Path::new(script_path);
// Check if the directory exists
if !script_dir.exists() || !script_dir.is_dir() {
eprintln!("Error: '{}' is not a valid directory", 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)?;
// Find all .rhai files in the directory
let mut script_files: Vec<PathBuf> = fs::read_dir(script_dir)?
.filter_map(Result::ok)
.filter(|entry| {
entry.path().is_file() &&
entry.path().extension().map_or(false, |ext| ext == "rhai")
})
.map(|entry| entry.path())
.collect();
// Sort the script files by name
script_files.sort();
if script_files.is_empty() {
println!("No Rhai scripts found in '{}'", script_path);
return Ok(());
}
println!("Found {} Rhai scripts to execute:", script_files.len());
// 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);
// Continue with the next script instead of stopping
}
}
}
println!("\nAll scripts executed");
Ok(())
}