Skip to main content

gitflow_gitlab/
runner.rs

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