How to checkout a new local branch using go-git?

4k views Asked by At

When i try to use worktree checkout; it doesn't work and the code returns error

err = worktree.Checkout(&git.CheckoutOptions{
    Create: true,
    Branch: "main",
})
if err != nil {
    log.Fatal("Cannot create 'main' branch\n" + err.Error())
}

Output:

[FATA] Cannot create 'main' branch
reference not found

I get the same error when i use

repository.CreateBranch(&config.Branch{
    Name: "main",
})
1

There are 1 answers

8
VonC On

While it is true GitHub will soon rename master to main, the default branch for a Git repository (on GitHub or not) is still master for now.

So try first:

err = worktree.Checkout(&git.CheckoutOptions{
    Create: true,
    Branch: "master",
})

But if the goal is to create a new branch, make sure the repo is either initialized or already checked out to a valid branch.
For example, see repository_test.go

    r, _ := Init(memory.NewStorage(), nil)
    testBranch := &config.Branch{
        Name:   "foo",
        Remote: "origin",
        Merge:  "refs/heads/foo",
    }
    err := r.CreateBranch(testBranch)

The OP capsci adds in the comments:

I tried removing Merge during branch create, but got "reference not found" error when checking out (w/ and w/o Create option)

I ended up using hack in hairyhenderson/gomplate PR 1217:

h := plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.ReferenceName("refs/heads/main")) 
err = storer.SetReference(h); 

these 2 lines after git.Init(storer, fs), and I was good to go.