简体   繁体   中英

Use Octokit or the GitHub Rest API to upload multiple files

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM