【发布时间】:2012-08-21 17:52:49
【问题描述】:
如何在 JGit 中合并?
假设我想将master 与foo 分支合并,我该怎么做?
【问题讨论】:
如何在 JGit 中合并?
假设我想将master 与foo 分支合并,我该怎么做?
【问题讨论】:
要合并,您可以在CheckoutCommand 之后使用MergeCommand(在包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 进行大量尝试
【讨论】:
您会在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);
【讨论】:
git merge 命令的包装器而不是完全原生的 java 实现,则可能是这种情况,但现在似乎不再如此了。
自 2010 年以来,JGit 拥有 git resolve 合并策略的完整 Java 实现。如果您需要示例,请查看相应的 JGit 测试用例并查看 EGit 如何使用 MergeCommand,请查看 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
【讨论】: