github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/githubCreatePullRequest.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/SAP/jenkins-library/pkg/log"
     7  	"github.com/SAP/jenkins-library/pkg/telemetry"
     8  	"github.com/google/go-github/v45/github"
     9  	"github.com/pkg/errors"
    10  
    11  	piperGithub "github.com/SAP/jenkins-library/pkg/github"
    12  )
    13  
    14  type githubPRService interface {
    15  	Create(ctx context.Context, owner string, repo string, pull *github.NewPullRequest) (*github.PullRequest, *github.Response, error)
    16  }
    17  
    18  type githubIssueService interface {
    19  	Edit(ctx context.Context, owner string, repo string, number int, issue *github.IssueRequest) (*github.Issue, *github.Response, error)
    20  }
    21  
    22  func githubCreatePullRequest(config githubCreatePullRequestOptions, telemetryData *telemetry.CustomData) {
    23  	// TODO provide parameter for trusted certs
    24  	ctx, client, err := piperGithub.NewClientBuilder(config.Token, config.APIURL).Build()
    25  	if err != nil {
    26  		log.Entry().WithError(err).Fatal("Failed to get GitHub client")
    27  	}
    28  
    29  	err = runGithubCreatePullRequest(ctx, &config, client.PullRequests, client.Issues)
    30  	if err != nil {
    31  		log.Entry().WithError(err).Fatal("Failed to create GitHub pull request")
    32  	}
    33  }
    34  
    35  func runGithubCreatePullRequest(ctx context.Context, config *githubCreatePullRequestOptions, ghPRService githubPRService, ghIssueService githubIssueService) error {
    36  	prRequest := github.NewPullRequest{
    37  		Title: &config.Title,
    38  		Head:  &config.Head,
    39  		Base:  &config.Base,
    40  		Body:  &config.Body,
    41  	}
    42  
    43  	newPR, resp, err := ghPRService.Create(ctx, config.Owner, config.Repository, &prRequest)
    44  	if err != nil {
    45  		log.Entry().Errorf("GitHub response code %v", resp.Status)
    46  		return errors.Wrap(err, "Error occurred when creating pull request")
    47  	}
    48  	log.Entry().Debugf("New pull request created: %v", newPR)
    49  
    50  	issueRequest := github.IssueRequest{
    51  		Labels:    &config.Labels,
    52  		Assignees: &config.Assignees,
    53  	}
    54  
    55  	updatedPr, resp, err := ghIssueService.Edit(ctx, config.Owner, config.Repository, newPR.GetNumber(), &issueRequest)
    56  	if err != nil {
    57  		log.Entry().Errorf("GitHub response code %v", resp.Status)
    58  		return errors.Wrap(err, "Error occurred when editing pull request")
    59  	}
    60  	log.Entry().Debugf("Updated pull request: %v", updatedPr)
    61  
    62  	return nil
    63  }