6

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.

nebffa
  • 1,529
  • 1
  • 16
  • 26

2 Answers2

9

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)
ash
  • 653
  • 9
  • 20
nebffa
  • 1,529
  • 1
  • 16
  • 26
1

I had a lot of trouble with this and this is one of the only relevant StackOverflow posts regarding this, so I thought I'd leave a full working example of how to clone a repo from Github and checkout the specified branch.

def clone_repo(clone_url, clone_path, branch, auth_token):
  # Use pygit2 to clone the repo to disk
  # if using github app pem key token, use x-access-token like below
  # if you were using a personal access token, use auth_method = 'x-oauth-basic' AND reverse the auth_method and token parameters
  auth_method = 'x-access-token'
  callbacks = pygit2.RemoteCallbacks(pygit2.UserPass(auth_method, auth_token))
  pygit2_repo = pygit2.clone_repository(clone_url, clone_path, callbacks=callbacks)
  pygit2_branch = pygit2_repo.branches['origin/' + branch]
  pygit2_ref = pygit2_repo.lookup_reference(pygit2_branch.name)
  pygit2_repo.checkout(pygit2_ref)
Andy Fraley
  • 1,043
  • 9
  • 16