在JGit中获取最新提交的分支(名称)详细信息

时间:2016-11-10 11:40:10

标签: git jgit

如何确定Git存储库中最新提交的分支? 我想克隆最近更新的分支而不是克隆所有分支,尽管它是否合并到master(默认分支)。

LsRemoteCommand remoteCommand = Git.lsRemoteRepository();
Collection <Ref> refs = remoteCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password))
                    .setHeads(true)
                    .setRemote(uri)
                    .call();

for (Ref ref : refs) {
    System.out.println("Ref: " + ref.getName());
}


//cloning the repo
CloneCommand cloneCommand = Git.cloneRepository();
result = cloneCommand.setURI(uri.trim())
 .setDirectory(localPath).setBranchesToClone(branchList)
.setBranch("refs/heads/branchName")
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName,password)).call();

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

我担心你必须用它的所有分支克隆整个存储库才能找到最新的分支。

LsRemoteCommand列出了分支名称和它们指向的提交的id,但不列出提交的时间戳。

Git的'一切都是本地'设计要求您在检查其内容之前克隆存储库。注意:使用Git / JGit的低级命令/ API可以获取分支的头部提交以供检查,但这与其设计相矛盾。

一旦克隆了存储库(没有初始结账),您可以遍历所有分支,加载相应的头部提交并查看哪个是最新的。

下面的示例使用其所有分支克隆存储库,然后列出所有分支,以找出他们各自的头部提交的位置:

Git git = Git.cloneRepository().setURI( ... ).setNoCheckout( true ).setCloneAllBranches( true ).call();
List<Ref> branches = git.branchList().setListMode( ListMode.REMOTE ).call();
try( RevWalk walk = new RevWalk( git.getRepository() ) ) {
  for( Ref branch : branches ) {
    RevCommit commit = walk.parseCommit( branch.getObjectId() );
    System.out.println( "Time committed: " + commit.getCommitterIdent().getWhen() );
    System.out.println( "Time authored: " + commit.getAuthorIdent().getWhen() );
  }
}

现在你知道了最新的分支,你可以查看这个分支。