Skip to main content

gitflow_github/
pipeline.rs

1//! GitHub Pipeline 提供者实现。
2//!
3//! 通过 `gh run list` / `gh run view` CLI 实现 [`PipelineProvider`] trait。
4
5use async_trait::async_trait;
6use gitflow_core::{
7    CoreError, Result,
8    pipeline::{JobData, PipelineProvider, PipelineReport, PipelineStatus, PipelineStatusEnum},
9};
10use serde::Deserialize;
11use tracing::debug;
12
13use crate::{
14    error::parse_gh_error,
15    runner::{CommandRunner, RealCommandRunner},
16};
17
18/// `gh run list` 请求的 JSON 字段列表。
19const PIPELINE_FIELDS: &str = "databaseId,headBranch,status,conclusion,createdAt,updatedAt,url";
20
21/// 将 GitHub `gh run list` 返回的 status 字符串映射为 [`PipelineStatusEnum`]。
22///
23/// GitHub 返回小写状态:`queued`、`in_progress`、`completed`、`waiting`、
24/// `requested`、`pending` 等。其中 `completed` 需要结合 `conclusion`
25/// 判断最终结果。
26fn gh_status_to_enum(status: &str, conclusion: Option<&str>) -> PipelineStatusEnum {
27    match status {
28        "completed" => match conclusion {
29            Some("success") => PipelineStatusEnum::Success,
30            Some("failure" | "startup_failure" | "timed_out") => PipelineStatusEnum::Failed,
31            Some("cancelled") => PipelineStatusEnum::Cancelled,
32            Some("skipped" | "neutral") => PipelineStatusEnum::Pending,
33            _ => PipelineStatusEnum::Running,
34        },
35        "queued" | "waiting" | "requested" | "pending" => PipelineStatusEnum::Pending,
36        _ => PipelineStatusEnum::Running,
37    }
38}
39
40/// GitHub 单次 run 的原始响应,用于反序列化。
41#[derive(Debug, Deserialize)]
42#[serde(rename_all = "camelCase")]
43struct GhRun {
44    database_id: u64,
45    head_branch: String,
46    status: String,
47    conclusion: Option<String>,
48    created_at: String,
49    updated_at: String,
50    url: String,
51}
52
53impl GhRun {
54    fn into_status(self) -> PipelineStatus {
55        let created_at = chrono::DateTime::parse_from_rfc3339(&self.created_at)
56            .ok()
57            .map_or_else(chrono::Utc::now, |dt| dt.with_timezone(&chrono::Utc));
58        let updated_at = chrono::DateTime::parse_from_rfc3339(&self.updated_at)
59            .ok()
60            .map_or_else(chrono::Utc::now, |dt| dt.with_timezone(&chrono::Utc));
61
62        PipelineStatus {
63            id: self.database_id,
64            ref_name: self.head_branch,
65            status: gh_status_to_enum(&self.status, self.conclusion.as_deref()),
66            conclusion: self.conclusion,
67            created_at,
68            updated_at,
69            url: self.url,
70        }
71    }
72}
73
74/// `gh run view --json jobs` 的包裹结构体。
75///
76/// GitHub 返回 `{"jobs": [...]}` 而非直接数组。
77#[derive(Debug, Deserialize)]
78struct JobsResponse {
79    jobs: Vec<GhJob>,
80}
81
82/// GitHub 单次 job 的原始响应。
83#[derive(Debug, Deserialize)]
84#[serde(rename_all = "camelCase")]
85struct GhJob {
86    database_id: u64,
87    name: String,
88    status: String,
89    conclusion: Option<String>,
90    started_at: Option<String>,
91    completed_at: Option<String>,
92    url: String,
93}
94
95impl GhJob {
96    fn into_job_data(self) -> JobData {
97        let parse_ts = |s: Option<&str>| {
98            s.and_then(|v| {
99                chrono::DateTime::parse_from_rfc3339(v)
100                    .ok()
101                    .map(|dt| dt.with_timezone(&chrono::Utc))
102            })
103        };
104
105        JobData {
106            id: self.database_id,
107            name: self.name,
108            status: self.status,
109            conclusion: self.conclusion,
110            started_at: parse_ts(self.started_at.as_deref()),
111            completed_at: parse_ts(self.completed_at.as_deref()),
112            url: self.url,
113        }
114    }
115}
116
117/// GitHub Pipeline 提供者,通过 `gh` CLI 操作 CI/CD 流水线。
118///
119/// 该结构体通过调用 `gh` CLI 实现 [`PipelineProvider`] trait 的所有方法,
120/// 使上层命令能够以统一的方式查看 GitHub Actions 流水线状态。
121///
122/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
123/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
124///
125/// # Examples
126///
127/// ```no_run
128/// use gitflow_github::GitHubPipelineProvider;
129///
130/// let provider = GitHubPipelineProvider::new("octocat/hello-world");
131/// ```
132#[derive(Debug, Clone)]
133pub struct GitHubPipelineProvider<R: CommandRunner = RealCommandRunner> {
134    /// GitHub `owner/repo`,如 `"byx-darwin/gitflow-cli"`。
135    repo: String,
136    /// 用于执行 `gh` CLI 命令的 runner。
137    runner: R,
138}
139
140impl GitHubPipelineProvider<RealCommandRunner> {
141    /// 创建新的 GitHub Pipeline 提供者,使用真实的进程执行器。
142    ///
143    /// `repo` 格式为 `owner/repo`。
144    #[must_use]
145    pub fn new(repo: impl Into<String>) -> Self {
146        Self {
147            repo: repo.into(),
148            runner: RealCommandRunner,
149        }
150    }
151}
152
153impl<R: CommandRunner> GitHubPipelineProvider<R> {
154    /// 使用自定义 [`CommandRunner`] 创建提供者。
155    ///
156    /// 主要用于测试,可注入模拟 runner 以控制 `gh` CLI 的输出。
157    /// `repo` 格式为 `owner/repo`。
158    #[must_use]
159    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
160        Self {
161            repo: repo.into(),
162            runner,
163        }
164    }
165}
166
167/// `gh run list` 的 report 统计所需最小字段集。
168#[derive(Debug, Deserialize)]
169#[serde(rename_all = "camelCase")]
170struct ReportRun {
171    conclusion: Option<String>,
172    created_at: String,
173    updated_at: String,
174}
175
176/// 为 [`GitHubPipelineProvider::report`] 聚合每次运行的指标。
177///
178/// 返回 `(success_count, total_duration_secs, failure_counts, runs_with_duration)`。
179fn aggregate_report_metrics(
180    runs: &[ReportRun],
181) -> (u64, f64, std::collections::HashMap<String, u64>, u64) {
182    let mut success_count: u64 = 0;
183    let mut total_duration_secs: f64 = 0.0;
184    let mut failure_counts: std::collections::HashMap<String, u64> =
185        std::collections::HashMap::new();
186    let mut has_duration: u64 = 0;
187
188    for run in runs {
189        if let Some(ref conclusion) = run.conclusion {
190            if conclusion == "success" {
191                success_count += 1;
192            } else if !matches!(conclusion.as_str(), "cancelled" | "skipped" | "neutral") {
193                // Counts all failure conclusions: "failure", "startup_failure",
194                // "timed_out", and any other non-success/non-neutral conclusion.
195                *failure_counts.entry(conclusion.clone()).or_insert(0) += 1;
196            }
197        }
198
199        if let (Ok(created), Ok(updated)) = (
200            chrono::DateTime::parse_from_rfc3339(&run.created_at),
201            chrono::DateTime::parse_from_rfc3339(&run.updated_at),
202        ) {
203            let duration = (updated.with_timezone(&chrono::Utc)
204                - created.with_timezone(&chrono::Utc))
205            .num_seconds();
206            if duration > 0 {
207                #[allow(
208                    clippy::cast_precision_loss,
209                    reason = "Duration values are small enough to fit in f64 without loss"
210                )]
211                let duration_f64 = duration as f64;
212                total_duration_secs += duration_f64;
213                has_duration += 1;
214            }
215        }
216    }
217
218    (
219        success_count,
220        total_duration_secs,
221        failure_counts,
222        has_duration,
223    )
224}
225
226#[async_trait]
227impl<R: CommandRunner + 'static> PipelineProvider for GitHubPipelineProvider<R> {
228    async fn status(&self, branch: &str) -> Result<Vec<PipelineStatus>> {
229        debug!(repo = %self.repo, branch = %branch, "spawning `gh run list`");
230
231        let output = self
232            .runner
233            .run(
234                "gh",
235                &[
236                    "run",
237                    "list",
238                    "--branch",
239                    branch,
240                    "--repo",
241                    &self.repo,
242                    "--json",
243                    PIPELINE_FIELDS,
244                    "--limit",
245                    "30",
246                ],
247            )
248            .await
249            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
250
251        if !output.status.success() {
252            return Err(parse_gh_error(&output.stderr).into());
253        }
254
255        let runs: Vec<GhRun> =
256            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
257
258        Ok(runs.into_iter().map(GhRun::into_status).collect())
259    }
260
261    async fn logs(&self, pipeline_id: u64) -> Result<String> {
262        debug!(repo = %self.repo, pipeline_id, "spawning `gh run view --log`");
263
264        let run_id = pipeline_id.to_string();
265        let output = self
266            .runner
267            .run(
268                "gh",
269                &["run", "view", &run_id, "--repo", &self.repo, "--log"],
270            )
271            .await
272            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
273
274        if !output.status.success() {
275            return Err(parse_gh_error(&output.stderr).into());
276        }
277
278        String::from_utf8(output.stdout)
279            .map_err(|e| CoreError::Platform(format!("Failed to decode log output as UTF-8: {e}")))
280    }
281
282    async fn jobs(&self, pipeline_id: u64) -> Result<Vec<JobData>> {
283        debug!(repo = %self.repo, pipeline_id, "spawning `gh run view --json jobs`");
284
285        let run_id = pipeline_id.to_string();
286        let output = self
287            .runner
288            .run(
289                "gh",
290                &[
291                    "run", "view", &run_id, "--repo", &self.repo, "--json", "jobs",
292                ],
293            )
294            .await
295            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
296
297        if !output.status.success() {
298            return Err(parse_gh_error(&output.stderr).into());
299        }
300
301        let resp: JobsResponse =
302            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
303
304        Ok(resp.jobs.into_iter().map(GhJob::into_job_data).collect())
305    }
306
307    async fn report(&self, branch: &str, days: u32) -> Result<PipelineReport> {
308        debug!(
309            repo = %self.repo,
310            branch = %branch,
311            days,
312            "spawning `gh run list` for report"
313        );
314
315        let output = self
316            .runner
317            .run(
318                "gh",
319                &[
320                    "run",
321                    "list",
322                    "--branch",
323                    branch,
324                    "--repo",
325                    &self.repo,
326                    "--json",
327                    "conclusion,createdAt,updatedAt",
328                    "--limit",
329                    "100",
330                ],
331            )
332            .await
333            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
334
335        if !output.status.success() {
336            return Err(parse_gh_error(&output.stderr).into());
337        }
338
339        let all_runs: Vec<ReportRun> =
340            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
341
342        // Filter to the requested time window. Unparsable timestamps are kept
343        // (conservative: never drop runs because of a date format surprise).
344        let cutoff = chrono::Utc::now() - chrono::Duration::days(i64::from(days));
345        let runs: Vec<ReportRun> = all_runs
346            .into_iter()
347            .filter(|run| {
348                chrono::DateTime::parse_from_rfc3339(&run.created_at)
349                    .map_or(true, |dt| dt.with_timezone(&chrono::Utc) >= cutoff)
350            })
351            .collect();
352
353        let total_runs = runs.len() as u64;
354
355        let (success_count, total_duration_secs, failure_counts, has_duration) =
356            aggregate_report_metrics(&runs);
357
358        #[allow(
359            clippy::cast_precision_loss,
360            reason = "Run counts are small enough to fit in f64 without loss"
361        )]
362        let success_rate = if total_runs > 0 {
363            success_count as f64 / total_runs as f64
364        } else {
365            0.0
366        };
367
368        #[allow(
369            clippy::cast_precision_loss,
370            reason = "Duration count is small enough to fit in f64 without loss"
371        )]
372        let avg_duration_secs = if has_duration > 0 {
373            total_duration_secs / has_duration as f64
374        } else {
375            0.0
376        };
377
378        // 按失败次数降序取 top 失败结论
379        let mut failures: Vec<_> = failure_counts.into_iter().collect();
380        failures.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
381        let top_failures: Vec<String> = failures.into_iter().map(|(k, _)| k).collect();
382
383        Ok(PipelineReport {
384            total_runs,
385            success_rate,
386            avg_duration_secs,
387            top_failures,
388        })
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use crate::runner::MockCommandRunner;
396
397    #[test]
398    fn test_should_construct_github_pipeline_provider() {
399        let provider = GitHubPipelineProvider::new("octocat/hello-world");
400        assert_eq!(provider.repo, "octocat/hello-world");
401    }
402
403    #[test]
404    fn test_should_construct_github_pipeline_provider_from_string() {
405        let repo = String::from("octocat/hello-world");
406        let provider = GitHubPipelineProvider::new(repo);
407        assert_eq!(provider.repo, "octocat/hello-world");
408    }
409
410    #[test]
411    fn test_should_debug_format_provider() {
412        let provider = GitHubPipelineProvider::new("octocat/hello-world");
413        let debug = format!("{provider:?}");
414        assert!(debug.contains("GitHubPipelineProvider"));
415        assert!(debug.contains("octocat/hello-world"));
416    }
417
418    #[test]
419    fn test_should_clone_github_pipeline_provider() {
420        let original = GitHubPipelineProvider::new("owner/repo");
421        let cloned = original.clone();
422        assert_eq!(original.repo, cloned.repo);
423    }
424
425    #[test]
426    fn test_should_deserialize_gh_run_from_json() {
427        let json = br#"{
428            "databaseId": 12345,
429            "headBranch": "main",
430            "status": "completed",
431            "conclusion": "success",
432            "createdAt": "2026-07-01T10:00:00Z",
433            "updatedAt": "2026-07-01T10:05:30Z",
434            "url": "https://github.com/example/repo/actions/runs/12345"
435        }"#;
436
437        let run: GhRun = serde_json::from_slice(json).expect("valid GhRun JSON");
438        assert_eq!(run.database_id, 12345);
439        assert_eq!(run.head_branch, "main");
440        assert_eq!(run.status, "completed");
441        assert_eq!(run.conclusion.as_deref(), Some("success"));
442        assert_eq!(
443            run.url,
444            "https://github.com/example/repo/actions/runs/12345"
445        );
446    }
447
448    #[test]
449    fn test_should_deserialize_gh_run_list_from_json_array() {
450        let json = br#"[
451            {
452                "databaseId": 1,
453                "headBranch": "main",
454                "status": "completed",
455                "conclusion": "success",
456                "createdAt": "2026-07-01T10:00:00Z",
457                "updatedAt": "2026-07-01T10:05:00Z",
458                "url": "https://example.com/1"
459            },
460            {
461                "databaseId": 2,
462                "headBranch": "main",
463                "status": "in_progress",
464                "conclusion": null,
465                "createdAt": "2026-07-01T11:00:00Z",
466                "updatedAt": "2026-07-01T11:01:00Z",
467                "url": "https://example.com/2"
468            }
469        ]"#;
470
471        let runs: Vec<GhRun> = serde_json::from_slice(json).expect("valid GhRun list");
472        assert_eq!(runs.len(), 2);
473        assert_eq!(runs[0].database_id, 1);
474        assert_eq!(runs[1].database_id, 2);
475    }
476
477    #[test]
478    fn test_should_deserialize_empty_run_list() {
479        let json = b"[]";
480        let runs: Vec<GhRun> = serde_json::from_slice(json).expect("empty list");
481        assert!(runs.is_empty());
482    }
483
484    #[test]
485    fn test_should_convert_gh_run_to_pipeline_status() {
486        let run = GhRun {
487            database_id: 42,
488            head_branch: "main".into(),
489            status: "completed".into(),
490            conclusion: Some("success".into()),
491            created_at: "2026-07-01T10:00:00Z".into(),
492            updated_at: "2026-07-01T10:05:30Z".into(),
493            url: "https://example.com/42".into(),
494        };
495
496        let status = run.into_status();
497        assert_eq!(status.id, 42);
498        assert_eq!(status.ref_name, "main");
499        assert_eq!(status.status, PipelineStatusEnum::Success);
500        assert_eq!(status.conclusion.as_deref(), Some("success"));
501    }
502
503    #[test]
504    fn test_should_map_gh_status_completed_success() {
505        assert_eq!(
506            gh_status_to_enum("completed", Some("success")),
507            PipelineStatusEnum::Success
508        );
509    }
510
511    #[test]
512    fn test_should_map_gh_status_completed_failure() {
513        assert_eq!(
514            gh_status_to_enum("completed", Some("failure")),
515            PipelineStatusEnum::Failed
516        );
517        assert_eq!(
518            gh_status_to_enum("completed", Some("startup_failure")),
519            PipelineStatusEnum::Failed
520        );
521        assert_eq!(
522            gh_status_to_enum("completed", Some("timed_out")),
523            PipelineStatusEnum::Failed
524        );
525    }
526
527    #[test]
528    fn test_should_map_gh_status_completed_cancelled() {
529        assert_eq!(
530            gh_status_to_enum("completed", Some("cancelled")),
531            PipelineStatusEnum::Cancelled
532        );
533    }
534
535    #[test]
536    fn test_should_map_gh_status_completed_skipped() {
537        assert_eq!(
538            gh_status_to_enum("completed", Some("skipped")),
539            PipelineStatusEnum::Pending
540        );
541        assert_eq!(
542            gh_status_to_enum("completed", Some("neutral")),
543            PipelineStatusEnum::Pending
544        );
545    }
546
547    #[test]
548    fn test_should_map_gh_status_in_progress() {
549        assert_eq!(
550            gh_status_to_enum("in_progress", None),
551            PipelineStatusEnum::Running
552        );
553        assert_eq!(
554            gh_status_to_enum("action_required", None),
555            PipelineStatusEnum::Running
556        );
557    }
558
559    #[test]
560    fn test_should_map_gh_status_queued() {
561        assert_eq!(
562            gh_status_to_enum("queued", None),
563            PipelineStatusEnum::Pending
564        );
565        assert_eq!(
566            gh_status_to_enum("waiting", None),
567            PipelineStatusEnum::Pending
568        );
569        assert_eq!(
570            gh_status_to_enum("requested", None),
571            PipelineStatusEnum::Pending
572        );
573    }
574
575    #[test]
576    fn test_should_map_gh_status_unknown() {
577        assert_eq!(
578            gh_status_to_enum("some_unknown_status", None),
579            PipelineStatusEnum::Running
580        );
581    }
582
583    #[test]
584    fn test_should_map_completed_with_unknown_conclusion() {
585        // completed + unknown conclusion -> Running
586        assert_eq!(
587            gh_status_to_enum("completed", Some("weird")),
588            PipelineStatusEnum::Running
589        );
590    }
591
592    #[test]
593    fn test_should_map_completed_with_none_conclusion() {
594        // completed + None conclusion -> Running
595        assert_eq!(
596            gh_status_to_enum("completed", None),
597            PipelineStatusEnum::Running
598        );
599    }
600
601    #[test]
602    fn test_should_deserialize_jobs_response_from_json() {
603        let json = br#"{
604            "jobs": [
605                {
606                    "databaseId": 98765,
607                    "name": "build",
608                    "status": "completed",
609                    "conclusion": "success",
610                    "startedAt": "2026-07-01T10:00:00Z",
611                    "completedAt": "2026-07-01T10:03:00Z",
612                    "url": "https://example.com/job/98765"
613                }
614            ]
615        }"#;
616
617        let resp: JobsResponse = serde_json::from_slice(json).expect("valid JobsResponse");
618        assert_eq!(resp.jobs.len(), 1);
619        assert_eq!(resp.jobs[0].database_id, 98765);
620        assert_eq!(resp.jobs[0].name, "build");
621    }
622
623    #[test]
624    fn test_should_deserialize_empty_jobs_response() {
625        let json = br#"{"jobs": []}"#;
626        let resp: JobsResponse = serde_json::from_slice(json).expect("valid");
627        assert!(resp.jobs.is_empty());
628    }
629
630    #[test]
631    fn test_should_convert_gh_job_to_job_data() {
632        let job = GhJob {
633            database_id: 100,
634            name: "test".into(),
635            status: "completed".into(),
636            conclusion: Some("success".into()),
637            started_at: Some("2026-07-01T10:00:00Z".into()),
638            completed_at: Some("2026-07-01T10:03:00Z".into()),
639            url: "https://example.com/job/100".into(),
640        };
641
642        let data = job.into_job_data();
643        assert_eq!(data.id, 100);
644        assert_eq!(data.name, "test");
645        assert_eq!(data.status, "completed");
646        assert_eq!(data.conclusion.as_deref(), Some("success"));
647        assert!(data.started_at.is_some());
648        assert!(data.completed_at.is_some());
649    }
650
651    #[test]
652    fn test_should_convert_gh_job_with_null_timestamps() {
653        let job = GhJob {
654            database_id: 1,
655            name: "queued-job".into(),
656            status: "queued".into(),
657            conclusion: None,
658            started_at: None,
659            completed_at: None,
660            url: "https://example.com/job/1".into(),
661        };
662
663        let data = job.into_job_data();
664        assert!(data.started_at.is_none());
665        assert!(data.completed_at.is_none());
666    }
667
668    #[test]
669    fn test_should_deserialize_run_with_null_conclusion() {
670        let json = br#"{
671            "databaseId": 1,
672            "headBranch": "develop",
673            "status": "in_progress",
674            "conclusion": null,
675            "createdAt": "2026-07-02T08:00:00Z",
676            "updatedAt": "2026-07-02T08:00:00Z",
677            "url": "https://example.com/1"
678        }"#;
679
680        let run: GhRun = serde_json::from_slice(json).expect("deserialize");
681        assert!(run.conclusion.is_none());
682        assert_eq!(run.status, "in_progress");
683    }
684
685    #[test]
686    fn test_should_compute_report_from_runs() {
687        // 模拟 report 使用的最小结构体
688        #[derive(Debug, Deserialize)]
689        #[allow(
690            dead_code,
691            reason = "Test fixture struct fields are deserialized but not all read"
692        )]
693        #[serde(rename_all = "camelCase")]
694        struct TestReportRun {
695            conclusion: Option<String>,
696            created_at: String,
697            updated_at: String,
698        }
699
700        let json = br#"[
701            {"conclusion": "success", "createdAt": "2026-07-01T10:00:00Z", "updatedAt": "2026-07-01T10:05:00Z"},
702            {"conclusion": "success", "createdAt": "2026-07-01T11:00:00Z", "updatedAt": "2026-07-01T11:03:00Z"},
703            {"conclusion": "failure", "createdAt": "2026-07-01T12:00:00Z", "updatedAt": "2026-07-01T12:02:00Z"},
704            {"conclusion": null, "createdAt": "2026-07-01T13:00:00Z", "updatedAt": "2026-07-01T13:01:00Z"}
705        ]"#;
706
707        let runs: Vec<TestReportRun> = serde_json::from_slice(json).expect("valid");
708        assert_eq!(runs.len(), 4);
709
710        let total = runs.len() as u64;
711        let success: u64 = runs
712            .iter()
713            .filter(|r| r.conclusion.as_deref() == Some("success"))
714            .count() as u64;
715        #[allow(
716            clippy::cast_precision_loss,
717            reason = "Test values are small enough to fit in f64 without loss"
718        )]
719        let rate = success as f64 / total as f64;
720
721        assert_eq!(total, 4);
722        assert_eq!(success, 2);
723        assert!((rate - 0.5).abs() < f64::EPSILON);
724    }
725
726    #[test]
727    fn test_should_count_all_failure_types_in_report_logic() {
728        // 验证 report 方法中的失败计数逻辑:
729        // "failure"、"startup_failure"、"timed_out" 都应被计入 top_failures,
730        // 而 "cancelled"、"skipped"、"neutral" 不应被计入。
731        use std::collections::HashMap;
732
733        let conclusions = [
734            "success",
735            "success",
736            "failure",
737            "failure",
738            "startup_failure",
739            "timed_out",
740            "cancelled",
741            "skipped",
742            "neutral",
743        ];
744
745        let mut success_count: u64 = 0;
746        let mut failure_counts: HashMap<String, u64> = HashMap::new();
747
748        for conclusion in &conclusions {
749            if *conclusion == "success" {
750                success_count += 1;
751            } else if !matches!(*conclusion, "cancelled" | "skipped" | "neutral") {
752                *failure_counts.entry(conclusion.to_string()).or_insert(0) += 1;
753            }
754        }
755
756        assert_eq!(success_count, 2);
757
758        assert_eq!(failure_counts.get("failure"), Some(&2));
759        assert_eq!(failure_counts.get("startup_failure"), Some(&1));
760        assert_eq!(failure_counts.get("timed_out"), Some(&1));
761        assert_eq!(failure_counts.get("cancelled"), None);
762        assert_eq!(failure_counts.get("skipped"), None);
763        assert_eq!(failure_counts.get("neutral"), None);
764
765        // 验证 top_failures 排序(按数量降序)
766        let mut failures: Vec<_> = failure_counts.into_iter().collect();
767        failures.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
768        let top_failures: Vec<String> = failures.into_iter().map(|(k, _)| k).collect();
769
770        // "failure" 有 2 次排第一,其余各 1 次按字母序
771        assert_eq!(top_failures[0], "failure");
772        assert!(top_failures.contains(&"startup_failure".to_string()));
773        assert!(top_failures.contains(&"timed_out".to_string()));
774        assert_eq!(top_failures.len(), 3);
775    }
776
777    // --- Failure-path tests using an injected MockCommandRunner ---
778
779    #[tokio::test]
780    async fn test_should_return_platform_error_when_gh_fails_for_status() {
781        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
782        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
783
784        let result = provider.status("main").await;
785
786        assert!(result.is_err());
787        assert!(matches!(
788            result.unwrap_err(),
789            gitflow_core::CoreError::Cli(_)
790        ));
791    }
792
793    #[tokio::test]
794    async fn test_should_return_serialization_error_on_invalid_json_for_status() {
795        let runner = MockCommandRunner::success("invalid json");
796        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
797
798        let result = provider.status("main").await;
799
800        assert!(result.is_err());
801        assert!(matches!(
802            result.unwrap_err(),
803            gitflow_core::CoreError::Serialization(_)
804        ));
805    }
806
807    #[tokio::test]
808    async fn test_should_return_platform_error_when_gh_fails_for_logs() {
809        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
810        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
811
812        let result = provider.logs(42).await;
813
814        assert!(result.is_err());
815        assert!(matches!(
816            result.unwrap_err(),
817            gitflow_core::CoreError::Cli(_)
818        ));
819    }
820
821    #[tokio::test]
822    async fn test_should_return_platform_error_when_gh_fails_for_jobs() {
823        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
824        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
825
826        let result = provider.jobs(42).await;
827
828        assert!(result.is_err());
829        assert!(matches!(
830            result.unwrap_err(),
831            gitflow_core::CoreError::Cli(_)
832        ));
833    }
834
835    #[tokio::test]
836    async fn test_should_return_serialization_error_on_invalid_json_for_jobs() {
837        let runner = MockCommandRunner::success("invalid json");
838        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
839
840        let result = provider.jobs(42).await;
841
842        assert!(result.is_err());
843        assert!(matches!(
844            result.unwrap_err(),
845            gitflow_core::CoreError::Serialization(_)
846        ));
847    }
848
849    #[tokio::test]
850    async fn test_should_return_platform_error_when_gh_fails_for_report() {
851        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
852        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
853
854        let result = provider.report("main", 7).await;
855
856        assert!(result.is_err());
857        assert!(matches!(
858            result.unwrap_err(),
859            gitflow_core::CoreError::Cli(_)
860        ));
861    }
862
863    #[tokio::test]
864    async fn test_should_return_serialization_error_on_invalid_json_for_report() {
865        let runner = MockCommandRunner::success("invalid json");
866        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
867
868        let result = provider.report("main", 7).await;
869
870        assert!(result.is_err());
871        assert!(matches!(
872            result.unwrap_err(),
873            gitflow_core::CoreError::Serialization(_)
874        ));
875    }
876}