小智 26
如果您不想或不能使用 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]
Run Code Online (Sandbox Code Playgroud)
Raz*_*ssa 16
要获得传统的"速记"名称:
from pygit2 import Repository
Repository('.').head.shorthand # 'master'
Run Code Online (Sandbox Code Playgroud)
来自 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)
Run Code Online (Sandbox Code Playgroud)
您可以使用GitPython
:
from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11611 次 |
最近记录: |