How to get master/main branch from gitpython
Asked Answered
A

2

6

How one can know about the master/main branch at git remote with git-python.

I am aware that we can iterate over the heads of the repository and then check the results. Something like

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

for refs in remote_refs:
    print(refs)

This will give list of all branch heads at remote including the main/master branch.

Is their a direct way to get the main branch?

Account answered 20/10, 2021 at 18:50 Comment(13)
Does this answer your question? Checkout or list remote branches in GitPythonApiarian
What do you mean by "get" here? Checkout? Pull? Something else?Apiarian
by get i mean , to know which is the main branch , whether main or master is the main branchAccount
What if a repo has both branches? Why not try checking out both?Apiarian
Thats the issue , how would someone know which is the main branch?Account
#16500961Apiarian
That is in my knowledge , is their a way to get the same from git-python?Account
Did you look at the documentation?Apiarian
yes, there isn't specific to the answerAccount
Right. So if you've checked the documentation and haven't found an answer...Apiarian
this looks like the answerAccount
Not to me. Using the github API will be a much easier approach. Gitpython doesn't look to have anything that deals with a github repo's default branch (which is a github thing, not a git thing).Apiarian
Yeah that makes perfect senseAccount
G
7

There is no official way, but this works well.

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)
Grevera answered 12/10, 2023 at 15:3 Comment(0)
F
1

Git itself doesn't have a concept of a "main branch". It has a default name for the first branch that is created but you can rename it as you wish, create more branches from the first commit and let them all head in their own directions.

The concept of a "main branch" is really only relevant in the central repository management systems such as GitHub, GitLab and Bitbucket.

So if you want the branch that is considered the "main branch" by those systems, you'd have to use their API to query the name of that branch for the project in question.

So the answer is no, there is no way to find the "default branch" with git-python, as there isn't even a way to do that with git itself.

Flap answered 27/10, 2022 at 18:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.