JGit: How to get all commits of a branch? (Without changes to the working directory …)

前端 未结 6 1871
春和景丽
春和景丽 2020-12-15 23:43

how do I get all commits of a branch with JGit, without changing the working directory?

Unfortunately the JGit docs are not very good ...

In ruby with grit i

6条回答
  •  忘掉有多难
    2020-12-16 00:17

    With the code below you can get all commits of a branch or tag:

    Repository repository = new FileRepository("/path/to/repository/.git");
    String treeName = "refs/heads/master"; // tag or branch
    for (RevCommit commit : git.log().add(repository.resolve(treeName)).call()) {
        System.out.println(commit.getName());
    }
    

    The varialbe treeName will define the tag or branch. This treeName is the complete name of the branch or tag, for example refs/heads/master for the master branch or refs/tags/v1.0 for a tag called v1.0.

    Alternatively, you can use the gitective API. The following code does the same as the code above:

    Repository repository = new FileRepository("/path/to/repository/.git");
    
    AndCommitFilter filters = new AndCommitFilter();
    CommitListFilter revCommits = new CommitListFilter();
    filters.add(revCommits);
    
    CommitFinder finder = new CommitFinder(repository);
    finder.setFilter(filters);
    String treeName = "refs/heads/master"; // tag or branch
    finder.findFrom(treeName);
    
    for (RevCommit commit : revCommits) {
        System.out.println(commit.getName());
    }
    

    Some try/catch will be necessary, I hide them to make the code shorter. Good luck.

提交回复
热议问题