GitPython: Get current tag (detached head)
Asked Answered
F

2

13

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.

Francisco answered 11/9, 2015 at 12:5 Comment(0)
K
16

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)
Kursh answered 11/9, 2015 at 13:33 Comment(2)
Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.Engadine
@Kursh thank you. the next() trick was new to me. It returns the first match or None. For other people: next(iter([1, 2, 3]), None) --> 1Francisco
S
6

It looks like you might be able to get what you want with GitCmd calling describe.

g = Git(git_dir)
rval = g.describe()

I don't see any way to directly access this information.

Spade answered 11/9, 2015 at 12:58 Comment(1)
or with repo.git.describe().Lapin

© 2022 - 2024 — McMap. All rights reserved.