这个问题应该与以下内容有关:
但我想知道如何通过pygit2实现这个功能?
为了获得传统的“速记”名称:
from pygit2 import Repository
Repository('.').head.shorthand # 'master'
如果您不想使用pygit2,或是无法使用它
可能需要更改路径 - 这假设您位于.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]
来自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
repo
是什么? - Borhan KazimipourGitPython
:from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name
Repo().head.ref.name
就成功了。这会返回分支的名称。 - havryliuk
repo.head
没有达到你的预期?请参考 http://www.pygit2.org/references.html#the-head。 - Andrew C