You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PyGitHub获取GitHub仓库的最新构建状态?

解决PyGitHub获取仓库分支构建状态的问题

核心问题分析

你遇到的两个问题本质是对PyGitHub中的对象类型和GitHub API的两种状态机制理解不到位:

  1. GitCommit对象确实没有get_check_runs()方法——你需要用绑定仓库上下文的Commit对象。
  2. get_statuses()返回空是因为多数现代CI工具用Checks API而非旧的Status API报告状态。

完整解决方案代码

from github import Github
from github.GithubException import UnknownObjectException

# 初始化GitHub认证(替换成你的个人访问令牌)
g = Github("your-personal-access-token")

# 读取仓库列表文件
with open("repo_list.txt", "r") as f:
    repo_names = [line.strip() for line in f if line.strip()]

for repo_name in repo_names:
    try:
        repo = g.get_repo(repo_name)
        print(f"\n=== 仓库: {repo_name} ===")
        
        # 优先选择dev分支,不存在则降级到master
        target_branch = None
        try:
            target_branch = repo.get_branch("dev")
            print("检测到dev分支,使用该分支")
        except UnknownObjectException:
            try:
                target_branch = repo.get_branch("master")
                print("dev分支不存在,使用master分支")
            except UnknownObjectException:
                print("dev和master分支均不存在,跳过该仓库")
                continue
        
        # 关键:从GitCommit转为Commit对象(绑定仓库上下文)
        commit_sha = target_branch.commit.sha
        repo_commit = repo.get_commit(commit_sha)
        
        # 优先获取Check Runs(GitHub Actions等现代CI用这个)
        check_runs = repo_commit.get_check_runs()
        if check_runs.totalCount > 0:
            print("最新构建Check Runs状态:")
            for run in check_runs:
                print(f"- 任务名: {run.name} | 状态: {run.status} | 结果: {run.conclusion}")
        else:
            # 降级获取旧版Statuses(适用于Travis CI旧版等工具)
            statuses = repo_commit.get_statuses()
            if statuses.totalCount > 0:
                print("最新构建Statuses状态:")
                for status in statuses:
                    print(f"- 上下文: {status.context} | 状态: {status.state}")
            else:
                print("未找到任何构建状态记录")
                
    except UnknownObjectException:
        print(f"仓库 {repo_name} 不存在或无权限访问,跳过")
    except Exception as e:
        print(f"处理仓库 {repo_name} 时出错: {str(e)}")

关键细节说明

  1. 区分GitCommit和Commit对象

    • repo.get_branch("dev").commit返回的是GitCommit:仅包含提交的基础信息(SHA、作者、提交信息),没有仓库关联的方法。
    • repo.get_commit(commit_sha)返回的是Commit:绑定了当前仓库,因此拥有get_check_runs()、get_statuses()等API方法。
  2. 两种状态机制的区别

    • Check Runs:GitHub官方推荐的现代机制,GitHub Actions、GitLab CI(接入GitHub)、CircleCI等工具默认使用,包含更丰富的构建元数据。
    • Statuses:旧版API,仅支持简单的状态标记(成功/失败/等待),现在很少有工具主动使用。
  3. 权限要求

    • 确保你的GitHub个人访问令牌(PAT)拥有repo权限(私有仓库)或public_repo权限(公开仓库),否则无法读取状态信息。

内容的提问来源于stack exchange,提问作者DevopitionBro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 14:00:21