gitflow-gitlab 2.1.0

gf 的 GitLab 适配器,基于 glab CLI 提供 Issue/MR/Release/Review 等能力。GitLab adapter for gf via glab 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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! GitLab Pipeline (CI/CD) 提供者实现。
//!
//! 通过 `glab ci` CLI 命令实现 [`PipelineProvider`] trait,支持 Pipeline
//! 状态查看、日志获取、任务列表和报告生成。
//! 所有方法通过 [`CommandRunner`] 抽象调用 `glab`,测试可注入自定义 runner
//! 以模拟成功或失败场景。
//!
//! glab 命令映射:
//! - `status` → `glab ci list`
//! - `logs` → `glab ci trace`
//! - `jobs` → `glab ci view --output json`
//! - `report` → 调用 `status` 后计算统计

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use gitflow_core::{
    CoreError, Result,
    pipeline::{JobData, PipelineProvider, PipelineReport, PipelineStatus, PipelineStatusEnum},
};
use serde::Deserialize;
use tracing::debug;

use crate::{
    commit::encode_project_path,
    error::parse_glab_error,
    runner::{CommandRunner, RealCommandRunner},
};

/// GitLab Pipeline 提供者,通过 `glab ci` 操作 CI/CD 管线。
///
/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
///
/// # Examples
///
/// ```no_run
/// use gitflow_gitlab::GitLabPipelineProvider;
///
/// let provider = GitLabPipelineProvider::new("gitlab-org/gitlab");
/// ```
#[derive(Debug, Clone)]
pub struct GitLabPipelineProvider<R: CommandRunner = RealCommandRunner> {
    /// GitLab `namespace/project`。
    repo: String,
    /// 传给 `glab ci ...` 子命令 `--repo` 参数的目标字符串。默认等于 `repo`;
    /// 通过 [`with_remote_url`](GitLabPipelineProvider::with_remote_url) 构造时
    /// 为完整 git remote URL,用于在自建 GitLab 实例上显式锁定 host。
    repo_target: String,
    /// 用于执行 `glab` CLI 命令的 runner。
    runner: R,
}

impl GitLabPipelineProvider<RealCommandRunner> {
    /// 创建新的 GitLab Pipeline 提供者,使用真实的进程执行器。
    ///
    /// `repo` 格式为 `namespace/project`。
    #[must_use]
    pub fn new(repo: impl Into<String>) -> Self {
        let repo = repo.into();
        Self {
            repo_target: repo.clone(),
            repo,
            runner: RealCommandRunner,
        }
    }

    /// Create a new provider from a shared [`Session`].
    ///
    /// This enables state reuse across multiple operations in workflow chains.
    #[must_use]
    pub fn with_session(session: &gitflow_core::Session) -> Self {
        let repo = session.repo.clone();
        Self {
            repo_target: repo.clone(),
            repo,
            runner: RealCommandRunner,
        }
    }

    /// 使用完整 git remote URL 作为 `glab ci ...` 的 `--repo` 目标创建提供者。
    #[must_use]
    pub fn with_remote_url(repo: impl Into<String>, remote_url: impl Into<String>) -> Self {
        Self {
            repo: repo.into(),
            repo_target: remote_url.into(),
            runner: RealCommandRunner,
        }
    }
}

impl<R: CommandRunner> GitLabPipelineProvider<R> {
    /// 使用自定义 [`CommandRunner`] 创建提供者。
    ///
    /// 主要用于测试,可注入模拟 runner 以控制 `glab` CLI 的输出。
    /// `repo` 格式为 `namespace/project`。
    #[must_use]
    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
        let repo = repo.into();
        Self {
            repo_target: repo.clone(),
            repo,
            runner,
        }
    }

    /// 使用自定义 [`CommandRunner`] 并显式指定 `--repo` 目标创建提供者。
    ///
    /// 主要用于测试,验证 `repo_target`(如完整 remote URL)被正确传给 `glab`。
    #[must_use]
    pub fn with_runner_and_repo_target(
        repo: impl Into<String>,
        repo_target: impl Into<String>,
        runner: R,
    ) -> Self {
        Self {
            repo: repo.into(),
            repo_target: repo_target.into(),
            runner,
        }
    }
}

