gitflow-gitcode 1.2.0

gf 的 GitCode 适配器,基于 gitcode CLI 提供 Issue/MR/Release/Review 等能力。GitCode adapter for gf via gitcode CLI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Command execution abstraction for GitCode CLI (`gitcode`/`gc`).
//!
//! This module provides the [`CommandRunner`] trait and its implementations,
//! allowing the GitCode crate to spawn CLI processes in production and inject
//! controlled outputs in tests.

use std::process::ExitStatus;

/// Output from a CLI command execution.
#[derive(Debug, Clone)]
pub struct CommandOutput {
    /// Process exit status.
    pub status: ExitStatus,
    /// Standard output bytes.
    pub stdout: Vec<u8>,
    /// Standard error bytes.
    pub stderr: Vec<u8>,
}

/// Trait for executing CLI commands. Abstracts process spawning for testability.
#[async_trait::async_trait]
pub trait CommandRunner: std::fmt::Debug + Send + Sync {
    /// Execute a command with the given program and arguments.
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the command cannot be spawned.
    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput>;

    /// Execute a command with the given program and arguments, writing
    /// `stdin_data` to the child process's standard input.
    ///
    /// This avoids exposing sensitive values (such as tokens) in process
    /// arguments, where they would be visible to other users via `ps`.
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the command cannot be spawned or if
    /// writing to its standard input fails.
    async fn run_with_stdin(
        &self,
        program: &str,
        args: &[&str],
        stdin_data: &[u8],
    ) -> std::io::Result<CommandOutput>;
}

/// Default implementation that spawns real processes via [`tokio::process::Command`].
#[derive(Debug, Clone, Default)]
pub struct RealCommandRunner;

#[async_trait::async_trait]
impl CommandRunner for RealCommandRunner {
    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
        let output = tokio::process::Command::new(program)
            .args(args)
            .output()
            .await?;
        Ok(CommandOutput {
            status: output.status,
            stdout: output.stdout,
            stderr: output.stderr,
        })
    }

    async fn run_with_stdin(
        &self,
        program: &str,
        args: &[&str],
        stdin_data: &[u8],
    ) -> std::io::Result<CommandOutput> {
        use tokio::io::AsyncWriteExt;

        let mut child = tokio::process::Command::new(program)
            .args(args)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()?;

        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(stdin_data).await?;
            drop(stdin);
        }

        let output = child.wait_with_output().await?;
        Ok(CommandOutput {
            status: output.status,
            stdout: output.stdout,
            stderr: output.stderr,
        })
    }
}

/// Mock implementation for testing failure scenarios.
///
/// Stores either a success output or an error kind with a message,
/// enabling `Clone` without requiring [`std::io::Error`] itself to be cloneable.
#[cfg(test)]
#[derive(Debug, Clone)]
pub struct MockCommandRunner {
    result: MockResult,
}

#[cfg(test)]
#[derive(Debug, Clone)]
enum MockResult {
    /// Successful command output.
    Output(CommandOutput),
    /// Spawn error with kind and message.
    Error(std::io::ErrorKind, String),
}

#[cfg(test)]
impl MockCommandRunner {
    #[cfg(unix)]
    pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
        use std::os::unix::process::ExitStatusExt;
        ExitStatus::from_raw(code)
    }

    #[cfg(windows)]
    pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
        use std::os::windows::process::ExitStatusExt;
        // Exit codes are conventionally non-negative; clamp negatives to 1.
        let raw = u32::try_from(code).unwrap_or(1);
        ExitStatus::from_raw(raw)
    }

    /// Create a mock that returns success with the given stdout.
    #[must_use]
    pub fn success(stdout: &str) -> Self {
        Self {
            result: MockResult::Output(CommandOutput {
                status: Self::make_exit_status(0),
                stdout: stdout.as_bytes().to_vec(),
                stderr: Vec::new(),
            }),
        }
    }

    /// Create a mock that returns failure with the given stderr and exit code.
    #[must_use]
    pub fn failure(stderr: &str, code: i32) -> Self {
        Self {
            result: MockResult::Output(CommandOutput {
                status: Self::make_exit_status(code),
                stdout: Vec::new(),
                stderr: stderr.as_bytes().to_vec(),
            }),
        }
    }

    /// Create a mock that returns a spawn error.
    #[must_use]
    pub fn spawn_error() -> Self {
        Self {
            result: MockResult::Error(std::io::ErrorKind::NotFound, "command not found".to_owned()),
        }
    }
}

