简体   繁体   English

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

[英]Get the latest commit in a repository with JGit

I want to get the last commit metadata (the youngest one by date) in a repository using JGit.我想使用 JGit 在存储库中获取最后一个提交元数据(按日​​期计算最年轻的元数据)。

I know that I can get the commit metadata using我知道我可以使用

try (RevWalk walk = new RevWalk(repository)) {
    RevCommit commit = walk.parseCommit(repository.resolve(commitHash));
}

But how to get the latest commit hash?但是如何获得最新的提交哈希?

Is there any other way to get the youngest by date RevCommit in a repository directly?有没有其他方法可以直接在存储库中获得最年轻的按日期RevCommit

You could make use of git log and set it to only return the top most commit:您可以使用git log并将其设置为仅返回最高的提交:

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

String latestCommitHash = latestCommit.getName();

Compare by dates of last commits in all branches.按所有分支中上次提交的日期进行比较。 ListMode.ALL can be changed to ListMode.REMOTE to compare only remote branches. ListMode.ALL可以更改为ListMode.REMOTE以仅比较远程分支。 Or... the fluent setter .setListMode(whatever) can be omitted to read from the local repository.或者...流畅的 setter .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 (...)

To find the newest commit within a repository, configure a RevWalk to start from all known refs and sort it descending by commit date.要在存储库中查找最新提交, RevWalk配置为从所有已知引用开始并按提交日期降序排序。 For example:例如:

Repository repo = ...
try( RevWalk revWalk = new RevWalk( repo ) ) {
  revWalk.sort( RevSort.COMMIT_TIME_DESC );
  Map<String, Ref> allRefs = repo.getRefDatabase().getRefs( RefDatabase.ALL );
  for( Ref ref : allRefs.values() ) {
    RevCommit commit = revWalk.parseCommit( ref.getLeaf().getObjectId() );
    revWalk.markStart( commit );
  }
  RevCommit newestCommit = revWalk.next();
}

Depending on your use case, you may also want to mark start points from refs from repo.getRefDatabase().getAdditionalRefs() which includes refs like FETCH_RESULT , ORIG_HEAD , etc. If you find that there are still untracked refs, use repo.getRefDatabase().getRef() .根据您的用例,您可能还想从repo.getRefDatabase().getAdditionalRefs() refs 中标记起点,其中包括FETCH_RESULTORIG_HEAD等 refs。 如果您发现仍有未跟踪的 refs,请使用repo.getRefDatabase().getRef()

Below you can find a Java 8 Stream API solution:您可以在下面找到Java 8 Stream API解决方案:

final List<Ref> branches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
final RevWalk revWalk = new RevWalk(git.getRepository());

branches.stream()
        .map(branch -> {
            try {
                return revWalk.parseCommit(branch.getObjectId());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        })
        .sorted(Comparator.comparing((RevCommit commit) -> commit.getAuthorIdent().getWhen()).reversed())
        .findFirst()
        .ifPresent(commit -> {
            System.out.printf("%s: %s (%s)%n", commit.getAuthorIdent().getWhen(), commit.getShortMessage(), commit.getAuthorIdent().getName());
        });

It iterates over all branches and picks recent commits in those branches, then it sorts list of commits by date in descendant order and picks the first one.它遍历所有分支并选择这些分支中最近的提交,然后按日期按降序对提交列表进行排序并选择第一个。 If it exists it prints to console output something like this:如果它存在,它会打印到控制台输出,如下所示:

Wed Aug 30 09:49:42 CEST 2017: test file added (Szymon Stepniak)

Of course the behavior on last commit existence is exemplary and it can be easily replaced with any additional business logic.当然,上次提交时的行为是示范性的,可以很容易地替换为任何其他业务逻辑。 I hope it helps.我希望它有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM