如何使用嵌套目录创建 git 树?

How to create git tree with nested directories?

通过 Github 的 API,我想提交一个嵌套了 2 个文件的文件,即 .github/workflows/main.yaml.

当我执行以下操作时,我收到 404 not found 错误响应

const createTree = ({
  ownerName,
  repoName,
  masterSha,
  sha
}) => {
  return axios.post(`https://api.github.com/repos/${ownerName}/${repoName}/git/trees`, {
    base_tree: masterSha,
    tree: [
      {
        path: ".github/workflows/main.yaml",
        mode: "100644", 
        type: "blob",
        sha
      }
    ]
  })  
})

如果我将路径设置为 workflows/main.yaml,它似乎工作正常。

如何在子目录中创建树?

原来你需要先创建文件树,然后从文件树sha创建目录树。

这是对我有用的代码

const createTree = ({
  ownerName,
  repoName,
  masterSha,
  sha
}) => {
  // Create main.yaml file in workflows/main.yaml
  const { tree } = await axios.post(`https://api.github.com/repos/${ownerName}/${repoName}/git/trees`, {
    base_tree: masterSha,
    tree: [
      {
        path: "workflows/main.yaml",
        mode: "100644", 
        type: "blob",
        sha
      }
    ]
  })  

  const workflowTree = tree.find(t => t.path === "workflows");

  // Create .github directory from the previous tree sha
  await axios.post(`https://api.github.com/repos/${ownerName}/${repoName}/git/trees`, {
    base_tree: masterSha,
    tree: [
      {
        path: ".github/workflows",
        mode: workflowTree.mode, // "040000"
        type: workflowTree.type, // "tree"
        sha: workflowTree.sha 
      }
    ]
  })
})