如何从GitHub API获取最后一次提交

Rog*_*nco 8 git github github-api

我想知道哪种是使用GitHub API(Rest API v3)从git存储库获取最新提交信息的最佳方法.

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

选项2:GET /repos/:owner/:repo/git/commits/5a2ff 或者调用,一个通过从master获取HEAD ref来获取sha,然后使用返回的sha获取提交信息.

谢谢您的帮助

Von*_*onC 22

这取决于你对"最后"的定义.

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

  • 但是您也可以考虑最后一次推送事件:这将代表最后一次和最近的提交(在任何分支上),由用户推送到此repo.


pyt*_*ice 10

从用户获取最新提交的另一种方法是使用以下端点。需要澄清的是,这只会显示public事件,因此不会显示推送到私有存储库的情况。

https://api.github.com/users/<username>/events/public
Run Code Online (Sandbox Code Playgroud)

  • 哇,您甚至不需要进行身份验证。感谢您分享这个! (3认同)

Ant*_*ton 9

如果您只需要某个分支的最新提交的 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}"
Run Code Online (Sandbox Code Playgroud)

  • “Accept”标头对于获取 SHA 非常重要,请参阅 https://docs.github.com/en/rest/reference/repos#get-a-commit (4认同)

Ber*_*tel 7

您还可以使用Github GraphQL v4获取默认分支的最后一次提交:

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

或者对于所有分支机构:

{
  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
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在资源管理器中尝试一下