Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check out a branch with GitPython

Tags:

I have cloned a repository with GitPython, now I would like to checkout a branch and update the local repository's working tree with the contents of that branch. Ideally, I'd also be able to check if the branch exists before doing this. This is what I have so far:

import git  repo_clone_url = "[email protected]:mygithubuser/myrepo.git" local_repo = "mytestproject" test_branch = "test-branch" repo = git.Repo.clone_from(repo_clone_url, local_repo) # Check out branch test_branch somehow # write to file in working directory repo.index.add(["test.txt"]) commit = repo.index.commit("Commit test") 

I am not sure what to put in the place of the comments above. The documentation seems to give an example of how to detach the HEAD, but not how to checkout an named branch.

like image 846
Alex Spurling Avatar asked Dec 18 '17 16:12

Alex Spurling


1 Answers

If the branch exists:

repo.git.checkout('branchename') 

If not:

repo.git.checkout('-b', 'branchename') 

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')

like image 83
Arount Avatar answered Sep 20 '22 19:09

Arount