#[cfg(test)]
#[async_trait::async_trait]
impl CommandRunner for MockCommandRunner {
    async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
        match &self.result {
            MockResult::Output(output) => Ok(output.clone()),
            MockResult::Error(kind, message) => Err(std::io::Error::new(*kind, message.clone())),
        }
    }

    async fn run_with_stdin(
        &self,
        program: &str,
        args: &[&str],
        _stdin_data: &[u8],
    ) -> std::io::Result<CommandOutput> {
        self.run(program, args).await
    }
}

/// Mock implementation that records every call's arguments while returning
/// a preconfigured result.
///
/// Used by regression tests that must assert the exact CLI invocation shape
/// (e.g. which flags the adapter passes to `gitcode`).
#[cfg(test)]
#[derive(Debug, Clone)]
pub struct RecordingMockRunner {
    inner: MockCommandRunner,
    calls: std::sync::Arc<std::sync::Mutex<Vec<Vec<String>>>>,
}

#[cfg(test)]
impl RecordingMockRunner {
    /// Create a recording runner that returns success with the given stdout.
    #[must_use]
    pub fn success(stdout: &str) -> Self {
        Self {
            inner: MockCommandRunner::success(stdout),
            calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        }
    }

    /// Create a recording runner that returns failure with the given stderr.
    #[must_use]
    pub fn failure(stderr: &str, code: i32) -> Self {
        Self {
            inner: MockCommandRunner::failure(stderr, code),
            calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
        }
    }

    /// Snapshot of all recorded calls; each entry is the argv (without program).
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (a precedent panic occurred while
    /// holding the lock).
    #[must_use]
    pub fn calls(&self) -> Vec<Vec<String>> {
        self.calls
            .lock()
            .expect("RecordingMockRunner mutex poisoned")
            .clone()
    }
}

#[cfg(test)]
#[async_trait::async_trait]
impl CommandRunner for RecordingMockRunner {
    async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
        self.calls
            .lock()
            .expect("RecordingMockRunner mutex poisoned")
            .push(args.iter().map(|s| (*s).to_owned()).collect());
        self.inner.run(program, args).await
    }

    async fn run_with_stdin(
        &self,
        program: &str,
        args: &[&str],
        stdin_data: &[u8],
    ) -> std::io::Result<CommandOutput> {
        self.calls
            .lock()
            .expect("RecordingMockRunner mutex poisoned")
            .push(args.iter().map(|s| (*s).to_owned()).collect());
        self.inner.run_with_stdin(program, args, stdin_data).await
    }
}

/// Mock implementation that returns a sequence of preconfigured responses.
///
/// Each call to [`CommandRunner::run`] pops the next response from the queue.
/// Useful for testing retry logic where different commands must succeed or fail
/// in a specific order (e.g., `add_labels` retries after auto-creating a label).
#[cfg(test)]
#[derive(Debug, Clone)]
pub struct SequencedMockCommandRunner {
    responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
}

#[cfg(test)]
impl SequencedMockCommandRunner {
    /// Build a runner that yields `outputs` in order, one per `run` call.
    #[must_use]
    pub fn new(outputs: Vec<CommandOutput>) -> Self {
        Self {
            responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
        }
    }

    /// Convenience: build a sequence from `(success, stdout_or_stderr)` tuples.
    #[must_use]
    pub fn from_results(results: &[(bool, &str)]) -> Self {
        let outputs = results
            .iter()
            .map(|&(ok, text)| {
                if ok {
                    CommandOutput {
                        status: MockCommandRunner::make_exit_status(0),
                        stdout: text.as_bytes().to_vec(),
                        stderr: Vec::new(),
                    }
                } else {
                    CommandOutput {
                        status: MockCommandRunner::make_exit_status(1),
                        stdout: Vec::new(),
                        stderr: text.as_bytes().to_vec(),
                    }
                }
            })
            .collect();
        Self::new(outputs)
    }
}

