【问题标题】:How to merge in JGit?如何在 JGit 中合并?
【发布时间】:2012-08-21 17:52:49
【问题描述】:

如何在 JGit 中合并?

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

【问题讨论】:

    标签: java git jgit


    【解决方案1】:

    要合并,您可以在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 进行大量尝试

    【讨论】:

    • 我正在使用的类 org.eclipse.jgit.api.MergeCommand 没有标记公共方法 include(String)。有 3 个名为“include”的公共方法,但没有一个只接受一个字符串。
    【解决方案2】:

    您会在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);
    

    【讨论】:

    • 您提供给 Github 的相同链接指出合并是一个缺失的功能。那是怎么回事?
    • @rFactor 如果它只提供了 git merge 命令的包装器而不是完全原生的 java 实现,则可能是这种情况,但现在似乎不再如此了。
    • 你能确认吗?我不在开发机器上,所以目前我无法弄清楚太多,或者我会在某个时候检查它并在此处发布我的发现。
    • @rFactor 不,我没有直接测试过。我期待着阅读您的结论。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      传递一个 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

      【讨论】:

        猜你喜欢
        • 2015-06-30
        • 2016-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-26
        • 2013-12-28
        • 1970-01-01
        相关资源
        最近更新 更多