use std::process::Command;
pub fn run_cmd_result(cmd: &str) -> std::io::Result<String> {
let output = Command::new("sh").arg("-c").arg(cmd).output()?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Err(std::io::Error::other(format!(
"Command '{}' exited with {}: {}",
cmd,
output.status,
stderr.trim(),
)))
}
}
#[must_use]
pub fn run_cmd(cmd: &str) -> String {
match run_cmd_result(cmd) {
Ok(stdout) => stdout,
Err(e) => {
eprintln!("[runtimo] run_cmd failed — {} — cmd: {}", e, cmd);
String::new()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_run_cmd_echo() {
let result = run_cmd("echo hello");
assert_eq!(result, "hello");
}
#[test]
fn test_run_cmd_echo_with_spaces() {
let result = run_cmd("echo 'hello world'");
assert!(result.contains("hello world"), "Got: {}", result);
}
#[test]
fn test_run_cmd_empty_string() {
let result = run_cmd("");
assert_eq!(result, "", "Empty command should produce empty output");
}
#[test]
fn test_run_cmd_nonexistent_command() {
let result = run_cmd("nonexistent_command_xyz_123");
assert_eq!(result, "");
}
#[test]
fn test_run_cmd_exit_nonzero() {
let result = run_cmd("exit 1");
assert_eq!(result, "");
}
#[test]
fn test_run_cmd_returns_trimmed_output() {
let result = run_cmd("echo ' spaces '");
assert_eq!(result, "spaces");
}
}