Last active
November 7, 2019 21:49
-
-
Save siordache/63b19f515e4db6944e2411265f89e92f to your computer and use it in GitHub Desktop.
Committing multiple files with github-api (PR #361 - https://github.com/kohsuke/github-api/pull/361)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.io.IOUtils; | |
import org.kohsuke.github.*; | |
import java.net.URL; | |
public class MultiCommit { | |
public static void main(String[] args) throws Exception { | |
String userId = "your-user-id"; | |
String password = "your-password"; | |
String repoName = "your-repo-name"; | |
GitHub gitHub = GitHub.connectUsingPassword(userId, password); | |
GHRepository repo = gitHub.getRepository(repoName); | |
// get the reference to the master branch | |
GHRef masterRef = repo.getRef("heads/master"); | |
// get the SHA of the latest commit on the master branch | |
String masterTreeSha = repo | |
.getTreeRecursive("master", 1) | |
.getSha(); | |
// get an image as byte[] | |
byte[] avatarContent = IOUtils.toByteArray( | |
new URL("https://avatars1.githubusercontent.com/u/50003").openStream()); | |
// create a blob containing the image and get its SHA | |
String avatarSha = new GHBlobBuilder(repo) | |
.binaryContent(avatarContent) | |
.create() | |
.getSha(); | |
// create a tree with four entries (three text files and the previously created blob) and get its SHA | |
String treeSha = new GHTreeBuilder(repo) | |
.baseTree(masterTreeSha) | |
.textEntry("README", "This is public domain software.", false) | |
.textEntry("doc/userGuide.txt", "Press F1 for help.", false) | |
.textEntry("bin/start.sh", "#/bin/sh\necho 'Hello!'", true) // executable | |
.shaEntry("avatar.png", avatarSha, false) | |
.create() | |
.getSha(); | |
// create a commit for the new tree and get its SHA | |
String commitSha = new GHCommitBuilder(repo) | |
.message("add some important files") | |
.tree(treeSha) | |
.parent(masterRef.getObject().getSha()) | |
.create() | |
.getSHA1(); | |
// Update the master reference to refer to the new commit | |
masterRef.updateTo(commitSha); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment