如何通过pygit2获取当前已检出的Git分支名称?

30

2
repo.head 没有达到你的预期?请参考 http://www.pygit2.org/references.html#the-head。 - Andrew C
你介意把它作为答案发布吗?我相信这也可以帮助其他人 :) - Drake Guan
4个回答

45

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

from pygit2 import Repository

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

24

如果您不想使用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]

13

来自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 Kazimipour
1
@BorhanKazimipour 这是你正在工作的仓库的引用 repo = Repository('path/to/git_repo') - Andrew C

9
你可以使用GitPython
from git import Repo
local_repo = Repo(path=settings.BASE_DIR)
local_branch = local_repo.active_branch.name

1
我只用 Repo().head.ref.name 就成功了。这会返回分支的名称。 - havryliuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接