Search code examples
pythongitpygit2

How do you checkout a branch with pygit2?


I want to use pygit2 to checkout a branch-name.

For example, if I have two branches: master and new and HEAD is at master, I would expect to be able to do:

import pygit2
repository = pygit2.Repository('.git')
repository.checkout('new')

or even

import pygit2
repository = pygit2.Repository('.git')
repository.lookup_branch('new').checkout()

but neither works and the pygit2 docs don't mention how to checkout a branch.


Solution

  • It seems you can do:

    import pygit2
    repo = pygit2.Repository('.git')
    branch = repo.lookup_branch('new')
    ref = repo.lookup_reference(branch.name)
    repo.checkout(ref)