gitflow-github 1.0.0

gf 的 GitHub 适配器,基于 gh CLI 提供 Issue/PR/Release/Review 等能力。GitHub adapter for gf via gh 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
//! GitHub Pipeline 提供者实现。
//!
//! 通过 `gh run list` / `gh run view` CLI 实现 [`PipelineProvider`] trait。

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

use crate::{
    error::parse_gh_error,
    runner::{CommandRunner, RealCommandRunner},
};

/// `gh run list` 请求的 JSON 字段列表。
const PIPELINE_FIELDS: &str = "databaseId,headBranch,status,conclusion,createdAt,updatedAt,url";

/// 将 GitHub `gh run list` 返回的 status 字符串映射为 [`PipelineStatusEnum`]。
///
/// GitHub 返回小写状态:`queued`、`in_progress`、`completed`、`waiting`、
/// `requested`、`pending` 等。其中 `completed` 需要结合 `conclusion`
/// 判断最终结果。
fn gh_status_to_enum(status: &str, conclusion: Option<&str>) -> PipelineStatusEnum {
    match status {
        "completed" => match conclusion {
            Some("success") => PipelineStatusEnum::Success,
            Some("failure" | "startup_failure" | "timed_out") => PipelineStatusEnum::Failed,
            Some("cancelled") => PipelineStatusEnum::Cancelled,
            Some("skipped" | "neutral") => PipelineStatusEnum::Pending,
            _ => PipelineStatusEnum::Running,
        },
        "queued" | "waiting" | "requested" | "pending" => PipelineStatusEnum::Pending,
        _ => PipelineStatusEnum::Running,
    }
}

/// GitHub 单次 run 的原始响应,用于反序列化。
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GhRun {
    database_id: u64,
    head_branch: String,
    status: String,
    conclusion: Option<String>,
    created_at: String,
    updated_at: String,
    url: String,
}

impl GhRun {
    fn into_status(self) -> PipelineStatus {
        let created_at = chrono::DateTime::parse_from_rfc3339(&self.created_at)
            .ok()
            .map_or_else(chrono::Utc::now, |dt| dt.with_timezone(&chrono::Utc));
        let updated_at = chrono::DateTime::parse_from_rfc3339(&self.updated_at)
            .ok()
            .map_or_else(chrono::Utc::now, |dt| dt.with_timezone(&chrono::Utc));

        PipelineStatus {
            id: self.database_id,
            ref_name: self.head_branch,
            status: gh_status_to_enum(&self.status, self.conclusion.as_deref()),
            conclusion: self.conclusion,
            created_at,
            updated_at,
            url: self.url,
        }
    }
}

/// `gh run view --json jobs` 的包裹结构体。
///
/// GitHub 返回 `{"jobs": [...]}` 而非直接数组。
#[derive(Debug, Deserialize)]
struct JobsResponse {
    jobs: Vec<GhJob>,
}

/// GitHub 单次 job 的原始响应。
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GhJob {
    database_id: u64,
    name: String,
    status: String,
    conclusion: Option<String>,
    started_at: Option<String>,
    completed_at: Option<String>,
    url: String,
}

impl GhJob {
    fn into_job_data(self) -> JobData {
        let parse_ts = |s: Option<&str>| {
            s.and_then(|v| {
                chrono::DateTime::parse_from_rfc3339(v)
                    .ok()
                    .map(|dt| dt.with_timezone(&chrono::Utc))
            })
        };

        JobData {
            id: self.database_id,
            name: self.name,
            status: self.status,
            conclusion: self.conclusion,
            started_at: parse_ts(self.started_at.as_deref()),
            completed_at: parse_ts(self.completed_at.as_deref()),
            url: self.url,
        }
    }
}

/// GitHub Pipeline 提供者,通过 `gh` CLI 操作 CI/CD 流水线。
///
/// 该结构体通过调用 `gh` CLI 实现 [`PipelineProvider`] trait 的所有方法,
/// 使上层命令能够以统一的方式查看 GitHub Actions 流水线状态。
///
/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
///
/// # Examples
///
/// ```no_run
/// use gitflow_github::GitHubPipelineProvider;
///
/// let provider = GitHubPipelineProvider::new("octocat/hello-world");
/// ```
#[derive(Debug, Clone)]
pub struct GitHubPipelineProvider<R: CommandRunner = RealCommandRunner> {
    /// GitHub `owner/repo`,如 `"byx-darwin/gitflow-cli"`。
    repo: String,
    /// 用于执行 `gh` CLI 命令的 runner。
    runner: R,
}

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

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

