From 8458e61d170fcdff7b1744851f0da1111f845d87 Mon Sep 17 00:00:00 2001 From: "Franz Heinzmann (Frando)" Date: Thu, 11 Aug 2022 14:14:31 +0200 Subject: [PATCH] fix: branch checking logic See https://github.com/go-git/go-git/issues/518 for why this is needed. --- pkg/git/branch.go | 19 +++++++++++++++++++ pkg/recipe/recipe.go | 4 ++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/pkg/git/branch.go b/pkg/git/branch.go index 8c17f9c0..9bc5bbb2 100644 --- a/pkg/git/branch.go +++ b/pkg/git/branch.go @@ -5,6 +5,25 @@ import ( "github.com/go-git/go-git/v5/plumbing" ) +// Check if a branch exists in a repo. +// Use this and not repository.Branch(), because the latter does not +// actually check for existing branches. +// See https://github.com/go-git/go-git/issues/518 +func HasBranch(repository *git.Repository, name string) bool { + var exist bool + if iter, err := repository.Branches(); err == nil { + iterFunc := func(reference *plumbing.Reference) error { + if name == reference.Name().Short() { + exist = true + return nil + } + return nil + } + _ = iter.ForEach(iterFunc) + } + return exist +} + // GetCurrentBranch retrieves the current branch of a repository func GetCurrentBranch(repository *git.Repository) (string, error) { branchRefs, err := repository.Branches() diff --git a/pkg/recipe/recipe.go b/pkg/recipe/recipe.go index 52e83b7d..57f840fb 100644 --- a/pkg/recipe/recipe.go +++ b/pkg/recipe/recipe.go @@ -625,8 +625,8 @@ func GetDefaultBranch(repo *git.Repository, recipeName string) (plumbing.Referen } branch := "master" - if _, err := repo.Branch("master"); err != nil { - if _, err := repo.Branch("main"); err != nil { + if !gitPkg.HasBranch(repo, "master") { + if !gitPkg.HasBranch(repo, "main") { return "", fmt.Errorf("failed to select default branch in %s", recipeDir) } branch = "main"