Checkout or list remote branches in GitPython Checkout or list remote branches in GitPython python python

Checkout or list remote branches in GitPython


To list branches you can use:

from git import Repor = 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.


For those who want to just print the remote branches:

# Execute from the repository root directoryrepo = git.Repo('.')remote_refs = repo.remote().refsfor refs in remote_refs:    print(refs.name)


After you’ve done

from git import Gitg = 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.