Skip to main content

windjammer_runtime/
process.rs

1//! Process management
2//!
3//! Windjammer's `std::process` module maps to these functions.
4
5use std::process::Command;
6
7/// Run a command and return output
8pub fn run(program: &str, args: &[String]) -> Result<String, String> {
9    let output = Command::new(program)
10        .args(args)
11        .output()
12        .map_err(|e| e.to_string())?;
13
14    if output.status.success() {
15        String::from_utf8(output.stdout).map_err(|e| e.to_string())
16    } else {
17        Err(String::from_utf8_lossy(&output.stderr).to_string())
18    }
19}
20
21/// Run a command and return full output
22pub fn run_with_output(program: &str, args: &[String]) -> Result<ProcessOutput, String> {
23    let output = Command::new(program)
24        .args(args)
25        .output()
26        .map_err(|e| e.to_string())?;
27
28    Ok(ProcessOutput {
29        status: output.status.code().unwrap_or(-1),
30        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
31        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
32    })
33}
34
35/// Exit the current process
36pub fn exit(code: i32) -> ! {
37    std::process::exit(code);
38}
39
40/// Process output
41#[derive(Debug, Clone)]
42pub struct ProcessOutput {
43    pub status: i32,
44    pub stdout: String,
45    pub stderr: String,
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn test_run_echo() {
54        #[cfg(unix)]
55        {
56            let result = run("echo", &["hello".to_string()]);
57            assert!(result.is_ok());
58            assert_eq!(result.unwrap().trim(), "hello");
59        }
60    }
61
62    #[test]
63    fn test_run_with_output() {
64        #[cfg(unix)]
65        {
66            let result = run_with_output("echo", &["test".to_string()]);
67            assert!(result.is_ok());
68            let output = result.unwrap();
69            assert_eq!(output.status, 0);
70            assert_eq!(output.stdout.trim(), "test");
71        }
72    }
73}