Skip to content

Instantly share code, notes, and snippets.

@aclarknexient
Created November 23, 2023 18:34
Show Gist options
  • Save aclarknexient/e397c23230c0e8f8a6d84792831a11f0 to your computer and use it in GitHub Desktop.
Save aclarknexient/e397c23230c0e8f8a6d84792831a11f0 to your computer and use it in GitHub Desktop.
python git checkout using pygit2
import pygit2
def checkout_branch(path, branch_name):
repo = pygit2.Repository(path)
# If the branch isn't already in the local list,
# you have to create a ref for it to point at
# in order to avoid detached head state
if branch_name not in repo.branches.local:
print(f"Branch {branch_name} not found in local branches")
remote_branch = "origin/" + branch_name
if remote_branch not in repo.branches.remote:
raise SystemExit(f"Branch {remote_branch} not found in remote branches")
(commit, remote_ref) = repo.resolve_refish(remote_branch)
repo.create_reference("refs/heads/" + branch_name, commit.hex)
branch = repo.lookup_branch(branch_name)
print(f"Branch name: {branch.name}")
repo.checkout(branch)
print(f"Is branch head? {branch.is_head()}")
(commit, branch_remote) = repo.resolve_refish("origin/" + branch_name)
print(f"Remote branch: {branch_remote.name}")
branch.upstream = branch_remote
checkout_branch("path/to/your/repo", "branch-name")
# This avoids detached head and also sets the remote target correctly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment