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.
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 (eg 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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.