How to get the current checked out Git branch name through pygit2?

From PyGit Documentation

Either of these should work

#!/usr/bin/python
from pygit2 import Repository

repo = Repository('/path/to/your/git/repo')

# option 1
head = repo.head
print("Head is " + head.name)

# option 2
head = repo.lookup_reference('HEAD').resolve()
print("Head is " + head.name)

You'll get the full name including /refs/heads/. If you don't want that strip it out or use shorthand instead of name.

./pygit_test.py  
Head is refs/heads/master 
Head is refs/heads/master

To get the conventional "shorthand" name:

from pygit2 import Repository

Repository('.').head.shorthand  # 'master'

Tags:

Python

Git

Pygit2