Skip to main content

gitflow_gitcode/
pipeline.rs

1//! GitCode Pipeline 提供者实现。
2//!
3//! **注意**: GitCode CLI v0.6.1 不支持 `run` 命令,GitCode API 也没有 pipeline 端点。
4//! 所有方法返回友好错误消息。保留结构体供未来使用。
5
6use async_trait::async_trait;
7use gitflow_core::{
8    CoreError, Result,
9    pipeline::{JobData, PipelineProvider, PipelineReport, PipelineStatus, PipelineStatusEnum},
10};
11use serde::Deserialize;
12
13/// 将 GitCode `gc run list` 返回的 status 字符串映射为 [`PipelineStatusEnum`]。
14///
15/// GitCode 返回小写状态:`queued`、`in_progress`、`completed`、`waiting`、
16/// `requested`、`pending` 等。其中 `completed` 需要结合 `conclusion`
17/// 判断最终结果。
18#[allow(dead_code, reason = "Kept for future GitCode pipeline support")]
19fn gc_status_to_enum(status: &str, conclusion: Option<&str>) -> PipelineStatusEnum {
20    match status {
21        "completed" => match conclusion {
22            Some("success") => PipelineStatusEnum::Success,
23            Some("failure" | "startup_failure" | "timed_out") => PipelineStatusEnum::Failed,
24            Some("cancelled") => PipelineStatusEnum::Cancelled,
25            Some("skipped" | "neutral") => PipelineStatusEnum::Pending,
26            _ => PipelineStatusEnum::Running,
27        },
28        "queued" | "waiting" | "requested" | "pending" => PipelineStatusEnum::Pending,
29        _ => PipelineStatusEnum::Running,
30    }
31}
32
33/// GitCode 单次 run 的原始响应,用于反序列化。
34///
35/// Note: Currently unused because GitCode CLI v0.6.1 does not support `run` command.
36/// Kept for future use when pipeline support is added.
37#[derive(Debug, Deserialize)]
38#[serde(rename_all = "camelCase")]
39#[allow(dead_code, reason = "Kept for future GitCode pipeline support")]
40struct GcRun {
41    database_id: u64,
42    head_branch: String,
43    status: String,
44    conclusion: Option<String>,
45    created_at: String,
46    updated_at: String,
47    url: String,
48}
49
50impl GcRun {
51    #[allow(dead_code, reason = "Kept for future GitCode pipeline support")]
52    fn into_status(self) -> PipelineStatus {
53        let created_at = chrono::DateTime::parse_from_rfc3339(&self.created_at)
54            .map_or_else(|_| chrono::Utc::now(), |dt| dt.with_timezone(&chrono::Utc));
55        let updated_at = chrono::DateTime::parse_from_rfc3339(&self.updated_at)
56            .map_or_else(|_| chrono::Utc::now(), |dt| dt.with_timezone(&chrono::Utc));
57
58        PipelineStatus {
59            id: self.database_id,
60            ref_name: self.head_branch,
61            status: gc_status_to_enum(&self.status, self.conclusion.as_deref()),
62            conclusion: self.conclusion,
63            created_at,
64            updated_at,
65            url: self.url,
66        }
67    }
68}
69
70/// GitCode Pipeline 提供者,通过 `gitcode` CLI 操作 CI/CD 流水线。
71///
72/// # Examples
73///
74/// ```no_run
75/// use gitflow_gitcode::GitCodePipelineProvider;
76///
77/// let provider = GitCodePipelineProvider::new("octocat/hello-world");
78/// ```
79#[derive(Debug, Clone)]
80pub struct GitCodePipelineProvider {
81    #[allow(dead_code, reason = "Stored for future pipeline API calls")]
82    repo: String,
83}
84
85impl GitCodePipelineProvider {
86    /// 创建新的 GitCode Pipeline 提供者。
87    ///
88    /// `repo` 格式为 `owner/repo`。
89    #[must_use]
90    pub fn new(repo: impl Into<String>) -> Self {
91        Self { repo: repo.into() }
92    }
93}
94
95#[async_trait]
96impl PipelineProvider for GitCodePipelineProvider {
97    async fn status(&self, _branch: &str) -> Result<Vec<PipelineStatus>> {
98        Err(CoreError::Platform(
99            "GitCode does not support pipeline management. GitCode CLI v0.6.1 does not have 'run' \
100             command."
101                .into(),
102        ))
103    }
104
105    async fn logs(&self, _pipeline_id: u64) -> Result<String> {
106        Err(CoreError::Platform(
107            "GitCode does not support pipeline management. GitCode CLI v0.6.1 does not have 'run' \
108             command."
109                .into(),
110        ))
111    }
112
113    async fn jobs(&self, _pipeline_id: u64) -> Result<Vec<JobData>> {
114        Err(CoreError::Platform(
115            "GitCode does not support pipeline management. GitCode CLI v0.6.1 does not have 'run' \
116             command."
117                .into(),
118        ))
119    }
120
121    async fn report(&self, _branch: &str, _days: u32) -> Result<PipelineReport> {
122        Err(CoreError::Platform(
123            "GitCode does not support pipeline management. GitCode CLI v0.6.1 does not have 'run' \
124             command."
125                .into(),
126        ))
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn test_should_construct_gitcode_pipeline_provider() {
136        let provider = GitCodePipelineProvider::new("octocat/hello-world");
137        assert_eq!(provider.repo, "octocat/hello-world");
138    }
139
140    #[test]
141    fn test_should_construct_gitcode_pipeline_provider_from_string() {
142        let repo = String::from("octocat/hello-world");
143        let provider = GitCodePipelineProvider::new(repo);
144        assert_eq!(provider.repo, "octocat/hello-world");
145    }
146
147    #[test]
148    fn test_should_debug_format_provider() {
149        let provider = GitCodePipelineProvider::new("octocat/hello-world");
150        let debug = format!("{provider:?}");
151        assert!(debug.contains("GitCodePipelineProvider"));
152        assert!(debug.contains("octocat/hello-world"));
153    }
154
155    #[test]
156    fn test_should_clone_gitcode_pipeline_provider() {
157        let original = GitCodePipelineProvider::new("owner/repo");
158        let cloned = original.clone();
159        assert_eq!(original.repo, cloned.repo);
160    }
161
162    // --- Stub behavior: all pipeline operations are unsupported on GitCode ---
163
164    #[tokio::test]
165    async fn test_should_return_platform_error_for_status() {
166        let provider = GitCodePipelineProvider::new("owner/repo");
167        let result = provider.status("main").await;
168        assert!(matches!(result.unwrap_err(), CoreError::Platform(_)));
169    }
170
171    #[tokio::test]
172    async fn test_should_return_platform_error_for_logs() {
173        let provider = GitCodePipelineProvider::new("owner/repo");
174        let result = provider.logs(123).await;
175        assert!(matches!(result.unwrap_err(), CoreError::Platform(_)));
176    }
177
178    #[tokio::test]
179    async fn test_should_return_platform_error_for_jobs() {
180        let provider = GitCodePipelineProvider::new("owner/repo");
181        let result = provider.jobs(123).await;
182        assert!(matches!(result.unwrap_err(), CoreError::Platform(_)));
183    }
184
185    #[tokio::test]
186    async fn test_should_return_platform_error_for_report() {
187        let provider = GitCodePipelineProvider::new("owner/repo");
188        let result = provider.report("main", 7).await;
189        assert!(matches!(result.unwrap_err(), CoreError::Platform(_)));
190    }
191
192    #[test]
193    fn test_should_map_gc_status_completed_success() {
194        assert_eq!(
195            gc_status_to_enum("completed", Some("success")),
196            PipelineStatusEnum::Success
197        );
198    }
199
200    #[test]
201    fn test_should_map_gc_status_completed_failure() {
202        assert_eq!(
203            gc_status_to_enum("completed", Some("failure")),
204            PipelineStatusEnum::Failed
205        );
206        assert_eq!(
207            gc_status_to_enum("completed", Some("startup_failure")),
208            PipelineStatusEnum::Failed
209        );
210        assert_eq!(
211            gc_status_to_enum("completed", Some("timed_out")),
212            PipelineStatusEnum::Failed
213        );
214    }
215
216    #[test]
217    fn test_should_map_gc_status_completed_cancelled() {
218        assert_eq!(
219            gc_status_to_enum("completed", Some("cancelled")),
220            PipelineStatusEnum::Cancelled
221        );
222    }
223
224    #[test]
225    fn test_should_map_gc_status_completed_skipped() {
226        assert_eq!(
227            gc_status_to_enum("completed", Some("skipped")),
228            PipelineStatusEnum::Pending
229        );
230        assert_eq!(
231            gc_status_to_enum("completed", Some("neutral")),
232            PipelineStatusEnum::Pending
233        );
234    }
235
236    #[test]
237    fn test_should_map_gc_status_in_progress() {
238        assert_eq!(
239            gc_status_to_enum("in_progress", None),
240            PipelineStatusEnum::Running
241        );
242        assert_eq!(
243            gc_status_to_enum("action_required", None),
244            PipelineStatusEnum::Running
245        );
246    }
247
248    #[test]
249    fn test_should_map_gc_status_queued() {
250        assert_eq!(
251            gc_status_to_enum("queued", None),
252            PipelineStatusEnum::Pending
253        );
254        assert_eq!(
255            gc_status_to_enum("waiting", None),
256            PipelineStatusEnum::Pending
257        );
258        assert_eq!(
259            gc_status_to_enum("requested", None),
260            PipelineStatusEnum::Pending
261        );
262    }
263
264    #[test]
265    fn test_should_map_gc_status_unknown() {
266        assert_eq!(
267            gc_status_to_enum("some_unknown_status", None),
268            PipelineStatusEnum::Running
269        );
270    }
271
272    #[test]
273    fn test_should_map_completed_with_unknown_conclusion() {
274        assert_eq!(
275            gc_status_to_enum("completed", Some("weird")),
276            PipelineStatusEnum::Running
277        );
278    }
279
280    #[test]
281    fn test_should_map_completed_with_none_conclusion() {
282        assert_eq!(
283            gc_status_to_enum("completed", None),
284            PipelineStatusEnum::Running
285        );
286    }
287
288    #[test]
289    fn test_should_deserialize_gc_run_from_json() {
290        let json = br#"{
291            "databaseId": 12345,
292            "headBranch": "main",
293            "status": "completed",
294            "conclusion": "success",
295            "createdAt": "2026-07-01T10:00:00Z",
296            "updatedAt": "2026-07-01T10:05:30Z",
297            "url": "https://gitcode.com/example/repo/actions/runs/12345"
298        }"#;
299
300        let run: GcRun = serde_json::from_slice(json).expect("valid GcRun JSON");
301        assert_eq!(run.database_id, 12345);
302        assert_eq!(run.head_branch, "main");
303        assert_eq!(run.status, "completed");
304        assert_eq!(run.conclusion.as_deref(), Some("success"));
305        assert_eq!(
306            run.url,
307            "https://gitcode.com/example/repo/actions/runs/12345"
308        );
309    }
310
311    #[test]
312    fn test_should_convert_gc_run_to_pipeline_status() {
313        let run = GcRun {
314            database_id: 42,
315            head_branch: "main".into(),
316            status: "completed".into(),
317            conclusion: Some("success".into()),
318            created_at: "2026-07-01T10:00:00Z".into(),
319            updated_at: "2026-07-01T10:05:30Z".into(),
320            url: "https://example.com/42".into(),
321        };
322
323        let status = run.into_status();
324        assert_eq!(status.id, 42);
325        assert_eq!(status.ref_name, "main");
326        assert_eq!(status.status, PipelineStatusEnum::Success);
327        assert_eq!(status.conclusion.as_deref(), Some("success"));
328    }
329}