简体   繁体   中英

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

This question should be related to:

But I am wondering how to do that through pygit2 ?

To get the conventional "shorthand" name:

from pygit2 import Repository

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

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

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]

You can use GitPython :

from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM