How to merge in JGit?

Tower picture Tower · Aug 27, 2012 · Viewed 8.4k times · Source

How do I merge in JGit?

Let's say I want to merge master with foo branch, how do I do this?

Answer

Vince picture Vince · Aug 27, 2012

To merge, you can use the MergeCommand (in package org.eclipse.jgit.api), after a CheckoutCommand. To provide you with an example, because indeed Jgit lacks examples:

Git git = ... // you get it through a CloneCommand, InitCommand 
              // or through the file system

CheckoutCommand coCmd = git.checkout(); 
// Commands are part of the api module, which include git-like calls
coCmd.setName("master");
coCmd.setCreateBranch(false); // probably not needed, just to make sure
coCmd.call(); // switch to "master" branch

MergeCommand mgCmd = git.merge();
mgCmd.include("foo"); // "foo" is considered as a Ref to a branch
MergeResult res = mgCmd.call(); // actually do the merge

if (res.getMergeStatus().equals(MergeResult.MergeStatus.CONFLICTING)){
   System.out.println(res.getConflicts().toString());
   // inform the user he has to handle the conflicts
}

I did not try the code so it might not be perfect, but it's just to provide a start. And I didn't include the imports. Developing with JGit implies a lot of tries based on the javadoc