使用 JGit 获取存储库中的最新提交

Mas*_*ind 9 java git jgit

我想使用 JGit 在存储库中获取最后一个提交元数据(按日​​期计算的最年轻的元数据)。

我知道我可以使用

try (RevWalk walk = new RevWalk(repository)) {
    RevCommit commit = walk.parseCommit(repository.resolve(commitHash));
}
Run Code Online (Sandbox Code Playgroud)

但是如何获得最新的提交哈希?

有没有其他方法可以RevCommit直接在存储库中获得最年轻的日期?

小智 7

您可以使用git log并将其设置为仅返回最高的提交:

RevCommit latestCommit = new Git(repository).log().setMaxCount(1).call().iterator().next();

String latestCommitHash = latestCommit.getName();
Run Code Online (Sandbox Code Playgroud)


Grz*_*icz 5

按所有分支中最后提交的日期进行比较。 ListMode.ALL可以更改为ListMode.REMOTE仅比较远程分支。或者...可以省略流畅的设置器.setListMode(whatever)来从本地存储库读取。

RevCommit youngestCommit = null;
Git git = new Git(repository);
List<Ref> branches = git.branchList().setListMode(ListMode.ALL).call();
try {
    RevWalk walk = new RevWalk(git.getRepository());
    for(Ref branch : branches) {
        RevCommit commit = walk.parseCommit(branch.getObjectId());
        if(youngestCommit == null || commit.getAuthorIdent().getWhen().compareTo(
           youngestCommit.getAuthorIdent().getWhen()) > 0)
           youngestCommit = commit;
    }
} catch (...)
Run Code Online (Sandbox Code Playgroud)