Checkout / List of remote branches in git -python

I do not see options for checking or list of remote / local branches in this module

http://gitorious.org/git-python/

+7
git python gitpython
source share
4 answers

After doing

from git import Git g = Git() 

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

Thus:

 g.checkout("mybranch") 

should do what you want.

 g.branch() 

will display branches. However, note that these are very low level commands and they will return the exact code that will return the git executables. Therefore, do not expect a good list. Ill is just a line of several lines and one line with an asterisk as the first character.

There may be a better way to do this in the library. For example, repo.py has a special active_branch command. You will have to go a little through the source and look for yourself.

+7
source share

To list the branches, you can currently use:

 from git import Repo r = Repo(your_repo_path) repo_heads = r.heads # or it 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 for verification, for example. master :

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

The module mentioned in the question is GitPython , which is moved from gitorious to Github .

+4
source share

I had a similar problem. In my case, I only wanted to specify 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) 

If all the remote branches are needed, I would prefer to use git directly:

 def get_all_branches(path): cmd = ['git', '-C', path, 'branch', '-a'] out = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return out 
+1
source share

Just to make it obvious - 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) 
0
source share

All Articles