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    commit::encode_project_path,
25    error::parse_glab_error,
26    runner::{CommandRunner, RealCommandRunner},
27};
28
29/// GitLab Pipeline 提供者,通过 `glab ci` 操作 CI/CD 管线。
30///
31/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
32/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
33///
34/// # Examples
35///
36/// ```no_run
37/// use gitflow_gitlab::GitLabPipelineProvider;
38///
39/// let provider = GitLabPipelineProvider::new("gitlab-org/gitlab");
40/// ```
41#[derive(Debug, Clone)]
42pub struct GitLabPipelineProvider<R: CommandRunner = RealCommandRunner> {
43    /// GitLab `namespace/project`。
44    repo: String,
45    /// 传给 `glab ci ...` 子命令 `--repo` 参数的目标字符串。默认等于 `repo`;
46    /// 通过 [`with_remote_url`](GitLabPipelineProvider::with_remote_url) 构造时
47    /// 为完整 git remote URL,用于在自建 GitLab 实例上显式锁定 host。
48    repo_target: String,
49    /// 用于执行 `glab` CLI 命令的 runner。
50    runner: R,
51}
52
53impl GitLabPipelineProvider<RealCommandRunner> {
54    /// 创建新的 GitLab Pipeline 提供者,使用真实的进程执行器。
55    ///
56    /// `repo` 格式为 `namespace/project`。
57    #[must_use]
58    pub fn new(repo: impl Into<String>) -> Self {
59        let repo = repo.into();
60        Self {
61            repo_target: repo.clone(),
62            repo,
63            runner: RealCommandRunner,
64        }
65    }
66
67    /// Create a new provider from a shared [`Session`].
68    ///
69    /// This enables state reuse across multiple operations in workflow chains.
70    #[must_use]
71    pub fn with_session(session: &gitflow_core::Session) -> Self {
72        let repo = session.repo.clone();
73        Self {
74            repo_target: repo.clone(),
75            repo,
76            runner: RealCommandRunner,
77        }
78    }
79
80    /// 使用完整 git remote URL 作为 `glab ci ...` 的 `--repo` 目标创建提供者。
81    #[must_use]
82    pub fn with_remote_url(repo: impl Into<String>, remote_url: impl Into<String>) -> Self {
83        Self {
84            repo: repo.into(),
85            repo_target: remote_url.into(),
86            runner: RealCommandRunner,
87        }
88    }
89}
90
91impl<R: CommandRunner> GitLabPipelineProvider<R> {
92    /// 使用自定义 [`CommandRunner`] 创建提供者。
93    ///
94    /// 主要用于测试,可注入模拟 runner 以控制 `glab` CLI 的输出。
95    /// `repo` 格式为 `namespace/project`。
96    #[must_use]
97    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
98        let repo = repo.into();
99        Self {
100            repo_target: repo.clone(),
101            repo,
102            runner,
103        }
104    }
105
106    /// 使用自定义 [`CommandRunner`] 并显式指定 `--repo` 目标创建提供者。
107    ///
108    /// 主要用于测试,验证 `repo_target`(如完整 remote URL)被正确传给 `glab`。
109    #[must_use]
110    pub fn with_runner_and_repo_target(
111        repo: impl Into<String>,
112        repo_target: impl Into<String>,
113        runner: R,
114    ) -> Self {
115        Self {
116            repo: repo.into(),
117            repo_target: repo_target.into(),
118            runner,
119        }
120    }
121}
122
123// ── 中间 API 响应类型 ──────────────────────────────────────────────
124
125/// `glab ci list --output json` 返回的 Pipeline JSON 结构。
126#[derive(Debug, Clone, Deserialize)]
127#[allow(
128    dead_code,
129    reason = "Used for deserialization; not all fields are read"
130)]
131struct PipelineApiResponse {
132    id: u64,
133    #[serde(default)]
134    ref_name: Option<String>,
135    /// glab may use `ref` instead of `ref_name`
136    #[serde(alias = "ref")]
137    #[serde(default)]
138    git_ref: Option<String>,
139    #[serde(default)]
140    status: String,
141    #[serde(default)]
142    created_at: Option<DateTime<Utc>>,
143    #[serde(default)]
144    updated_at: Option<DateTime<Utc>>,
145    #[serde(default)]
146    web_url: Option<String>,
147    /// Some glab versions include a `sha` field
148    #[serde(default)]
149    sha: Option<String>,
150}
151
152impl PipelineApiResponse {
153    fn effective_ref(&self) -> String {
154        self.ref_name
155            .clone()
156            .or_else(|| self.git_ref.clone())
157            .unwrap_or_default()
158    }
159}
160
161fn parse_pipeline_status(status: &str) -> PipelineStatusEnum {
162    match status {
163        "running" => PipelineStatusEnum::Running,
164        "success" => PipelineStatusEnum::Success,
165        "failed" => PipelineStatusEnum::Failed,
166        "canceled" | "cancelled" => PipelineStatusEnum::Cancelled,
167        _ => PipelineStatusEnum::Pending,
168    }
169}
170
171impl From<PipelineApiResponse> for PipelineStatus {
172    fn from(api: PipelineApiResponse) -> Self {
173        let status_enum = parse_pipeline_status(&api.status);
174        let conclusion = if api.status == "success" {
175            Some("success".into())
176        } else if api.status == "failed" {
177            Some("failure".into())
178        } else if api.status == "canceled" || api.status == "cancelled" {
179            Some("cancelled".into())
180        } else {
181            None
182        };
183
184        Self {
185            id: api.id,
186            ref_name: api.effective_ref(),
187            status: status_enum,
188            conclusion,
189            created_at: api.created_at,
190            updated_at: api.updated_at,
191            url: api.web_url.unwrap_or_default(),
192        }
193    }
194}
195
196/// `glab ci view --output json` 返回的 Job JSON 结构。
197#[derive(Debug, Clone, Deserialize)]
198#[allow(
199    dead_code,
200    reason = "Used for deserialization; not all fields are read"
201)]
202struct JobApiResponse {
203    id: u64,
204    #[serde(default)]
205    name: String,
206    #[serde(default)]
207    status: String,
208    #[serde(default)]
209    stage: Option<String>,
210    #[serde(default)]
211    started_at: Option<DateTime<Utc>>,
212    #[serde(default)]
213    finished_at: Option<DateTime<Utc>>,
214    #[serde(default)]
215    web_url: Option<String>,
216}
217
218impl From<JobApiResponse> for JobData {
219    fn from(api: JobApiResponse) -> Self {
220        let conclusion = if api.status == "success" {
221            Some("success".into())
222        } else if api.status == "failed" {
223            Some("failure".into())
224        } else if api.status == "canceled" || api.status == "cancelled" {
225            Some("cancelled".into())
226        } else {
227            None
228        };
229
230        Self {
231            id: api.id,
232            name: api.name,
233            status: api.status,
234            conclusion,
235            started_at: api.started_at,
236            completed_at: api.finished_at,
237            url: api.web_url.unwrap_or_default(),
238        }
239    }
240}
241
242// ── trait 实现 ──────────────────────────────────────────────────────
243
244#[async_trait]
245impl<R: CommandRunner + 'static> PipelineProvider for GitLabPipelineProvider<R> {
246    /// 获取指定分支的 Pipeline 状态列表。
247    ///
248    /// 调用 `glab ci list --ref <branch> --output json`。
249    async fn status(&self, branch: &str) -> Result<Vec<PipelineStatus>> {
250        debug!(repo = %self.repo, branch, "spawning `glab ci list`");
251
252        let output = self
253            .runner
254            .run(
255                "glab",
256                &[
257                    "ci",
258                    "list",
259                    "--repo",
260                    &self.repo_target,
261                    "--ref",
262                    branch,
263                    "--output",
264                    "json",
265                ],
266            )
267            .await
268            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab ci list: {e}")))?;
269
270        if !output.status.success() {
271            return Err(parse_glab_error(&output.stderr).into());
272        }
273
274        let api_responses: Vec<PipelineApiResponse> =
275            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
276
277        Ok(api_responses
278            .into_iter()
279            .map(PipelineStatus::from)
280            .collect())
281    }
282
283    /// 获取指定 Pipeline 的日志。
284    ///
285    /// 调用 `glab ci trace <pipeline_id>` 或 `glab ci view <pipeline_id>`。
286    async fn logs(&self, pipeline_id: u64) -> Result<String> {
287        debug!(repo = %self.repo, pipeline_id, "spawning `glab ci trace`");
288
289        let id_str = pipeline_id.to_string();
290        let output = self
291            .runner
292            .run(
293                "glab",
294                &["ci", "trace", &id_str, "--repo", &self.repo_target],
295            )
296            .await
297            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab ci trace: {e}")))?;
298
299        if !output.status.success() {
300            return Err(parse_glab_error(&output.stderr).into());
301        }
302
303        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
304    }
305
306    /// 获取指定 Pipeline 的 Job 列表。
307    ///
308    /// 调用 `glab api /projects/{repo-encoded}/pipelines/{pipeline_id}/jobs`,
309    /// 其中 `{repo-encoded}` 为全量 URL 编码的项目路径
310    /// (如 `group/subgroup/project` → `group%2Fsubgroup%2Fproject`)。
311    async fn jobs(&self, pipeline_id: u64) -> Result<Vec<JobData>> {
312        debug!(repo = %self.repo, pipeline_id, "spawning `glab api` GET pipeline jobs");
313
314        let encoded_path = encode_project_path(&self.repo);
315        let api_path = format!("/projects/{encoded_path}/pipelines/{pipeline_id}/jobs");
316
317        let output = self
318            .runner
319            .run("glab", &["api", &api_path])
320            .await
321            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab api: {e}")))?;
322
323        if !output.status.success() {
324            return Err(parse_glab_error(&output.stderr).into());
325        }
326
327        let jobs: Vec<JobApiResponse> =
328            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
329        Ok(jobs.into_iter().map(JobData::from).collect())
330    }
331
332    /// 生成指定分支最近 `days` 天的 Pipeline 报告。
333    ///
334    /// 调用 `status` 获取 Pipeline 列表,然后计算统计信息。
335    async fn report(&self, branch: &str, days: u32) -> Result<PipelineReport> {
336        debug!(
337            repo = %self.repo,
338            branch,
339            days,
340            "generating pipeline report"
341        );
342
343        let pipelines = self.status(branch).await?;
344
345        // Filter by date range. A pipeline with no created_at has an unknown
346        // creation time and must be excluded, not guessed into or out of the
347        // window (#380 design §3.2).
348        let cutoff = Utc::now() - chrono::Duration::days(i64::from(days));
349        let recent: Vec<&PipelineStatus> = pipelines
350            .iter()
351            .filter(|p| p.created_at.is_some_and(|c| c >= cutoff))
352            .collect();
353
354        // Only pipelines that have reached a terminal state (Success/Failed/
355        // Cancelled) count toward the denominator used for `success_rate`.
356        // Running/Pending pipelines are still in flight and must not
357        // silently deflate the reported rate.
358        let total_runs = recent.iter().filter(|p| p.status.is_terminal()).count() as u64;
359        if total_runs == 0 {
360            return Ok(PipelineReport {
361                total_runs: 0,
362                success_rate: 0.0,
363                avg_duration_secs: 0.0,
364                top_failures: vec![],
365            });
366        }
367
368        let success_count = recent
369            .iter()
370            .filter(|p| matches!(p.status, PipelineStatusEnum::Success))
371            .count() as u64;
372
373        let success_rate = {
374            #[allow(
375                clippy::cast_precision_loss,
376                reason = "Pipeline counts never exceed f64 precision"
377            )]
378            {
379                success_count as f64 / total_runs as f64
380            }
381        };
382
383        // Calculate average duration. A pipeline missing either timestamp
384        // cannot have its duration computed and must be excluded from the
385        // sample set entirely, not treated as a 0-second run (#380 design
386        // §3.2).
387        #[allow(
388            clippy::cast_precision_loss,
389            reason = "Duration values never exceed f64 precision"
390        )]
391        let durations: Vec<f64> = recent
392            .iter()
393            .filter_map(|p| {
394                let created = p.created_at?;
395                let updated = p.updated_at?;
396                Some((updated - created).num_seconds().max(0) as f64)
397            })
398            .filter(|d| *d > 0.0)
399            .collect();
400
401        let avg_duration_secs = if durations.is_empty() {
402            0.0
403        } else {
404            #[allow(
405                clippy::cast_precision_loss,
406                reason = "Duration length never exceeds f64 precision"
407            )]
408            {
409                durations.iter().sum::<f64>() / durations.len() as f64
410            }
411        };
412
413        // Find top failures (by ref)
414        let mut failure_refs: Vec<String> = recent
415            .iter()
416            .filter(|p| matches!(p.status, PipelineStatusEnum::Failed))
417            .map(|p| p.ref_name.clone())
418            .collect();
419        failure_refs.sort();
420        failure_refs.dedup();
421
422        Ok(PipelineReport {
423            total_runs,
424            success_rate,
425            avg_duration_secs,
426            top_failures: failure_refs,
427        })
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use crate::runner::MockCommandRunner;
435
436    #[test]
437    fn test_should_construct_gitlab_pipeline_provider() {
438        let provider = GitLabPipelineProvider::new("gitlab-org/gitlab");
439        assert_eq!(provider.repo, "gitlab-org/gitlab");
440    }
441
442    #[test]
443    fn test_should_construct_gitlab_pipeline_provider_from_string() {
444        let repo = String::from("gitlab-org/gitlab");
445        let provider = GitLabPipelineProvider::new(repo);
446        assert_eq!(provider.repo, "gitlab-org/gitlab");
447    }
448
449    #[tokio::test]
450    async fn test_should_use_explicit_repo_target_for_logs() {
451        let runner = MockCommandRunner::success("log output");
452        let provider = GitLabPipelineProvider::with_runner_and_repo_target(
453            "owner/repo",
454            "https://192.168.230.23/iproost/proxy/api-src.git",
455            runner.clone(),
456        );
457
458        let result = provider.logs(99).await;
459
460        assert!(result.is_ok(), "expected Ok, got {result:?}");
461        assert_eq!(
462            runner.recorded_calls()[0].1,
463            vec![
464                "ci",
465                "trace",
466                "99",
467                "--repo",
468                "https://192.168.230.23/iproost/proxy/api-src.git",
469            ]
470            .into_iter()
471            .map(String::from)
472            .collect::<Vec<_>>()
473        );
474    }
475
476    #[test]
477    fn test_should_debug_format_pipeline_provider() {
478        let provider = GitLabPipelineProvider::new("owner/repo");
479        let debug = format!("{provider:?}");
480        assert!(debug.contains("GitLabPipelineProvider"));
481        assert!(debug.contains("owner/repo"));
482    }
483
484    #[test]
485    fn test_should_clone_gitlab_pipeline_provider() {
486        let original = GitLabPipelineProvider::new("owner/repo");
487        let cloned = original.clone();
488        assert_eq!(original.repo, cloned.repo);
489    }
490
491    // --- API response deserialization tests ---
492
493    #[test]
494    fn test_should_deserialize_pipeline_api_response() {
495        let json = br#"{
496            "id": 12345,
497            "ref_name": "main",
498            "status": "success",
499            "created_at": "2026-01-15T09:30:00Z",
500            "updated_at": "2026-01-15T09:35:00Z",
501            "web_url": "https://gitlab.com/gitlab-org/gitlab/-/pipelines/12345"
502        }"#;
503
504        let api: PipelineApiResponse =
505            serde_json::from_slice(json).expect("valid PipelineApiResponse");
506        assert_eq!(api.id, 12345);
507        assert_eq!(api.status, "success");
508        assert_eq!(api.effective_ref(), "main");
509    }
510
511    #[test]
512    fn test_should_deserialize_pipeline_with_ref_alias() {
513        let json = br#"{
514            "id": 12345,
515            "ref": "main",
516            "status": "success",
517            "created_at": "2026-01-15T09:30:00Z",
518            "updated_at": "2026-01-15T09:35:00Z"
519        }"#;
520
521        let api: PipelineApiResponse =
522            serde_json::from_slice(json).expect("valid PipelineApiResponse");
523        assert_eq!(api.effective_ref(), "main");
524    }
525
526    #[test]
527    fn test_should_convert_pipeline_to_status() {
528        let api = PipelineApiResponse {
529            id: 100,
530            ref_name: Some("main".into()),
531            git_ref: None,
532            status: "success".into(),
533            created_at: Some("2026-01-01T00:00:00Z".parse().expect("valid date")),
534            updated_at: Some("2026-01-01T00:05:00Z".parse().expect("valid date")),
535            web_url: Some("https://gitlab.com/org/project/-/pipelines/100".into()),
536            sha: None,
537        };
538
539        let status: PipelineStatus = api.into();
540        assert_eq!(status.id, 100);
541        assert_eq!(status.ref_name, "main");
542        assert_eq!(status.status, PipelineStatusEnum::Success);
543        assert_eq!(status.conclusion.as_deref(), Some("success"));
544    }
545
546    #[test]
547    fn test_should_keep_pipeline_timestamps_none_when_api_omits_them() {
548        let api = PipelineApiResponse {
549            id: 101,
550            ref_name: Some("main".into()),
551            git_ref: None,
552            status: "success".into(),
553            created_at: None,
554            updated_at: None,
555            web_url: None,
556            sha: None,
557        };
558
559        let status: PipelineStatus = api.into();
560        assert!(
561            status.created_at.is_none(),
562            "missing created_at must stay None, not fall back to Utc::now()"
563        );
564        assert!(
565            status.updated_at.is_none(),
566            "missing updated_at must stay None, not fall back to Utc::now()"
567        );
568    }
569
570    #[test]
571    fn test_should_parse_pipeline_status_enum() {
572        assert_eq!(
573            parse_pipeline_status("running"),
574            PipelineStatusEnum::Running
575        );
576        assert_eq!(
577            parse_pipeline_status("success"),
578            PipelineStatusEnum::Success
579        );
580        assert_eq!(parse_pipeline_status("failed"), PipelineStatusEnum::Failed);
581        assert_eq!(
582            parse_pipeline_status("canceled"),
583            PipelineStatusEnum::Cancelled
584        );
585        assert_eq!(
586            parse_pipeline_status("cancelled"),
587            PipelineStatusEnum::Cancelled
588        );
589        assert_eq!(
590            parse_pipeline_status("pending"),
591            PipelineStatusEnum::Pending
592        );
593        assert_eq!(
594            parse_pipeline_status("created"),
595            PipelineStatusEnum::Pending
596        );
597        assert_eq!(
598            parse_pipeline_status("unknown"),
599            PipelineStatusEnum::Pending
600        );
601    }
602
603    #[test]
604    fn test_should_deserialize_job_api_response() {
605        let json = br#"{
606            "id": 5001,
607            "name": "test-unit",
608            "status": "success",
609            "stage": "test",
610            "started_at": "2026-01-15T09:30:00Z",
611            "finished_at": "2026-01-15T09:35:00Z",
612            "web_url": "https://gitlab.com/org/project/-/jobs/5001"
613        }"#;
614
615        let api: JobApiResponse = serde_json::from_slice(json).expect("valid JobApiResponse");
616        let job: JobData = api.into();
617
618        assert_eq!(job.id, 5001);
619        assert_eq!(job.name, "test-unit");
620        assert_eq!(job.status, "success");
621        assert_eq!(job.conclusion.as_deref(), Some("success"));
622    }
623
624    #[test]
625    fn test_should_deserialize_failed_job() {
626        let json = br#"{
627            "id": 5002,
628            "name": "test-integration",
629            "status": "failed",
630            "started_at": "2026-01-15T09:30:00Z",
631            "finished_at": "2026-01-15T09:40:00Z",
632            "web_url": "https://gitlab.com/org/project/-/jobs/5002"
633        }"#;
634
635        let api: JobApiResponse = serde_json::from_slice(json).expect("valid JobApiResponse");
636        let job: JobData = api.into();
637        assert_eq!(job.conclusion.as_deref(), Some("failure"));
638    }
639
640    #[test]
641    fn test_should_deserialize_empty_pipeline_list() {
642        let json = b"[]";
643        let list: Vec<PipelineApiResponse> =
644            serde_json::from_slice(json).expect("valid empty list");
645        assert!(list.is_empty());
646    }
647
648    #[test]
649    fn test_should_deserialize_empty_job_list() {
650        let json = b"[]";
651        let list: Vec<JobApiResponse> = serde_json::from_slice(json).expect("valid empty list");
652        assert!(list.is_empty());
653    }
654
655    // --- Failure-path tests using an injected MockCommandRunner ---
656
657    #[tokio::test]
658    async fn test_should_return_platform_error_when_glab_fails_for_status() {
659        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
660        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
661
662        let result = provider.status("main").await;
663
664        assert!(matches!(
665            result.unwrap_err(),
666            gitflow_core::CoreError::Cli(_)
667        ));
668    }
669
670    #[tokio::test]
671    async fn test_should_return_serialization_error_on_invalid_json_for_status() {
672        let runner = MockCommandRunner::success("not valid json");
673        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
674
675        let result = provider.status("main").await;
676
677        assert!(matches!(
678            result.unwrap_err(),
679            gitflow_core::CoreError::Serialization(_)
680        ));
681    }
682
683    #[tokio::test]
684    async fn test_should_return_platform_error_when_glab_fails_for_logs() {
685        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
686        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
687
688        let result = provider.logs(12345).await;
689
690        assert!(matches!(
691            result.unwrap_err(),
692            gitflow_core::CoreError::Cli(_)
693        ));
694    }
695
696    #[tokio::test]
697    async fn test_should_return_platform_error_when_glab_fails_for_jobs() {
698        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
699        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
700
701        let result = provider.jobs(12345).await;
702
703        assert!(matches!(
704            result.unwrap_err(),
705            gitflow_core::CoreError::Cli(_)
706        ));
707    }
708
709    #[tokio::test]
710    async fn test_should_return_serialization_error_on_invalid_json_for_jobs() {
711        let runner = MockCommandRunner::success("not valid json");
712        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
713
714        let result = provider.jobs(12345).await;
715
716        assert!(matches!(
717            result.unwrap_err(),
718            gitflow_core::CoreError::Serialization(_)
719        ));
720    }
721
722    #[tokio::test]
723    async fn test_should_fetch_jobs_via_glab_api() {
724        let runner = MockCommandRunner::success(
725            r#"[{"id":1,"name":"build","status":"success"},{"id":2,"name":"test","status":"running"}]"#,
726        );
727        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner.clone());
728
729        let jobs = provider.jobs(5).await.expect("should fetch");
730
731        assert_eq!(jobs.len(), 2);
732        assert_eq!(
733            runner.recorded_calls()[0].1,
734            vec!["api", "/projects/owner%2Frepo/pipelines/5/jobs"]
735                .into_iter()
736                .map(String::from)
737                .collect::<Vec<_>>()
738        );
739    }
740
741    #[tokio::test]
742    async fn test_should_encode_nested_group_repo_path_for_pipeline_jobs() {
743        let runner = MockCommandRunner::success(
744            r#"[{"id":1,"name":"build","status":"success"},{"id":2,"name":"test","status":"running"}]"#,
745        );
746        let provider =
747            GitLabPipelineProvider::with_runner("group/subgroup/project", runner.clone());
748
749        let jobs = provider.jobs(5).await.expect("should fetch");
750
751        assert_eq!(jobs.len(), 2);
752        assert_eq!(
753            runner.recorded_calls()[0].1,
754            vec![
755                "api",
756                "/projects/group%2Fsubgroup%2Fproject/pipelines/5/jobs"
757            ]
758            .into_iter()
759            .map(String::from)
760            .collect::<Vec<_>>()
761        );
762    }
763
764    #[tokio::test]
765    async fn test_should_return_platform_error_when_glab_fails_for_report() {
766        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
767        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
768
769        let result = provider.report("main", 7).await;
770
771        assert!(matches!(
772            result.unwrap_err(),
773            gitflow_core::CoreError::Cli(_)
774        ));
775    }
776
777    #[tokio::test]
778    async fn test_should_return_serialization_error_on_invalid_json_for_report() {
779        let runner = MockCommandRunner::success("not valid json");
780        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
781
782        let result = provider.report("main", 7).await;
783
784        assert!(matches!(
785            result.unwrap_err(),
786            gitflow_core::CoreError::Serialization(_)
787        ));
788    }
789
790    #[tokio::test]
791    async fn test_should_exclude_non_terminal_pipelines_from_report_total_runs() {
792        // 4 pipelines in the report window: 2 success, 1 failed, 1 still running.
793        let now = Utc::now();
794        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
795
796        let json = format!(
797            r#"[
798                {{"id": 1, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
799                {{"id": 2, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
800                {{"id": 3, "ref_name": "main", "status": "failed", "created_at": "{}", "updated_at": "{}"}},
801                {{"id": 4, "ref_name": "main", "status": "running", "created_at": "{}", "updated_at": "{}"}}
802            ]"#,
803            ts(600),
804            ts(300),
805            ts(500),
806            ts(200),
807            ts(400),
808            ts(100),
809            ts(60),
810            ts(30),
811        );
812
813        let runner = MockCommandRunner::success(&json);
814        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
815
816        let report = provider
817            .report("main", 7)
818            .await
819            .expect("report should succeed");
820
821        // Only 3 of the 4 pipelines have reached a terminal state
822        // (Success/Failed/Cancelled); the running one must be excluded
823        // from total_runs, not just from success/failure counts.
824        assert_eq!(report.total_runs, 3);
825        assert!((report.success_rate - (2.0 / 3.0)).abs() < f64::EPSILON);
826    }
827
828    #[tokio::test]
829    async fn test_should_zero_report_when_all_pipelines_are_running() {
830        // No terminal pipelines at all in the window -> total_runs must be
831        // 0 (not the raw count of running pipelines), success_rate 0.0, and
832        // no division-by-zero NaN leaking into the report.
833        let now = Utc::now();
834        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
835
836        let json = format!(
837            r#"[{{"id": 1, "ref_name": "main", "status": "running", "created_at": "{}", "updated_at": "{}"}}]"#,
838            ts(60),
839            ts(30),
840        );
841
842        let runner = MockCommandRunner::success(&json);
843        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
844
845        let report = provider
846            .report("main", 7)
847            .await
848            .expect("report should succeed");
849
850        assert_eq!(report.total_runs, 0);
851        assert!((report.success_rate - 0.0).abs() < f64::EPSILON);
852        assert!(!report.success_rate.is_nan());
853    }
854
855    #[tokio::test]
856    async fn test_should_exclude_pipelines_with_missing_created_at_from_report_cutoff() {
857        // One pipeline has a real, in-window created_at; the other omits it
858        // entirely. The one with no created_at must not count toward
859        // total_runs — we cannot know whether it falls in the requested
860        // window, so we exclude it rather than guess.
861        let now = Utc::now();
862        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
863
864        let json = format!(
865            r#"[
866                {{"id": 1, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
867                {{"id": 2, "ref_name": "main", "status": "success"}}
868            ]"#,
869            ts(600),
870            ts(300),
871        );
872
873        let runner = MockCommandRunner::success(&json);
874        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
875
876        let report = provider
877            .report("main", 7)
878            .await
879            .expect("report should succeed");
880
881        assert_eq!(
882            report.total_runs, 1,
883            "pipeline #2 has no created_at and must be excluded from the report, not counted as \
884             in-window"
885        );
886    }
887
888    #[tokio::test]
889    async fn test_should_exclude_pipeline_with_missing_timestamp_from_duration_average() {
890        // Pipeline #1 has both timestamps present (contributes a real duration
891        // sample). Pipeline #2 has created_at but no updated_at — it must be
892        // excluded from the average, not treated as a 0-second duration.
893        let now = Utc::now();
894        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
895
896        let json = format!(
897            r#"[
898                {{"id": 1, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
899                {{"id": 2, "ref_name": "main", "status": "success", "created_at": "{}"}}
900            ]"#,
901            ts(600),
902            ts(300),
903            ts(500),
904        );
905
906        let runner = MockCommandRunner::success(&json);
907        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);
908
909        let report = provider
910            .report("main", 7)
911            .await
912            .expect("report should succeed");
913
914        // Only pipeline #1 contributes a duration sample (300s); pipeline #2's
915        // missing updated_at must not be treated as 0, which would drag the
916        // average down incorrectly.
917        assert!(
918            (report.avg_duration_secs - 300.0).abs() < 1.0,
919            "expected ~300s average from the one complete sample, got {}",
920            report.avg_duration_secs
921        );
922    }
923}