7y4bm7vi

7y4bm7vi1#

要获得传统的“简写”名称:

from pygit2 import Repository

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

字符串

uwopmtnx

uwopmtnx2#

如果你不想或不能使用pygit 2
可能需要更改路径-这假设您位于.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]

字符串

jhiyze9q

jhiyze9q3#

PyGit文档
这两种方法都可以

#!/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)

字符串
你会得到完整的名字,包括/refs/heads/。如果你不想这样,把它去掉或者用简写代替名字。

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

laawzig2

laawzig24#

可以使用GitPython

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

字符串

jtjikinw

jtjikinw5#

您还可以执行以下操作:

process = subprocess.Popen(["git", "branch", "--show-current"], stdout=subprocess.PIPE)
branch_name, branch_error = process.communicate()

字符串
这将工作,而不管文件路径,并且不需要额外的包。

相关问题