/// `gh run list` 的 report 统计所需最小字段集。
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReportRun {
    conclusion: Option<String>,
    created_at: String,
    updated_at: String,
}

/// 为 [`GitHubPipelineProvider::report`] 聚合每次运行的指标。
///
/// 返回 `(success_count, total_duration_secs, failure_counts, runs_with_duration)`。
fn aggregate_report_metrics(
    runs: &[ReportRun],
) -> (u64, f64, std::collections::HashMap<String, u64>, u64) {
    let mut success_count: u64 = 0;
    let mut total_duration_secs: f64 = 0.0;
    let mut failure_counts: std::collections::HashMap<String, u64> =
        std::collections::HashMap::new();
    let mut has_duration: u64 = 0;

    for run in runs {
        if let Some(ref conclusion) = run.conclusion {
            if conclusion == "success" {
                success_count += 1;
            } else if !matches!(conclusion.as_str(), "cancelled" | "skipped" | "neutral") {
                // Counts all failure conclusions: "failure", "startup_failure",
                // "timed_out", and any other non-success/non-neutral conclusion.
                *failure_counts.entry(conclusion.clone()).or_insert(0) += 1;
            }
        }

        if let (Ok(created), Ok(updated)) = (
            chrono::DateTime::parse_from_rfc3339(&run.created_at),
            chrono::DateTime::parse_from_rfc3339(&run.updated_at),
        ) {
            let duration = (updated.with_timezone(&chrono::Utc)
                - created.with_timezone(&chrono::Utc))
            .num_seconds();
            if duration > 0 {
                #[allow(
                    clippy::cast_precision_loss,
                    reason = "Duration values are small enough to fit in f64 without loss"
                )]
                let duration_f64 = duration as f64;
                total_duration_secs += duration_f64;
                has_duration += 1;
            }
        }
    }

    (
        success_count,
        total_duration_secs,
        failure_counts,
        has_duration,
    )
}

