如何从gitpython获取master/main分支

问题描述 投票:0回答:2

如何使用

master
了解 git Remote 上的
main
/
git-python
分支。

我知道我们可以迭代存储库的头部,然后检查结果。类似的东西

repo = git.Repo('git-repo')
remote_refs = repo.remote().refs

for refs in remote_refs:
    print(refs)

这将给出远程所有分支头的列表,包括主/主分支。

他们是获得主分支的直接方式吗?

python-3.x github git-branch gitpython
2个回答
1
投票

Git 本身没有“主分支”的概念。它对创建的第一个分支有一个默认名称,但您可以根据需要重命名它,从第一次提交创建更多分支,并让它们都朝着自己的方向前进。

“主分支”的概念实际上只与中央存储库管理系统相关,例如 GitHub、GitLab 和 Bitbucket。

因此,如果您希望这些系统将分支视为“主分支”,则必须使用他们的 API 来查询相关项目的该分支的名称。

所以答案是否定的,没有办法用 git-python 找到“默认分支”,因为甚至没有办法用 git 本身来做到这一点。


0
投票

没有官方的方法,但这很有效。

import re
from git import Repo


# provide path to your repository instead of `your_project_path`
repo = Repo.init(your_project_path)

# replace "origin" with your remote name if differs
show_result = repo.git.remote("show", "origin")  

# The show_result contains a wall of text in the language that 
# is set by your locales. Now you can use regex to extract the 
# default branch name, but if your language is different
# from english, you need to adjust this regex pattern.

matches = re.search(r"\s*HEAD branch:\s*(.*)", show_result)
if matches:
    default_branch = matches.group(1)
    print(default_branch)
© www.soinside.com 2019 - 2024. All rights reserved.