github.com/jaylevin/jenkins-library@v1.230.4/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/v32/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.NewClient(config.Token, config.APIURL, "", []string{})
    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  
    37  	prRequest := github.NewPullRequest{
    38  		Title: &config.Title,
    39  		Head:  &config.Head,
    40  		Base:  &config.Base,
    41  		Body:  &config.Body,
    42  	}
    43  
    44  	newPR, resp, err := ghPRService.Create(ctx, config.Owner, config.Repository, &prRequest)
    45  	if err != nil {
    46  		log.Entry().Errorf("GitHub response code %v", resp.Status)
    47  		return errors.Wrap(err, "Error occurred when creating pull request")
    48  	}
    49  	log.Entry().Debugf("New pull request created: %v", newPR)
    50  
    51  	issueRequest := github.IssueRequest{
    52  		Labels:    &config.Labels,
    53  		Assignees: &config.Assignees,
    54  	}
    55  
    56  	updatedPr, resp, err := ghIssueService.Edit(ctx, config.Owner, config.Repository, newPR.GetNumber(), &issueRequest)
    57  	if err != nil {
    58  		log.Entry().Errorf("GitHub response code %v", resp.Status)
    59  		return errors.Wrap(err, "Error occurred when editing pull request")
    60  	}
    61  	log.Entry().Debugf("Updated pull request: %v", updatedPr)
    62  
    63  	return nil
    64  }