首页 > 解决方案 > 如何从 Github API 获取最新版本的提交哈希

问题描述

我想在 repo 中从 Github 获取最新标记版本的 git commit 哈希。是否可以通过 GitHub API 获得它?

这将很有帮助,如果不仅适用于下面的用例,我需要使用 Git Commit 哈希(而不是标签)来下载 vscode 服务器代码。

这是我尝试获取 microsoft/vscode 最新提交哈希的代码: https://github.com/b01/faith-works-t-shirts/blob/main/.docker/download-vs-code-server。嘘

标签: github-api

解决方案


使用 Github Rest v3

您需要使用get latest release API获取标签:

GET /repos/{owner}/{repo}/releases/latest

示例:https ://api.github.com/repos/mui-org/material-ui/releases/latest

然后使用 get tag API 获取标签 sha:

GET /repos/{owner}/{repo}/git/ref/tags/{tag_name}

示例:https ://api.github.com/repos/mui-org/material-ui/git/ref/tags/v4.11.3

如果typecommit,则标记 sha 指向一个提交,否则您需要调用:

GET /repos/{owner}/{repo}/git/tags/{tag_sha}

获取object.sha https://api.github.com/repos/$repo/git/tags/$tag_sha 示例:

repo=microsoft/vscode

tag=$(curl -s "https://api.github.com/repos/$repo/releases/latest" | jq -r '.tag_name')
read type tag_sha < <(echo $(curl -s "https://api.github.com/repos/$repo/git/ref/tags/$tag" | 
     jq -r '.object.type,.object.sha'))

if [ $type == "commit" ]; then
    echo "commit sha: $tag_sha"
else
    sha=$(curl -s "https://api.github.com/repos/$repo/git/tags/$tag_sha" | jq '.object.sha')
    echo "commit sha: $sha"
fi

GraphQL v4

使用Graphql API v4,它更简单:

{
  repository(owner: "microsoft", name: "vscode") {
    latestRelease{
      tagCommit {
        oid
      }
    }
  }
}

使用的示例:

repo=material-ui
owner=mui-org
token=YOUR_TOKEN

curl -s -H "Authorization: token $token" \
     -H  "Content-Type:application/json" \
     -d '{ 
          "query": "{repository(owner:\"'"$owner"'\", name:\"'"$repo"'\"){latestRelease{tagCommit {oid}}}}"
      }' https://api.github.com/graphql | jq -r '.data.repository.latestRelease.tagCommit.oid'

推荐阅读