gitflow-gitlab 1.2.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
//! 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::{
    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` CLI 命令的 runner。
    runner: R,
}

impl GitLabPipelineProvider<RealCommandRunner> {
    /// 创建新的 GitLab Pipeline 提供者,使用真实的进程执行器。
    ///
    /// `repo` 格式为 `namespace/project`。
    #[must_use]
    pub fn new(repo: impl Into<String>) -> Self {
        Self {
            repo: repo.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 {
        Self {
            repo: repo.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.unwrap_or_else(Utc::now),
            updated_at: api.updated_at.unwrap_or_else(Utc::now),
            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(),
        }
    }
}

/// Helper struct for parsing `glab ci view` output that may contain
/// a pipeline object with an embedded `jobs` field.
#[derive(Debug, Deserialize)]
struct PipelineWithJobs {
    #[serde(default)]
    jobs: Vec<JobApiResponse>,
}

// ── 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, "--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])
            .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 ci view <pipeline_id> --output json`。
    async fn jobs(&self, pipeline_id: u64) -> Result<Vec<JobData>> {
        debug!(repo = %self.repo, pipeline_id, "spawning `glab ci view`");

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

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

        // glab ci view may return the pipeline object with embedded jobs,
        // or a jobs list depending on version. Try parsing as jobs first.
        if let Ok(jobs) = serde_json::from_slice::<Vec<JobApiResponse>>(&output.stdout) {
            return Ok(jobs.into_iter().map(JobData::from).collect());
        }

        // If that fails, try parsing as a pipeline with jobs field
        let pipeline: PipelineWithJobs =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
        Ok(pipeline.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
        let cutoff = Utc::now() - chrono::Duration::days(i64::from(days));
        let recent: Vec<&PipelineStatus> = pipelines
            .iter()
            .filter(|p| p.created_at >= cutoff)
            .collect();

        let total_runs = recent.len() 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
        #[allow(
            clippy::cast_precision_loss,
            reason = "Duration values never exceed f64 precision"
        )]
        let durations: Vec<f64> = recent
            .iter()
            .map(|p| (p.updated_at - p.created_at).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");
    }

    #[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_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_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(_)
        ));
    }
}