1use std::process::ExitStatus;
8
9#[derive(Debug, Clone)]
11pub struct CommandOutput {
12 pub status: ExitStatus,
14 pub stdout: Vec<u8>,
16 pub stderr: Vec<u8>,
18}
19
20#[async_trait::async_trait]
22pub trait CommandRunner: std::fmt::Debug + Send + Sync {
23 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput>;
29
30 async fn run_with_stdin(
41 &self,
42 program: &str,
43 args: &[&str],
44 stdin_data: &[u8],
45 ) -> std::io::Result<CommandOutput>;
46}
47
48#[derive(Debug, Clone, Default)]
50pub struct RealCommandRunner;
51
52#[async_trait::async_trait]
53impl CommandRunner for RealCommandRunner {
54 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
55 let output = tokio::process::Command::new(program)
56 .args(args)
57 .output()
58 .await?;
59 Ok(CommandOutput {
60 status: output.status,
61 stdout: output.stdout,
62 stderr: output.stderr,
63 })
64 }
65
66 async fn run_with_stdin(
67 &self,
68 program: &str,
69 args: &[&str],
70 stdin_data: &[u8],
71 ) -> std::io::Result<CommandOutput> {
72 use tokio::io::AsyncWriteExt;
73
74 let mut child = tokio::process::Command::new(program)
75 .args(args)
76 .stdin(std::process::Stdio::piped())
77 .stdout(std::process::Stdio::piped())
78 .stderr(std::process::Stdio::piped())
79 .spawn()?;
80
81 if let Some(mut stdin) = child.stdin.take() {
82 stdin.write_all(stdin_data).await?;
83 drop(stdin);
84 }
85
86 let output = child.wait_with_output().await?;
87 Ok(CommandOutput {
88 status: output.status,
89 stdout: output.stdout,
90 stderr: output.stderr,
91 })
92 }
93}
94
95#[cfg(test)]
100#[derive(Debug, Clone)]
101pub struct MockCommandRunner {
102 result: MockResult,
103}
104
105#[cfg(test)]
106#[derive(Debug, Clone)]
107enum MockResult {
108 Output(CommandOutput),
110 Error(std::io::ErrorKind, String),
112}
113
114#[cfg(test)]
115impl MockCommandRunner {
116 #[cfg(unix)]
117 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
118 use std::os::unix::process::ExitStatusExt;
119 ExitStatus::from_raw(code)
120 }
121
122 #[cfg(windows)]
123 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
124 use std::os::windows::process::ExitStatusExt;
125 let raw = u32::try_from(code).unwrap_or(1);
127 ExitStatus::from_raw(raw)
128 }
129
130 #[must_use]
132 pub fn success(stdout: &str) -> Self {
133 Self {
134 result: MockResult::Output(CommandOutput {
135 status: Self::make_exit_status(0),
136 stdout: stdout.as_bytes().to_vec(),
137 stderr: Vec::new(),
138 }),
139 }
140 }
141
142 #[must_use]
144 pub fn failure(stderr: &str, code: i32) -> Self {
145 Self {
146 result: MockResult::Output(CommandOutput {
147 status: Self::make_exit_status(code),
148 stdout: Vec::new(),
149 stderr: stderr.as_bytes().to_vec(),
150 }),
151 }
152 }
153
154 #[must_use]
156 pub fn spawn_error() -> Self {
157 Self {
158 result: MockResult::Error(std::io::ErrorKind::NotFound, "command not found".to_owned()),
159 }
160 }
161}
162
163#[cfg(test)]
164#[async_trait::async_trait]
165impl CommandRunner for MockCommandRunner {
166 async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
167 match &self.result {
168 MockResult::Output(output) => Ok(output.clone()),
169 MockResult::Error(kind, message) => Err(std::io::Error::new(*kind, message.clone())),
170 }
171 }
172
173 async fn run_with_stdin(
174 &self,
175 program: &str,
176 args: &[&str],
177 _stdin_data: &[u8],
178 ) -> std::io::Result<CommandOutput> {
179 self.run(program, args).await
180 }
181}
182
183#[cfg(test)]
191#[derive(Debug, Clone)]
192pub struct SequencedMockCommandRunner {
193 responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
194}
195
196#[cfg(test)]
197impl SequencedMockCommandRunner {
198 #[must_use]
205 pub fn new(outputs: Vec<CommandOutput>) -> Self {
206 Self {
207 responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
208 }
209 }
210
211 #[must_use]
216 pub fn from_results(results: &[(bool, &str)]) -> Self {
217 let outputs = results
218 .iter()
219 .map(|&(ok, text)| {
220 if ok {
221 CommandOutput {
222 status: MockCommandRunner::make_exit_status(0),
223 stdout: text.as_bytes().to_vec(),
224 stderr: Vec::new(),
225 }
226 } else {
227 CommandOutput {
228 status: MockCommandRunner::make_exit_status(1),
229 stdout: Vec::new(),
230 stderr: text.as_bytes().to_vec(),
231 }
232 }
233 })
234 .collect();
235 Self::new(outputs)
236 }
237}
238
239#[cfg(test)]
240#[async_trait::async_trait]
241impl CommandRunner for SequencedMockCommandRunner {
242 async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
243 let mut guard = self
244 .responses
245 .lock()
246 .expect("SequencedMockCommandRunner mutex poisoned");
247 guard
248 .pop_front()
249 .ok_or_else(|| std::io::Error::other("no more responses"))
250 }
251
252 async fn run_with_stdin(
253 &self,
254 program: &str,
255 args: &[&str],
256 _stdin_data: &[u8],
257 ) -> std::io::Result<CommandOutput> {
258 self.run(program, args).await
259 }
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 #[tokio::test]
267 async fn test_should_return_success_output_from_mock() {
268 let runner = MockCommandRunner::success("hello");
269 let output = runner
270 .run("gh", &["--version"])
271 .await
272 .expect("should succeed");
273 assert!(output.status.success());
274 assert_eq!(output.stdout, b"hello");
275 assert!(output.stderr.is_empty());
276 }
277
278 #[tokio::test]
279 async fn test_should_return_failure_output_from_mock() {
280 let runner = MockCommandRunner::failure("not found", 1);
281 let output = runner
282 .run("gh", &["repo", "view"])
283 .await
284 .expect("should succeed");
285 assert!(!output.status.success());
286 assert!(output.stdout.is_empty());
287 assert_eq!(output.stderr, b"not found");
288 }
289
290 #[tokio::test]
291 async fn test_should_return_spawn_error_from_mock() {
292 let runner = MockCommandRunner::spawn_error();
293 let err = runner
294 .run("gh", &["--version"])
295 .await
296 .expect_err("should fail");
297 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
298 }
299
300 #[tokio::test]
301 async fn test_should_clone_command_output() {
302 let runner = MockCommandRunner::success("data");
303 let output = runner.run("gh", &[]).await.expect("should succeed");
304 let cloned = output.clone();
305 assert_eq!(output.stdout, cloned.stdout);
306 assert_eq!(output.stderr, cloned.stderr);
307 }
308
309 #[tokio::test]
310 async fn test_should_clone_mock_runner() {
311 let runner = MockCommandRunner::success("cloneable");
312 let cloned = runner.clone();
313 let output = cloned.run("gh", &[]).await.expect("should succeed");
314 assert_eq!(output.stdout, b"cloneable");
315 }
316}