2

I'm trying to delete a local branch using go-git, but getting an error branch not found when I run

branch := "refs/heads/template/test"
err = repo.DeleteBranch(branch)

or

err = repo.DeleteBranch(plumbing.ReferenceName(branch))

Using just the name of the branch (template/test) doesn't work either. The branch is included in the list of branches. This

refs, err := repo.Branches()
err = refs.ForEach(func(ref *plumbing.Reference) error {
    fmt.Println(ref)
    return nil
})

provides the following output:

f2d93bb67ced13936dbbbbfb44502abd42e7df13 refs/heads/global
df46ab083f17051afd6ca20e3ea4bfe01aedbb37 refs/heads/template/test
141f45305380aa0dc9f6802512ea76c5d48a87a1 refs/heads/template/test2

How can I delete it?

Update: I checked the function DeleteBranch, it looks like this:

// DeleteBranch delete a Branch from the repository and delete the config
func (r *Repository) DeleteBranch(name string) error {
    cfg, err := r.Storer.Config()
    if err != nil {
        return err
    }

    if _, ok := cfg.Branches[name]; !ok {
        return ErrBranchNotFound
    }

    delete(cfg.Branches, name)
    return r.Storer.SetConfig(cfg)

}

then I created cfg := repo.Storer.Config() and checked what cfg.Branches contains. Surprisingly, this map has only the following element: &{global origin refs/heads/global 0xc0007fbf80}. So other branches can't be deleted because they are not found in this config.

lawful_neutral
  • 633
  • 8
  • 29
  • 2
    I think you got tripped up by the method name `DeleteBranch`, in the same way that I got tripped up by the method name `CreateBranch`; see: https://stackoverflow.com/q/67152490/1337498 As near as I can tell, neither of these functions do anything to _branches_ (i.e., refs) as such. They just manipulate entries in the `.git/config` file. So why they are methods of `git.Repository`, rather than `config.Config`, is completely beyond me. – Hephaestus Apr 19 '21 at 17:48

1 Answers1

3

I know that this question is quite old but the naming here tripped me up as well so I thought I'd provide an answer.

Thanks to @Hephaestus and the post linked to, I was able to sort out the correct approach. If you're trying to delete a local branch (e.g. git branch -d foo) it looks like you're meant to use repo.Storer.RemoveReference.

In my case I already have a slice of (short) branch names:

for _, branchName := range branches {
  ref := plumbing.NewBranchReferenceName(branchName)
  err = repo.Storer.RemoveReference(ref)

  if err != nil {
    return "", err
  }
}
jallen7usa
  • 3,128
  • 1
  • 17
  • 8