13

如何在 JGit 中合并?

假设我想masterfoo分支合并,我该怎么做?

4

4 回答 4

9

要合并,您可以MergeCommandCheckoutCommand. 给大家举个例子,因为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的大量尝试

于 2012-08-27T09:49:07.657 回答
4

您将在JGit 存储库中找到 Merge 的各种测试类,例如SimpleMergeTest

Merger ourMerger = MergeStrategy.OURS.newMerger(db);
boolean merge = ourMerger.merge(new ObjectId[] { db.resolve("a"), db.resolve("c") });
assertTrue(merge);
于 2012-08-27T09:44:18.617 回答
2

自 2010 年以来,JGit 拥有 git resolve 合并策略的完整 Java 实现。如果您需要示例,请查看相应的 JGit 测试用例并查看 EGit 如何使用 MergeCommand,请查看 class org.eclipse.egit.core.op.MergeOperation

于 2012-09-01T08:40:58.000 回答
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

于 2020-09-08T03:36:24.853 回答