20

This question should be related to:

But I am wondering how to do that through pygit2?

Community
  • 1
  • 1
Drake Guan
  • 13,644
  • 11
  • 59
  • 92

4 Answers4

35

To get the conventional "shorthand" name:

from pygit2 import Repository

Repository('.').head.shorthand  # 'master'
Razzi Abuissa
  • 2,504
  • 2
  • 24
  • 24
13

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
Andrew C
  • 12,870
  • 5
  • 48
  • 54
8

In case you don't want to or can't use pygit2

May need to alter path - this assumes you are in the parent directory of .git

from pathlib import Path

def get_active_branch_name():

    head_dir = Path(".") / ".git" / "HEAD"
    with head_dir.open("r") as f: content = f.read().splitlines()

    for line in content:
        if line[0:4] == "ref:":
            return line.partition("refs/heads/")[2]
merfi
  • 81
  • 1
  • 2
2

You can use GitPython:

from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name
lennon310
  • 12,178
  • 11
  • 41
  • 60