19

这个问题应该与:

但我想知道如何通过pygit2做到这一点?

4

4 回答 4

35

要获得传统的“速记”名称:

from pygit2 import Repository

Repository('.').head.shorthand  # 'master'
于 2016-04-15T02:55:01.297 回答
12

来自 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
于 2014-10-01T04:57:02.443 回答
5

如果您不想或不能使用 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]
于 2020-07-04T00:55:07.873 回答
2

您可以使用GitPython

from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name
于 2020-11-11T21:30:15.240 回答