github.com/redhat-appstudio/e2e-tests@v0.0.0-20230619105049-9a422b2094d7/pkg/apis/github/git.go (about)

     1  package github
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/google/go-github/v44/github"
     9  )
    10  
    11  func (g *Github) DeleteRef(repository, branchName string) error {
    12  	_, err := g.client.Git.DeleteRef(context.Background(), g.organization, repository, fmt.Sprintf("heads/%s", branchName))
    13  	if err != nil {
    14  		return err
    15  	}
    16  	return nil
    17  }
    18  
    19  // CreateRef creates a new ref (GitHub branch) in a specified GitHub repository,
    20  // that will be based on the latest commit from a specified branch name
    21  func (g *Github) CreateRef(repository, baseBranchName, newBranchName string) error {
    22  	ctx := context.Background()
    23  	ref, _, err := g.client.Git.GetRef(ctx, g.organization, repository, fmt.Sprintf("heads/%s", baseBranchName))
    24  	if err != nil {
    25  		return fmt.Errorf("error when getting the base branch name '%s' for the repo '%s': %+v", baseBranchName, repository, err)
    26  	}
    27  	ref.Ref = github.String(fmt.Sprintf("heads/%s", newBranchName))
    28  	_, _, err = g.client.Git.CreateRef(ctx, g.organization, repository, ref)
    29  	if err != nil {
    30  		return fmt.Errorf("error when creating a new branch '%s' for the repo '%s': %+v", newBranchName, repository, err)
    31  	}
    32  	return nil
    33  }
    34  
    35  func (g *Github) ExistsRef(repository, branchName string) (bool, error) {
    36  	_, _, err := g.client.Git.GetRef(context.Background(), g.organization, repository, fmt.Sprintf("heads/%s", branchName))
    37  	if err != nil {
    38  		if strings.Contains(err.Error(), "404 Not Found") {
    39  			return false, nil
    40  		} else {
    41  			return false, fmt.Errorf("error when getting the branch '%s' for the repo '%s': %+v", branchName, repository, err)
    42  		}
    43  	}
    44  	return true, nil
    45  }