Search code examples
pythongitpython

How to Checkout out a branch


I got gitpython working to clone a repo, now i need to checkout out branches inside that repo i've been looking at the documentation but cant seem to find it

import git
import os
import shutil

DIR_NAME = "temp"
REMOTE_URL = "<REPO>"

if os.path.isdir(DIR_NAME):
    shutil.rmtree(DIR_NAME)

os.mkdir(DIR_NAME)

repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0].remote_head)

Solution

  • repo.git.checkout('branchename')
    

    or, if the branch does not yet exist..

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