package git

import (
	"github.com/go-git/go-git/v5"
	"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()
	if err != nil {
		return "", err
	}

	headRef, err := repository.Head()
	if err != nil {
		return "", err
	}

	var currentBranchName string
	err = branchRefs.ForEach(func(branchRef *plumbing.Reference) error {
		if branchRef.Hash() == headRef.Hash() {
			currentBranchName = branchRef.Name().String()

			return nil
		}

		return nil
	})
	if err != nil {
		return "", err
	}

	return currentBranchName, nil
}