Skip to main content

gitflow_cli_adapter_utils/
lib.rs

1//! Shared utilities for gf platform adapter crates.
2//!
3//! Provides the [`CommandRunner`] trait and [`RealCommandRunner`] implementation
4//! for spawning CLI processes, along with the [`CommandOutput`] type for
5//! representing command results.
6
7#![forbid(unsafe_code)]
8#![warn(missing_docs)]
9#![warn(missing_debug_implementations)]
10
11use std::process::ExitStatus;
12
13/// Output from a CLI command execution.
14#[derive(Debug, Clone)]
15pub struct CommandOutput {
16    /// Process exit status.
17    pub status: ExitStatus,
18    /// Standard output bytes.
19    pub stdout: Vec<u8>,
20    /// Standard error bytes.
21    pub stderr: Vec<u8>,
22}
23
24/// Trait for executing CLI commands. Abstracts process spawning for testability.
25///
26/// Platform adapter crates use this trait to spawn their respective CLI tools
27/// (`gh`, `glab`, `gc`). Tests can inject mock implementations to control
28/// command output without requiring the actual CLI tools to be installed.
29#[async_trait::async_trait]
30pub trait CommandRunner: std::fmt::Debug + Send + Sync {
31    /// Execute a command with the given program and arguments.
32    ///
33    /// # Errors
34    ///
35    /// Returns [`std::io::Error`] if the command cannot be spawned.
36    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput>;
37
38    /// Execute a command with the given program and arguments, writing
39    /// `stdin_data` to the child process's standard input.
40    ///
41    /// This avoids exposing sensitive values (such as tokens) in process
42    /// arguments, where they would be visible to other users via `ps`.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`std::io::Error`] if the command cannot be spawned or if
47    /// writing to its standard input fails.
48    async fn run_with_stdin(
49        &self,
50        program: &str,
51        args: &[&str],
52        stdin_data: &[u8],
53    ) -> std::io::Result<CommandOutput>;
54}
55
56/// Default implementation that spawns real processes via [`tokio::process::Command`].
57///
58/// Used in production by all platform adapter crates.
59#[derive(Debug, Clone, Default)]
60pub struct RealCommandRunner;
61
62#[async_trait::async_trait]
63impl CommandRunner for RealCommandRunner {
64    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
65        let output = tokio::process::Command::new(program)
66            .args(args)
67            .output()
68            .await?;
69        Ok(CommandOutput {
70            status: output.status,
71            stdout: output.stdout,
72            stderr: output.stderr,
73        })
74    }
75
76    async fn run_with_stdin(
77        &self,
78        program: &str,
79        args: &[&str],
80        stdin_data: &[u8],
81    ) -> std::io::Result<CommandOutput> {
82        use tokio::io::AsyncWriteExt;
83
84        let mut child = tokio::process::Command::new(program)
85            .args(args)
86            .stdin(std::process::Stdio::piped())
87            .stdout(std::process::Stdio::piped())
88            .stderr(std::process::Stdio::piped())
89            .spawn()?;
90
91        if let Some(mut stdin) = child.stdin.take() {
92            stdin.write_all(stdin_data).await?;
93            drop(stdin);
94        }
95
96        let output = child.wait_with_output().await?;
97        Ok(CommandOutput {
98            status: output.status,
99            stdout: output.stdout,
100            stderr: output.stderr,
101        })
102    }
103}
104
105/// Read-only access to process environment variables.
106///
107/// Abstracts environment lookups so tests can inject deterministic values
108/// instead of mutating process-global state. Mutating the real environment
109/// races with other tests running in parallel threads of the same process.
110pub trait EnvSource: std::fmt::Debug + Send + Sync {
111    /// Return the value of `key`.
112    ///
113    /// Returns `None` when the variable is unset or its value is not valid
114    /// UTF-8 — both cases are indistinguishable to callers, matching the
115    /// `std::env::var(..).ok()` behaviour this trait replaces.
116    fn var(&self, key: &str) -> Option<String>;
117}
118
119/// Default [`EnvSource`] reading the real process environment.
120///
121/// Used in production by all platform adapter crates.
122#[derive(Debug, Clone, Copy, Default)]
123pub struct RealEnv;
124
125impl EnvSource for RealEnv {
126    fn var(&self, key: &str) -> Option<String> {
127        std::env::var(key).ok()
128    }
129}
130
131/// In-memory [`EnvSource`] for tests.
132///
133/// Holds a fixed set of variables and never touches the process environment,
134/// so tests using it are immune both to parallel-test interference and to
135/// whatever the developer happens to have exported in their shell.
136///
137/// # Examples
138///
139/// ```
140/// use gitflow_cli_adapter_utils::{EnvSource, MockEnv};
141///
142/// let env = MockEnv::with("GL_TOKEN", "glpat-example");
143/// assert_eq!(env.var("GL_TOKEN"), Some("glpat-example".to_string()));
144/// assert_eq!(env.var("GITLAB_HOST"), None);
145/// ```
146#[cfg(feature = "test-util")]
147#[derive(Debug, Clone, Default)]
148pub struct MockEnv {
149    /// Fixed variable table consulted by [`EnvSource::var`].
150    vars: std::collections::HashMap<String, String>,
151}
152
153#[cfg(feature = "test-util")]
154impl MockEnv {
155    /// Create a source where every lookup returns `None`.
156    #[must_use]
157    pub fn empty() -> Self {
158        Self::default()
159    }
160
161    /// Create a source holding exactly one variable.
162    #[must_use]
163    pub fn with(key: &str, value: &str) -> Self {
164        let mut vars = std::collections::HashMap::new();
165        vars.insert(key.to_string(), value.to_string());
166        Self { vars }
167    }
168}
169
170#[cfg(feature = "test-util")]
171impl EnvSource for MockEnv {
172    fn var(&self, key: &str) -> Option<String> {
173        self.vars.get(key).cloned()
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[cfg(feature = "test-util")]
182    #[test]
183    fn test_should_return_none_from_mock_env_when_key_absent() {
184        let env = MockEnv::empty();
185        assert_eq!(env.var("GL_TOKEN"), None);
186    }
187
188    #[cfg(feature = "test-util")]
189    #[test]
190    fn test_should_return_value_from_mock_env_when_key_present() {
191        let env = MockEnv::with("GL_TOKEN", "glpat-mock");
192        assert_eq!(env.var("GL_TOKEN"), Some("glpat-mock".to_string()));
193    }
194
195    #[cfg(feature = "test-util")]
196    #[test]
197    fn test_should_isolate_unrelated_keys_in_mock_env() {
198        let env = MockEnv::with("GL_TOKEN", "glpat-mock");
199        assert_eq!(env.var("GITLAB_HOST"), None);
200    }
201
202    #[test]
203    fn test_should_read_real_process_env_through_real_env() {
204        // PATH 在所有支持的平台上均已设置,且本测试只读不写,
205        // 因此不会与并行测试产生竞态。
206        let env = RealEnv;
207        assert!(env.var("PATH").is_some());
208    }
209
210    #[test]
211    fn test_should_return_none_from_real_env_for_absent_key() {
212        let env = RealEnv;
213        assert_eq!(env.var("GF_DEFINITELY_NOT_SET_12345"), None);
214    }
215}