1use mlua::{self, Lua};
2
3pub fn add_cmd_util(lua: &Lua, quiet: bool) -> Result<(), mlua::Error> {
4 let cmd_fn = lua.create_function(move |lua, command: String| {
5 let build_dir: String = lua.globals().get("BUILD_DIR")?;
6
7 if !quiet {
8 println!("Executing: {}", command);
9 }
10 let output = if cfg!(target_os = "windows") {
11 std::process::Command::new("pwsh")
12 .arg("-Command")
13 .arg(&command)
14 .current_dir(&build_dir)
15 .output()
16 } else {
17 std::process::Command::new("bash")
18 .arg("-c")
19 .arg(&command)
20 .current_dir(&build_dir)
21 .output()
22 };
23
24 match output {
25 Ok(out) => {
26 let stdout = String::from_utf8_lossy(&out.stdout).to_string();
27 let stderr = String::from_utf8_lossy(&out.stderr).to_string();
28 let exit_code =
29 out.status
30 .code()
31 .unwrap_or(if out.status.success() { 0 } else { 1 });
32
33 if !out.status.success() && !quiet {
34 eprintln!("[cmd] {}", stderr);
35 }
36
37 Ok((stdout, stderr, exit_code))
38 }
39 Err(e) => {
40 if !quiet {
41 eprintln!("[cmd] Failed to execute command: {}", e);
42 }
43 Ok((String::new(), e.to_string(), 1))
44 }
45 }
46 })?;
47 lua.globals().set("cmd", cmd_fn)?;
48 Ok(())
49}
50
51pub fn add_zpatch(lua: &Lua, quiet: bool) -> Result<(), mlua::Error> {
52 let zpatch_fn =
53 lua.create_function(move |lua, (patch_file, strip): (String, Option<u32>)| {
54 let build_dir: String = lua.globals().get("BUILD_DIR")?;
55 let strip_level = strip.unwrap_or(1);
56
57 if !quiet {
58 println!("Applying patch: {}", patch_file);
59 }
60
61 let output = std::process::Command::new("patch")
62 .arg(format!("-p{}", strip_level))
63 .arg("-i")
64 .arg(&patch_file)
65 .current_dir(&build_dir)
66 .output();
67
68 match output {
69 Ok(out) => {
70 if !out.status.success() {
71 let stderr = String::from_utf8_lossy(&out.stderr);
72 return Err(mlua::Error::RuntimeError(format!(
73 "patch failed: {}",
74 stderr
75 )));
76 }
77 if !quiet {
78 println!("Successfully applied patch {}", patch_file);
79 }
80 Ok(())
81 }
82 Err(e) => Err(mlua::Error::RuntimeError(format!(
83 "Failed to execute patch command: {}",
84 e
85 ))),
86 }
87 })?;
88 lua.globals().set("zpatch", zpatch_fn)?;
89 Ok(())
90}