// ── 中间 API 响应类型 ──────────────────────────────────────────────

/// `glab ci list --output json` 返回的 Pipeline JSON 结构。
#[derive(Debug, Clone, Deserialize)]
#[allow(
    dead_code,
    reason = "Used for deserialization; not all fields are read"
)]
struct PipelineApiResponse {
    id: u64,
    #[serde(default)]
    ref_name: Option<String>,
    /// glab may use `ref` instead of `ref_name`
    #[serde(alias = "ref")]
    #[serde(default)]
    git_ref: Option<String>,
    #[serde(default)]
    status: String,
    #[serde(default)]
    created_at: Option<DateTime<Utc>>,
    #[serde(default)]
    updated_at: Option<DateTime<Utc>>,
    #[serde(default)]
    web_url: Option<String>,
    /// Some glab versions include a `sha` field
    #[serde(default)]
    sha: Option<String>,
}

impl PipelineApiResponse {
    fn effective_ref(&self) -> String {
        self.ref_name
            .clone()
            .or_else(|| self.git_ref.clone())
            .unwrap_or_default()
    }
}

fn parse_pipeline_status(status: &str) -> PipelineStatusEnum {
    match status {
        "running" => PipelineStatusEnum::Running,
        "success" => PipelineStatusEnum::Success,
        "failed" => PipelineStatusEnum::Failed,
        "canceled" | "cancelled" => PipelineStatusEnum::Cancelled,
        _ => PipelineStatusEnum::Pending,
    }
}

impl From<PipelineApiResponse> for PipelineStatus {
    fn from(api: PipelineApiResponse) -> Self {
        let status_enum = parse_pipeline_status(&api.status);
        let conclusion = if api.status == "success" {
            Some("success".into())
        } else if api.status == "failed" {
            Some("failure".into())
        } else if api.status == "canceled" || api.status == "cancelled" {
            Some("cancelled".into())
        } else {
            None
        };

        Self {
            id: api.id,
            ref_name: api.effective_ref(),
            status: status_enum,
            conclusion,
            created_at: api.created_at,
            updated_at: api.updated_at,
            url: api.web_url.unwrap_or_default(),
        }
    }
}

/// `glab ci view --output json` 返回的 Job JSON 结构。
#[derive(Debug, Clone, Deserialize)]
#[allow(
    dead_code,
    reason = "Used for deserialization; not all fields are read"
)]
struct JobApiResponse {
    id: u64,
    #[serde(default)]
    name: String,
    #[serde(default)]
    status: String,
    #[serde(default)]
    stage: Option<String>,
    #[serde(default)]
    started_at: Option<DateTime<Utc>>,
    #[serde(default)]
    finished_at: Option<DateTime<Utc>>,
    #[serde(default)]
    web_url: Option<String>,
}

impl From<JobApiResponse> for JobData {
    fn from(api: JobApiResponse) -> Self {
        let conclusion = if api.status == "success" {
            Some("success".into())
        } else if api.status == "failed" {
            Some("failure".into())
        } else if api.status == "canceled" || api.status == "cancelled" {
            Some("cancelled".into())
        } else {
            None
        };

        Self {
            id: api.id,
            name: api.name,
            status: api.status,
            conclusion,
            started_at: api.started_at,
            completed_at: api.finished_at,
            url: api.web_url.unwrap_or_default(),
        }
    }
}

// ── trait 实现 ──────────────────────────────────────────────────────

