Files
osiris/examples/engine/main.rs
Timur Gordon 87c556df7a wip
2025-10-29 16:52:33 +01:00

85 lines
3.0 KiB
Rust

/// OSIRIS Engine Example
///
/// Demonstrates how to create an OSIRIS engine with the package
/// and execute multiple Rhai scripts
use osiris::register_osiris_full;
use rhai::Engine;
use std::fs;
use std::path::Path;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("=== OSIRIS Engine Example ===\n");
// Get all .rhai files in the current directory
let example_dir = Path::new(file!()).parent().unwrap();
let mut rhai_files: Vec<_> = fs::read_dir(example_dir)?
.filter_map(|entry| entry.ok())
.filter(|entry| {
entry.path().extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext == "rhai")
.unwrap_or(false)
})
.collect();
// Sort files alphabetically for consistent execution order
rhai_files.sort_by_key(|entry| entry.file_name());
if rhai_files.is_empty() {
println!("No .rhai files found in examples/engine/");
return Ok(());
}
println!("Found {} Rhai script(s):\n", rhai_files.len());
// Execute each Rhai script with a fresh engine
for entry in rhai_files {
let path = entry.path();
let filename = path.file_name().unwrap().to_string_lossy();
println!("─────────────────────────────────────");
println!("Running: {}", filename);
println!("─────────────────────────────────────");
// Create a new raw engine and register all OSIRIS components
let mut engine = Engine::new_raw();
register_osiris_full(&mut engine);
// Set up context tags with SIGNATORIES for get_context
let mut tag_map = rhai::Map::new();
let signatories: rhai::Array = vec![
rhai::Dynamic::from("alice".to_string()),
rhai::Dynamic::from("bob".to_string()),
rhai::Dynamic::from("charlie".to_string()),
];
tag_map.insert("SIGNATORIES".into(), rhai::Dynamic::from(signatories));
tag_map.insert("DB_PATH".into(), "/tmp/osiris_example".to_string().into());
tag_map.insert("CONTEXT_ID".into(), "example_context".to_string().into());
engine.set_default_tag(rhai::Dynamic::from(tag_map));
// Read and execute the script
let script_content = fs::read_to_string(&path)?;
match engine.eval::<rhai::Dynamic>(&script_content) {
Ok(result) => {
println!("\n✓ Success!");
if !result.is_unit() {
println!("Result: {}", result);
}
}
Err(e) => {
println!("\n✗ Error: {}", e);
}
}
println!();
}
println!("─────────────────────────────────────");
println!("All scripts executed!");
Ok(())
}