如何在JGit中合并?
假设我想将master
与foo
分支合并,我该怎么做?
答案 0 :(得分:7)
要合并,您可以在MergeCommand
之后使用CheckoutCommand
(在包org.eclipse.jgit.api中)。为了给你一个例子,因为Jgit确实没有例子:
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
}
我没有尝试过代码,所以它可能不完美,但它只是提供一个开始。我没有包括进口。使用JGit进行开发意味着基于javadoc
的大量尝试答案 1 :(得分:4)
您会在JGit repository各种test classes for Merge中找到,例如SimpleMergeTest
Merger ourMerger = MergeStrategy.OURS.newMerger(db);
boolean merge = ourMerger.merge(new ObjectId[] { db.resolve("a"), db.resolve("c") });
assertTrue(merge);
答案 2 :(得分:2)
自2010年以来,JGit对git resolve merge策略进行了全面的Java实现。如果需要示例,请查看相应的JGit测试用例,看看EGit如何使用MergeCommand,查看类org.eclipse.egit.core.op.MergeOperation
。
答案 3 :(得分:0)
例如,传递ObjectId对我来说很方便
void merge(String uri,File file){
try(Git git = Git.cloneRepository()
.setURI(uri)
.setBranch("master")
.setDirectory(file)
.call()){
ObjectId objectId = git.getRepository().resolve("origin/develop");
MergeResult mergeResult = git.merge().include(objectId).call();
log.debug(mergeResult.getMergeStatus());
} catch (GitAPIException | IOException e) {
log.error("error",e);
}
}
此外,您可以在此处找到更多示例:https://github.com/centic9/jgit-cookbook