Search code examples
pythongitgitpython

GitPython: Get current tag (detached head)


I use the library gitpython

If the local git is on a checked out tag, I want to get the name of the tag.

repo=git.Repo(repo_dir)
repo.tag # --> tags. But which is the current?

On the command line, the git tool knows it. Example

user@host> git status
HEAD detached at release/1.2.3

I want to get the string "release/1.2.3" via gitpython.


Solution

  • You can iterate through tags and compare each tag commit with current head commit:

    next((tag for tag in repo.tags if tag.commit == repo.head.commit), None)