首页 > 解决方案 > 如何通过 Github API 创建树?

问题描述

我正在尝试以编程方式创建一个 git commit ,作为其中的一部分,我需要创建一个git tree

阅读文档后,我不确定在请求正文中发送什么。

我能够创建一个 blob 并获得一个 sha 响应,但是当我尝试调用创建树端点时,我得到以下信息:

{
    "url": "https://api.github.com/repos/<owner>/<repo>/git/trees/",
    "status": 404,
    "statusText": "Not Found",
    "body": {
        "message": "Not Found",
        "documentation_url": "https://docs.github.com/rest"
    }
}

我的代码如下所示,我在其中创建了 blob,然后尝试创建树:

const blobContent = fs.readFileSync(__dirname + '/../../../templates/main.yaml', { encoding: "utf8" })

const blob = await this.post<IBlobResponse>(`https://api.github.com/repos/${ownerName}/${repoName}/git/blobs`, {
  content: blobContent,
  encoding: "utf-8"
})

const tree = await this.post(`https://api.github.com/repos/${ownerName}/${repoName}/git/trees/`, {
  base_tree: masterRef.object.sha,
  tree: [
    {
      path: "main.yaml",
      mode: "100644",
      type: "tree",
      sha: blob.sha,
      content: blobContent
    }
  ]
})

创建树的有效载荷是否正确?

  1. 应该path是本地相对路径还是文件将存在于存储库中的路径?
  2. 我需要两者shacontent
  3. 内容是 yaml 文件这一事实是否存在问题?

标签: javascriptnode.jsgitgithubgithub-api

解决方案


原来我/在创建树时在 POST 端点中包含了尾随:

更改https://api.github.com/repos/${ownerName}/${repoName}/git/trees/https://api.github.com/repos/${ownerName}/${repoName}/git/trees并且有效。

非常简单的修复,但我想我会分享以防其他人有类似的问题


推荐阅读