Skip to content

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

@pablocompagni-contractorvp

Description

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions