Skip to main content

gitflow_gitcode/
runner.rs

1//! Command execution abstraction for GitCode CLI (`gitcode`/`gc`).
2//!
3//! This module provides the [`CommandRunner`] trait and its implementations,
4//! allowing the GitCode 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 records every call's arguments while returning
184/// a preconfigured result.
185///
186/// Used by regression tests that must assert the exact CLI invocation shape
187/// (e.g. which flags the adapter passes to `gitcode`).
188#[cfg(test)]
189#[derive(Debug, Clone)]
190pub struct RecordingMockRunner {
191    inner: MockCommandRunner,
192    calls: std::sync::Arc<std::sync::Mutex<Vec<Vec<String>>>>,
193}
194
195#[cfg(test)]
196impl RecordingMockRunner {
197    /// Create a recording runner that returns success with the given stdout.
198    #[must_use]
199    pub fn success(stdout: &str) -> Self {
200        Self {
201            inner: MockCommandRunner::success(stdout),
202            calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
203        }
204    }
205
206    /// Create a recording runner that returns failure with the given stderr.
207    #[must_use]
208    pub fn failure(stderr: &str, code: i32) -> Self {
209        Self {
210            inner: MockCommandRunner::failure(stderr, code),
211            calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
212        }
213    }
214
215    /// Snapshot of all recorded calls; each entry is the argv (without program).
216    ///
217    /// # Panics
218    ///
219    /// Panics if the internal mutex is poisoned (a precedent panic occurred while
220    /// holding the lock).
221    #[must_use]
222    pub fn calls(&self) -> Vec<Vec<String>> {
223        self.calls
224            .lock()
225            .expect("RecordingMockRunner mutex poisoned")
226            .clone()
227    }
228}
229
230#[cfg(test)]
231#[async_trait::async_trait]
232impl CommandRunner for RecordingMockRunner {
233    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
234        self.calls
235            .lock()
236            .expect("RecordingMockRunner mutex poisoned")
237            .push(args.iter().map(|s| (*s).to_owned()).collect());
238        self.inner.run(program, args).await
239    }
240
241    async fn run_with_stdin(
242        &self,
243        program: &str,
244        args: &[&str],
245        stdin_data: &[u8],
246    ) -> std::io::Result<CommandOutput> {
247        self.calls
248            .lock()
249            .expect("RecordingMockRunner mutex poisoned")
250            .push(args.iter().map(|s| (*s).to_owned()).collect());
251        self.inner.run_with_stdin(program, args, stdin_data).await
252    }
253}
254
255/// Mock implementation that returns a sequence of preconfigured responses.
256///
257/// Each call to [`CommandRunner::run`] pops the next response from the queue.
258/// Useful for testing retry logic where different commands must succeed or fail
259/// in a specific order (e.g., `add_labels` retries after auto-creating a label).
260#[cfg(test)]
261#[derive(Debug, Clone)]
262pub struct SequencedMockCommandRunner {
263    responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
264}
265
266#[cfg(test)]
267impl SequencedMockCommandRunner {
268    /// Build a runner that yields `outputs` in order, one per `run` call.
269    #[must_use]
270    pub fn new(outputs: Vec<CommandOutput>) -> Self {
271        Self {
272            responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
273        }
274    }
275
276    /// Convenience: build a sequence from `(success, stdout_or_stderr)` tuples.
277    #[must_use]
278    pub fn from_results(results: &[(bool, &str)]) -> Self {
279        let outputs = results
280            .iter()
281            .map(|&(ok, text)| {
282                if ok {
283                    CommandOutput {
284                        status: MockCommandRunner::make_exit_status(0),
285                        stdout: text.as_bytes().to_vec(),
286                        stderr: Vec::new(),
287                    }
288                } else {
289                    CommandOutput {
290                        status: MockCommandRunner::make_exit_status(1),
291                        stdout: Vec::new(),
292                        stderr: text.as_bytes().to_vec(),
293                    }
294                }
295            })
296            .collect();
297        Self::new(outputs)
298    }
299}
300
301#[cfg(test)]
302#[async_trait::async_trait]
303impl CommandRunner for SequencedMockCommandRunner {
304    async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
305        let mut guard = self
306            .responses
307            .lock()
308            .expect("SequencedMockCommandRunner mutex poisoned");
309        guard
310            .pop_front()
311            .ok_or_else(|| std::io::Error::other("no more responses"))
312    }
313
314    async fn run_with_stdin(
315        &self,
316        program: &str,
317        args: &[&str],
318        _stdin_data: &[u8],
319    ) -> std::io::Result<CommandOutput> {
320        self.run(program, args).await
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[tokio::test]
329    async fn test_should_return_success_output_from_mock() {
330        let runner = MockCommandRunner::success("hello");
331        let output = runner
332            .run("gitcode", &["--version"])
333            .await
334            .expect("should succeed");
335        assert!(output.status.success());
336        assert_eq!(output.stdout, b"hello");
337        assert!(output.stderr.is_empty());
338    }
339
340    #[tokio::test]
341    async fn test_should_return_failure_output_from_mock() {
342        let runner = MockCommandRunner::failure("not found", 1);
343        let output = runner
344            .run("gitcode", &["repo", "view"])
345            .await
346            .expect("should succeed");
347        assert!(!output.status.success());
348        assert!(output.stdout.is_empty());
349        assert_eq!(output.stderr, b"not found");
350    }
351
352    #[tokio::test]
353    async fn test_should_return_spawn_error_from_mock() {
354        let runner = MockCommandRunner::spawn_error();
355        let err = runner
356            .run("gitcode", &["--version"])
357            .await
358            .expect_err("should fail");
359        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
360    }
361
362    #[tokio::test]
363    async fn test_should_clone_command_output() {
364        let runner = MockCommandRunner::success("data");
365        let output = runner.run("gitcode", &[]).await.expect("should succeed");
366        let cloned = output.clone();
367        assert_eq!(output.stdout, cloned.stdout);
368        assert_eq!(output.stderr, cloned.stderr);
369    }
370
371    #[tokio::test]
372    async fn test_should_clone_mock_runner() {
373        let runner = MockCommandRunner::success("cloneable");
374        let cloned = runner.clone();
375        let output = cloned.run("gitcode", &[]).await.expect("should succeed");
376        assert_eq!(output.stdout, b"cloneable");
377    }
378
379    #[tokio::test]
380    async fn test_should_record_arguments_in_recording_runner() {
381        let runner = RecordingMockRunner::success("{}");
382        let output = runner
383            .run("gitcode", &["pr", "view", "20", "--json"])
384            .await
385            .expect("should succeed");
386        assert!(output.status.success());
387
388        let calls = runner.calls();
389        assert_eq!(calls.len(), 1);
390        assert_eq!(calls[0], vec!["pr", "view", "20", "--json"]);
391    }
392
393    #[tokio::test]
394    async fn test_should_record_multiple_calls_in_order() {
395        let runner = RecordingMockRunner::success("ok");
396        runner
397            .run("gitcode", &["issue", "label", "1", "--add", "bug"])
398            .await
399            .expect("first");
400        runner
401            .run("gitcode", &["issue", "label", "1", "--remove", "bug"])
402            .await
403            .expect("second");
404
405        let calls = runner.calls();
406        assert_eq!(calls.len(), 2);
407        assert_eq!(calls[1], vec!["issue", "label", "1", "--remove", "bug"]);
408    }
409}