Checkout or list remote branches in GitPython
Asked Answered
O

7

22

I don't see an option to checkout or list remote/local branches in this module: https://gitpython.readthedocs.io/en/stable/

Ogawa answered 18/3, 2010 at 20:9 Comment(0)
N
9

After you’ve done

from git import Git
g = Git()

(and possibly some other command to init g to the repository you care about) all attribute requests on g are more or less transformed into a call of git attr *args.

Therefore:

g.checkout("mybranch")

should do what you want.

g.branch()

will list the branches. However, note that these are very low level commands and they will return the exact code that the git executables will return. Therefore, don’t expect a nice list. I’ll just be a string of several lines and with one line having an asterisk as the first character.

There might be some better way to do this in the library. In repo.py for example is a special active_branch command. You’ll have to go through the source a little and look for yourself.

Neel answered 18/3, 2010 at 20:23 Comment(2)
when i run r = Git.clone("git ...") r.checkout("develop") does not work.. AttributeError: 'str' object has no attribute 'checkout'Ogawa
ok looks like I need to run a g = Git("dir") then I can checkoutOgawa
U
20

For those who want to just print the remote branches:

# Execute from the repository root directory
repo = git.Repo('.')
remote_refs = repo.remote().refs

for refs in remote_refs:
    print(refs.name)
Underwear answered 9/3, 2020 at 18:32 Comment(0)
A
17

To list branches you can use:

from git import Repo
r = Repo(your_repo_path)
repo_heads = r.heads # or it's alias: r.branches

r.heads returns git.util.IterableList (inherits after list) of git.Head objects, so you can:

repo_heads_names = [h.name for h in repo_heads]

And to checkout eg. master:

repo_heads['master'].checkout() 
# you can get elements of IterableList through it_list['branch_name'] 
# or it_list.branch_name

Module mentioned in the question is GitPython which moved from gitorious to Github.

Atwekk answered 13/2, 2017 at 22:19 Comment(1)
Looks like its documented here: gitpython.readthedocs.io/en/stable/…Dominions
N
9

After you’ve done

from git import Git
g = Git()

(and possibly some other command to init g to the repository you care about) all attribute requests on g are more or less transformed into a call of git attr *args.

Therefore:

g.checkout("mybranch")

should do what you want.

g.branch()

will list the branches. However, note that these are very low level commands and they will return the exact code that the git executables will return. Therefore, don’t expect a nice list. I’ll just be a string of several lines and with one line having an asterisk as the first character.

There might be some better way to do this in the library. In repo.py for example is a special active_branch command. You’ll have to go through the source a little and look for yourself.

Neel answered 18/3, 2010 at 20:23 Comment(2)
when i run r = Git.clone("git ...") r.checkout("develop") does not work.. AttributeError: 'str' object has no attribute 'checkout'Ogawa
ok looks like I need to run a g = Git("dir") then I can checkoutOgawa
C
5

I had a similar issue. In my case I only wanted to list the remote branches that are tracked locally. This worked for me:

import git

repo = git.Repo(repo_path)
branches = []
for r in repo.branches:
    branches.append(r)
    # check if a tracking branch exists
    tb = t.tracking_branch()
    if tb:
        branches.append(tb) 

In case all remote branches are needed, I would prefer running git directly:

def get_all_branches(path):
    cmd = ['git', '-C', path, 'branch', '-a']
    out = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
    return out
Cyprinid answered 1/3, 2017 at 11:4 Comment(1)
If you already have a Repo instance, you can call git commands directly as: repo.git.branch('-a')Dagall
U
4

Just to make it obvious - to get a list of remote branches from the current repo directory:

import os, git

# Create repo for current directory
repo = git.Repo(os.getcwd())

# Run "git branch -r" and collect results into array
remote_branches = []
for ref in repo.git.branch('-r').split('\n'):
    print(ref)
    remote_branches.append(ref)
Urial answered 19/11, 2017 at 1:8 Comment(0)
R
1

Basically, with GitPython, if you know how to do it within command line, but not within the API, just use repo.git.action("your command without leading 'git' and 'action'"), example: git log --reverse => repo.git.log('--reverse')

in this case https://mcmap.net/q/401569/-how-to-check-out-a-branch-with-gitpython

So I try this command:

repo = git.Repo()

repo.git.checkout('-b', local_branch, remote_branch)

this command can make a new local branch name local_branch(if already haved, rasie error) and set up to track remote branch remote_branch

it works very well!

Run answered 28/5, 2020 at 2:29 Comment(0)
J
0

I took a slightly different approach here, based on the desire to obtain a list of branches that can be checked out:

repo = git.Repo(YOUR_REPO_HERE)
branch_list = [r.remote_head for r in repo.remote().refs]

Unlike the answer using refs.name, this obtains the name without the remote prefix, in the form you would want to use to check out the repository.

Jelly answered 20/3, 2023 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.