Jgit:如何在合并提交中显示更改的文件

时间:2015-12-01 16:47:17

标签: git jgit git-show

我想使用jgit来获取合并提交中已更改的文件列表,类似于git中的git show --name-only

有很多关于如何使用父父进行正常提交更改文件的示例,但它们不适用于具有多个父项的合并提交。

1 个答案:

答案 0 :(得分:1)

根据我的理解,你只需要将合并提交的父母的差异与他们各自的父母相结合。

下面的代码片段创建了两个提交,每个文件都添加了一个(main.txtside.txt),然后合并提交将如上所述进行区分

public void diffMerge() throws Exception {
  RevCommit baseCommit = commitChanges();
  Ref sideBranch = git.branchCreate().setName( "side" ).call();
  File mainFile = new File( git.getRepository().getWorkTree(), "main.txt" );
  mainFile.createNewFile();
  RevCommit mainCommit = commitChanges();
  git.checkout().setName( sideBranch.getName() ).call();
  File sideFile = new File( git.getRepository().getWorkTree(), "side.txt" );
  sideFile.createNewFile();
  RevCommit sideCommit = commitChanges();
  git.checkout().setName( "refs/heads/master" ).call();
  ObjectId mergeCommitId = git.merge().include( sideCommit ).call().getNewHead();

  DiffFormatter diffFormatter = new DiffFormatter( NullOutputStream.INSTANCE );
  diffFormatter.setRepository( git.getRepository() );
  RevCommit mergeCommit = parseCommit( mergeCommitId );
  List<DiffEntry> mainEntries = diffFormatter.scan( parseCommit( mergeCommit.getParent( 0 ) ).getParent( 0 ), mergeCommit.getParent( 0 ) );
  List<DiffEntry> sideEntries = diffFormatter.scan( parseCommit( mergeCommit.getParent( 1 ) ).getParent( 0 ), mergeCommit.getParent( 1 ) );
  diffFormatter.close();

  mainEntries.forEach( entry -> System.out.println( entry.getNewPath() ) );
  sideEntries.forEach( entry -> System.out.println( entry.getNewPath() ) );
}

private RevCommit parseCommit( ObjectId commitId ) throws IOException {
  try( RevWalk revWalk = new RevWalk( git.getRepository() ) ) {
    return revWalk.parseCommit( commitId );
  }
}

private RevCommit commitChanges() throws GitAPIException {
  git.add().addFilepattern( "." ).call();
  return git.commit().setMessage( "commit message" ).call();
}

请注意,代码盲目地假定合并提交的父级不是自己合并的。