Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Danw33/67d967e888ea13a2e615c5d460d6f492 to your computer and use it in GitHub Desktop.
Save Danw33/67d967e888ea13a2e615c5d460d6f492 to your computer and use it in GitHub Desktop.
How to do a git checkout branch using git2go
package main
import (
"errors"
"log"
"github.com/libgit2/git2go"
)
func checkoutBranch(repo *git.Repository, branchName string) error {
checkoutOpts := &git.CheckoutOpts{
Strategy: git.CheckoutSafe | git.CheckoutRecreateMissing | git.CheckoutAllowConflicts | git.CheckoutUseTheirs,
}
//Getting the reference for the remote branch
// remoteBranch, err := repo.References.Lookup("refs/remotes/origin/" + branchName)
remoteBranch, err := repo.LookupBranch("origin/"+branchName, git.BranchRemote)
if err != nil {
log.Print("Failed to find remote branch: " + branchName)
return err
}
defer remoteBranch.Free()
// Lookup for commit from remote branch
commit, err := repo.LookupCommit(remoteBranch.Target())
if err != nil {
log.Print("Failed to find remote branch commit: " + branchName)
return err
}
defer commit.Free()
localBranch, err := repo.LookupBranch(branchName, git.BranchLocal)
// No local branch, lets create one
if localBranch == nil || err != nil {
// Creating local branch
localBranch, err = repo.CreateBranch(branchName, commit, false)
if err != nil {
log.Print("Failed to create local branch: " + branchName)
return err
}
// Setting upstream to origin branch
err = localBranch.SetUpstream("origin/" + branchName)
if err != nil {
log.Print("Failed to create upstream to origin/" + branchName)
return err
}
}
if localBranch == nil {
return errors.New("Error while locating/creating local branch")
}
defer localBranch.Free()
// Getting the tree for the branch
localCommit, err := repo.LookupCommit(localBranch.Target())
if err != nil {
log.Print("Failed to lookup for commit in local branch " + branchName)
return err
}
defer localCommit.Free()
tree, err := repo.LookupTree(localCommit.TreeId())
if err != nil {
log.Print("Failed to lookup for tree " + branchName)
return err
}
defer tree.Free()
// Checkout the tree
err = repo.CheckoutTree(tree, checkoutOpts)
if err != nil {
log.Print("Failed to checkout tree " + branchName)
return err
}
// Setting the Head to point to our branch
repo.SetHead("refs/heads/" + branchName)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment