|
| 1 | +use std::io::{Write, Error}; |
| 2 | +use std::process::{Command, Stdio}; |
| 3 | +use std::result::Result; |
| 4 | +use types::ExecutorResult; |
| 5 | + |
| 6 | +pub fn run_stdin(work_dir: &str, stdin: &str, args: &[&str]) -> Result<ExecutorResult, Error> { |
| 7 | + let mut command = Command::new(&args[0]); |
| 8 | + command |
| 9 | + .args(&args[1..]) |
| 10 | + .current_dir(work_dir) |
| 11 | + .stdin(Stdio::piped()) |
| 12 | + .stdout(Stdio::piped()) |
| 13 | + .stderr(Stdio::piped()); |
| 14 | + |
| 15 | + let mut child = command |
| 16 | + .spawn() |
| 17 | + .expect("Failed to spawn child process"); |
| 18 | + |
| 19 | + { |
| 20 | + let stdin_stream = child.stdin.as_mut().expect("Failed to open stdin"); |
| 21 | + stdin_stream.write_all(stdin.as_bytes()).expect("Failed to write to stdin"); |
| 22 | + } |
| 23 | + |
| 24 | + let output = child.wait_with_output().expect("Failed to read stdout"); |
| 25 | + |
| 26 | + let code = match output.status.code() { |
| 27 | + Some(code) => code, |
| 28 | + None => -1 |
| 29 | + }; |
| 30 | + |
| 31 | + Ok(ExecutorResult{ |
| 32 | + stdout: String::from_utf8_lossy(&output.stdout).to_string(), |
| 33 | + stderr: String::from_utf8_lossy(&output.stderr).to_string(), |
| 34 | + status_code: code.to_string() |
| 35 | + }) |
| 36 | +} |
| 37 | + |
| 38 | +pub fn run(work_dir: &str, args: &[&str]) -> Result<ExecutorResult, Error>{ |
| 39 | + run_stdin(work_dir, "", &args) |
| 40 | +} |
| 41 | + |
| 42 | +pub fn run_bash_stdin(work_dir: &str, command: &str, stdin: &str) -> Result<ExecutorResult, Error> { |
| 43 | + run_stdin(work_dir, stdin, &["bash", "-c", command]) |
| 44 | +} |
| 45 | + |
| 46 | +/* pub fn run_bash(work_dir: &str, command: &str) -> Result<ExecutorResult, Error> { |
| 47 | + run(work_dir, &["bash", "-c", command]) |
| 48 | +} */ |
0 commit comments