如何在 JGit 中合并?
假设我想master
与foo
分支合并,我该怎么做?
要合并,您可以MergeCommand
在CheckoutCommand
. 给大家举个例子,因为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的大量尝试
您将在JGit 存储库中找到 Merge 的各种测试类,例如SimpleMergeTest
Merger ourMerger = MergeStrategy.OURS.newMerger(db);
boolean merge = ourMerger.merge(new ObjectId[] { db.resolve("a"), db.resolve("c") });
assertTrue(merge);
自 2010 年以来,JGit 拥有 git resolve 合并策略的完整 Java 实现。如果您需要示例,请查看相应的 JGit 测试用例并查看 EGit 如何使用 MergeCommand,请查看 class org.eclipse.egit.core.op.MergeOperation
。
传递 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