Skip to main content

gitflow_github/
runner.rs

1//! Command execution abstraction for GitHub CLI (`gh`).
2//!
3//! This module provides the [`CommandRunner`] trait and its implementations,
4//! allowing the GitHub crate to spawn CLI processes in production and inject
5//! controlled outputs in tests.
6
7use std::process::ExitStatus;
8
9/// Output from a CLI command execution.
10#[derive(Debug, Clone)]
11pub struct CommandOutput {
12    /// Process exit status.
13    pub status: ExitStatus,
14    /// Standard output bytes.
15    pub stdout: Vec<u8>,
16    /// Standard error bytes.
17    pub stderr: Vec<u8>,
18}
19
20/// Trait for executing CLI commands. Abstracts process spawning for testability.
21#[async_trait::async_trait]
22pub trait CommandRunner: std::fmt::Debug + Send + Sync {
23    /// Execute a command with the given program and arguments.
24    ///
25    /// # Errors
26    ///
27    /// Returns [`std::io::Error`] if the command cannot be spawned.
28    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput>;
29
30    /// Execute a command with the given program and arguments, writing
31    /// `stdin_data` to the child process's standard input.
32    ///
33    /// This avoids exposing sensitive values (such as tokens) in process
34    /// arguments, where they would be visible to other users via `ps`.
35    ///
36    /// # Errors
37    ///
38    /// Returns [`std::io::Error`] if the command cannot be spawned or if
39    /// writing to its standard input fails.
40    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/// Default implementation that spawns real processes via [`tokio::process::Command`].
49#[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/// Mock implementation for testing failure scenarios.
96///
97/// Stores either a success output or an error kind with a message,
98/// enabling `Clone` without requiring [`std::io::Error`] itself to be cloneable.
99#[cfg(test)]
100#[derive(Debug, Clone)]
101pub struct MockCommandRunner {
102    result: MockResult,
103}
104
105#[cfg(test)]
106#[derive(Debug, Clone)]
107enum MockResult {
108    /// Successful command output.
109    Output(CommandOutput),
110    /// Spawn error with kind and message.
111    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        // Exit codes are conventionally non-negative; clamp negatives to 1.
126        let raw = u32::try_from(code).unwrap_or(1);
127        ExitStatus::from_raw(raw)
128    }
129
130    /// Create a mock that returns success with the given stdout.
131    #[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    /// Create a mock that returns failure with the given stderr and exit code.
143    #[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    /// Create a mock that returns a spawn error.
155    #[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/// Mock implementation that returns a sequence of preconfigured responses.
184///
185/// Each call to [`CommandRunner::run`] pops the next response from the queue.
186/// Useful for testing retry logic where different commands must succeed or fail
187/// in a specific order (e.g., `add_labels` retries after auto-creating a label).
188///
189/// Cloning shares the same queue via `Arc<Mutex<...>>`, so clones advance together.
190#[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    /// Build a runner that yields `outputs` in order, one per `run` call.
199    ///
200    /// # Panics
201    ///
202    /// The runner panics at runtime if `run` is called more times than there are
203    /// entries in `outputs`.
204    #[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    /// Convenience: build a sequence from a list of `(success, stdout_or_stderr)` tuples.
212    ///
213    /// When `success` is `true`, the string is used as stdout with exit code 0.
214    /// When `false`, it is used as stderr with exit code 1.
215    #[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}