javagroovyjgit

Get latest tag in branch with JGit


I am trying to get the JGit equivalent of the command

git describe --match "[0-9]*.[0-9]*.[0-9]*" --abbrev=0 --tags $(git rev-list --tags --branches=master --max-count=1)

I have tried getting all the tags in the project and then finding the greatest tag in the branch via the BranchListCommand, but that is to slow.

I am stuck and I cannot find anything that help via my searches.

Does anyone have any idea how to do the intended result?


Solution

  • You can fetch all tags and then walk the commits on the branch and check for each commit if there is a tag for this ref.

    i.e. fetch all tags via:

    git.tagList().call()
    

    then fetch all commits of the branch via:

    git.log().add(repository.resolve(BRANCH)).call()
    

    And then for each commit check if a tag exists at this ref.

    When run on a fairly large repository on a branch with more than 60k commits, walking all the commits this way is done in 1.2 seconds.

    Had 60843 commits overall on branch remotes/origin/master, iteration took 1200ms
    

    An even larger branch takes 8 seconds when walking 380k commits.

    Had 388613 commits overall on branch remotes/origin/master, iteration took 8261ms
    

    I have added a ready-to-run snippet to the jgit-cookboot, see ListTagsOnBranch.java