Skip to main content

gitflow_gitlab/
pipeline.rs

1//! GitLab Pipeline (CI/CD) 提供者实现。
2//!
3//! 通过 `glab ci` CLI 命令实现 [`PipelineProvider`] trait,支持 Pipeline
4//! 状态查看、日志获取、任务列表和报告生成。
5//! 所有方法通过 [`CommandRunner`] 抽象调用 `glab`,测试可注入自定义 runner
6//! 以模拟成功或失败场景。
7//!
8//! glab 命令映射:
9//! - `status` → `glab ci list`
10//! - `logs` → `glab ci trace`
11//! - `jobs` → `glab ci view --output json`
12//! - `report` → 调用 `status` 后计算统计
13
14use async_trait::async_trait;
15use chrono::{DateTime, Utc};
16use gitflow_core::{
17    CoreError, Result,
18    pipeline::{JobData, PipelineProvider, PipelineReport, PipelineStatus, PipelineStatusEnum},
19};
20use serde::Deserialize;
21use tracing::debug;
22
23use crate::{
24    error::parse_glab_error,
25    runner::{CommandRunner, RealCommandRunner},
26};
27
28/// GitLab Pipeline 提供者,通过 `glab ci` 操作 CI/CD 管线。
29///
30/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
31/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
32///
33/// # Examples
34///
35/// ```no_run
36/// use gitflow_gitlab::GitLabPipelineProvider;
37///
38/// let provider = GitLabPipelineProvider::new("gitlab-org/gitlab");
39/// ```
40#[derive(Debug, Clone)]
41pub struct GitLabPipelineProvider<R: CommandRunner = RealCommandRunner> {
42    /// GitLab `namespace/project`。
43    repo: String,
44    /// 用于执行 `glab` CLI 命令的 runner。
45    runner: R,
46}
47
48impl GitLabPipelineProvider<RealCommandRunner> {
49    /// 创建新的 GitLab Pipeline 提供者,使用真实的进程执行器。
50    ///
51    /// `repo` 格式为 `namespace/project`。
52    #[must_use]
53    pub fn new(repo: impl Into<String>) -> Self {
54        Self {
55            repo: repo.into(),
56            runner: RealCommandRunner,
57        }
58    }
59}
60
61impl<R: CommandRunner> GitLabPipelineProvider<R> {
62    /// 使用自定义 [`CommandRunner`] 创建提供者。
63    ///
64    /// 主要用于测试,可注入模拟 runner 以控制 `glab` CLI 的输出。
65    /// `repo` 格式为 `namespace/project`。
66    #[must_use]
67    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
68        Self {
69            repo: repo.into(),
70            runner,
71        }
72    }
73}
74
75// ── 中间 API 响应类型 ──────────────────────────────────────────────
76
77/// `glab ci list --output json` 返回的 Pipeline JSON 结构。
78#[derive(Debug, Clone, Deserialize)]
79#[allow(
80    dead_code,
81    reason = "Used for deserialization; not all fields are read"
82)]
83struct PipelineApiResponse {
84    id: u64,
85    #[serde(default)]
86    ref_name: Option<String>,
87    /// glab may use `ref` instead of `ref_name`
88    #[serde(alias = "ref")]
89    #[serde(default)]
90    git_ref: Option<String>,
91    #[serde(default)]
92    status: String,
93    #[serde(default)]
94    created_at: Option<DateTime<Utc>>,
95    #[serde(default)]
96    updated_at: Option<DateTime<Utc>>,
97    #[serde(default)]
98    web_url: Option<String>,
99    /// Some glab versions include a `sha` field
100    #[serde(default)]
101    sha: Option<String>,
102}
103
104impl PipelineApiResponse {
105    fn effective_ref(&self) -> String {
106        self.ref_name
107            .clone()
108            .or_else(|| self.git_ref.clone())
109            .unwrap_or_default()
110    }
111}
112
113fn parse_pipeline_status(status: &str) -> PipelineStatusEnum {
114    match status {
115        "running" => PipelineStatusEnum::Running,
116        "success" => PipelineStatusEnum::Success,
117        "failed" => PipelineStatusEnum::Failed,
118        "canceled" | "cancelled" => PipelineStatusEnum::Cancelled,
119        _ => PipelineStatusEnum::Pending,
120    }
121}
122
123impl From<PipelineApiResponse> for PipelineStatus {
124    fn from(api: PipelineApiResponse) -> Self {
125        let status_enum = parse_pipeline_status(&api.status);
126        let conclusion = if api.status == "success" {
127            Some("success".into())
128        } else if api.status == "failed" {
129            Some("failure".into())
130        } else if api.status == "canceled" || api.status == "cancelled" {
131            Some("cancelled".into())
132        } else {
133            None
134        };
135
136        Self {
137            id: api.id,
138            ref_name: api.effective_ref(),
139            status: status_enum,
140            conclusion,
141            created_at: api.created_at.unwrap_or_else(Utc::now),
142            updated_at: api.updated_at.unwrap_or_else(Utc::now),
143            url: api.web_url.unwrap_or_default(),
144        }
145    }
146}
147
148/// `glab ci view --output json` 返回的 Job JSON 结构。
149#[derive(Debug, Clone, Deserialize)]
150#[allow(
151    dead_code,
152    reason = "Used for deserialization; not all fields are read"
153)]
154struct JobApiResponse {
155    id: u64,
156    #[serde(default)]
157    name: String,
158    #[serde(default)]
159    status: String,
160    #[serde(default)]
161    stage: Option<String>,
162    #[serde(default)]
163    started_at: Option<DateTime<Utc>>,
164    #[serde(default)]
165    finished_at: Option<DateTime<Utc>>,
166    #[serde(default)]
167    web_url: Option<String>,
168}
169
170impl From<JobApiResponse> for JobData {
171    fn from(api: JobApiResponse) -> Self {
172        let conclusion = if api.status == "success" {
173            Some("success".into())
174        } else if api.status == "failed" {
175            Some("failure".into())
176        } else if api.status == "canceled" || api.status == "cancelled" {
177            Some("cancelled".into())
178        } else {
179            None
180        };
181
182        Self {
183            id: api.id,
184            name: api.name,
185            status: api.status,
186            conclusion,
187            started_at: api.started_at,
188            completed_at: api.finished_at,
189            url: api.web_url.unwrap_or_default(),
190        }
191    }
192}
193
194/// Helper struct for parsing `glab ci view` output that may contain
195/// a pipeline object with an embedded `jobs` field.
196#[derive(Debug, Deserialize)]
197struct PipelineWithJobs {
198    #[serde(default)]
199    jobs: Vec<JobApiResponse>,
200}
201
202// ── trait 实现 ──────────────────────────────────────────────────────
203
204#[async_trait]
205impl<R: CommandRunner + 'static> PipelineProvider for GitLabPipelineProvider<R> {
206    /// 获取指定分支的 Pipeline 状态列表。
207    ///
208    /// 调用 `glab ci list --ref <branch> --output json`。
209    async fn status(&self, branch: &str) -> Result<Vec<PipelineStatus>> {
210        debug!(repo = %self.repo, branch, "spawning `glab ci list`");
211
212        let output = self
213            .runner
214            .run(
215                "glab",
216                &[
217                    "ci", "list", "--repo", &self.repo, "--ref", branch, "--output", "json",
218                ],
219            )
220            .await
221            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab ci list: {e}")))?;
222
223        if !output.status.success() {
224            return Err(parse_glab_error(&output.stderr).into());
225        }
226
227        let api_responses: Vec<PipelineApiResponse> =
228            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
229
230        Ok(api_responses
231            .into_iter()
232            .map(PipelineStatus::from)
233            .collect())
234    }
235
236    /// 获取指定 Pipeline 的日志。
237    ///
238    /// 调用 `glab ci trace <pipeline_id>` 或 `glab ci view <pipeline_id>`。
239    async fn logs(&self, pipeline_id: u64) -> Result<String> {
240        debug!(repo = %self.repo, pipeline_id, "spawning `glab ci trace`");
241
242        let id_str = pipeline_id.to_string();
243        let output = self
244            .runner
245            .run("glab", &["ci", "trace", &id_str, "--repo", &self.repo])
246            .await
247            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab ci trace: {e}")))?;
248
249        if !output.status.success() {
250            return Err(parse_glab_error(&output.stderr).into());
251        }
252
253        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
254    }
255
256    /// 获取指定 Pipeline 的 Job 列表。
257    ///
258    /// 调用 `glab ci view <pipeline_id> --output json`。
259    async fn jobs(&self, pipeline_id: u64) -> Result<Vec<JobData>> {
260        debug!(repo = %self.repo, pipeline_id, "spawning `glab ci view`");
261
262        let id_str = pipeline_id.to_string();
263        let output = self
264            .runner
265            .run(
266                "glab",
267                &[
268                    "ci", "view", &id_str, "--repo", &self.repo, "--output", "json",
269                ],
270            )
271            .await
272            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab ci view: {e}")))?;
273
274        if !output.status.success() {
275            return Err(parse_glab_error(&output.stderr).into());
276        }
277
278        // glab ci view may return the pipeline object with embedded jobs,
279        // or a jobs list depending on version. Try parsing as jobs first.
280        if let Ok(jobs) = serde_json::from_slice::<Vec<JobApiResponse>>(&output.stdout) {
281            return Ok(jobs.into_iter().map(JobData::from).collect());
282        }
283
284        // If that fails, try parsing as a pipeline with jobs field
285        let pipeline: PipelineWithJobs =
286            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
287        Ok(pipeline.jobs.into_iter().map(JobData::from).collect())
288    }
289
290    /// 生成指定分支最近 `days` 天的 Pipeline 报告。
291    ///
292    /// 调用 `status` 获取 Pipeline 列表,然后计算统计信息。
293    async fn report(&self, branch: &str, days: u32) -> Result<PipelineReport> {
294        debug!(
295            repo = %self.repo,
296            branch,
297            days,
298            "generating pipeline report"
299        );
300
301        let pipelines = self.status(branch).await?;
302
303        // Filter by date range
304        let cutoff = Utc::now() - chrono::Duration::days(i64::from(days));
305        let recent: Vec<&PipelineStatus> = pipelines
306            .iter()
307            .filter(|p| p.created_at >= cutoff)
308            .collect();
309
310        let total_runs = recent.len() as u64;
311        if total_runs == 0 {
312            return Ok(PipelineReport {
313                total_runs: 0,
314                success_rate: 0.0,
315                avg_duration_secs: 0.0,
316                top_failures: vec![],
317            });
318        }
319
320        let success_count = recent
321            .iter()
322            .filter(|p| matches!(p.status, PipelineStatusEnum::Success))
323            .count() as u64;
324
325        let success_rate = {
326            #[allow(
327                clippy::cast_precision_loss,
328                reason = "Pipeline counts never exceed f64 precision"
329            )]
330            {
331                success_count as f64 / total_runs as f64
332            }
333        };
334
335        // Calculate average duration
336        #[allow(
337            clippy::cast_precision_loss,
338            reason = "Duration values never exceed f64 precision"
339        )]
340        let durations: Vec<f64> = recent
341            .iter()
342            .map(|p| (p.updated_at - p.created_at).num_seconds().max(0) as f64)
343            .filter(|d| *d > 0.0)
344            .collect();
345
346        let avg_duration_secs = if durations.is_empty() {
347            0.0
348        } else {
349            #[allow(
350                clippy::cast_precision_loss,
351                reason = "Duration length never exceeds f64 precision"
352            )]
353            {
354                durations.iter().sum::<f64>() / durations.len() as f64
355            }
356        };
357
358        // Find top failures (by ref)
359        let mut failure_refs: Vec<String> = recent
360            .iter()
361            .filter(|p| matches!(p.status, PipelineStatusEnum::Failed))
362            .map(|p| p.ref_name.clone())
363            .collect();
364        failure_refs.sort();
365        failure_refs.dedup();
366
367        Ok(PipelineReport {
368            total_runs,
369            success_rate,
370            avg_duration_secs,
371            top_failures: failure_refs,
372        })
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379    use crate::runner::MockCommandRunner;
380
381    #[test]
382    fn test_should_construct_gitlab_pipeline_provider() {
383        let provider = GitLabPipelineProvider::new("gitlab-org/gitlab");
384        assert_eq!(provider.repo, "gitlab-org/gitlab");
385    }
386
387    #[test]
388    fn test_should_construct_gitlab_pipeline_provider_from_string() {
389        let repo = String::from("gitlab-org/gitlab");
390        let provider = GitLabPipelineProvider::new(repo);
391        assert_eq!(provider.repo, "gitlab-org/gitlab");
392    }
393
394    #[test]
395    fn test_should_debug_format_pipeline_provider() {
396        let provider = GitLabPipelineProvider::new("owner/repo");
397        let debug = format!("{provider:?}");
398        assert!(debug.contains("GitLabPipelineProvider"));
399        assert!(debug.contains("owner/repo"));
400    }
401
402    #[test]
403    fn test_should_clone_gitlab_pipeline_provider() {
404        let original = GitLabPipelineProvider::new("owner/repo");
405        let cloned = original.clone();
406        assert_eq!(original.repo, cloned.repo);
407    }
408
409    // --- API response deserialization tests ---
410
411    #[test]
412    fn test_should_deserialize_pipeline_api_response() {
413        let json = br#"{
414            "id": 12345,
415            "ref_name": "main",
416            "status": "success",
417            "created_at": "2026-01-15T09:30:00Z",
418            "updated_at": "2026-01-15T09:35:00Z",
419            "web_url": "https://gitlab.com/gitlab-org/gitlab/-/pipelines/12345"
420        }"#;
421
422        let api: PipelineApiResponse =
423            serde_json::from_slice(json).expect("valid PipelineApiResponse");
424        assert_eq!(api.id, 12345);
425        assert_eq!(api.status, "success");
426        assert_eq!(api.effective_ref(), "main");
427    }
428
429    #[test]
430    fn test_should_deserialize_pipeline_with_ref_alias() {
431        let json = br#"{
432            "id": 12345,
433            "ref": "main",
434            "status": "success",
435            "created_at": "2026-01-15T09:30:00Z",
436            "updated_at": "2026-01-15T09:35:00Z"
437        }"#;
438
439        let api: PipelineApiResponse =
440            serde_json::from_slice(json).expect("valid PipelineApiResponse");
441        assert_eq!(api.effective_ref(), "main");
442    }
443
444    #[test]
445    fn test_should_convert_pipeline_to_status() {
446        let api = PipelineApiResponse {
447            id: 100,
448            ref_name: Some("main".into()),
449            git_ref: None,
450            status: "success".into(),
451            created_at: Some("2026-01-01T00:00:00Z".parse().expect("valid date")),
452            updated_at: Some("2026-01-01T00:05:00Z".parse().expect("valid date")),
453            web_url: Some("https://gitlab.com/org/project/-/pipelines/100".into()),
454            sha: None,
455        };
456
457        let status: PipelineStatus = api.into();
458        assert_eq!(status.id, 100);
459        assert_eq!(status.ref_name, "main");
460        assert_eq!(status.status, PipelineStatusEnum::Success);
461        assert_eq!(status.conclusion.as_deref(), Some("success"));
462    }
463
464    #[test]
465    fn test_should_parse_pipeline_status_enum() {
466        assert_eq!(
467            parse_pipeline_status("running"),
468            PipelineStatusEnum::Running
469        );
470        assert_eq!(
471            parse_pipeline_status("success"),
472            PipelineStatusEnum::Success
473        );
474        assert_eq!(parse_pipeline_status("failed"), PipelineStatusEnum::Failed);
475        assert_eq!(
476            parse_pipeline_status("canceled"),
477            PipelineStatusEnum::Cancelled
478        );
479        assert_eq!(
480            parse_pipeline_status("cancelled"),
481            PipelineStatusEnum::Cancelled
482        );
483        assert_eq!(
484            parse_pipeline_status("pending"),
485            PipelineStatusEnum::Pending
486        );
487        assert_eq!(
488            parse_pipeline_status("created"),
489            PipelineStatusEnum::Pending
490        );
491        assert_eq!(
492            parse_pipeline_status("unknown"),
493            PipelineStatusEnum::Pending
494        );
495    }
496
497    #[test]
498    fn test_should_deserialize_job_api_response() {
499        let json = br#"{
500            "id": 5001,
501            "name": "test-unit",
502            "status": "success",
503            "stage": "test",
504            "started_at": "2026-01-15T09:30:00Z",
505            "finished_at": "2026-01-15T09:35:00Z",
506            "web_url": "https://gitlab.com/org/project/-/jobs/5001"
507        }"#;
508
509        let api: JobApiResponse = serde_json::from_slice(json).expect("valid JobApiResponse");
510        let job: JobData = api.into();
511
512        assert_eq!(job.id, 5001);
513        assert_eq!(job.name, "test-unit");
514        assert_eq!(job.status, "success");
515        assert_eq!(job.conclusion.as_deref(), Some("success"));
516    }
517
518    #[test]
519    fn test_should_deserialize_failed_job() {
520        let json = br#"{
521            "id": 5002,
522            "name": "test-integration",
523            "status": "failed",
524            "started_at": "2026-01-15T09:30:00Z",
525            "finished_at": "2026-01-15T09:40:00Z",
526            "web_url": "https://gitlab.com/org/project/-/jobs/5002"
527        }"#;
528
529        let api: JobApiResponse = serde_json::from_slice(json).expect("valid JobApiResponse");
530        let job: JobData = api.into();
531        assert_eq!(job.conclusion.as_deref(), Some("failure"));
532    }
533
534    #[test]
535    fn test_should_deserialize_empty_pipeline_list() {
536        let json = b"[]";
537        let list: Vec<PipelineApiResponse> =
538            serde_json::from_slice(json).expect("valid empty list");
539        assert!(list.is_empty());
540    }
541
542    #[test]
543    fn test_should_deserialize_empty_job_list() {
544        let json = b"[]";
545        let list: Vec<JobApiResponse> = serde_json::from_slice(json).expect("valid empty list");
546        assert!(list.is_empty());
547    }
548
549    // --- Failure-path tests using an injected MockCommandRunner ---
550
551    #[tokio::test]
552    async fn test_should_return_platform_error_when_glab_fails_for_status() {
553        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
554        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
555
556        let result = provider.status("main").await;
557
558        assert!(matches!(
559            result.unwrap_err(),
560            gitflow_core::CoreError::Cli(_)
561        ));
562    }
563
564    #[tokio::test]
565    async fn test_should_return_serialization_error_on_invalid_json_for_status() {
566        let runner = MockCommandRunner::success("not valid json");
567        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
568
569        let result = provider.status("main").await;
570
571        assert!(matches!(
572            result.unwrap_err(),
573            gitflow_core::CoreError::Serialization(_)
574        ));
575    }
576
577    #[tokio::test]
578    async fn test_should_return_platform_error_when_glab_fails_for_logs() {
579        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
580        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
581
582        let result = provider.logs(12345).await;
583
584        assert!(matches!(
585            result.unwrap_err(),
586            gitflow_core::CoreError::Cli(_)
587        ));
588    }
589
590    #[tokio::test]
591    async fn test_should_return_platform_error_when_glab_fails_for_jobs() {
592        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
593        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
594
595        let result = provider.jobs(12345).await;
596
597        assert!(matches!(
598            result.unwrap_err(),
599            gitflow_core::CoreError::Cli(_)
600        ));
601    }
602
603    #[tokio::test]
604    async fn test_should_return_serialization_error_on_invalid_json_for_jobs() {
605        let runner = MockCommandRunner::success("not valid json");
606        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
607
608        let result = provider.jobs(12345).await;
609
610        assert!(matches!(
611            result.unwrap_err(),
612            gitflow_core::CoreError::Serialization(_)
613        ));
614    }
615
616    #[tokio::test]
617    async fn test_should_return_platform_error_when_glab_fails_for_report() {
618        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
619        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
620
621        let result = provider.report("main", 7).await;
622
623        assert!(matches!(
624            result.unwrap_err(),
625            gitflow_core::CoreError::Cli(_)
626        ));
627    }
628
629    #[tokio::test]
630    async fn test_should_return_serialization_error_on_invalid_json_for_report() {
631        let runner = MockCommandRunner::success("not valid json");
632        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
633
634        let result = provider.report("main", 7).await;
635
636        assert!(matches!(
637            result.unwrap_err(),
638            gitflow_core::CoreError::Serialization(_)
639        ));
640    }
641}