command.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use std::process::{Command, Stdio};
  2. use mlua::{FromLua, UserData};
  3. enum StdioFromString {
  4. Inherit,
  5. Piped,
  6. Null,
  7. }
  8. impl<'lua> FromLua<'lua> for StdioFromString {
  9. fn from_lua(lua_value: mlua::Value<'lua>, _lua: &'lua mlua::Lua) -> mlua::Result<Self> {
  10. if let mlua::Value::String(v) = lua_value {
  11. let v = v.to_str().unwrap();
  12. return Ok(match v.to_lowercase().as_str() {
  13. "inherit" => Self::Inherit,
  14. "piped" => Self::Piped,
  15. "null" => Self::Null,
  16. _ => Self::Inherit,
  17. });
  18. }
  19. Ok(Self::Inherit)
  20. }
  21. }
  22. impl StdioFromString {
  23. pub fn to_stdio(self) -> Stdio {
  24. match self {
  25. StdioFromString::Inherit => Stdio::inherit(),
  26. StdioFromString::Piped => Stdio::piped(),
  27. StdioFromString::Null => Stdio::null(),
  28. }
  29. }
  30. }
  31. pub struct PluginCommander;
  32. impl UserData for PluginCommander {
  33. fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
  34. methods.add_function(
  35. "exec",
  36. |_, args: (Vec<String>, StdioFromString, StdioFromString)| {
  37. let cmd = args.0;
  38. let stdout = args.1;
  39. let stderr = args.2;
  40. if cmd.len() == 0 {
  41. return Ok(());
  42. }
  43. let cmd_name = cmd.get(0).unwrap();
  44. let mut command = Command::new(cmd_name);
  45. let t = cmd
  46. .iter()
  47. .enumerate()
  48. .filter(|(i, _)| *i > 0)
  49. .map(|v| v.1.clone())
  50. .collect::<Vec<String>>();
  51. command.args(t);
  52. command.stdout(stdout.to_stdio()).stderr(stderr.to_stdio());
  53. command.output()?;
  54. Ok(())
  55. },
  56. );
  57. }
  58. fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(_fields: &mut F) {}
  59. }