如何从GitHub API获取最新提交记录

30

使用GitHub API(Rest API v3)从git存储库获取最新提交信息的最佳方法是什么。

选项1:GET /repos/:owner/:repo/commits/master
我可以假设响应中的“commit”对象是来自主分支的最新提交吗?

选项2:GET /repos/:owner/:repo/git/commits/5a2ff
或者进行两次调用,一次通过获取主分支的HEAD引用来获取SHA,然后使用返回的SHA获取提交信息。


我正在使用 Rest API v3。 - Rogelio Blanco
为什么“/repos/:owner/:repo/commits/:branch”不是最新的提交? - OneCricketeer
4个回答

54

这取决于你对 "last" 的定义。

  • 对于给定的分支(如 master),GET /repos/:owner/:repo/commits/master 确实是最后(最近)的提交。

  • 但你也可以考虑最后一次 push 事件:它代表了用户推送到该仓库的任何分支上的最新的和最近的提交。


如何在 API 中使用 GET 方法?它如何包含在 Curl 中? - John Wooten
但我需要传递一个所有者。我怎么知道那个开发者是最后一个将某些东西推送到存储库的? - Dani
1
@Dani 为什么在你的情况下传递存储库所有者是个问题? - VonC
啊,抱歉,我以为那是提交者。那样就可以了。 - Dani
1
@SridharSarnobat 没错,但不要使用您的GHE帐户密码,而是使用令牌:https://github.blog/changelog/2020-11-13-token-authentication-required-for-api-operations/(2020年11月) - VonC
显示剩余2条评论

10
另一种获取用户最新提交的方法是使用以下端点。需要澄清的是,这只会显示公共事件,因此不会显示对私有存储库的推送。
https://api.github.com/users/<username>/events/public

3
哇,你甚至不需要进行身份验证。谢谢分享这个! - Joe Previte

8
如果您只需要某个分支最新提交的SHA1哈希值,下面是一个curl请求可以实现:
curl -s -H "Authorization: token {your_github_access_token}" \
-H "Accept: application/vnd.github.VERSION.sha" \ 
"https://api.github.com/repos/{owner}/{repository_name}/commits/{branch_name}"

4
“Accept”头很重要,只需获取SHA,请参见https://docs.github.com/en/rest/reference/repos#get-a-commit - George Birbilis

7

您也可以使用Github GraphQL v4来获取默认分支的最新提交:

{
  repository(name: "linux", owner: "torvalds") {
    defaultBranchRef {
      target {
        ... on Commit {
          history(first: 1) {
            nodes {
              message
              committedDate
              authoredDate
              oid
              author {
                email
                name
              }
            }
          }
        }
      }
    }
  }
}

或者对于所有分支:

{
  repository(name: "material-ui", owner: "mui-org") {
    refs(first: 100, refPrefix: "refs/heads/") {
      edges {
        node {
          name
          target {
            ... on Commit {
              history(first: 1) {
                nodes {
                  message
                  committedDate
                  authoredDate
                  oid
                  author {
                    email
                    name
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

在浏览器中尝试


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接