github.com/redhat-appstudio/e2e-tests@v0.0.0-20240520140907-9709f6f59323/pkg/clients/github/git.go (about)

     1  package github
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  	"time"
     8  
     9  	. "github.com/onsi/gomega"
    10  
    11  	"github.com/google/go-github/v44/github"
    12  )
    13  
    14  func (g *Github) DeleteRef(repository, branchName string) error {
    15  	_, err := g.client.Git.DeleteRef(context.Background(), g.organization, repository, fmt.Sprintf(HEADS, branchName))
    16  	if err != nil {
    17  		return err
    18  	}
    19  	return nil
    20  }
    21  
    22  // CreateRef creates a new ref (GitHub branch) in a specified GitHub repository,
    23  // that will be based on the commit specified with sha. If sha is not specified
    24  // the latest commit from base branch will be used.
    25  func (g *Github) CreateRef(repository, baseBranchName, sha, newBranchName string) error {
    26  	ctx := context.Background()
    27  	ref, _, err := g.client.Git.GetRef(ctx, g.organization, repository, fmt.Sprintf(HEADS, baseBranchName))
    28  	if err != nil {
    29  		return fmt.Errorf("error when getting the base branch name '%s' for the repo '%s': %+v", baseBranchName, repository, err)
    30  	}
    31  
    32  	ref.Ref = github.String(fmt.Sprintf(HEADS, newBranchName))
    33  
    34  	if sha != "" {
    35  		ref.Object.SHA = &sha
    36  	}
    37  
    38  	_, _, err = g.client.Git.CreateRef(ctx, g.organization, repository, ref)
    39  	if err != nil {
    40  		return fmt.Errorf("error when creating a new branch '%s' for the repo '%s': %+v", newBranchName, repository, err)
    41  	}
    42  	Eventually(func(gomega Gomega) {
    43  		exist, err := g.ExistsRef(repository, newBranchName)
    44  		gomega.Expect((err)).NotTo(HaveOccurred())
    45  		gomega.Expect(exist).To(BeTrue())
    46  
    47  	}, 2*time.Minute, 2*time.Second).Should(Succeed()) //Wait for the branch to actually exist
    48  	return nil
    49  }
    50  
    51  func (g *Github) ExistsRef(repository, branchName string) (bool, error) {
    52  	_, _, err := g.client.Git.GetRef(context.Background(), g.organization, repository, fmt.Sprintf(HEADS, branchName))
    53  	if err != nil {
    54  		if strings.Contains(err.Error(), "404 Not Found") {
    55  			return false, nil
    56  		} else {
    57  			return false, fmt.Errorf("error when getting the branch '%s' for the repo '%s': %+v", branchName, repository, err)
    58  		}
    59  	}
    60  	return true, nil
    61  }