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

Get latest committed branch(name) details in 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();

谁能帮我解决这个问题?

恐怕您必须克隆整个存储库及其所有分支才能找到 最新 分支。

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

Git 的 'everything is local' 设计要求您在检查其内容之前克隆存储库。注意:使用 Git/JGit 的低级 commands/APIs 可以获取分支的头部提交进行检查,但这与其设计相矛盾。

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

下面的示例克隆一个存储库及其所有分支,然后列出所有分支以找出它们各自的头部提交的时间:

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() );
  }
}

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