Push multiple files with GitHub tree API using Java

Viewed 196

I was trying to push multiple files at single instance, so by searching I got to know that we have to:

  • create the blobs for each of the files, then
  • add 'sha' of the blob to tree object, then
  • create a tree and finally
  • commit that tree.

I'm trying to replicate the same using java code but struggling a lot:
kindly help me out with this.

1 Answers

You can take inspiration from JGit mentioned in "Embedding Git in your Applications - JGit" of the Pro Git book.

If you want to use Git from within a Java program, there is a fully featured Git library called JGit.

JGit is a relatively full-featured implementation of Git written natively in Java, and is widely used in the Java community.
The JGit project is under the Eclipse umbrella, and its home can be found at https://www.eclipse.org/jgit/.

You can find a mirror of the repository in github.com/eclipse/jgit, where:

That is (extract):


try (ObjectInserter odi = repo.newObjectInserter()) {
    if (!only.isEmpty())
        index = createTemporaryIndex(headId, index, rw);

    // Write the index as tree to the object database. This may
    // fail for example when the index contains unmerged paths
    // (unresolved conflicts)
    ObjectId indexTreeId = index.writeTree(odi);

    if (insertChangeId)
        insertChangeId(indexTreeId);

    checkIfEmpty(rw, headId, indexTreeId);

    // Create a Commit object, populate it and write it
    CommitBuilder commit = new CommitBuilder();
    commit.setCommitter(committer);
    commit.setAuthor(author);
    commit.setMessage(message);
    commit.setParentIds(parents);
    commit.setTreeId(indexTreeId);

    if (signCommit.booleanValue()) {
        sign(commit);
    }
    ...
}
Related