GitPython tags sorted

Ilia Shakitko picture Ilia Shakitko · Jul 31, 2014 · Viewed 10.4k times · Source

I am trying to get the latest tag in the repo using GitPython lib. Usually I was doing it this way:

repo = Repo(project_root)
last_tag = str(repo.tags[-1])

But once version 1.10 was released, I am always getting 1.9 ;( I know it's related to output git tag -l being listing same order. So it will be 1.1, 1.10, 1.2, ..., 1.9

The question is how to get the latest tag using GitPython? (I am aware of git tag -l | sort -V and I know how to solve this not using the repo object. But maybe someone knows what am I missing in getting sorted tags list in this lib)

Custom sorting function is always an option too, but still, I wonder if there a way to do it with GitPython?

Answer

robotic_chaos picture robotic_chaos · Feb 14, 2017

The IterableList object returned by repo.tags in GitPython inherits from the list python class, which means that you can sort it the way you want. To get the latest tag created, you can simply do:

import git
repo = git.Repo('path/to/repo')
tags = sorted(repo.tags, key=lambda t: t.commit.committed_datetime)
latest_tag = tags[-1]