Skip to main content

gitflow_github/
runner.rs

1//! Command execution abstraction for GitHub CLI (`gh`).
2//!
3//! Re-exports the shared [`CommandRunner`] trait, [`CommandOutput`],
4//! [`RealCommandRunner`], [`EnvSource`] trait, and [`RealEnv`] from
5//! `gitflow-cli-adapter-utils`.
6//! Platform-specific mock implementations live in this module for testing.
7
8#[cfg(test)]
9use std::process::ExitStatus;
10
11pub use gitflow_cli_adapter_utils::{
12    CommandOutput, CommandRunner, EnvSource, RealCommandRunner, RealEnv,
13};
14
15/// Mock implementation for testing failure scenarios.
16///
17/// Stores either a success output or an error kind with a message,
18/// enabling `Clone` without requiring [`std::io::Error`] itself to be cloneable.
19#[cfg(test)]
20#[derive(Debug, Clone)]
21pub struct MockCommandRunner {
22    result: MockResult,
23    /// Recorded `(program, args)` sequences for every `run` call.
24    recorded: std::sync::Arc<std::sync::Mutex<RecordedCalls>>,
25}
26
27/// A single recorded command invocation: `(program, args)`.
28#[cfg(test)]
29type RecordedCall = (String, Vec<String>);
30
31/// All recorded command invocations in execution order.
32#[cfg(test)]
33type RecordedCalls = Vec<RecordedCall>;
34
35#[cfg(test)]
36#[derive(Debug, Clone)]
37enum MockResult {
38    /// Successful command output.
39    Output(CommandOutput),
40    /// Spawn error with kind and message.
41    Error(std::io::ErrorKind, String),
42}
43
44#[cfg(test)]
45impl MockCommandRunner {
46    #[cfg(unix)]
47    pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
48        use std::os::unix::process::ExitStatusExt;
49        ExitStatus::from_raw(code)
50    }
51
52    #[cfg(windows)]
53    pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
54        use std::os::windows::process::ExitStatusExt;
55        // Exit codes are conventionally non-negative; clamp negatives to 1.
56        let raw = u32::try_from(code).unwrap_or(1);
57        ExitStatus::from_raw(raw)
58    }
59
60    /// Create a mock that returns success with the given stdout.
61    #[must_use]
62    pub fn success(stdout: &str) -> Self {
63        Self {
64            result: MockResult::Output(CommandOutput {
65                status: Self::make_exit_status(0),
66                stdout: stdout.as_bytes().to_vec(),
67                stderr: Vec::new(),
68            }),
69            recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
70        }
71    }
72
73    /// Create a mock that returns failure with the given stderr and exit code.
74    #[must_use]
75    pub fn failure(stderr: &str, code: i32) -> Self {
76        Self {
77            result: MockResult::Output(CommandOutput {
78                status: Self::make_exit_status(code),
79                stdout: Vec::new(),
80                stderr: stderr.as_bytes().to_vec(),
81            }),
82            recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
83        }
84    }
85
86    /// Create a mock that returns a spawn error.
87    #[must_use]
88    pub fn spawn_error() -> Self {
89        Self {
90            result: MockResult::Error(std::io::ErrorKind::NotFound, "command not found".to_owned()),
91            recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
92        }
93    }
94
95    /// Return the recorded `(program, args)` sequences from every executed call.
96    ///
97    /// # Panics
98    ///
99    /// Panics if the internal recording mutex is poisoned (a prior panic while
100    /// holding the lock).
101    #[must_use]
102    pub fn recorded_calls(&self) -> Vec<(String, Vec<String>)> {
103        self.recorded.lock().expect("mock mutex poisoned").clone()
104    }
105}
106
107#[cfg(test)]
108#[async_trait::async_trait]
109impl CommandRunner for MockCommandRunner {
110    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
111        self.recorded.lock().expect("mock mutex poisoned").push((
112            program.to_string(),
113            args.iter().map(|s| (*s).to_string()).collect(),
114        ));
115        match &self.result {
116            MockResult::Output(output) => Ok(output.clone()),
117            MockResult::Error(kind, message) => Err(std::io::Error::new(*kind, message.clone())),
118        }
119    }
120
121    async fn run_with_stdin(
122        &self,
123        program: &str,
124        args: &[&str],
125        _stdin_data: &[u8],
126    ) -> std::io::Result<CommandOutput> {
127        self.run(program, args).await
128    }
129}
130
131/// Mock implementation that returns a sequence of preconfigured responses.
132///
133/// Each call to [`CommandRunner::run`] pops the next response from the queue.
134/// Useful for testing retry logic where different commands must succeed or fail
135/// in a specific order (e.g., `add_labels` retries after auto-creating a label).
136///
137/// Cloning shares the same queue via `Arc<Mutex<...>>`, so clones advance together.
138#[cfg(test)]
139#[derive(Debug, Clone)]
140pub struct SequencedMockCommandRunner {
141    responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
142    /// Recorded `(program, args)` sequences for every `run`/`run_with_stdin` call.
143    recorded: std::sync::Arc<std::sync::Mutex<RecordedCalls>>,
144}
145
146#[cfg(test)]
147impl SequencedMockCommandRunner {
148    /// Build a runner that yields `outputs` in order, one per `run` call.
149    ///
150    /// # Panics
151    ///
152    /// The runner panics at runtime if `run` is called more times than there are
153    /// entries in `outputs`.
154    #[must_use]
155    pub fn new(outputs: Vec<CommandOutput>) -> Self {
156        Self {
157            responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
158            recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
159        }
160    }
161
162    /// Convenience: build a sequence from a list of `(success, stdout_or_stderr)` tuples.
163    ///
164    /// When `success` is `true`, the string is used as stdout with exit code 0.
165    /// When `false`, it is used as stderr with exit code 1.
166    #[must_use]
167    pub fn from_results(results: &[(bool, &str)]) -> Self {
168        let outputs = results
169            .iter()
170            .map(|&(ok, text)| {
171                if ok {
172                    CommandOutput {
173                        status: MockCommandRunner::make_exit_status(0),
174                        stdout: text.as_bytes().to_vec(),
175                        stderr: Vec::new(),
176                    }
177                } else {
178                    CommandOutput {
179                        status: MockCommandRunner::make_exit_status(1),
180                        stdout: Vec::new(),
181                        stderr: text.as_bytes().to_vec(),
182                    }
183                }
184            })
185            .collect();
186        Self::new(outputs)
187    }
188
189    /// Return the recorded `(program, args)` sequences from every executed call.
190    ///
191    /// # Panics
192    ///
193    /// Panics if the internal recording mutex is poisoned (a prior panic while
194    /// holding the lock).
195    #[must_use]
196    pub fn recorded_calls(&self) -> RecordedCalls {
197        self.recorded.lock().expect("mock mutex poisoned").clone()
198    }
199}
200
201#[cfg(test)]
202#[async_trait::async_trait]
203impl CommandRunner for SequencedMockCommandRunner {
204    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
205        self.recorded.lock().expect("mock mutex poisoned").push((
206            program.to_string(),
207            args.iter().map(|s| (*s).to_string()).collect(),
208        ));
209        let mut guard = self
210            .responses
211            .lock()
212            .expect("SequencedMockCommandRunner mutex poisoned");
213        guard
214            .pop_front()
215            .ok_or_else(|| std::io::Error::other("no more responses"))
216    }
217
218    async fn run_with_stdin(
219        &self,
220        program: &str,
221        args: &[&str],
222        _stdin_data: &[u8],
223    ) -> std::io::Result<CommandOutput> {
224        self.run(program, args).await
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[tokio::test]
233    async fn test_should_return_success_output_from_mock() {
234        let runner = MockCommandRunner::success("hello");
235        let output = runner
236            .run("gh", &["--version"])
237            .await
238            .expect("should succeed");
239        assert!(output.status.success());
240        assert_eq!(output.stdout, b"hello");
241        assert!(output.stderr.is_empty());
242    }
243
244    #[tokio::test]
245    async fn test_should_return_failure_output_from_mock() {
246        let runner = MockCommandRunner::failure("not found", 1);
247        let output = runner
248            .run("gh", &["repo", "view"])
249            .await
250            .expect("should succeed");
251        assert!(!output.status.success());
252        assert!(output.stdout.is_empty());
253        assert_eq!(output.stderr, b"not found");
254    }
255
256    #[tokio::test]
257    async fn test_should_return_spawn_error_from_mock() {
258        let runner = MockCommandRunner::spawn_error();
259        let err = runner
260            .run("gh", &["--version"])
261            .await
262            .expect_err("should fail");
263        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
264    }
265
266    #[tokio::test]
267    async fn test_should_clone_command_output() {
268        let runner = MockCommandRunner::success("data");
269        let output = runner.run("gh", &[]).await.expect("should succeed");
270        let cloned = output.clone();
271        assert_eq!(output.stdout, cloned.stdout);
272        assert_eq!(output.stderr, cloned.stderr);
273    }
274
275    #[tokio::test]
276    async fn test_should_clone_mock_runner() {
277        let runner = MockCommandRunner::success("cloneable");
278        let cloned = runner.clone();
279        let output = cloned.run("gh", &[]).await.expect("should succeed");
280        assert_eq!(output.stdout, b"cloneable");
281    }
282
283    #[tokio::test]
284    async fn test_should_yield_sequenced_responses() {
285        let runner = SequencedMockCommandRunner::from_results(&[
286            (true, "first"),
287            (false, "error"),
288            (true, "third"),
289        ]);
290
291        let out1 = runner.run("gh", &[]).await.expect("first should succeed");
292        assert!(out1.status.success());
293        assert_eq!(out1.stdout, b"first");
294
295        let out2 = runner
296            .run("gh", &[])
297            .await
298            .expect("second should 'succeed' as Output");
299        assert!(!out2.status.success());
300        assert_eq!(out2.stderr, b"error");
301
302        let out3 = runner.run("gh", &[]).await.expect("third should succeed");
303        assert_eq!(out3.stdout, b"third");
304    }
305
306    #[tokio::test]
307    async fn test_should_error_when_sequence_exhausted() {
308        let runner = SequencedMockCommandRunner::from_results(&[(true, "only")]);
309
310        let _ = runner.run("gh", &[]).await.expect("first call");
311        let err = runner.run("gh", &[]).await.expect_err("exhausted");
312        assert_eq!(err.kind(), std::io::ErrorKind::Other);
313    }
314
315    #[tokio::test]
316    async fn test_should_record_calls() {
317        let runner = MockCommandRunner::success("ok");
318        runner
319            .run("gh", &["label", "list"])
320            .await
321            .expect("should run");
322        runner
323            .run_with_stdin("gh", &["api", "repos/o/r"], b"data")
324            .await
325            .expect("should run with stdin");
326        let calls = runner.recorded_calls();
327        assert_eq!(calls.len(), 2);
328        assert_eq!(calls[0].0, "gh");
329        assert_eq!(calls[0].1, vec!["label", "list"]);
330        assert_eq!(calls[1].0, "gh");
331        assert_eq!(calls[1].1, vec!["api", "repos/o/r"]);
332    }
333}