Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created February 7, 2012 17:33
Show Gist options
  • Save igniteflow/1760854 to your computer and use it in GitHub Desktop.
Save igniteflow/1760854 to your computer and use it in GitHub Desktop.
GitPython get current active branch
"""
Gets the name of the active Git branch as a string.
Depends on GitPython
pip install GitPython
"""
from git import Repo
repo = Repo('/path/to/your/repo')
branch = repo.active_branch
print branch.name
"""
Example usage from my local Django settings:
try:
# use the develop database if we are using develop
import os
from git import Repo
repo = Repo(os.getcwd())
branch = repo.active_branch
branch = branch.name
if branch == 'develop':
DATABASES['default']['NAME'] = 'myproject__develop'
except ImportError:
pass
"""
@VictorZhang2014
Copy link

Thank you for sharing the code. It's very good.

try:
    from git import Repo
except ImportError:
    print("\n警告⚠️  :")
    print("1.检测到你的macOS没有安装gitpython module,请先安装gitpython module。参考链接:http://gitpython.readthedocs.io/en/stable/intro.html 。")
    print("2.也可以直接在Terminal中输入:pip install gitpython 来进行安装。\n")
    exit(0)

my_repo = Repo("./")
print(my_repo.active_branch.name)

@krectra
Copy link

krectra commented Aug 22, 2019

Try this:

>>> import git
>>> repo = git.Repo(search_parent_directories=True)
>>> branch = repo.active_branch
>>> branch.name

@ssbarnea
Copy link

Any standard way to retrieve the default branch of the repository instead of current active branch?

@Symbolk
Copy link

Symbolk commented May 17, 2021

Any standard way to retrieve the default branch of the repository instead of current active branch?

AFAK, no off-the-shelf API in GitPython 3.1.17, here is a workaround:

    def get_default_branch(self):
        print("Fetching remote for default branch...")
        lines = self.repo.git.remote('show', self.git_url)
        print(lines)
        lines = lines.split("\n")
        default_branch = ''
        for line in lines:
            if "HEAD branch" in line:
                default_branch = line.split(":")[1].strip()
                break
        if default_branch == "":
            default_branch = "master"
        print("Default branch: " + default_branch)
        return default_branch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment