【问题标题】:How to find a Github file 's SHA blob如何查找 Github 文件的 SHA blob
【发布时间】:2021-09-10 16:37:52
【问题描述】:

我正在使用此 API 更新我的 repo 中的文件,它要求我为要更新的文件拥有一个有效的 SHA blob:

http://developer.github.com/v3/repos/contents/

如何找到特定文件的 SHA blob?假设在我的 testrepo 中的测试帐户中,test.txt 文件的 SHA blob 是什么?

https://github.com/testacc01/testrepo01

非常感谢!

【问题讨论】:

    标签: git github sha github-api


    【解决方案1】:

    更新文件的文档指定您需要为要替换的文件提供 SHA。最简单的方法也是查询 github。例如:

    > curl https://api.github.com/repos/testacc01/testrepo01/contents/test.txt
    {
      "name": "test.txt",
      "path": "test.txt",
      "sha": "4f8a0fd8ab3537b85a64dcffa1487f4196164d78",
      "size": 13,
     …
    

    因此,您可以在 JSON 响应的“sha”字段中看到 SHA 是什么。当您提出用新版本更新文件的请求时使用它。成功更新文件后,该文件将具有一个新的 SHA,您需要先请求该新 SHA,然后才能再次对其进行更新。 (除非,我猜,你的下一次更新会在不同的分支上进行。)

    【讨论】:

    • 谢谢,对我有用,我忘记了文件更新后SHA会自动更新。
    • 我无法在 GitHub 的 v3 API 文档中找到他们用来生成这些的特定 SHA 哈希函数 - SHA1、SHA256 等(这样我就可以自己验证文件内容)。我相信 git 使用 SHA-1 进行提交哈希,但我不清楚 GitHub 使用哪个哈希函数来哈希文件内容。我已经向他们开了一张票,要求提供这些信息。
    • @TaylorEdmiston 您好,您收到 github 的任何回复了吗?
    • 嗯,我不确定。我搜索了我的电子邮件,但没有找到来自 GitHub 的回复。
    • 关于使用的 SHA 哈希函数:developer.github.com/v3/git/blobs/#get-a-blob 声明 [t]he file's SHA-1 hash is computed and stored in the blob object。所以它是 SHA-1。
    【解决方案2】:

    如果您使用GraphQL API v4,您可以使用以下内容来查找特定文件的sha:

    {
      repository(owner: "testacc01", name: "testrepo01") {
        object(expression: "master:test.txt") {
          ... on Blob {
            oid
          }
        }
      }
    }
    

    Try it in the explorer

    【讨论】:

      【解决方案3】:

      如果您不想点击 api,您可以自己生成 SHA。 Git 通过连接 blob {content.length} {null byte} 形式的标头和文件内容来生成 SHA。例如:

      content = "what is up, doc?"
      header = "blob #{content.bytesize}\0"
      combined = header + content # will be "blob 16\u0000what is up, doc?"
      sha1 = Digest::SHA1.hexdigest(combined)
      

      来源:https://git-scm.com/book/en/v2/Git-Internals-Git-Objects

      【讨论】:

        【解决方案4】:

        使用Octokit Rest API

        import { Octokit } from "@octokit/rest";
        
        const { data: { sha } } = await octokit.request('GET /repos/{owner}/{repo}/contents/{file_path}', {
              owner: "owner-name",
              repo: "repo-name",
              file_path: "file-path-with-extension-from-root"
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-10
          • 1970-01-01
          • 2021-05-18
          • 1970-01-01
          • 2020-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多