这个问题应该与:
但我想知道如何通过pygit2做到这一点?
这个问题应该与:
但我想知道如何通过pygit2做到这一点?
要获得传统的“速记”名称:
from pygit2 import Repository
Repository('.').head.shorthand # 'master'
来自 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
如果您不想或不能使用 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]
您可以使用GitPython
:
from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name