#[async_trait]
impl<R: CommandRunner + 'static> PipelineProvider for GitLabPipelineProvider<R> {
    /// 获取指定分支的 Pipeline 状态列表。
    ///
    /// 调用 `glab ci list --ref <branch> --output json`。
    async fn status(&self, branch: &str) -> Result<Vec<PipelineStatus>> {
        debug!(repo = %self.repo, branch, "spawning `glab ci list`");

        let output = self
            .runner
            .run(
                "glab",
                &[
                    "ci",
                    "list",
                    "--repo",
                    &self.repo_target,
                    "--ref",
                    branch,
                    "--output",
                    "json",
                ],
            )
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab ci list: {e}")))?;

        if !output.status.success() {
            return Err(parse_glab_error(&output.stderr).into());
        }

        let api_responses: Vec<PipelineApiResponse> =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_responses
            .into_iter()
            .map(PipelineStatus::from)
            .collect())
    }

    /// 获取指定 Pipeline 的日志。
    ///
    /// 调用 `glab ci trace <pipeline_id>` 或 `glab ci view <pipeline_id>`。
    async fn logs(&self, pipeline_id: u64) -> Result<String> {
        debug!(repo = %self.repo, pipeline_id, "spawning `glab ci trace`");

        let id_str = pipeline_id.to_string();
        let output = self
            .runner
            .run(
                "glab",
                &["ci", "trace", &id_str, "--repo", &self.repo_target],
            )
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab ci trace: {e}")))?;

        if !output.status.success() {
            return Err(parse_glab_error(&output.stderr).into());
        }

        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
    }

    /// 获取指定 Pipeline 的 Job 列表。
    ///
    /// 调用 `glab api /projects/{repo-encoded}/pipelines/{pipeline_id}/jobs`,
    /// 其中 `{repo-encoded}` 为全量 URL 编码的项目路径
    /// (如 `group/subgroup/project` → `group%2Fsubgroup%2Fproject`)。
    async fn jobs(&self, pipeline_id: u64) -> Result<Vec<JobData>> {
        debug!(repo = %self.repo, pipeline_id, "spawning `glab api` GET pipeline jobs");

        let encoded_path = encode_project_path(&self.repo);
        let api_path = format!("/projects/{encoded_path}/pipelines/{pipeline_id}/jobs");

        let output = self
            .runner
            .run("glab", &["api", &api_path])
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn glab api: {e}")))?;

        if !output.status.success() {
            return Err(parse_glab_error(&output.stderr).into());
        }

        let jobs: Vec<JobApiResponse> =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
        Ok(jobs.into_iter().map(JobData::from).collect())
    }

    /// 生成指定分支最近 `days` 天的 Pipeline 报告。
    ///
    /// 调用 `status` 获取 Pipeline 列表,然后计算统计信息。
    async fn report(&self, branch: &str, days: u32) -> Result<PipelineReport> {
        debug!(
            repo = %self.repo,
            branch,
            days,
            "generating pipeline report"
        );

        let pipelines = self.status(branch).await?;

        // Filter by date range. A pipeline with no created_at has an unknown
        // creation time and must be excluded, not guessed into or out of the
        // window (#380 design §3.2).
        let cutoff = Utc::now() - chrono::Duration::days(i64::from(days));
        let recent: Vec<&PipelineStatus> = pipelines
            .iter()
            .filter(|p| p.created_at.is_some_and(|c| c >= cutoff))
            .collect();

        // Only pipelines that have reached a terminal state (Success/Failed/
        // Cancelled) count toward the denominator used for `success_rate`.
        // Running/Pending pipelines are still in flight and must not
        // silently deflate the reported rate.
        let total_runs = recent.iter().filter(|p| p.status.is_terminal()).count() as u64;
        if total_runs == 0 {
            return Ok(PipelineReport {
                total_runs: 0,
                success_rate: 0.0,
                avg_duration_secs: 0.0,
                top_failures: vec![],
            });
        }

        let success_count = recent
            .iter()
            .filter(|p| matches!(p.status, PipelineStatusEnum::Success))
            .count() as u64;

        let success_rate = {
            #[allow(
                clippy::cast_precision_loss,
                reason = "Pipeline counts never exceed f64 precision"
            )]
            {
                success_count as f64 / total_runs as f64
            }
        };

        // Calculate average duration. A pipeline missing either timestamp
        // cannot have its duration computed and must be excluded from the
        // sample set entirely, not treated as a 0-second run (#380 design
        // §3.2).
        #[allow(
            clippy::cast_precision_loss,
            reason = "Duration values never exceed f64 precision"
        )]
        let durations: Vec<f64> = recent
            .iter()
            .filter_map(|p| {
                let created = p.created_at?;
                let updated = p.updated_at?;
                Some((updated - created).num_seconds().max(0) as f64)
            })
            .filter(|d| *d > 0.0)
            .collect();

        let avg_duration_secs = if durations.is_empty() {
            0.0
        } else {
            #[allow(
                clippy::cast_precision_loss,
                reason = "Duration length never exceeds f64 precision"
            )]
            {
                durations.iter().sum::<f64>() / durations.len() as f64
            }
        };

        // Find top failures (by ref)
        let mut failure_refs: Vec<String> = recent
            .iter()
            .filter(|p| matches!(p.status, PipelineStatusEnum::Failed))
            .map(|p| p.ref_name.clone())
            .collect();
        failure_refs.sort();
        failure_refs.dedup();

        Ok(PipelineReport {
            total_runs,
            success_rate,
            avg_duration_secs,
            top_failures: failure_refs,
        })
    }
}

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

    #[test]
    fn test_should_construct_gitlab_pipeline_provider() {
        let provider = GitLabPipelineProvider::new("gitlab-org/gitlab");
        assert_eq!(provider.repo, "gitlab-org/gitlab");
    }

    #[test]
    fn test_should_construct_gitlab_pipeline_provider_from_string() {
        let repo = String::from("gitlab-org/gitlab");
        let provider = GitLabPipelineProvider::new(repo);
        assert_eq!(provider.repo, "gitlab-org/gitlab");
    }

    #[tokio::test]
    async fn test_should_use_explicit_repo_target_for_logs() {
        let runner = MockCommandRunner::success("log output");
        let provider = GitLabPipelineProvider::with_runner_and_repo_target(
            "owner/repo",
            "https://192.168.230.23/iproost/proxy/api-src.git",
            runner.clone(),
        );

        let result = provider.logs(99).await;

        assert!(result.is_ok(), "expected Ok, got {result:?}");
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec![
                "ci",
                "trace",
                "99",
                "--repo",
                "https://192.168.230.23/iproost/proxy/api-src.git",
            ]
            .into_iter()
            .map(String::from)
            .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_should_debug_format_pipeline_provider() {
        let provider = GitLabPipelineProvider::new("owner/repo");
        let debug = format!("{provider:?}");
        assert!(debug.contains("GitLabPipelineProvider"));
        assert!(debug.contains("owner/repo"));
    }

    #[test]
    fn test_should_clone_gitlab_pipeline_provider() {
        let original = GitLabPipelineProvider::new("owner/repo");
        let cloned = original.clone();
        assert_eq!(original.repo, cloned.repo);
    }

    // --- API response deserialization tests ---

    #[test]
    fn test_should_deserialize_pipeline_api_response() {
        let json = br#"{
            "id": 12345,
            "ref_name": "main",
            "status": "success",
            "created_at": "2026-01-15T09:30:00Z",
            "updated_at": "2026-01-15T09:35:00Z",
            "web_url": "https://gitlab.com/gitlab-org/gitlab/-/pipelines/12345"
        }"#;

        let api: PipelineApiResponse =
            serde_json::from_slice(json).expect("valid PipelineApiResponse");
        assert_eq!(api.id, 12345);
        assert_eq!(api.status, "success");
        assert_eq!(api.effective_ref(), "main");
    }

    #[test]
    fn test_should_deserialize_pipeline_with_ref_alias() {
        let json = br#"{
            "id": 12345,
            "ref": "main",
            "status": "success",
            "created_at": "2026-01-15T09:30:00Z",
            "updated_at": "2026-01-15T09:35:00Z"
        }"#;

        let api: PipelineApiResponse =
            serde_json::from_slice(json).expect("valid PipelineApiResponse");
        assert_eq!(api.effective_ref(), "main");
    }

    #[test]
    fn test_should_convert_pipeline_to_status() {
        let api = PipelineApiResponse {
            id: 100,
            ref_name: Some("main".into()),
            git_ref: None,
            status: "success".into(),
            created_at: Some("2026-01-01T00:00:00Z".parse().expect("valid date")),
            updated_at: Some("2026-01-01T00:05:00Z".parse().expect("valid date")),
            web_url: Some("https://gitlab.com/org/project/-/pipelines/100".into()),
            sha: None,
        };

        let status: PipelineStatus = api.into();
        assert_eq!(status.id, 100);
        assert_eq!(status.ref_name, "main");
        assert_eq!(status.status, PipelineStatusEnum::Success);
        assert_eq!(status.conclusion.as_deref(), Some("success"));
    }

    #[test]
    fn test_should_keep_pipeline_timestamps_none_when_api_omits_them() {
        let api = PipelineApiResponse {
            id: 101,
            ref_name: Some("main".into()),
            git_ref: None,
            status: "success".into(),
            created_at: None,
            updated_at: None,
            web_url: None,
            sha: None,
        };

        let status: PipelineStatus = api.into();
        assert!(
            status.created_at.is_none(),
            "missing created_at must stay None, not fall back to Utc::now()"
        );
        assert!(
            status.updated_at.is_none(),
            "missing updated_at must stay None, not fall back to Utc::now()"
        );
    }

    #[test]
    fn test_should_parse_pipeline_status_enum() {
        assert_eq!(
            parse_pipeline_status("running"),
            PipelineStatusEnum::Running
        );
        assert_eq!(
            parse_pipeline_status("success"),
            PipelineStatusEnum::Success
        );
        assert_eq!(parse_pipeline_status("failed"), PipelineStatusEnum::Failed);
        assert_eq!(
            parse_pipeline_status("canceled"),
            PipelineStatusEnum::Cancelled
        );
        assert_eq!(
            parse_pipeline_status("cancelled"),
            PipelineStatusEnum::Cancelled
        );
        assert_eq!(
            parse_pipeline_status("pending"),
            PipelineStatusEnum::Pending
        );
        assert_eq!(
            parse_pipeline_status("created"),
            PipelineStatusEnum::Pending
        );
        assert_eq!(
            parse_pipeline_status("unknown"),
            PipelineStatusEnum::Pending
        );
    }

    #[test]
    fn test_should_deserialize_job_api_response() {
        let json = br#"{
            "id": 5001,
            "name": "test-unit",
            "status": "success",
            "stage": "test",
            "started_at": "2026-01-15T09:30:00Z",
            "finished_at": "2026-01-15T09:35:00Z",
            "web_url": "https://gitlab.com/org/project/-/jobs/5001"
        }"#;

        let api: JobApiResponse = serde_json::from_slice(json).expect("valid JobApiResponse");
        let job: JobData = api.into();

        assert_eq!(job.id, 5001);
        assert_eq!(job.name, "test-unit");
        assert_eq!(job.status, "success");
        assert_eq!(job.conclusion.as_deref(), Some("success"));
    }

    #[test]
    fn test_should_deserialize_failed_job() {
        let json = br#"{
            "id": 5002,
            "name": "test-integration",
            "status": "failed",
            "started_at": "2026-01-15T09:30:00Z",
            "finished_at": "2026-01-15T09:40:00Z",
            "web_url": "https://gitlab.com/org/project/-/jobs/5002"
        }"#;

        let api: JobApiResponse = serde_json::from_slice(json).expect("valid JobApiResponse");
        let job: JobData = api.into();
        assert_eq!(job.conclusion.as_deref(), Some("failure"));
    }

    #[test]
    fn test_should_deserialize_empty_pipeline_list() {
        let json = b"[]";
        let list: Vec<PipelineApiResponse> =
            serde_json::from_slice(json).expect("valid empty list");
        assert!(list.is_empty());
    }

    #[test]
    fn test_should_deserialize_empty_job_list() {
        let json = b"[]";
        let list: Vec<JobApiResponse> = serde_json::from_slice(json).expect("valid empty list");
        assert!(list.is_empty());
    }

    // --- Failure-path tests using an injected MockCommandRunner ---

    #[tokio::test]
    async fn test_should_return_platform_error_when_glab_fails_for_status() {
        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let result = provider.status("main").await;

        assert!(matches!(
            result.unwrap_err(),
            gitflow_core::CoreError::Cli(_)
        ));
    }

    #[tokio::test]
    async fn test_should_return_serialization_error_on_invalid_json_for_status() {
        let runner = MockCommandRunner::success("not valid json");
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let result = provider.status("main").await;

        assert!(matches!(
            result.unwrap_err(),
            gitflow_core::CoreError::Serialization(_)
        ));
    }

    #[tokio::test]
    async fn test_should_return_platform_error_when_glab_fails_for_logs() {
        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let result = provider.logs(12345).await;

        assert!(matches!(
            result.unwrap_err(),
            gitflow_core::CoreError::Cli(_)
        ));
    }

    #[tokio::test]
    async fn test_should_return_platform_error_when_glab_fails_for_jobs() {
        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let result = provider.jobs(12345).await;

        assert!(matches!(
            result.unwrap_err(),
            gitflow_core::CoreError::Cli(_)
        ));
    }

    #[tokio::test]
    async fn test_should_return_serialization_error_on_invalid_json_for_jobs() {
        let runner = MockCommandRunner::success("not valid json");
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let result = provider.jobs(12345).await;

        assert!(matches!(
            result.unwrap_err(),
            gitflow_core::CoreError::Serialization(_)
        ));
    }

    #[tokio::test]
    async fn test_should_fetch_jobs_via_glab_api() {
        let runner = MockCommandRunner::success(
            r#"[{"id":1,"name":"build","status":"success"},{"id":2,"name":"test","status":"running"}]"#,
        );
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner.clone());

        let jobs = provider.jobs(5).await.expect("should fetch");

        assert_eq!(jobs.len(), 2);
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec!["api", "/projects/owner%2Frepo/pipelines/5/jobs"]
                .into_iter()
                .map(String::from)
                .collect::<Vec<_>>()
        );
    }

    #[tokio::test]
    async fn test_should_encode_nested_group_repo_path_for_pipeline_jobs() {
        let runner = MockCommandRunner::success(
            r#"[{"id":1,"name":"build","status":"success"},{"id":2,"name":"test","status":"running"}]"#,
        );
        let provider =
            GitLabPipelineProvider::with_runner("group/subgroup/project", runner.clone());

        let jobs = provider.jobs(5).await.expect("should fetch");

        assert_eq!(jobs.len(), 2);
        assert_eq!(
            runner.recorded_calls()[0].1,
            vec![
                "api",
                "/projects/group%2Fsubgroup%2Fproject/pipelines/5/jobs"
            ]
            .into_iter()
            .map(String::from)
            .collect::<Vec<_>>()
        );
    }

    #[tokio::test]
    async fn test_should_return_platform_error_when_glab_fails_for_report() {
        let runner = MockCommandRunner::failure(r#"{"message": "Forbidden"}"#, 256);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let result = provider.report("main", 7).await;

        assert!(matches!(
            result.unwrap_err(),
            gitflow_core::CoreError::Cli(_)
        ));
    }

    #[tokio::test]
    async fn test_should_return_serialization_error_on_invalid_json_for_report() {
        let runner = MockCommandRunner::success("not valid json");
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let result = provider.report("main", 7).await;

        assert!(matches!(
            result.unwrap_err(),
            gitflow_core::CoreError::Serialization(_)
        ));
    }

    #[tokio::test]
    async fn test_should_exclude_non_terminal_pipelines_from_report_total_runs() {
        // 4 pipelines in the report window: 2 success, 1 failed, 1 still running.
        let now = Utc::now();
        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();

        let json = format!(
            r#"[
                {{"id": 1, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
                {{"id": 2, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
                {{"id": 3, "ref_name": "main", "status": "failed", "created_at": "{}", "updated_at": "{}"}},
                {{"id": 4, "ref_name": "main", "status": "running", "created_at": "{}", "updated_at": "{}"}}
            ]"#,
            ts(600),
            ts(300),
            ts(500),
            ts(200),
            ts(400),
            ts(100),
            ts(60),
            ts(30),
        );

        let runner = MockCommandRunner::success(&json);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let report = provider
            .report("main", 7)
            .await
            .expect("report should succeed");

        // Only 3 of the 4 pipelines have reached a terminal state
        // (Success/Failed/Cancelled); the running one must be excluded
        // from total_runs, not just from success/failure counts.
        assert_eq!(report.total_runs, 3);
        assert!((report.success_rate - (2.0 / 3.0)).abs() < f64::EPSILON);
    }

    #[tokio::test]
    async fn test_should_zero_report_when_all_pipelines_are_running() {
        // No terminal pipelines at all in the window -> total_runs must be
        // 0 (not the raw count of running pipelines), success_rate 0.0, and
        // no division-by-zero NaN leaking into the report.
        let now = Utc::now();
        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();

        let json = format!(
            r#"[{{"id": 1, "ref_name": "main", "status": "running", "created_at": "{}", "updated_at": "{}"}}]"#,
            ts(60),
            ts(30),
        );

        let runner = MockCommandRunner::success(&json);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let report = provider
            .report("main", 7)
            .await
            .expect("report should succeed");

        assert_eq!(report.total_runs, 0);
        assert!((report.success_rate - 0.0).abs() < f64::EPSILON);
        assert!(!report.success_rate.is_nan());
    }

    #[tokio::test]
    async fn test_should_exclude_pipelines_with_missing_created_at_from_report_cutoff() {
        // One pipeline has a real, in-window created_at; the other omits it
        // entirely. The one with no created_at must not count toward
        // total_runs — we cannot know whether it falls in the requested
        // window, so we exclude it rather than guess.
        let now = Utc::now();
        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();

        let json = format!(
            r#"[
                {{"id": 1, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
                {{"id": 2, "ref_name": "main", "status": "success"}}
            ]"#,
            ts(600),
            ts(300),
        );

        let runner = MockCommandRunner::success(&json);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let report = provider
            .report("main", 7)
            .await
            .expect("report should succeed");

        assert_eq!(
            report.total_runs, 1,
            "pipeline #2 has no created_at and must be excluded from the report, not counted as \
             in-window"
        );
    }

    #[tokio::test]
    async fn test_should_exclude_pipeline_with_missing_timestamp_from_duration_average() {
        // Pipeline #1 has both timestamps present (contributes a real duration
        // sample). Pipeline #2 has created_at but no updated_at — it must be
        // excluded from the average, not treated as a 0-second duration.
        let now = Utc::now();
        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();

        let json = format!(
            r#"[
                {{"id": 1, "ref_name": "main", "status": "success", "created_at": "{}", "updated_at": "{}"}},
                {{"id": 2, "ref_name": "main", "status": "success", "created_at": "{}"}}
            ]"#,
            ts(600),
            ts(300),
            ts(500),
        );

        let runner = MockCommandRunner::success(&json);
        let provider = GitLabPipelineProvider::with_runner("owner/repo", runner);

        let report = provider
            .report("main", 7)
            .await
            .expect("report should succeed");

        // Only pipeline #1 contributes a duration sample (300s); pipeline #2's
        // missing updated_at must not be treated as 0, which would drag the
        // average down incorrectly.
        assert!(
            (report.avg_duration_secs - 300.0).abs() < 1.0,
            "expected ~300s average from the one complete sample, got {}",
            report.avg_duration_secs
        );
    }
}