Using the GitPython Module for the Remote HEAD Branch

I am trying to use GitPython to write Python scripts, which I can use to simplify my daily tasks, as I manage many branches.

I am also completely new to Python when it comes to writing complex scripts.

This is the API I used: GitPython API Document

I want to write it to GitPython, which simply does the following and parses the part that shows what the remote HEAD branch indicates. In other words, I want to basically get remotes/origin/HEAD

 $ git branch -a master * branch_to_remove remotes/origin/HEAD -> origin/master remotes/origin/master remotes/origin/testing 

I look through an API document many times, at first it’s hard for me to understand the Python format of these API documents, and I could not find anything useful for this except remote_head in class git.refs.reference.Reference(repo, path, check_path=True)

But I don’t even know how to call / initialize it.

Here is what I had so far, and you can say what I'm trying to do is simply reset to the "no branch" state and delete the current branch on which I am on:

 import git from git import * repo = git.Repo("/some/path/testing") repo.git.branch() [some code to get the remotes/origin/HEAD, set it to remoteHeadBranch ] repo.git.checkout(remoteHeadBranch) # this should reset the Git back to 'no branch' state repo.git.checkout(D="branch_to_remove") 

Any help is much appreciated!

Thanks.

+8
git python gitpython
source share
2 answers

I just saw your question, which I was wondering about this gitPython, looks like a really good tool, and I looked for this specific question in the GitPython documentation with no luck, but if you search on github you will see a lot of tests there and there the test for of this.

You will see something like this when searching for "delete new branch":

 # remove new branch Head.delete(new_remote_branch.repo, new_remote_branch) 

GitPython Reference

+3
source share

To print the current branch:

 print(repo.head.ref) 

To display branches

 print [str(b) for b in repo.heads] 

To check a branch

 repo.heads[branch].checkout() 

or repo.git.checkout(branch)

If you are trying to delete a branch, you need to be in another LOCAL branch, which you can do in several ways.

 repo.heads['master'].checkout() 

or repo.git.checkout('master') or repo.git.checkout('remotes/origin/master')

Hope this helps

+3
source share

All Articles