This commit is contained in:
2025-04-04 18:21:16 +02:00
parent eca7e6f552
commit c9b4010089
18 changed files with 1018 additions and 45 deletions

View File

@@ -2,7 +2,7 @@
//!
//! This module provides Rhai wrappers for the functions in the Process module.
use rhai::{Engine, EvalAltResult, Array, Dynamic};
use rhai::{Engine, EvalAltResult, Array, Dynamic, Map};
use crate::process::{self, CommandResult, ProcessInfo, RunError, ProcessError};
/// Register Process module functions with the Rhai engine
@@ -21,6 +21,8 @@ pub fn register_process_module(engine: &mut Engine) -> Result<(), Box<EvalAltRes
// Register run functions
engine.register_fn("run_command", run_command);
engine.register_fn("run_silent", run_silent);
engine.register_fn("run", run_with_options);
engine.register_fn("new_run_options", new_run_options);
// Register process management functions
engine.register_fn("which", which);
@@ -51,9 +53,6 @@ fn register_process_types(engine: &mut Engine) -> Result<(), Box<EvalAltResult>>
engine.register_get("memory", |p: &mut ProcessInfo| p.memory);
engine.register_get("cpu", |p: &mut ProcessInfo| p.cpu);
// Register error conversion functions
engine.register_fn("to_string", |err: &str| err.to_string());
Ok(())
}
@@ -76,6 +75,16 @@ fn process_error_to_rhai_error<T>(result: Result<T, ProcessError>) -> Result<T,
})
}
/// Create a new Map with default run options
pub fn new_run_options() -> Map {
let mut map = Map::new();
map.insert("die".into(), Dynamic::from(true));
map.insert("silent".into(), Dynamic::from(false));
map.insert("async_exec".into(), Dynamic::from(false));
map.insert("log".into(), Dynamic::from(false));
map
}
//
// Run Function Wrappers
//
@@ -94,6 +103,50 @@ pub fn run_silent(command: &str) -> Result<CommandResult, Box<EvalAltResult>> {
run_error_to_rhai_error(process::run_silent(command))
}
/// Run a command with options specified in a Map
///
/// This provides a builder-style interface for Rhai scripts.
///
/// # Example
///
/// ```rhai
/// let options = new_run_options();
/// options.die = false;
/// options.silent = true;
/// let result = run("echo Hello", options);
/// ```
pub fn run_with_options(command: &str, options: Map) -> Result<CommandResult, Box<EvalAltResult>> {
let mut builder = process::run(command);
// Apply options from the map
if let Some(die) = options.get("die") {
if let Ok(die_val) = die.clone().as_bool() {
builder = builder.die(die_val);
}
}
if let Some(silent) = options.get("silent") {
if let Ok(silent_val) = silent.clone().as_bool() {
builder = builder.silent(silent_val);
}
}
if let Some(async_exec) = options.get("async_exec") {
if let Ok(async_val) = async_exec.clone().as_bool() {
builder = builder.async_exec(async_val);
}
}
if let Some(log) = options.get("log") {
if let Ok(log_val) = log.clone().as_bool() {
builder = builder.log(log_val);
}
}
// Execute the command
run_error_to_rhai_error(builder.execute())
}
//
// Process Management Function Wrappers
//