How to check out a branch with GitPython

Alex Spurling picture Alex Spurling · Dec 18, 2017 · Viewed 20.8k times · Source

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.

Answer

Arount picture Arount · Dec 18, 2017

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