go-git icon indicating copy to clipboard operation
go-git copied to clipboard

CreateBranch does not work correctly

Open behinddwalls opened this issue 3 years ago • 2 comments

repository.CreateBranch only adds the branch to .git/config but doesn't create the local ref which causes git to not find it...

err := repository.CreateBranch(&config.Branch{
		Name:   name,
		Remote: ".",
		Merge:  plumbing.NewBranchReferenceName(upstream),
	})
w, _ := repository.Worktree()
err = w.Checkout(&git.CheckoutOptions{
		Branch: plumbing.NewBranchReferenceName(name),
	})

This results in error Error: failed to checkout branch: reference not found. After checking the .git folder..it seems only config was updated but no refs were created for new branch

behinddwalls avatar Dec 12 '22 00:12 behinddwalls

@behinddwalls, this tripped me up, too. I just started using this library today, so I may be missing something else, but...

I think, despite the documentation:

CreateBranch creates a new Branch

CreateBranch(&config.Branch{...}) just creates or updates the repo's config file.

Also, I see in your example that you try to create (and check out) the branch without saying what the branch is from; in both examples below, I have hash, h, of the commit (from ref,_:=r.Head();h:=ref.Hash()) I want to branch from. Maybe you thought you could use the Merge field of the Checkout config, but that should just be the path of the final ref, like refs/heads/NAME or refs/tags/NAME.

To actually update the underlying Storer and write to the refs directory, I see two options:

  1. Worktree.Checkout if you want the git checkout -b name behavior:

    err = w.Checkout(&git.CheckoutOptions{
        Hash:   h,
        Branch: branchRefName,
        Create: true,
    })
    must(err)
    fmt.Println("Created and checked-out branch", branchRefName, "pointing at", h)
    

    I found this in examples/checkout.

  2. Repository.Storer.SetReference:

    branchRef := plumbing.NewHashReference(branchRefName, h)
    err = r.Storer.SetReference(branchRef)
    must(err)
    fmt.Println("Created branch", branchRefName, "pointing at", h)
    

    I found this in examples/branch.

Neither of these affect the config file, looks like we always need to run CreateBranch independent of modifying the storage.

zacharysyoung avatar Jun 26 '23 22:06 zacharysyoung

To help us keep things tidy and focus on the active tasks, we've introduced a stale bot to spot issues/PRs that haven't had any activity in a while.

This particular issue hasn't had any updates or activity in the past 90 days, so it's been labeled as 'stale'. If it remains inactive for the next 30 days, it'll be automatically closed.

We understand everyone's busy, but if this issue is still important to you, please feel free to add a comment or make an update to keep it active.

Thanks for your understanding and cooperation!

github-actions[bot] avatar Oct 10 '24 07:10 github-actions[bot]