5

I'm new to gitpython and haven't been able to find a reference to this anywhere. What I'm looking to do is something like:

If remote branch name exists:
  do something
else:
  do something else

Any suggestions?

1

6 Answers 6

3

GitPython has references to all the branches. A user can iterate to check if the branch is part of that reference or not.

To print all the branches use this as reference:

for ref in repo.references:
    print("Branch Name is: ", ref.name)

Similarly for your purpose, if you can do something like

for ref in repo.references:
    if branchName == ref.name:
        Do likely something
    else:
        Do unlikely something
Sign up to request clarification or add additional context in comments.

Comments

2

The simplest seems to be:

allBranches = git.Git().branch("-all").split()
"<testedBranch>" in allBranches
>>> true/false
  • this embeds the branches within all the standard techniques of a sequence protocol

Comments

0

This may not work, but give it a shot let me know how it goes:

does_exist = True
try:
    repo.git.checkout('branch_name')
except repo.exc.GitCommandError:
    does_exist = False

print(does_exist)

This may also work but give it a try:

repo.git.rev_parse('--verify', 'branch_name')

Comments

0

Worked for me:

def check_branch_exists(github_repo, branch) -> bool:
    for br in github_repo.get_branches():
        if branch == br.name:
            return True
    return False

Comments

0

To those like me that want to call using a remote url without a local repo

import git

def _ls_remote_branches(url):
    remote_branches = []
    g = git.cmd.Git()
    for ref in g.ls_remote(url).split("\n"):
        if "head" in ref:
            hash_ref_list = ref.split("\t")
            remote_branches.append(
                hash_ref_list[1].split("/")[-1]
            )
    return remote_branches

Edit 1: other answers did not work for me because I was looking for something that does not require a local git repo.

Edit 2: This was based on the upvoted answer to another question here

Comments

-2

Thanks Muadh! I was able to get this to work:

try:
    repo.git.checkout( 'origin/' + branch_name, b=branch_name )
except:
    repo.git.checkout( 'origin/master', b=branch_name )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.