How to create git tree with nested directories?

Viewed 209

Via Github's API, I want to commit a file that is nested 2 files deep i.e. .github/workflows/main.yaml.

When I do the following, I get a 404 not found error response

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
      }
    ]
  })  
})

If I set path to workflows/main.yaml it seems to work fine.

How do I create a tree within subdirectories?

1 Answers

Turns out you need to create the file tree first and then create the directory tree from the file tree sha.

This is the code that worked for me

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 
      }
    ]
  })
})
Related