sal/examples/rhai_process_example.rs
2025-04-04 15:28:50 +02:00

67 lines
2.1 KiB
Rust

//! Example of using the Rhai integration with SAL Process module
//!
//! This example demonstrates how to use the Rhai scripting language
//! with the System Abstraction Layer (SAL) Process module.
use rhai::{Engine, Map, Dynamic};
use sal::rhai;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a new Rhai engine
let mut engine = Engine::new();
// Register SAL functions with the engine
rhai::register(&mut engine)?;
// Run a Rhai script that uses SAL Process functions
let script = r#"
// Check if a command exists
let ls_exists = which("ls");
// Run a simple command
let echo_result = run_command("echo 'Hello from Rhai!'");
// Run a command silently
let silent_result = run_silent("ls -la");
// List processes
let processes = process_list("");
// Return a map with all the results
{
ls_exists: ls_exists,
echo_stdout: echo_result.stdout,
echo_success: echo_result.success,
silent_success: silent_result.success,
process_count: processes.len()
}
"#;
// Evaluate the script and get the results
let result = engine.eval::<Map>(script)?;
// Print the results
println!("Script results:");
if let Some(ls_exists) = result.get("ls_exists") {
println!(" ls command exists: {}", ls_exists);
}
if let Some(echo_stdout) = result.get("echo_stdout") {
println!(" Echo command output: {}", echo_stdout.clone().into_string().unwrap());
}
if let Some(echo_success) = result.get("echo_success") {
println!(" Echo command success: {}", echo_success.clone().as_bool().unwrap());
}
if let Some(silent_success) = result.get("silent_success") {
println!(" Silent command success: {}", silent_success.clone().as_bool().unwrap());
}
if let Some(process_count) = result.get("process_count") {
println!(" Number of processes: {}", process_count.clone().as_int().unwrap());
}
Ok(())
}