Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge in JGit?

Tags:

java

git

jgit

How do I merge in JGit?

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

like image 524
Tower Avatar asked Aug 27 '12 08:08

Tower


2 Answers

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

like image 103
Vince Avatar answered Oct 19 '22 19:10

Vince


You will find in the JGit repository various test classes for Merge, including for instance the SimpleMergeTest

Merger ourMerger = MergeStrategy.OURS.newMerger(db);
boolean merge = ourMerger.merge(new ObjectId[] { db.resolve("a"), db.resolve("c") });
assertTrue(merge);
like image 4
VonC Avatar answered Oct 19 '22 20:10

VonC