4

I'm trying to write a method which takes files from a path and uploads them to a GitHub repo. The files have to remain intact and separate (can't zip them). This is what I've got so far:

addFiles(branch) {
        const filePath = this.filePath
        fs.readdirSync(filePath).forEach((file, index) => {
            if (file.match('.txt')) {
                const fileData = fs.readFileSync(path.resolve(filePath, file));
                this.octokit.repos.createOrUpdateFile({
                    owner,
                    repo,
                    path: `test/${file}`,
                    branch,
                    message: `Commit ${index}`,
                    content: encode(fileData)
                })
                .catch(err => console.log(err))
            }
        })
    }

This works to a point but it will only upload one file and then fails with the following error:

PUT /path/to/repo/contents/test/example.txt - 201 in 1224ms
PUT /path/to/repo/contents/test/example-2.txt - 409 in 1228ms
{ HttpError: is at 90db2dadca8d061e77ca06fe7196197ada6f6687 but expected b7933883cbed4ff91cc2762e24c183b797db0b74
    at response.text.then.message (/project/node_modules/@octokit/request/dist-node/index.js:66:23)

Even if this worked fine though, it still wouldn't be ideal as this project is likely to scale to the point where hundreds of files are being uploaded at once, is there a way to just upload a directory or upload multiple files per commit? Failing that, can anyone solve my error?

Alex Foxleigh
  • 1,784
  • 2
  • 21
  • 47

1 Answers1

3

I worked it out in the end. createFile isn't the right way to go, it should be done with createTree: https://octokit.github.io/rest.js/#octokit-routes-git-create-tree

It wasn't as simple as creating just the tree though, you also have to create a commit and then update the reference, I followed this GitHub issue for guidance:

https://github.com/octokit/rest.js/issues/1308

Alex Foxleigh
  • 1,784
  • 2
  • 21
  • 47
  • 3
    Could you provide sample code which you used to push multiple files and folders – mnvbrtn Jun 08 '20 at 20:50
  • I backup @mnvbrtn. Link is dead, some more elaboration would be highly appreciated since I'm struggling with it.. – elect May 08 '21 at 20:24
  • they updated the repo name: https://github.com/octokit/octokit.js/issues/1308 the main docu can be found here: https://octokit.github.io/octokit.js I did not find the deep link or search working for me though – Julius Breckel Aug 12 '21 at 07:24