feat: add system command utils

This commit is contained in:
Ryan 2025-02-22 12:33:39 -05:00
parent b7a5ae03f6
commit 9b586e9b47
Signed by: ErrorNoInternet
GPG Key ID: 2486BFB7B1E6A4A3
2 changed files with 71 additions and 1 deletions

View File

@ -5,6 +5,7 @@ pub mod direction;
pub mod events;
pub mod logging;
pub mod player;
pub mod utils;
pub mod vec3;
use mlua::{Lua, Table};
@ -30,7 +31,8 @@ pub fn register_functions(lua: &Lua, globals: &Table) -> mlua::Result<()> {
)?;
block::register_functions(lua, globals)?;
logging::register_functions(lua, globals)
logging::register_functions(lua, globals)?;
utils::register_functions(lua, globals)
}
pub fn reload(lua: &Lua, sender: Option<String>) -> Result<(), Error> {

68
src/lua/utils.rs Normal file
View File

@ -0,0 +1,68 @@
use log::error;
use mlua::{Lua, Result, Table};
use std::{
ffi::OsString,
process::{Command, Stdio},
thread,
};
pub fn register_functions(lua: &Lua, globals: &Table) -> Result<()> {
globals.set(
"system",
lua.create_function(|_, (command, args): (String, Option<Vec<OsString>>)| {
thread::spawn(|| {
if let Err(error) = Command::new(command)
.args(args.unwrap_or_default().iter())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
error!("failed to run system command: {error:?}");
}
});
Ok(())
})?,
)?;
globals.set(
"system_print_output",
lua.create_function(|_, (command, args): (String, Option<Vec<OsString>>)| {
thread::spawn(|| {
if let Err(error) = Command::new(command)
.args(args.unwrap_or_default().iter())
.spawn()
{
error!("failed to run system command: {error:?}");
}
});
Ok(())
})?,
)?;
globals.set(
"system_with_output",
lua.create_function(|lua, (command, args): (String, Option<Vec<OsString>>)| {
Ok(
match Command::new(command)
.args(args.unwrap_or_default().iter())
.output()
{
Ok(o) => {
let output = lua.create_table()?;
output.set("status", o.status.code())?;
output.set("stdout", o.stdout)?;
output.set("stderr", o.stderr)?;
Some(output)
}
Err(error) => {
error!("failed to run system command: {error:?}");
None
}
},
)
})?,
)?;
Ok(())
}