#[cfg(test)]
#[async_trait::async_trait]
impl CommandRunner for SequencedMockCommandRunner {
    async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
        let mut guard = self
            .responses
            .lock()
            .expect("SequencedMockCommandRunner mutex poisoned");
        guard
            .pop_front()
            .ok_or_else(|| std::io::Error::other("no more responses"))
    }

    async fn run_with_stdin(
        &self,
        program: &str,
        args: &[&str],
        _stdin_data: &[u8],
    ) -> std::io::Result<CommandOutput> {
        self.run(program, args).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_should_return_success_output_from_mock() {
        let runner = MockCommandRunner::success("hello");
        let output = runner
            .run("gc", &["--version"])
            .await
            .expect("should succeed");
        assert!(output.status.success());
        assert_eq!(output.stdout, b"hello");
        assert!(output.stderr.is_empty());
    }

    #[tokio::test]
    async fn test_should_return_failure_output_from_mock() {
        let runner = MockCommandRunner::failure("not found", 1);
        let output = runner
            .run("gc", &["repo", "view"])
            .await
            .expect("should succeed");
        assert!(!output.status.success());
        assert!(output.stdout.is_empty());
        assert_eq!(output.stderr, b"not found");
    }

    #[tokio::test]
    async fn test_should_return_spawn_error_from_mock() {
        let runner = MockCommandRunner::spawn_error();
        let err = runner
            .run("gc", &["--version"])
            .await
            .expect_err("should fail");
        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
    }

    #[tokio::test]
    async fn test_should_clone_command_output() {
        let runner = MockCommandRunner::success("data");
        let output = runner.run("gc", &[]).await.expect("should succeed");
        let cloned = output.clone();
        assert_eq!(output.stdout, cloned.stdout);
        assert_eq!(output.stderr, cloned.stderr);
    }

    #[tokio::test]
    async fn test_should_clone_mock_runner() {
        let runner = MockCommandRunner::success("cloneable");
        let cloned = runner.clone();
        let output = cloned.run("gc", &[]).await.expect("should succeed");
        assert_eq!(output.stdout, b"cloneable");
    }

    #[tokio::test]
    async fn test_should_record_arguments_in_recording_runner() {
        let runner = RecordingMockRunner::success("{}");
        let output = runner
            .run("gc", &["pr", "view", "20", "--json"])
            .await
            .expect("should succeed");
        assert!(output.status.success());

        let calls = runner.calls();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0], vec!["pr", "view", "20", "--json"]);
    }

    #[tokio::test]
    async fn test_should_record_multiple_calls_in_order() {
        let runner = RecordingMockRunner::success("ok");
        runner
            .run("gc", &["issue", "label", "1", "--add", "bug"])
            .await
            .expect("first");
        runner
            .run("gc", &["issue", "label", "1", "--remove", "bug"])
            .await
            .expect("second");

        let calls = runner.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[1], vec!["issue", "label", "1", "--remove", "bug"]);
    }

    #[tokio::test]
    async fn test_should_yield_sequenced_responses() {
        let runner = SequencedMockCommandRunner::from_results(&[
            (true, "first"),
            (false, "error"),
            (true, "third"),
        ]);

        let out1 = runner.run("gc", &[]).await.expect("first should succeed");
        assert!(out1.status.success());
        assert_eq!(out1.stdout, b"first");

        let out2 = runner
            .run("gc", &[])
            .await
            .expect("second should 'succeed' as Output");
        assert!(!out2.status.success());
        assert_eq!(out2.stderr, b"error");

        let out3 = runner.run("gc", &[]).await.expect("third should succeed");
        assert_eq!(out3.stdout, b"third");
    }

    #[tokio::test]
    async fn test_should_error_when_sequence_exhausted() {
        let runner = SequencedMockCommandRunner::from_results(&[(true, "only")]);

        let _ = runner.run("gc", &[]).await.expect("first call");
        let err = runner.run("gc", &[]).await.expect_err("exhausted");
        assert_eq!(err.kind(), std::io::ErrorKind::Other);
    }
}