Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I checkout a branch in a similar way than the CLI does? #948

Open
pablocompagni-contractorvp opened this issue Mar 7, 2023 · 1 comment

Comments

@pablocompagni-contractorvp

Looking at this issue it seems this should be a branch switch and then a checkout, but I just can't figure out how to do it. #291

I've tried doing this:

func CheckoutBranch(r *git.Repository, b *git.Branch) error {
	err := r.SetHead(b.Reference.Name())
	if err != nil {
		return err
	}
	return nil
}

and this:

func CheckoutBranch(r *git.Repository, b *git.Branch) error {
	err := r.SetHead(b.Reference.Name())
	if err != nil {
		return err
	}

	return r.CheckoutHead(&git.CheckoutOptions{
		Strategy: git.CheckoutForce,
	})
}

But they both end up with a detached head. I've also tried, based on the suggestions from the other ticket, to do this:

func CheckoutBranch(r *git.Repository, b *git.Branch) error {
	err := r.SetHead(b.Reference.Name())
	if err != nil {
		return err
	}
	tree, err := r.LookupTree(b.Target())
	if err != nil {
		return err
	}
	
	return r.CheckoutTree(tree, &git.CheckoutOptions{
		Strategy: git.CheckoutForce,
	})
}

But this just throws and error.

@liuqianhong6007
Copy link

I do this as following

func Checkout(repo *git.Repository, branch *git.Branch) error {
	branchName, err := branch.Name()
	if err != nil {
		return err
	}

	commit, err := repo.LookupCommit(branch.Target())
	if err != nil {
		return err
	}
	defer commit.Free()

	tree, err := repo.LookupTree(commit.TreeId())
	if err != nil {
		return err
	}
	defer tree.Free()

	err = repo.CheckoutTree(tree, &git.CheckoutOptions{
		Strategy: git.CheckoutForce,
	})
	if err != nil {
		return err
	}

	err = repo.SetHead("refs/heads/" + branchName)
	if err != nil {
		return err
	}
	return nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants