简体   繁体   中英

How to commit files larger than 1mb to GitHub using the GitHub API and Octokit JavaScript

I need to update a file on GitHub from JavaScript running in a client browser application. The file may be larger than 1mb so I cannot use the octokit createFile() function which is limited to files less than 1mb.

I have an authenticated user through oauth, a file, and a repository that the file needs to end up in. Basically I have:

this.octokit = new Octokit();
this.octokit.authenticate({
    type: "oauth",
    token: github.access_token
})
this.file = "some text in a string thing";
this.octokit.repos.getContents({
    owner: this.currentUser,
    repo: this.currentRepoName,
    path: path
}).then(thisRepo => {

And I need to figure out how to get the contents of this.file into a file say project.stl in the root folder of that repo.

I have found this excellent blog post with a description of how the process works using the ruby version of the octokit library. I don't have any experience with ruby so understanding what is going on there will take me some time. This seems like it must be a common enough problem that there should be an example of a JavaScript solution out there. I would love any help that anyone can offer with uploading a file from JavaScript to GitHub, and I will post my solution if I can get to work to serve as an example.

Edit: I rewrote how it works like this, which I think is much better:

async createCommit (octokit, { owner, repo, base, changes }) { let response;

  if (!base) {
    response = await octokit.repos.get({ owner, repo })
    base = response.data.default_branch
  }

  response = await octokit.repos.listCommits({
    owner,
    repo,
    sha: base,
    per_page: 1
  })
  let latestCommitSha = response.data[0].sha
  const treeSha = response.data[0].commit.tree.sha

  response = await octokit.git.createTree({
    owner,
    repo,
    base_tree: treeSha,
    tree: Object.keys(changes.files).map(path => {
      return {
        path,
        mode: '100644',
        content: changes.files[path]
      }
    })
  })
  const newTreeSha = response.data.sha

  response = await octokit.git.createCommit({
    owner,
    repo,
    message: changes.commit,
    tree: newTreeSha,
    parents: [latestCommitSha]
  })
  latestCommitSha = response.data.sha

  await octokit.git.updateRef({
    owner,
    repo,
    sha: latestCommitSha,
    ref: `heads/master`,
    force: true
  })

  console.log("Project saved");

}

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