-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexecutor.rs
More file actions
268 lines (225 loc) · 8.75 KB
/
executor.rs
File metadata and controls
268 lines (225 loc) · 8.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! Command execution utilities
//!
//! This module provides the `CommandExecutor` struct for executing external commands
//! with proper error handling, logging, and output capture.
use std::path::Path;
use std::process::{Command, Stdio};
use tracing::info;
use super::error::CommandError;
use super::result::CommandResult;
/// A command executor that can run shell commands
#[derive(Debug)]
pub struct CommandExecutor {}
impl Default for CommandExecutor {
fn default() -> Self {
Self::new()
}
}
impl CommandExecutor {
/// Creates a new `CommandExecutor`
#[must_use]
pub fn new() -> Self {
Self {}
}
/// Runs a command with the given arguments and optional working directory
///
/// # Arguments
/// * `cmd` - The command to execute
/// * `args` - Arguments to pass to the command
/// * `working_dir` - Optional working directory to run the command in
///
/// # Returns
/// * `Ok(CommandResult)` - Complete command execution information if the command succeeds
/// * `Err(CommandError)` - A specific error describing what went wrong
///
/// # Errors
/// This function will return an error if:
/// * The working directory does not exist - `CommandError::WorkingDirectoryNotFound`
/// * The command cannot be started (e.g., command not found) - `CommandError::StartupFailed`
/// * The command execution fails with a non-zero exit code - `CommandError::ExecutionFailed`
pub fn run_command(
&self,
cmd: &str,
args: &[&str],
working_dir: Option<&Path>,
) -> Result<CommandResult, CommandError> {
Self::validate_working_directory(working_dir)?;
let mut command = Self::build_command(cmd, args, working_dir);
let command_display = Self::format_command_display(cmd, args);
Self::log_command_start(&command_display, working_dir);
let (status, stdout, stderr) = Self::execute_command(&mut command, &command_display)?;
Self::check_command_success(status, &command_display, &stdout, &stderr)?;
Self::log_command_output(&command_display, &stdout, &stderr);
Ok(CommandResult::new(status, stdout, stderr))
}
/// Validates that the working directory exists if provided.
///
/// This provides a clearer error message than the generic "No such file or directory"
/// that would be returned by the OS.
fn validate_working_directory(working_dir: Option<&Path>) -> Result<(), CommandError> {
if let Some(dir) = working_dir {
if !dir.exists() {
return Err(CommandError::WorkingDirectoryNotFound {
working_dir: dir.to_path_buf(),
});
}
}
Ok(())
}
/// Builds a Command with the given arguments and optional working directory.
fn build_command(cmd: &str, args: &[&str], working_dir: Option<&Path>) -> Command {
let mut command = Command::new(cmd);
command.args(args);
if let Some(dir) = working_dir {
command.current_dir(dir);
}
command
}
/// Formats a command and its arguments for display in logs and error messages.
fn format_command_display(cmd: &str, args: &[&str]) -> String {
format!("{} {}", cmd, args.join(" "))
}
/// Logs the command execution start with optional working directory.
fn log_command_start(command_display: &str, working_dir: Option<&Path>) {
info!(
operation = "command_execution",
command = %command_display,
"Running command"
);
if let Some(dir) = working_dir {
info!(
operation = "command_execution",
working_directory = %dir.display(),
"Working directory set"
);
}
}
/// Executes the command and captures its output.
///
/// Returns a tuple of (`exit_status`, `stdout`, `stderr`).
fn execute_command(
command: &mut Command,
command_display: &str,
) -> Result<(std::process::ExitStatus, String, String), CommandError> {
let output = command
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.map_err(|source| CommandError::StartupFailed {
command: command_display.to_string(),
source,
})?;
let (stdout, stderr) = Self::extract_output(&output);
Ok((output.status, stdout, stderr))
}
/// Extracts stdout and stderr from command output as strings.
fn extract_output(output: &std::process::Output) -> (String, String) {
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
(stdout, stderr)
}
/// Checks if the command executed successfully and returns an error if it failed.
fn check_command_success(
status: std::process::ExitStatus,
command_display: &str,
stdout: &str,
stderr: &str,
) -> Result<(), CommandError> {
if !status.success() {
let exit_code = status
.code()
.map_or_else(|| "unknown".to_string(), |code| code.to_string());
return Err(CommandError::ExecutionFailed {
command: command_display.to_string(),
exit_code,
stdout: stdout.to_string(),
stderr: stderr.to_string(),
});
}
Ok(())
}
/// Logs the command output (stdout/stderr) at debug level.
fn log_command_output(command_display: &str, stdout: &str, stderr: &str) {
if !stdout.trim().is_empty() {
tracing::debug!(
operation = "command_execution",
command = %command_display,
"stdout: {}",
stdout.trim()
);
}
if !stderr.trim().is_empty() {
tracing::debug!(
operation = "command_execution",
command = %command_display,
"stderr: {}",
stderr.trim()
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn it_should_execute_simple_command_successfully() {
let executor = CommandExecutor::new();
let result = executor.run_command("echo", &["hello"], None);
assert!(result.is_ok());
let output = result.unwrap();
assert_eq!(output.stdout_trimmed(), "hello");
assert!(output.is_success());
}
#[test]
fn it_should_respect_working_directory() {
let executor = CommandExecutor::new();
let temp_dir = env::temp_dir();
let result = executor.run_command("pwd", &[], Some(&temp_dir));
assert!(result.is_ok());
let output = result.unwrap();
// The output should contain the temp directory path
assert!(output.stdout.contains(temp_dir.to_string_lossy().as_ref()));
assert!(output.is_success());
}
#[test]
fn it_should_return_error_for_nonexistent_command() {
let executor = CommandExecutor::new();
let result = executor.run_command("nonexistent_command_xyz123", &[], None);
assert!(result.is_err());
}
#[test]
fn it_should_return_error_for_failing_command() {
let executor = CommandExecutor::new();
let result = executor.run_command("false", &[], None);
assert!(result.is_err());
let error_msg = result.unwrap_err().to_string();
assert!(error_msg.contains("failed with exit code"));
}
#[test]
fn it_should_use_tracing_for_logging() {
// This test verifies that the command executor uses tracing for logging
// We can't easily test the tracing output in unit tests without a subscriber
// but we can verify the executor runs correctly and uses tracing internally
let executor = CommandExecutor::new();
let result = executor.run_command("echo", &["tracing_test"], None);
assert!(result.is_ok());
let output = result.unwrap();
assert_eq!(output.stdout_trimmed(), "tracing_test");
assert!(output.is_success());
}
#[test]
fn it_should_return_clear_error_when_working_directory_does_not_exist() {
let executor = CommandExecutor::new();
let nonexistent_dir = Path::new("/nonexistent/path/that/does/not/exist");
let result = executor.run_command("echo", &["hello"], Some(nonexistent_dir));
assert!(result.is_err());
let error = result.unwrap_err();
match error {
CommandError::WorkingDirectoryNotFound { working_dir } => {
assert_eq!(working_dir, nonexistent_dir);
}
other => panic!("Expected WorkingDirectoryNotFound, got: {other:?}"),
}
}
}