如何找到Github文件的SHA blob

92dk7w1h  于 2023-06-04  发布在  Git
关注(0)|答案(4)|浏览(437)

我正在使用此API更新我的存储库上的文件,它要求我为要更新的文件提供有效的SHA blob:
http://developer.github.com/v3/repos/contents/
如何找到特定文件的SHA blob?假设在我的testrepo在这里的测试帐户,什么是SHA的blob的test.txt文件?
https://github.com/testacc01/testrepo01
谢谢你!

57hvy0tb

57hvy0tb1#

用于更新文件的文档指定您需要为要替换的文件提供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才能再次更新它。(除非,我猜,你的下一次更新是在另一个分支上。

nue99wik

nue99wik2#

如果你不想调用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

nlejzf6q

nlejzf6q3#

如果你使用GraphQL API v4,你可以使用下面的代码来查找特定文件的sha:

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

Try it in the explorer

eanckbw9

eanckbw94#

使用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"
});

相关问题