all_smi/device/common/
command_executor.rs1use crate::device::common::{DeviceError, DeviceResult, validate_args, validate_command};
24use crate::utils::{command_timeout::run_command_with_timeout, run_command_fast_fail};
25use std::time::Duration;
26
27#[derive(Debug, Clone, Default)]
29pub struct CommandOptions {
30 pub timeout: Option<Duration>,
32 pub check_status: bool,
34}
35
36#[derive(Debug, Clone)]
38pub struct CommandOutput {
39 pub status: i32,
41 pub stdout: String,
43 pub stderr: String,
45}
46
47pub fn execute_command(
54 command: &str,
55 args: &[&str],
56 options: &CommandOptions,
57) -> DeviceResult<CommandOutput> {
58 if !validate_command(command) {
60 return Err(DeviceError::Other(format!(
61 "Invalid command rejected: {command}"
62 )));
63 }
64
65 if !validate_args(args) {
66 return Err(DeviceError::Other(format!(
67 "Invalid arguments rejected for command: {command}"
68 )));
69 }
70
71 let output = if let Some(timeout) = options.timeout {
72 run_command_with_timeout(command, args, timeout)?
73 } else {
74 run_command_fast_fail(command, args)?
75 };
76
77 let status_code = output.status.code().unwrap_or(-1);
78 let out = CommandOutput {
79 status: status_code,
80 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
81 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
82 };
83
84 if options.check_status && status_code != 0 {
85 let full_command = if args.is_empty() {
86 command.to_string()
87 } else {
88 format!("{command} {}", args.join(" "))
89 };
90
91 eprintln!("Command execution failed: '{full_command}' (exit code: {status_code})");
92
93 if !out.stderr.is_empty() {
94 eprintln!("Stderr output: {}", out.stderr);
95 }
96
97 return Err(DeviceError::CommandFailed {
98 command: full_command,
99 code: Some(status_code),
100 stderr: out.stderr.clone(),
101 });
102 }
103
104 Ok(out)
105}
106
107pub fn execute_command_default(command: &str, args: &[&str]) -> DeviceResult<CommandOutput> {
111 execute_command(command, args, &CommandOptions::default())
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[cfg(unix)]
125 const ECHO: (&str, &[&str]) = ("echo", &["hello"]);
126 #[cfg(windows)]
127 const ECHO: (&str, &[&str]) = ("cmd", &["/C", "echo", "hello"]);
128
129 #[cfg(unix)]
130 const FAILS: (&str, &[&str]) = ("false", &[]);
131 #[cfg(windows)]
132 const FAILS: (&str, &[&str]) = ("cmd", &["/C", "exit", "1"]);
133
134 #[test]
135 fn test_execute_command_default_success() {
136 let (cmd, args) = ECHO;
137 let out = execute_command_default(cmd, args).expect("echo should succeed");
138 assert_eq!(out.status, 0);
139 assert!(out.stdout.contains("hello"));
140 }
141
142 #[test]
143 fn test_execute_command_with_status_check() {
144 let opts = CommandOptions {
145 timeout: Some(Duration::from_secs(2)),
146 check_status: true,
147 };
148 let (cmd, args) = FAILS;
149 let err = execute_command(cmd, args, &opts).unwrap_err();
150 match err {
151 DeviceError::CommandFailed { .. } => {}
152 _ => panic!("Expected CommandFailed error"),
153 }
154 }
155}