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    datetime::parse_api_datetime,
15    error::parse_gh_error,
16    runner::{CommandRunner, RealCommandRunner},
17};
18
19/// `gh run list` 请求的 JSON 字段列表。
20const PIPELINE_FIELDS: &str = "databaseId,headBranch,status,conclusion,createdAt,updatedAt,url";
21
22/// 将 GitHub `gh run list` 返回的 status 字符串映射为 [`PipelineStatusEnum`]。
23///
24/// GitHub 返回小写状态:`queued`、`in_progress`、`completed`、`waiting`、
25/// `requested`、`pending` 等。其中 `completed` 需要结合 `conclusion`
26/// 判断最终结果。
27fn gh_status_to_enum(status: &str, conclusion: Option<&str>) -> PipelineStatusEnum {
28    match status {
29        "completed" => match conclusion {
30            Some("success") => PipelineStatusEnum::Success,
31            Some("failure" | "startup_failure" | "timed_out") => PipelineStatusEnum::Failed,
32            Some("cancelled") => PipelineStatusEnum::Cancelled,
33            Some("skipped" | "neutral") => PipelineStatusEnum::Pending,
34            _ => PipelineStatusEnum::Running,
35        },
36        "queued" | "waiting" | "requested" | "pending" => PipelineStatusEnum::Pending,
37        _ => PipelineStatusEnum::Running,
38    }
39}
40
41/// GitHub 单次 run 的原始响应,用于反序列化。
42#[derive(Debug, Deserialize)]
43#[serde(rename_all = "camelCase")]
44struct GhRun {
45    database_id: u64,
46    head_branch: String,
47    status: String,
48    conclusion: Option<String>,
49    created_at: String,
50    updated_at: String,
51    url: String,
52}
53
54impl GhRun {
55    fn into_status(self) -> PipelineStatus {
56        let created_at = parse_api_datetime(&self.created_at);
57        let updated_at = parse_api_datetime(&self.updated_at);
58
59        PipelineStatus {
60            id: self.database_id,
61            ref_name: self.head_branch,
62            status: gh_status_to_enum(&self.status, self.conclusion.as_deref()),
63            conclusion: self.conclusion,
64            // Wrapped in Some for PipelineStatus's Option type (#380).
65            created_at: Some(created_at),
66            updated_at: Some(updated_at),
67            url: self.url,
68        }
69    }
70}
71
72/// `gh run view --json jobs` 的包裹结构体。
73///
74/// GitHub 返回 `{"jobs": [...]}` 而非直接数组。
75#[derive(Debug, Deserialize)]
76struct JobsResponse {
77    jobs: Vec<GhJob>,
78}
79
80/// GitHub 单次 job 的原始响应。
81#[derive(Debug, Deserialize)]
82#[serde(rename_all = "camelCase")]
83struct GhJob {
84    database_id: u64,
85    name: String,
86    status: String,
87    conclusion: Option<String>,
88    started_at: Option<String>,
89    completed_at: Option<String>,
90    url: String,
91}
92
93impl GhJob {
94    fn into_job_data(self) -> JobData {
95        let parse_ts = |s: Option<&str>| {
96            s.and_then(|v| {
97                chrono::DateTime::parse_from_rfc3339(v)
98                    .ok()
99                    .map(|dt| dt.with_timezone(&chrono::Utc))
100            })
101        };
102
103        JobData {
104            id: self.database_id,
105            name: self.name,
106            status: self.status,
107            conclusion: self.conclusion,
108            started_at: parse_ts(self.started_at.as_deref()),
109            completed_at: parse_ts(self.completed_at.as_deref()),
110            url: self.url,
111        }
112    }
113}
114
115/// GitHub Pipeline 提供者,通过 `gh` CLI 操作 CI/CD 流水线。
116///
117/// 该结构体通过调用 `gh` CLI 实现 [`PipelineProvider`] trait 的所有方法,
118/// 使上层命令能够以统一的方式查看 GitHub Actions 流水线状态。
119///
120/// 命令执行通过 [`CommandRunner`] 抽象,生产环境默认使用
121/// [`RealCommandRunner`],测试可注入自定义 runner 以模拟成功或失败场景。
122///
123/// # Examples
124///
125/// ```no_run
126/// use gitflow_github::GitHubPipelineProvider;
127///
128/// let provider = GitHubPipelineProvider::new("octocat/hello-world");
129/// ```
130#[derive(Debug, Clone)]
131pub struct GitHubPipelineProvider<R: CommandRunner = RealCommandRunner> {
132    /// GitHub `owner/repo`,如 `"byx-darwin/gitflow-cli"`。
133    repo: String,
134    /// 用于执行 `gh` CLI 命令的 runner。
135    runner: R,
136}
137
138impl GitHubPipelineProvider<RealCommandRunner> {
139    /// 创建新的 GitHub Pipeline 提供者,使用真实的进程执行器。
140    ///
141    /// `repo` 格式为 `owner/repo`。
142    #[must_use]
143    pub fn new(repo: impl Into<String>) -> Self {
144        Self {
145            repo: repo.into(),
146            runner: RealCommandRunner,
147        }
148    }
149
150    /// Create a new provider from a shared [`Session`].
151    ///
152    /// This enables state reuse across multiple operations in workflow chains.
153    #[must_use]
154    pub fn with_session(session: &gitflow_core::Session) -> Self {
155        Self {
156            repo: session.repo.clone(),
157            runner: RealCommandRunner,
158        }
159    }
160}
161
162impl<R: CommandRunner> GitHubPipelineProvider<R> {
163    /// 使用自定义 [`CommandRunner`] 创建提供者。
164    ///
165    /// 主要用于测试,可注入模拟 runner 以控制 `gh` CLI 的输出。
166    /// `repo` 格式为 `owner/repo`。
167    #[must_use]
168    pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
169        Self {
170            repo: repo.into(),
171            runner,
172        }
173    }
174}
175
176impl<R: CommandRunner + 'static> GitHubPipelineProvider<R> {
177    /// 为一批已收尾且失败类的 run 归因到具体失败 job 名称,用于 [`PipelineReport::top_failures`]。
178    ///
179    /// 只对结论落在失败类(见 [`is_failure_conclusion`])的 run 发起 `jobs` 查询,
180    /// 成功和非失败终态(`cancelled`/`skipped`/`neutral`)的 run 不消耗额外 API
181    /// 调用。若某次 run 的 job 级数据无法获取、其中没有失败类 job,或匹配到的
182    /// job 自身尚未收尾(`status != "completed"`,issue #324),则回退为该 run
183    /// 的通用 `conclusion` 字符串,确保该样本仍计入统计而不是被静默丢弃或
184    /// 误将一个仍在执行的 job 当作失败来源。
185    async fn attribute_top_failures(&self, runs: &[&ReportRun]) -> Vec<String> {
186        let mut failure_counts: std::collections::HashMap<String, u64> =
187            std::collections::HashMap::new();
188
189        for run in runs {
190            let Some(conclusion) = run.conclusion.as_deref() else {
191                continue;
192            };
193            if !is_failure_conclusion(conclusion) {
194                continue;
195            }
196
197            let label = match self.jobs(run.database_id).await {
198                Ok(jobs) => jobs
199                    .iter()
200                    .find(|job| {
201                        job.status == "completed"
202                            && job.conclusion.as_deref().is_some_and(is_failure_conclusion)
203                    })
204                    .map_or_else(|| conclusion.to_owned(), |job| job.name.clone()),
205                Err(err) => {
206                    debug!(
207                        repo = %self.repo,
208                        pipeline_id = run.database_id,
209                        error = %err,
210                        "failed to fetch jobs for failure attribution, falling back to generic conclusion"
211                    );
212                    conclusion.to_owned()
213                }
214            };
215
216            *failure_counts.entry(label).or_insert(0) += 1;
217        }
218
219        // 按失败次数降序排列;次数相同时按标签字母序,保证输出稳定。
220        let mut failures: Vec<_> = failure_counts.into_iter().collect();
221        failures.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
222        failures.into_iter().map(|(label, _)| label).collect()
223    }
224}
225
226/// `gh run list` 的 report 统计所需最小字段集。
227#[derive(Debug, Deserialize)]
228#[serde(rename_all = "camelCase")]
229struct ReportRun {
230    database_id: u64,
231    /// GitHub Actions run 的整体状态(`"queued"`/`"in_progress"`/`"completed"` 等)。
232    ///
233    /// 只有 `"completed"` 才代表该 run 已收尾——`conclusion` 字段不能单独
234    /// 作为收尾判据:观测到 `gh run list` 会在 run 仍未收尾时也为
235    /// `conclusion` 填入非 null 值(issue #324)。
236    status: String,
237    conclusion: Option<String>,
238    created_at: String,
239    updated_at: String,
240}
241
242/// 判断 run/job 的 `conclusion` 字符串是否属于失败类结论。
243///
244/// 与成功(`success`)、非失败终态(`cancelled`/`skipped`/`neutral`)区分开;
245/// 其余(`failure`/`startup_failure`/`timed_out` 及任何未知值)视为失败。
246fn is_failure_conclusion(conclusion: &str) -> bool {
247    !matches!(conclusion, "success" | "cancelled" | "skipped" | "neutral")
248}
249
250/// 为 [`GitHubPipelineProvider::report`] 聚合每次运行的成功数与耗时指标。
251///
252/// 失败归因(`top_failures`)由 [`GitHubPipelineProvider::attribute_top_failures`]
253/// 单独处理,因为它需要按需发起额外的 `jobs` API 调用。
254///
255/// 返回 `(success_count, total_duration_secs, runs_with_duration)`。
256fn aggregate_report_metrics(runs: &[&ReportRun]) -> (u64, f64, u64) {
257    let mut success_count: u64 = 0;
258    let mut total_duration_secs: f64 = 0.0;
259    let mut has_duration: u64 = 0;
260
261    for run in runs {
262        if run.conclusion.as_deref() == Some("success") {
263            success_count += 1;
264        }
265
266        if let (Ok(created), Ok(updated)) = (
267            chrono::DateTime::parse_from_rfc3339(&run.created_at),
268            chrono::DateTime::parse_from_rfc3339(&run.updated_at),
269        ) {
270            let duration = (updated.with_timezone(&chrono::Utc)
271                - created.with_timezone(&chrono::Utc))
272            .num_seconds();
273            if duration > 0 {
274                #[allow(
275                    clippy::cast_precision_loss,
276                    reason = "Duration values are small enough to fit in f64 without loss"
277                )]
278                let duration_f64 = duration as f64;
279                total_duration_secs += duration_f64;
280                has_duration += 1;
281            }
282        }
283    }
284
285    (success_count, total_duration_secs, has_duration)
286}
287
288#[async_trait]
289impl<R: CommandRunner + 'static> PipelineProvider for GitHubPipelineProvider<R> {
290    async fn status(&self, branch: &str) -> Result<Vec<PipelineStatus>> {
291        debug!(repo = %self.repo, branch = %branch, "spawning `gh run list`");
292
293        let output = self
294            .runner
295            .run(
296                "gh",
297                &[
298                    "run",
299                    "list",
300                    "--branch",
301                    branch,
302                    "--repo",
303                    &self.repo,
304                    "--json",
305                    PIPELINE_FIELDS,
306                    "--limit",
307                    "30",
308                ],
309            )
310            .await
311            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
312
313        if !output.status.success() {
314            return Err(parse_gh_error(&output.stderr).into());
315        }
316
317        let runs: Vec<GhRun> =
318            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
319
320        Ok(runs.into_iter().map(GhRun::into_status).collect())
321    }
322
323    async fn logs(&self, pipeline_id: u64) -> Result<String> {
324        debug!(repo = %self.repo, pipeline_id, "spawning `gh run view --log`");
325
326        let run_id = pipeline_id.to_string();
327        let output = self
328            .runner
329            .run(
330                "gh",
331                &["run", "view", &run_id, "--repo", &self.repo, "--log"],
332            )
333            .await
334            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
335
336        if !output.status.success() {
337            return Err(parse_gh_error(&output.stderr).into());
338        }
339
340        String::from_utf8(output.stdout)
341            .map_err(|e| CoreError::Platform(format!("Failed to decode log output as UTF-8: {e}")))
342    }
343
344    async fn jobs(&self, pipeline_id: u64) -> Result<Vec<JobData>> {
345        debug!(repo = %self.repo, pipeline_id, "spawning `gh run view --json jobs`");
346
347        let run_id = pipeline_id.to_string();
348        let output = self
349            .runner
350            .run(
351                "gh",
352                &[
353                    "run", "view", &run_id, "--repo", &self.repo, "--json", "jobs",
354                ],
355            )
356            .await
357            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
358
359        if !output.status.success() {
360            return Err(parse_gh_error(&output.stderr).into());
361        }
362
363        let resp: JobsResponse =
364            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
365
366        Ok(resp.jobs.into_iter().map(GhJob::into_job_data).collect())
367    }
368
369    async fn report(&self, branch: &str, days: u32) -> Result<PipelineReport> {
370        debug!(
371            repo = %self.repo,
372            branch = %branch,
373            days,
374            "spawning `gh run list` for report"
375        );
376
377        let output = self
378            .runner
379            .run(
380                "gh",
381                &[
382                    "run",
383                    "list",
384                    "--branch",
385                    branch,
386                    "--repo",
387                    &self.repo,
388                    "--json",
389                    "databaseId,status,conclusion,createdAt,updatedAt",
390                    "--limit",
391                    "100",
392                ],
393            )
394            .await
395            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh: {e}")))?;
396
397        if !output.status.success() {
398            return Err(parse_gh_error(&output.stderr).into());
399        }
400
401        let all_runs: Vec<ReportRun> =
402            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
403
404        // Filter to the requested time window. Unparsable timestamps are kept
405        // (conservative: never drop runs because of a date format surprise).
406        let cutoff = chrono::Utc::now() - chrono::Duration::days(i64::from(days));
407        let runs: Vec<ReportRun> = all_runs
408            .into_iter()
409            .filter(|run| {
410                chrono::DateTime::parse_from_rfc3339(&run.created_at)
411                    .map_or(true, |dt| dt.with_timezone(&chrono::Utc) >= cutoff)
412            })
413            .collect();
414
415        // A run only carries a meaningful `conclusion` once its `status` is
416        // `"completed"`. Gating on `status` (rather than `conclusion.is_some()`)
417        // is required because `gh run list` can populate `conclusion` for a
418        // run that has not actually finished (issue #324) — trusting presence
419        // alone re-admits in-progress runs into the denominator.
420        let terminal_runs: Vec<&ReportRun> = runs
421            .iter()
422            .filter(|run| run.status == "completed")
423            .collect();
424
425        let total_runs = terminal_runs.len() as u64;
426
427        let (success_count, total_duration_secs, has_duration) =
428            aggregate_report_metrics(&terminal_runs);
429
430        #[allow(
431            clippy::cast_precision_loss,
432            reason = "Run counts are small enough to fit in f64 without loss"
433        )]
434        let success_rate = if total_runs > 0 {
435            success_count as f64 / total_runs as f64
436        } else {
437            0.0
438        };
439
440        #[allow(
441            clippy::cast_precision_loss,
442            reason = "Duration count is small enough to fit in f64 without loss"
443        )]
444        let avg_duration_secs = if has_duration > 0 {
445            total_duration_secs / has_duration as f64
446        } else {
447            0.0
448        };
449
450        // 按失败次数降序取 top 失败归因标签(job 名称,若无法归因则回退为
451        // 通用 conclusion 字符串)。仅对失败类 run 发起额外的 jobs 查询,
452        // 避免对每个 run 都调用 API。
453        let top_failures = self.attribute_top_failures(&terminal_runs).await;
454
455        Ok(PipelineReport {
456            total_runs,
457            success_rate,
458            avg_duration_secs,
459            top_failures,
460        })
461    }
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467    use crate::runner::MockCommandRunner;
468
469    #[test]
470    fn test_should_construct_github_pipeline_provider() {
471        let provider = GitHubPipelineProvider::new("octocat/hello-world");
472        assert_eq!(provider.repo, "octocat/hello-world");
473    }
474
475    #[test]
476    fn test_should_construct_github_pipeline_provider_from_string() {
477        let repo = String::from("octocat/hello-world");
478        let provider = GitHubPipelineProvider::new(repo);
479        assert_eq!(provider.repo, "octocat/hello-world");
480    }
481
482    #[test]
483    fn test_should_debug_format_provider() {
484        let provider = GitHubPipelineProvider::new("octocat/hello-world");
485        let debug = format!("{provider:?}");
486        assert!(debug.contains("GitHubPipelineProvider"));
487        assert!(debug.contains("octocat/hello-world"));
488    }
489
490    #[test]
491    fn test_should_clone_github_pipeline_provider() {
492        let original = GitHubPipelineProvider::new("owner/repo");
493        let cloned = original.clone();
494        assert_eq!(original.repo, cloned.repo);
495    }
496
497    #[test]
498    fn test_should_deserialize_gh_run_from_json() {
499        let json = br#"{
500            "databaseId": 12345,
501            "headBranch": "main",
502            "status": "completed",
503            "conclusion": "success",
504            "createdAt": "2026-07-01T10:00:00Z",
505            "updatedAt": "2026-07-01T10:05:30Z",
506            "url": "https://github.com/example/repo/actions/runs/12345"
507        }"#;
508
509        let run: GhRun = serde_json::from_slice(json).expect("valid GhRun JSON");
510        assert_eq!(run.database_id, 12345);
511        assert_eq!(run.head_branch, "main");
512        assert_eq!(run.status, "completed");
513        assert_eq!(run.conclusion.as_deref(), Some("success"));
514        assert_eq!(
515            run.url,
516            "https://github.com/example/repo/actions/runs/12345"
517        );
518    }
519
520    #[test]
521    fn test_should_deserialize_gh_run_list_from_json_array() {
522        let json = br#"[
523            {
524                "databaseId": 1,
525                "headBranch": "main",
526                "status": "completed",
527                "conclusion": "success",
528                "createdAt": "2026-07-01T10:00:00Z",
529                "updatedAt": "2026-07-01T10:05:00Z",
530                "url": "https://example.com/1"
531            },
532            {
533                "databaseId": 2,
534                "headBranch": "main",
535                "status": "in_progress",
536                "conclusion": null,
537                "createdAt": "2026-07-01T11:00:00Z",
538                "updatedAt": "2026-07-01T11:01:00Z",
539                "url": "https://example.com/2"
540            }
541        ]"#;
542
543        let runs: Vec<GhRun> = serde_json::from_slice(json).expect("valid GhRun list");
544        assert_eq!(runs.len(), 2);
545        assert_eq!(runs[0].database_id, 1);
546        assert_eq!(runs[1].database_id, 2);
547    }
548
549    #[test]
550    fn test_should_deserialize_empty_run_list() {
551        let json = b"[]";
552        let runs: Vec<GhRun> = serde_json::from_slice(json).expect("empty list");
553        assert!(runs.is_empty());
554    }
555
556    #[test]
557    fn test_should_convert_gh_run_to_pipeline_status() {
558        let run = GhRun {
559            database_id: 42,
560            head_branch: "main".into(),
561            status: "completed".into(),
562            conclusion: Some("success".into()),
563            created_at: "2026-07-01T10:00:00Z".into(),
564            updated_at: "2026-07-01T10:05:30Z".into(),
565            url: "https://example.com/42".into(),
566        };
567
568        let status = run.into_status();
569        assert_eq!(status.id, 42);
570        assert_eq!(status.ref_name, "main");
571        assert_eq!(status.status, PipelineStatusEnum::Success);
572        assert_eq!(status.conclusion.as_deref(), Some("success"));
573    }
574
575    #[test]
576    fn test_should_convert_run_with_present_timestamps_to_some() {
577        let run = GhRun {
578            database_id: 1,
579            head_branch: "main".to_string(),
580            status: "completed".to_string(),
581            conclusion: Some("success".to_string()),
582            created_at: "2026-07-01T10:00:00Z".to_string(),
583            updated_at: "2026-07-01T10:05:30Z".to_string(),
584            url: "https://example.com/runs/1".to_string(),
585        };
586        let status = run.into_status();
587        assert!(status.created_at.is_some());
588        assert!(status.updated_at.is_some());
589    }
590
591    #[test]
592    fn test_should_use_epoch_for_malformed_pipeline_timestamps() {
593        let run = GhRun {
594            database_id: 1,
595            head_branch: "main".to_string(),
596            status: "completed".to_string(),
597            conclusion: Some("success".to_string()),
598            created_at: "invalid-created-at".to_string(),
599            updated_at: "invalid-updated-at".to_string(),
600            url: "https://example.com/runs/1".to_string(),
601        };
602
603        let status = run.into_status();
604        assert_eq!(status.created_at, Some(chrono::DateTime::UNIX_EPOCH));
605        assert_eq!(status.updated_at, Some(chrono::DateTime::UNIX_EPOCH));
606    }
607
608    #[test]
609    fn test_should_map_gh_status_completed_success() {
610        assert_eq!(
611            gh_status_to_enum("completed", Some("success")),
612            PipelineStatusEnum::Success
613        );
614    }
615
616    #[test]
617    fn test_should_map_gh_status_completed_failure() {
618        assert_eq!(
619            gh_status_to_enum("completed", Some("failure")),
620            PipelineStatusEnum::Failed
621        );
622        assert_eq!(
623            gh_status_to_enum("completed", Some("startup_failure")),
624            PipelineStatusEnum::Failed
625        );
626        assert_eq!(
627            gh_status_to_enum("completed", Some("timed_out")),
628            PipelineStatusEnum::Failed
629        );
630    }
631
632    #[test]
633    fn test_should_map_gh_status_completed_cancelled() {
634        assert_eq!(
635            gh_status_to_enum("completed", Some("cancelled")),
636            PipelineStatusEnum::Cancelled
637        );
638    }
639
640    #[test]
641    fn test_should_map_gh_status_completed_skipped() {
642        assert_eq!(
643            gh_status_to_enum("completed", Some("skipped")),
644            PipelineStatusEnum::Pending
645        );
646        assert_eq!(
647            gh_status_to_enum("completed", Some("neutral")),
648            PipelineStatusEnum::Pending
649        );
650    }
651
652    #[test]
653    fn test_should_map_gh_status_in_progress() {
654        assert_eq!(
655            gh_status_to_enum("in_progress", None),
656            PipelineStatusEnum::Running
657        );
658        assert_eq!(
659            gh_status_to_enum("action_required", None),
660            PipelineStatusEnum::Running
661        );
662    }
663
664    #[test]
665    fn test_should_map_gh_status_queued() {
666        assert_eq!(
667            gh_status_to_enum("queued", None),
668            PipelineStatusEnum::Pending
669        );
670        assert_eq!(
671            gh_status_to_enum("waiting", None),
672            PipelineStatusEnum::Pending
673        );
674        assert_eq!(
675            gh_status_to_enum("requested", None),
676            PipelineStatusEnum::Pending
677        );
678    }
679
680    #[test]
681    fn test_should_map_gh_status_unknown() {
682        assert_eq!(
683            gh_status_to_enum("some_unknown_status", None),
684            PipelineStatusEnum::Running
685        );
686    }
687
688    #[test]
689    fn test_should_map_completed_with_unknown_conclusion() {
690        // completed + unknown conclusion -> Running
691        assert_eq!(
692            gh_status_to_enum("completed", Some("weird")),
693            PipelineStatusEnum::Running
694        );
695    }
696
697    #[test]
698    fn test_should_map_completed_with_none_conclusion() {
699        // completed + None conclusion -> Running
700        assert_eq!(
701            gh_status_to_enum("completed", None),
702            PipelineStatusEnum::Running
703        );
704    }
705
706    #[test]
707    fn test_should_deserialize_jobs_response_from_json() {
708        let json = br#"{
709            "jobs": [
710                {
711                    "databaseId": 98765,
712                    "name": "build",
713                    "status": "completed",
714                    "conclusion": "success",
715                    "startedAt": "2026-07-01T10:00:00Z",
716                    "completedAt": "2026-07-01T10:03:00Z",
717                    "url": "https://example.com/job/98765"
718                }
719            ]
720        }"#;
721
722        let resp: JobsResponse = serde_json::from_slice(json).expect("valid JobsResponse");
723        assert_eq!(resp.jobs.len(), 1);
724        assert_eq!(resp.jobs[0].database_id, 98765);
725        assert_eq!(resp.jobs[0].name, "build");
726    }
727
728    #[test]
729    fn test_should_deserialize_empty_jobs_response() {
730        let json = br#"{"jobs": []}"#;
731        let resp: JobsResponse = serde_json::from_slice(json).expect("valid");
732        assert!(resp.jobs.is_empty());
733    }
734
735    #[test]
736    fn test_should_convert_gh_job_to_job_data() {
737        let job = GhJob {
738            database_id: 100,
739            name: "test".into(),
740            status: "completed".into(),
741            conclusion: Some("success".into()),
742            started_at: Some("2026-07-01T10:00:00Z".into()),
743            completed_at: Some("2026-07-01T10:03:00Z".into()),
744            url: "https://example.com/job/100".into(),
745        };
746
747        let data = job.into_job_data();
748        assert_eq!(data.id, 100);
749        assert_eq!(data.name, "test");
750        assert_eq!(data.status, "completed");
751        assert_eq!(data.conclusion.as_deref(), Some("success"));
752        assert!(data.started_at.is_some());
753        assert!(data.completed_at.is_some());
754    }
755
756    #[test]
757    fn test_should_convert_gh_job_with_null_timestamps() {
758        let job = GhJob {
759            database_id: 1,
760            name: "queued-job".into(),
761            status: "queued".into(),
762            conclusion: None,
763            started_at: None,
764            completed_at: None,
765            url: "https://example.com/job/1".into(),
766        };
767
768        let data = job.into_job_data();
769        assert!(data.started_at.is_none());
770        assert!(data.completed_at.is_none());
771    }
772
773    #[test]
774    fn test_should_deserialize_run_with_null_conclusion() {
775        let json = br#"{
776            "databaseId": 1,
777            "headBranch": "develop",
778            "status": "in_progress",
779            "conclusion": null,
780            "createdAt": "2026-07-02T08:00:00Z",
781            "updatedAt": "2026-07-02T08:00:00Z",
782            "url": "https://example.com/1"
783        }"#;
784
785        let run: GhRun = serde_json::from_slice(json).expect("deserialize");
786        assert!(run.conclusion.is_none());
787        assert_eq!(run.status, "in_progress");
788    }
789
790    #[test]
791    fn test_should_compute_report_from_runs() {
792        // 模拟 report 使用的最小结构体
793        #[derive(Debug, Deserialize)]
794        #[allow(
795            dead_code,
796            reason = "Test fixture struct fields are deserialized but not all read"
797        )]
798        #[serde(rename_all = "camelCase")]
799        struct TestReportRun {
800            conclusion: Option<String>,
801            created_at: String,
802            updated_at: String,
803        }
804
805        let json = br#"[
806            {"conclusion": "success", "createdAt": "2026-07-01T10:00:00Z", "updatedAt": "2026-07-01T10:05:00Z"},
807            {"conclusion": "success", "createdAt": "2026-07-01T11:00:00Z", "updatedAt": "2026-07-01T11:03:00Z"},
808            {"conclusion": "failure", "createdAt": "2026-07-01T12:00:00Z", "updatedAt": "2026-07-01T12:02:00Z"},
809            {"conclusion": null, "createdAt": "2026-07-01T13:00:00Z", "updatedAt": "2026-07-01T13:01:00Z"}
810        ]"#;
811
812        let runs: Vec<TestReportRun> = serde_json::from_slice(json).expect("valid");
813        assert_eq!(runs.len(), 4);
814
815        let total = runs.len() as u64;
816        let success: u64 = runs
817            .iter()
818            .filter(|r| r.conclusion.as_deref() == Some("success"))
819            .count() as u64;
820        #[allow(
821            clippy::cast_precision_loss,
822            reason = "Test values are small enough to fit in f64 without loss"
823        )]
824        let rate = success as f64 / total as f64;
825
826        assert_eq!(total, 4);
827        assert_eq!(success, 2);
828        assert!((rate - 0.5).abs() < f64::EPSILON);
829    }
830
831    #[test]
832    fn test_should_count_all_failure_types_in_report_logic() {
833        // 验证 report 方法中的失败计数逻辑:
834        // "failure"、"startup_failure"、"timed_out" 都应被计入 top_failures,
835        // 而 "cancelled"、"skipped"、"neutral" 不应被计入。
836        use std::collections::HashMap;
837
838        let conclusions = [
839            "success",
840            "success",
841            "failure",
842            "failure",
843            "startup_failure",
844            "timed_out",
845            "cancelled",
846            "skipped",
847            "neutral",
848        ];
849
850        let mut success_count: u64 = 0;
851        let mut failure_counts: HashMap<String, u64> = HashMap::new();
852
853        for conclusion in &conclusions {
854            if *conclusion == "success" {
855                success_count += 1;
856            } else if !matches!(*conclusion, "cancelled" | "skipped" | "neutral") {
857                *failure_counts.entry(conclusion.to_string()).or_insert(0) += 1;
858            }
859        }
860
861        assert_eq!(success_count, 2);
862
863        assert_eq!(failure_counts.get("failure"), Some(&2));
864        assert_eq!(failure_counts.get("startup_failure"), Some(&1));
865        assert_eq!(failure_counts.get("timed_out"), Some(&1));
866        assert_eq!(failure_counts.get("cancelled"), None);
867        assert_eq!(failure_counts.get("skipped"), None);
868        assert_eq!(failure_counts.get("neutral"), None);
869
870        // 验证 top_failures 排序(按数量降序)
871        let mut failures: Vec<_> = failure_counts.into_iter().collect();
872        failures.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
873        let top_failures: Vec<String> = failures.into_iter().map(|(k, _)| k).collect();
874
875        // "failure" 有 2 次排第一,其余各 1 次按字母序
876        assert_eq!(top_failures[0], "failure");
877        assert!(top_failures.contains(&"startup_failure".to_string()));
878        assert!(top_failures.contains(&"timed_out".to_string()));
879        assert_eq!(top_failures.len(), 3);
880    }
881
882    #[tokio::test]
883    async fn test_should_exclude_in_progress_runs_from_report_total_runs() {
884        // 4 runs in the report window: 2 success, 1 failure, 1 still in-progress
885        // (GitHub only sets `conclusion` once a run is `completed`, so an
886        // in-progress run serializes with `"conclusion": null`).
887        let now = chrono::Utc::now();
888        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
889
890        let json = format!(
891            r#"[
892                {{"databaseId": 1, "status": "completed", "conclusion": "success", "createdAt": "{}", "updatedAt": "{}"}},
893                {{"databaseId": 2, "status": "completed", "conclusion": "success", "createdAt": "{}", "updatedAt": "{}"}},
894                {{"databaseId": 3, "status": "completed", "conclusion": "failure", "createdAt": "{}", "updatedAt": "{}"}},
895                {{"databaseId": 4, "status": "in_progress", "conclusion": null, "createdAt": "{}", "updatedAt": "{}"}}
896            ]"#,
897            ts(600),
898            ts(300),
899            ts(500),
900            ts(200),
901            ts(400),
902            ts(100),
903            ts(60),
904            ts(30),
905        );
906
907        let runner = MockCommandRunner::success(&json);
908        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
909
910        let report = provider
911            .report("main", 7)
912            .await
913            .expect("report should succeed");
914
915        // Only 3 of the 4 runs have reached a terminal state (conclusion is
916        // Some); the in-progress run (conclusion: null) must be excluded
917        // from total_runs, not just from success/failure counts.
918        assert_eq!(report.total_runs, 3);
919        assert!((report.success_rate - (2.0 / 3.0)).abs() < f64::EPSILON);
920    }
921
922    #[tokio::test]
923    async fn test_should_exclude_runs_with_non_terminal_status_even_when_conclusion_is_present() {
924        // Reproduces issue #324: `gh run list` can report a non-null
925        // `conclusion` for a run whose `status` has not reached `"completed"`.
926        // Trusting `conclusion.is_some()` alone (the pre-fix behavior) would
927        // misclassify this still-running run as terminal, and even as a
928        // failure, inflating the denominator and corrupting `success_rate`.
929        let now = chrono::Utc::now();
930        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
931
932        let json = format!(
933            r#"[
934                {{"databaseId": 1, "status": "completed", "conclusion": "success", "createdAt": "{}", "updatedAt": "{}"}},
935                {{"databaseId": 2, "status": "in_progress", "conclusion": "failure", "createdAt": "{}", "updatedAt": "{}"}}
936            ]"#,
937            ts(600),
938            ts(300),
939            ts(200),
940            ts(100),
941        );
942
943        let runner = MockCommandRunner::success(&json);
944        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
945
946        let report = provider
947            .report("main", 7)
948            .await
949            .expect("report should succeed");
950
951        // Only the `completed` run counts; the `in_progress` run must be
952        // excluded from total_runs/success_rate despite carrying a non-null
953        // `conclusion`, and must not appear in top_failures either.
954        assert_eq!(report.total_runs, 1);
955        assert!((report.success_rate - 1.0).abs() < f64::EPSILON);
956        assert!(report.top_failures.is_empty());
957    }
958
959    #[tokio::test]
960    async fn test_should_not_attribute_failure_to_a_still_in_progress_job() {
961        use crate::runner::SequencedMockCommandRunner;
962
963        let now = chrono::Utc::now();
964        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
965
966        let run_list_json = format!(
967            r#"[{{"databaseId": 40, "status": "completed", "conclusion": "failure", "createdAt": "{}", "updatedAt": "{}"}}]"#,
968            ts(600),
969            ts(500),
970        );
971
972        // The run has concluded overall, but job-level data lags behind: one
973        // job already succeeded, the other is still `in_progress` yet
974        // (matching the real-world anomaly behind issue #324) already carries
975        // a non-null `conclusion` value. Attribution must not label the
976        // still-running job as the failure — it must fall back to the run's
977        // generic conclusion instead.
978        let jobs_json = r#"{
979            "jobs": [
980                {
981                    "databaseId": 1,
982                    "name": "MSRV",
983                    "status": "completed",
984                    "conclusion": "success",
985                    "startedAt": "2026-07-01T10:00:00Z",
986                    "completedAt": "2026-07-01T10:01:00Z",
987                    "url": "https://example.com/job/1"
988                },
989                {
990                    "databaseId": 2,
991                    "name": "Test (windows-latest)",
992                    "status": "in_progress",
993                    "conclusion": "failure",
994                    "startedAt": "2026-07-01T10:00:00Z",
995                    "url": "https://example.com/job/2"
996                }
997            ]
998        }"#;
999
1000        let runner =
1001            SequencedMockCommandRunner::from_results(&[(true, &run_list_json), (true, jobs_json)]);
1002        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1003
1004        let report = provider
1005            .report("main", 7)
1006            .await
1007            .expect("report should succeed");
1008
1009        assert_eq!(report.total_runs, 1);
1010        assert_eq!(report.top_failures, vec!["failure".to_string()]);
1011        assert!(!report.top_failures.contains(&"MSRV".to_string()));
1012        assert!(
1013            !report
1014                .top_failures
1015                .contains(&"Test (windows-latest)".to_string())
1016        );
1017    }
1018
1019    // --- Failure-path tests using an injected MockCommandRunner ---
1020
1021    #[tokio::test]
1022    async fn test_should_return_platform_error_when_gh_fails_for_status() {
1023        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1024        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1025
1026        let result = provider.status("main").await;
1027
1028        assert!(result.is_err());
1029        assert!(matches!(
1030            result.unwrap_err(),
1031            gitflow_core::CoreError::Cli(_)
1032        ));
1033    }
1034
1035    #[tokio::test]
1036    async fn test_should_return_serialization_error_on_invalid_json_for_status() {
1037        let runner = MockCommandRunner::success("invalid json");
1038        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1039
1040        let result = provider.status("main").await;
1041
1042        assert!(result.is_err());
1043        assert!(matches!(
1044            result.unwrap_err(),
1045            gitflow_core::CoreError::Serialization(_)
1046        ));
1047    }
1048
1049    #[tokio::test]
1050    async fn test_should_return_platform_error_when_gh_fails_for_logs() {
1051        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1052        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1053
1054        let result = provider.logs(42).await;
1055
1056        assert!(result.is_err());
1057        assert!(matches!(
1058            result.unwrap_err(),
1059            gitflow_core::CoreError::Cli(_)
1060        ));
1061    }
1062
1063    #[tokio::test]
1064    async fn test_should_return_platform_error_when_gh_fails_for_jobs() {
1065        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1066        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1067
1068        let result = provider.jobs(42).await;
1069
1070        assert!(result.is_err());
1071        assert!(matches!(
1072            result.unwrap_err(),
1073            gitflow_core::CoreError::Cli(_)
1074        ));
1075    }
1076
1077    #[tokio::test]
1078    async fn test_should_return_serialization_error_on_invalid_json_for_jobs() {
1079        let runner = MockCommandRunner::success("invalid json");
1080        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1081
1082        let result = provider.jobs(42).await;
1083
1084        assert!(result.is_err());
1085        assert!(matches!(
1086            result.unwrap_err(),
1087            gitflow_core::CoreError::Serialization(_)
1088        ));
1089    }
1090
1091    #[tokio::test]
1092    async fn test_should_return_platform_error_when_gh_fails_for_report() {
1093        let runner = MockCommandRunner::failure(r#"{"message": "Not found"}"#, 256);
1094        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1095
1096        let result = provider.report("main", 7).await;
1097
1098        assert!(result.is_err());
1099        assert!(matches!(
1100            result.unwrap_err(),
1101            gitflow_core::CoreError::Cli(_)
1102        ));
1103    }
1104
1105    #[tokio::test]
1106    async fn test_should_return_serialization_error_on_invalid_json_for_report() {
1107        let runner = MockCommandRunner::success("invalid json");
1108        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1109
1110        let result = provider.report("main", 7).await;
1111
1112        assert!(result.is_err());
1113        assert!(matches!(
1114            result.unwrap_err(),
1115            gitflow_core::CoreError::Serialization(_)
1116        ));
1117    }
1118
1119    // --- Job-level failure attribution (issue #289) ---
1120
1121    #[tokio::test]
1122    async fn test_should_attribute_top_failures_to_job_names_not_generic_conclusion() {
1123        use crate::runner::SequencedMockCommandRunner;
1124
1125        let now = chrono::Utc::now();
1126        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
1127
1128        // Two failed runs (databaseId 10 and 11) plus one success run.
1129        let run_list_json = format!(
1130            r#"[
1131                {{"databaseId": 10, "status": "completed", "conclusion": "failure", "createdAt": "{}", "updatedAt": "{}"}},
1132                {{"databaseId": 11, "status": "completed", "conclusion": "failure", "createdAt": "{}", "updatedAt": "{}"}},
1133                {{"databaseId": 12, "status": "completed", "conclusion": "success", "createdAt": "{}", "updatedAt": "{}"}}
1134            ]"#,
1135            ts(600),
1136            ts(500),
1137            ts(400),
1138            ts(300),
1139            ts(200),
1140            ts(100),
1141        );
1142
1143        // Both failed runs' `jobs` responses point at the same failing job name,
1144        // so it should be attributed by name rather than the generic "failure"
1145        // conclusion string.
1146        let jobs_json = r#"{
1147            "jobs": [
1148                {
1149                    "databaseId": 1,
1150                    "name": "Test (windows-latest)",
1151                    "status": "completed",
1152                    "conclusion": "success",
1153                    "startedAt": "2026-07-01T10:00:00Z",
1154                    "completedAt": "2026-07-01T10:01:00Z",
1155                    "url": "https://example.com/job/1"
1156                },
1157                {
1158                    "databaseId": 2,
1159                    "name": "Test (macos-latest)",
1160                    "status": "completed",
1161                    "conclusion": "failure",
1162                    "startedAt": "2026-07-01T10:00:00Z",
1163                    "completedAt": "2026-07-01T10:02:00Z",
1164                    "url": "https://example.com/job/2"
1165                }
1166            ]
1167        }"#;
1168
1169        let runner = SequencedMockCommandRunner::from_results(&[
1170            (true, &run_list_json),
1171            (true, jobs_json),
1172            (true, jobs_json),
1173        ]);
1174        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1175
1176        let report = provider
1177            .report("main", 7)
1178            .await
1179            .expect("report should succeed");
1180
1181        assert_eq!(report.total_runs, 3);
1182        assert_eq!(report.top_failures, vec!["Test (macos-latest)".to_string()]);
1183        assert!(!report.top_failures.contains(&"failure".to_string()));
1184    }
1185
1186    #[tokio::test]
1187    async fn test_should_fall_back_to_generic_conclusion_when_jobs_fetch_fails() {
1188        use crate::runner::SequencedMockCommandRunner;
1189
1190        let now = chrono::Utc::now();
1191        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
1192
1193        let run_list_json = format!(
1194            r#"[{{"databaseId": 20, "status": "completed", "conclusion": "failure", "createdAt": "{}", "updatedAt": "{}"}}]"#,
1195            ts(600),
1196            ts(500),
1197        );
1198
1199        // The `jobs` call for the failed run fails (e.g. permission error or
1200        // transient API failure); attribution must degrade gracefully to the
1201        // run's generic conclusion instead of panicking or dropping the run.
1202        let runner = SequencedMockCommandRunner::from_results(&[
1203            (true, &run_list_json),
1204            (false, r#"{"message": "Not found"}"#),
1205        ]);
1206        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1207
1208        let report = provider
1209            .report("main", 7)
1210            .await
1211            .expect("report should succeed despite jobs fetch failure");
1212
1213        assert_eq!(report.total_runs, 1);
1214        assert_eq!(report.top_failures, vec!["failure".to_string()]);
1215    }
1216
1217    #[tokio::test]
1218    async fn test_should_not_call_jobs_api_for_non_failure_runs() {
1219        use crate::runner::SequencedMockCommandRunner;
1220
1221        let now = chrono::Utc::now();
1222        let ts = |offset_secs: i64| (now - chrono::Duration::seconds(offset_secs)).to_rfc3339();
1223
1224        // success / cancelled / skipped / neutral runs must never trigger a
1225        // `jobs` API call — only one response (the run list) is queued, so
1226        // the test panics via SequencedMockCommandRunner if attribution tries
1227        // to fetch jobs for any of them.
1228        let run_list_json = format!(
1229            r#"[
1230                {{"databaseId": 30, "status": "completed", "conclusion": "success", "createdAt": "{}", "updatedAt": "{}"}},
1231                {{"databaseId": 31, "status": "completed", "conclusion": "cancelled", "createdAt": "{}", "updatedAt": "{}"}},
1232                {{"databaseId": 32, "status": "completed", "conclusion": "skipped", "createdAt": "{}", "updatedAt": "{}"}},
1233                {{"databaseId": 33, "status": "completed", "conclusion": "neutral", "createdAt": "{}", "updatedAt": "{}"}}
1234            ]"#,
1235            ts(800),
1236            ts(700),
1237            ts(600),
1238            ts(500),
1239            ts(400),
1240            ts(300),
1241            ts(200),
1242            ts(100),
1243        );
1244
1245        let runner = SequencedMockCommandRunner::from_results(&[(true, &run_list_json)]);
1246        let provider = GitHubPipelineProvider::with_runner("owner/repo", runner);
1247
1248        let report = provider
1249            .report("main", 7)
1250            .await
1251            .expect("report should succeed");
1252
1253        assert!(report.top_failures.is_empty());
1254    }
1255}