#[async_trait]
impl<R: CommandRunner + 'static> PipelineProvider for GitHubPipelineProvider<R> {
    async fn status(&self, branch: &str) -> Result<Vec<PipelineStatus>> {
        debug!(repo = %self.repo, branch = %branch, "spawning `gh run list`");

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

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

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

        Ok(runs.into_iter().map(GhRun::into_status).collect())
    }

    async fn logs(&self, pipeline_id: u64) -> Result<String> {
        debug!(repo = %self.repo, pipeline_id, "spawning `gh run view --log`");

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

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

        String::from_utf8(output.stdout)
            .map_err(|e| CoreError::Platform(format!("Failed to decode log output as UTF-8: {e}")))
    }

    async fn jobs(&self, pipeline_id: u64) -> Result<Vec<JobData>> {
        debug!(repo = %self.repo, pipeline_id, "spawning `gh run view --json jobs`");

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

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

        let resp: JobsResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(resp.jobs.into_iter().map(GhJob::into_job_data).collect())
    }

    async fn report(&self, branch: &str, days: u32) -> Result<PipelineReport> {
        debug!(
            repo = %self.repo,
            branch = %branch,
            days,
            "spawning `gh run list` for report"
        );

        let output = self
            .runner
            .run(
                "gh",
                &[
                    "run",
                    "list",
                    "--branch",
                    branch,
                    "--repo",
                    &self.repo,
                    "--json",
                    "conclusion,createdAt,updatedAt",
                    "--limit",
                    "100",
                ],
            )
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;

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

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

        // Filter to the requested time window. Unparsable timestamps are kept
        // (conservative: never drop runs because of a date format surprise).
        let cutoff = chrono::Utc::now() - chrono::Duration::days(i64::from(days));
        let runs: Vec<ReportRun> = all_runs
            .into_iter()
            .filter(|run| {
                chrono::DateTime::parse_from_rfc3339(&run.created_at)
                    .map_or(true, |dt| dt.with_timezone(&chrono::Utc) >= cutoff)
            })
            .collect();

        let total_runs = runs.len() as u64;

        let (success_count, total_duration_secs, failure_counts, has_duration) =
            aggregate_report_metrics(&runs);

        #[allow(
            clippy::cast_precision_loss,
            reason = "Run counts are small enough to fit in f64 without loss"
        )]
        let success_rate = if total_runs > 0 {
            success_count as f64 / total_runs as f64
        } else {
            0.0
        };

        #[allow(
            clippy::cast_precision_loss,
            reason = "Duration count is small enough to fit in f64 without loss"
        )]
        let avg_duration_secs = if has_duration > 0 {
            total_duration_secs / has_duration as f64
        } else {
            0.0
        };

        // 按失败次数降序取 top 失败结论
        let mut failures: Vec<_> = failure_counts.into_iter().collect();
        failures.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        let top_failures: Vec<String> = failures.into_iter().map(|(k, _)| k).collect();

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

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

    #[test]
    fn test_should_construct_github_pipeline_provider() {
        let provider = GitHubPipelineProvider::new("octocat/hello-world");
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_construct_github_pipeline_provider_from_string() {
        let repo = String::from("octocat/hello-world");
        let provider = GitHubPipelineProvider::new(repo);
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_debug_format_provider() {
        let provider = GitHubPipelineProvider::new("octocat/hello-world");
        let debug = format!("{provider:?}");
        assert!(debug.contains("GitHubPipelineProvider"));
        assert!(debug.contains("octocat/hello-world"));
    }

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

    #[test]
    fn test_should_deserialize_gh_run_from_json() {
        let json = br#"{
            "databaseId": 12345,
            "headBranch": "main",
            "status": "completed",
            "conclusion": "success",
            "createdAt": "2026-07-01T10:00:00Z",
            "updatedAt": "2026-07-01T10:05:30Z",
            "url": "https://github.com/example/repo/actions/runs/12345"
        }"#;

        let run: GhRun = serde_json::from_slice(json).expect("valid GhRun JSON");
        assert_eq!(run.database_id, 12345);
        assert_eq!(run.head_branch, "main");
        assert_eq!(run.status, "completed");
        assert_eq!(run.conclusion.as_deref(), Some("success"));
        assert_eq!(
            run.url,
            "https://github.com/example/repo/actions/runs/12345"
        );
    }

    #[test]
    fn test_should_deserialize_gh_run_list_from_json_array() {
        let json = br#"[
            {
                "databaseId": 1,
                "headBranch": "main",
                "status": "completed",
                "conclusion": "success",
                "createdAt": "2026-07-01T10:00:00Z",
                "updatedAt": "2026-07-01T10:05:00Z",
                "url": "https://example.com/1"
            },
            {
                "databaseId": 2,
                "headBranch": "main",
                "status": "in_progress",
                "conclusion": null,
                "createdAt": "2026-07-01T11:00:00Z",
                "updatedAt": "2026-07-01T11:01:00Z",
                "url": "https://example.com/2"
            }
        ]"#;

        let runs: Vec<GhRun> = serde_json::from_slice(json).expect("valid GhRun list");
        assert_eq!(runs.len(), 2);
        assert_eq!(runs[0].database_id, 1);
        assert_eq!(runs[1].database_id, 2);
    }

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

    #[test]
    fn test_should_convert_gh_run_to_pipeline_status() {
        let run = GhRun {
            database_id: 42,
            head_branch: "main".into(),
            status: "completed".into(),
            conclusion: Some("success".into()),
            created_at: "2026-07-01T10:00:00Z".into(),
            updated_at: "2026-07-01T10:05:30Z".into(),
            url: "https://example.com/42".into(),
        };

        let status = run.into_status();
        assert_eq!(status.id, 42);
        assert_eq!(status.ref_name, "main");
        assert_eq!(status.status, PipelineStatusEnum::Success);
        assert_eq!(status.conclusion.as_deref(), Some("success"));
    }

    #[test]
    fn test_should_map_gh_status_completed_success() {
        assert_eq!(
            gh_status_to_enum("completed", Some("success")),
            PipelineStatusEnum::Success
        );
    }

    #[test]
    fn test_should_map_gh_status_completed_failure() {
        assert_eq!(
            gh_status_to_enum("completed", Some("failure")),
            PipelineStatusEnum::Failed
        );
        assert_eq!(
            gh_status_to_enum("completed", Some("startup_failure")),
            PipelineStatusEnum::Failed
        );
        assert_eq!(
            gh_status_to_enum("completed", Some("timed_out")),
            PipelineStatusEnum::Failed
        );
    }

    #[test]
    fn test_should_map_gh_status_completed_cancelled() {
        assert_eq!(
            gh_status_to_enum("completed", Some("cancelled")),
            PipelineStatusEnum::Cancelled
        );
    }

    #[test]
    fn test_should_map_gh_status_completed_skipped() {
        assert_eq!(
            gh_status_to_enum("completed", Some("skipped")),
            PipelineStatusEnum::Pending
        );
        assert_eq!(
            gh_status_to_enum("completed", Some("neutral")),
            PipelineStatusEnum::Pending
        );
    }

    #[test]
    fn test_should_map_gh_status_in_progress() {
        assert_eq!(
            gh_status_to_enum("in_progress", None),
            PipelineStatusEnum::Running
        );
        assert_eq!(
            gh_status_to_enum("action_required", None),
            PipelineStatusEnum::Running
        );
    }

    #[test]
    fn test_should_map_gh_status_queued() {
        assert_eq!(
            gh_status_to_enum("queued", None),
            PipelineStatusEnum::Pending
        );
        assert_eq!(
            gh_status_to_enum("waiting", None),
            PipelineStatusEnum::Pending
        );
        assert_eq!(
            gh_status_to_enum("requested", None),
            PipelineStatusEnum::Pending
        );
    }

    #[test]
    fn test_should_map_gh_status_unknown() {
        assert_eq!(
            gh_status_to_enum("some_unknown_status", None),
            PipelineStatusEnum::Running
        );
    }

    #[test]
    fn test_should_map_completed_with_unknown_conclusion() {
        // completed + unknown conclusion -> Running
        assert_eq!(
            gh_status_to_enum("completed", Some("weird")),
            PipelineStatusEnum::Running
        );
    }

    #[test]
    fn test_should_map_completed_with_none_conclusion() {
        // completed + None conclusion -> Running
        assert_eq!(
            gh_status_to_enum("completed", None),
            PipelineStatusEnum::Running
        );
    }

    #[test]
    fn test_should_deserialize_jobs_response_from_json() {
        let json = br#"{
            "jobs": [
                {
                    "databaseId": 98765,
                    "name": "build",
                    "status": "completed",
                    "conclusion": "success",
                    "startedAt": "2026-07-01T10:00:00Z",
                    "completedAt": "2026-07-01T10:03:00Z",
                    "url": "https://example.com/job/98765"
                }
            ]
        }"#;

        let resp: JobsResponse = serde_json::from_slice(json).expect("valid JobsResponse");
        assert_eq!(resp.jobs.len(), 1);
        assert_eq!(resp.jobs[0].database_id, 98765);
        assert_eq!(resp.jobs[0].name, "build");
    }

    #[test]
    fn test_should_deserialize_empty_jobs_response() {
        let json = br#"{"jobs": []}"#;
        let resp: JobsResponse = serde_json::from_slice(json).expect("valid");
        assert!(resp.jobs.is_empty());
    }

    #[test]
    fn test_should_convert_gh_job_to_job_data() {
        let job = GhJob {
            database_id: 100,
            name: "test".into(),
            status: "completed".into(),
            conclusion: Some("success".into()),
            started_at: Some("2026-07-01T10:00:00Z".into()),
            completed_at: Some("2026-07-01T10:03:00Z".into()),
            url: "https://example.com/job/100".into(),
        };

        let data = job.into_job_data();
        assert_eq!(data.id, 100);
        assert_eq!(data.name, "test");
        assert_eq!(data.status, "completed");
        assert_eq!(data.conclusion.as_deref(), Some("success"));
        assert!(data.started_at.is_some());
        assert!(data.completed_at.is_some());
    }

    #[test]
    fn test_should_convert_gh_job_with_null_timestamps() {
        let job = GhJob {
            database_id: 1,
            name: "queued-job".into(),
            status: "queued".into(),
            conclusion: None,
            started_at: None,
            completed_at: None,
            url: "https://example.com/job/1".into(),
        };

        let data = job.into_job_data();
        assert!(data.started_at.is_none());
        assert!(data.completed_at.is_none());
    }

    #[test]
    fn test_should_deserialize_run_with_null_conclusion() {
        let json = br#"{
            "databaseId": 1,
            "headBranch": "develop",
            "status": "in_progress",
            "conclusion": null,
            "createdAt": "2026-07-02T08:00:00Z",
            "updatedAt": "2026-07-02T08:00:00Z",
            "url": "https://example.com/1"
        }"#;

        let run: GhRun = serde_json::from_slice(json).expect("deserialize");
        assert!(run.conclusion.is_none());
        assert_eq!(run.status, "in_progress");
    }

    #[test]
    fn test_should_compute_report_from_runs() {
        // 模拟 report 使用的最小结构体
        #[derive(Debug, Deserialize)]
        #[allow(
            dead_code,
            reason = "Test fixture struct fields are deserialized but not all read"
        )]
        #[serde(rename_all = "camelCase")]
        struct TestReportRun {
            conclusion: Option<String>,
            created_at: String,
            updated_at: String,
        }

        let json = br#"[
            {"conclusion": "success", "createdAt": "2026-07-01T10:00:00Z", "updatedAt": "2026-07-01T10:05:00Z"},
            {"conclusion": "success", "createdAt": "2026-07-01T11:00:00Z", "updatedAt": "2026-07-01T11:03:00Z"},
            {"conclusion": "failure", "createdAt": "2026-07-01T12:00:00Z", "updatedAt": "2026-07-01T12:02:00Z"},
            {"conclusion": null, "createdAt": "2026-07-01T13:00:00Z", "updatedAt": "2026-07-01T13:01:00Z"}
        ]"#;

        let runs: Vec<TestReportRun> = serde_json::from_slice(json).expect("valid");
        assert_eq!(runs.len(), 4);

        let total = runs.len() as u64;
        let success: u64 = runs
            .iter()
            .filter(|r| r.conclusion.as_deref() == Some("success"))
            .count() as u64;
        #[allow(
            clippy::cast_precision_loss,
            reason = "Test values are small enough to fit in f64 without loss"
        )]
        let rate = success as f64 / total as f64;

        assert_eq!(total, 4);
        assert_eq!(success, 2);
        assert!((rate - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_should_count_all_failure_types_in_report_logic() {
        // 验证 report 方法中的失败计数逻辑:
        // "failure"、"startup_failure"、"timed_out" 都应被计入 top_failures,
        // 而 "cancelled"、"skipped"、"neutral" 不应被计入。
        use std::collections::HashMap;

        let conclusions = [
            "success",
            "success",
            "failure",
            "failure",
            "startup_failure",
            "timed_out",
            "cancelled",
            "skipped",
            "neutral",
        ];

        let mut success_count: u64 = 0;
        let mut failure_counts: HashMap<String, u64> = HashMap::new();

        for conclusion in &conclusions {
            if *conclusion == "success" {
                success_count += 1;
            } else if !matches!(*conclusion, "cancelled" | "skipped" | "neutral") {
                *failure_counts.entry(conclusion.to_string()).or_insert(0) += 1;
            }
        }

        assert_eq!(success_count, 2);

        assert_eq!(failure_counts.get("failure"), Some(&2));
        assert_eq!(failure_counts.get("startup_failure"), Some(&1));
        assert_eq!(failure_counts.get("timed_out"), Some(&1));
        assert_eq!(failure_counts.get("cancelled"), None);
        assert_eq!(failure_counts.get("skipped"), None);
        assert_eq!(failure_counts.get("neutral"), None);

        // 验证 top_failures 排序(按数量降序)
        let mut failures: Vec<_> = failure_counts.into_iter().collect();
        failures.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        let top_failures: Vec<String> = failures.into_iter().map(|(k, _)| k).collect();

        // "failure" 有 2 次排第一,其余各 1 次按字母序
        assert_eq!(top_failures[0], "failure");
        assert!(top_failures.contains(&"startup_failure".to_string()));
        assert!(top_failures.contains(&"timed_out".to_string()));
        assert_eq!(top_failures.len(), 3);
    }

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

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

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

        assert!(result.is_err());
        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("invalid json");
        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);

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

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

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

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

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

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

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

        assert!(result.is_err());
        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("invalid json");
        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);

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

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

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

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

        assert!(result.is_err());
        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("invalid json");
        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);

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

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