Search code examples
python-3.xgitgitpython

Python git package get tag and commit


I would like to print a git commit and the tag in my Python code. How can I do this using git package?

When I am going to my Bitbucket I see

tag: 73-2-g46b9856

commit checksum: 46b9856

How can I retrieve this info from git package?

I have done the following:

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

Solution

  • Here is what solved my issue:

    repo = git.Repo(search_parent_directories = True)
    sha = repo.head.object.hexsha
    
    commit_chksum = repo.git.rev_parse(sha, short = 7)
    tag = subprocess.check_output(["git", "describe", "--always"]).strip().decode()