28

This question should be related to:

But I am wondering how to do that through pygit2?

Community
  • 1
  • 1
Drake Guan
  • 14,514
  • 15
  • 67
  • 94

4 Answers4

42

To get the conventional "shorthand" name:

from pygit2 import Repository

Repository('.').head.shorthand  # 'master'
Razzi Abuissa
  • 3,337
  • 2
  • 28
  • 29
24

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
  • 339
  • 2
  • 4
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
  • 13,845
  • 6
  • 50
  • 57
8

You can use GitPython:

from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name
lennon310
  • 12,503
  • 11
  • 43
  • 61