Skip to main content

gitflow_gitlab/
runner.rs

1//! Command execution abstraction for GitLab CLI (`glab`).
2//!
3//! This module provides the [`CommandRunner`] trait and its implementations,
4//! allowing the GitLab 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#[cfg(test)]
189#[derive(Debug, Clone)]
190pub struct SequencedMockCommandRunner {
191    responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
192}
193
194#[cfg(test)]
195impl SequencedMockCommandRunner {
196    /// Build a runner that yields `outputs` in order, one per `run` call.
197    #[must_use]
198    pub fn new(outputs: Vec<CommandOutput>) -> Self {
199        Self {
200            responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
201        }
202    }
203
204    /// Convenience: build a sequence from `(success, stdout_or_stderr)` tuples.
205    ///
206    /// When `success` is `true`, the string is used as stdout with exit code 0.
207    /// When `false`, it is used as stderr with exit code 1.
208    #[must_use]
209    pub fn from_results(results: &[(bool, &str)]) -> Self {
210        let outputs = results
211            .iter()
212            .map(|&(ok, text)| {
213                if ok {
214                    CommandOutput {
215                        status: MockCommandRunner::make_exit_status(0),
216                        stdout: text.as_bytes().to_vec(),
217                        stderr: Vec::new(),
218                    }
219                } else {
220                    CommandOutput {
221                        status: MockCommandRunner::make_exit_status(1),
222                        stdout: Vec::new(),
223                        stderr: text.as_bytes().to_vec(),
224                    }
225                }
226            })
227            .collect();
228        Self::new(outputs)
229    }
230}
231
232#[cfg(test)]
233#[async_trait::async_trait]
234impl CommandRunner for SequencedMockCommandRunner {
235    async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
236        let mut guard = self
237            .responses
238            .lock()
239            .expect("SequencedMockCommandRunner mutex poisoned");
240        guard
241            .pop_front()
242            .ok_or_else(|| std::io::Error::other("no more responses"))
243    }
244
245    async fn run_with_stdin(
246        &self,
247        program: &str,
248        args: &[&str],
249        _stdin_data: &[u8],
250    ) -> std::io::Result<CommandOutput> {
251        self.run(program, args).await
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[tokio::test]
260    async fn test_should_return_success_output_from_mock() {
261        let runner = MockCommandRunner::success("hello");
262        let output = runner
263            .run("glab", &["--version"])
264            .await
265            .expect("should succeed");
266        assert!(output.status.success());
267        assert_eq!(output.stdout, b"hello");
268        assert!(output.stderr.is_empty());
269    }
270
271    #[tokio::test]
272    async fn test_should_return_failure_output_from_mock() {
273        let runner = MockCommandRunner::failure("not found", 1);
274        let output = runner
275            .run("glab", &["repo", "view"])
276            .await
277            .expect("should succeed");
278        assert!(!output.status.success());
279        assert!(output.stdout.is_empty());
280        assert_eq!(output.stderr, b"not found");
281    }
282
283    #[tokio::test]
284    async fn test_should_return_spawn_error_from_mock() {
285        let runner = MockCommandRunner::spawn_error();
286        let err = runner
287            .run("glab", &["--version"])
288            .await
289            .expect_err("should fail");
290        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
291    }
292
293    #[tokio::test]
294    async fn test_should_clone_command_output() {
295        let runner = MockCommandRunner::success("data");
296        let output = runner.run("glab", &[]).await.expect("should succeed");
297        let cloned = output.clone();
298        assert_eq!(output.stdout, cloned.stdout);
299        assert_eq!(output.stderr, cloned.stderr);
300    }
301
302    #[tokio::test]
303    async fn test_should_clone_mock_runner() {
304        let runner = MockCommandRunner::success("cloneable");
305        let cloned = runner.clone();
306        let output = cloned.run("glab", &[]).await.expect("should succeed");
307        assert_eq!(output.stdout, b"cloneable");
308    }
309
310    #[tokio::test]
311    async fn test_should_yield_sequenced_responses() {
312        let runner = SequencedMockCommandRunner::from_results(&[
313            (true, "first"),
314            (false, "error"),
315            (true, "third"),
316        ]);
317
318        let out1 = runner.run("glab", &[]).await.expect("first should succeed");
319        assert!(out1.status.success());
320        assert_eq!(out1.stdout, b"first");
321
322        let out2 = runner
323            .run("glab", &[])
324            .await
325            .expect("second should 'succeed' as Output");
326        assert!(!out2.status.success());
327        assert_eq!(out2.stderr, b"error");
328
329        let out3 = runner.run("glab", &[]).await.expect("third should succeed");
330        assert_eq!(out3.stdout, b"third");
331    }
332
333    #[tokio::test]
334    async fn test_should_error_when_sequence_exhausted() {
335        let runner = SequencedMockCommandRunner::from_results(&[(true, "only")]);
336
337        let _ = runner.run("glab", &[]).await.expect("first call");
338        let err = runner.run("glab", &[]).await.expect_err("exhausted");
339        assert_eq!(err.kind(), std::io::ErrorKind::Other);
340    }
341}