github.com/google/go-github/v68@v68.0.0/github/pulls.go (about)

     1  // Copyright 2013 The go-github AUTHORS. All rights reserved.
     2  //
     3  // Use of this source code is governed by a BSD-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package github
     7  
     8  import (
     9  	"bytes"
    10  	"context"
    11  	"errors"
    12  	"fmt"
    13  )
    14  
    15  // PullRequestsService handles communication with the pull request related
    16  // methods of the GitHub API.
    17  //
    18  // GitHub API docs: https://docs.github.com/rest/pulls/
    19  type PullRequestsService service
    20  
    21  // PullRequestAutoMerge represents the "auto_merge" response for a PullRequest.
    22  type PullRequestAutoMerge struct {
    23  	EnabledBy     *User   `json:"enabled_by,omitempty"`
    24  	MergeMethod   *string `json:"merge_method,omitempty"`
    25  	CommitTitle   *string `json:"commit_title,omitempty"`
    26  	CommitMessage *string `json:"commit_message,omitempty"`
    27  }
    28  
    29  // PullRequest represents a GitHub pull request on a repository.
    30  type PullRequest struct {
    31  	ID                  *int64                `json:"id,omitempty"`
    32  	Number              *int                  `json:"number,omitempty"`
    33  	State               *string               `json:"state,omitempty"`
    34  	Locked              *bool                 `json:"locked,omitempty"`
    35  	Title               *string               `json:"title,omitempty"`
    36  	Body                *string               `json:"body,omitempty"`
    37  	CreatedAt           *Timestamp            `json:"created_at,omitempty"`
    38  	UpdatedAt           *Timestamp            `json:"updated_at,omitempty"`
    39  	ClosedAt            *Timestamp            `json:"closed_at,omitempty"`
    40  	MergedAt            *Timestamp            `json:"merged_at,omitempty"`
    41  	Labels              []*Label              `json:"labels,omitempty"`
    42  	User                *User                 `json:"user,omitempty"`
    43  	Draft               *bool                 `json:"draft,omitempty"`
    44  	Merged              *bool                 `json:"merged,omitempty"`
    45  	Mergeable           *bool                 `json:"mergeable,omitempty"`
    46  	MergeableState      *string               `json:"mergeable_state,omitempty"`
    47  	MergedBy            *User                 `json:"merged_by,omitempty"`
    48  	MergeCommitSHA      *string               `json:"merge_commit_sha,omitempty"`
    49  	Rebaseable          *bool                 `json:"rebaseable,omitempty"`
    50  	Comments            *int                  `json:"comments,omitempty"`
    51  	Commits             *int                  `json:"commits,omitempty"`
    52  	Additions           *int                  `json:"additions,omitempty"`
    53  	Deletions           *int                  `json:"deletions,omitempty"`
    54  	ChangedFiles        *int                  `json:"changed_files,omitempty"`
    55  	URL                 *string               `json:"url,omitempty"`
    56  	HTMLURL             *string               `json:"html_url,omitempty"`
    57  	IssueURL            *string               `json:"issue_url,omitempty"`
    58  	StatusesURL         *string               `json:"statuses_url,omitempty"`
    59  	DiffURL             *string               `json:"diff_url,omitempty"`
    60  	PatchURL            *string               `json:"patch_url,omitempty"`
    61  	CommitsURL          *string               `json:"commits_url,omitempty"`
    62  	CommentsURL         *string               `json:"comments_url,omitempty"`
    63  	ReviewCommentsURL   *string               `json:"review_comments_url,omitempty"`
    64  	ReviewCommentURL    *string               `json:"review_comment_url,omitempty"`
    65  	ReviewComments      *int                  `json:"review_comments,omitempty"`
    66  	Assignee            *User                 `json:"assignee,omitempty"`
    67  	Assignees           []*User               `json:"assignees,omitempty"`
    68  	Milestone           *Milestone            `json:"milestone,omitempty"`
    69  	MaintainerCanModify *bool                 `json:"maintainer_can_modify,omitempty"`
    70  	AuthorAssociation   *string               `json:"author_association,omitempty"`
    71  	NodeID              *string               `json:"node_id,omitempty"`
    72  	RequestedReviewers  []*User               `json:"requested_reviewers,omitempty"`
    73  	AutoMerge           *PullRequestAutoMerge `json:"auto_merge,omitempty"`
    74  
    75  	// RequestedTeams is populated as part of the PullRequestEvent.
    76  	// See, https://docs.github.com/developers/webhooks-and-events/github-event-types#pullrequestevent for an example.
    77  	RequestedTeams []*Team `json:"requested_teams,omitempty"`
    78  
    79  	Links *PRLinks           `json:"_links,omitempty"`
    80  	Head  *PullRequestBranch `json:"head,omitempty"`
    81  	Base  *PullRequestBranch `json:"base,omitempty"`
    82  
    83  	// ActiveLockReason is populated only when LockReason is provided while locking the pull request.
    84  	// Possible values are: "off-topic", "too heated", "resolved", and "spam".
    85  	ActiveLockReason *string `json:"active_lock_reason,omitempty"`
    86  }
    87  
    88  func (p PullRequest) String() string {
    89  	return Stringify(p)
    90  }
    91  
    92  // PRLink represents a single link object from GitHub pull request _links.
    93  type PRLink struct {
    94  	HRef *string `json:"href,omitempty"`
    95  }
    96  
    97  // PRLinks represents the "_links" object in a GitHub pull request.
    98  type PRLinks struct {
    99  	Self           *PRLink `json:"self,omitempty"`
   100  	HTML           *PRLink `json:"html,omitempty"`
   101  	Issue          *PRLink `json:"issue,omitempty"`
   102  	Comments       *PRLink `json:"comments,omitempty"`
   103  	ReviewComments *PRLink `json:"review_comments,omitempty"`
   104  	ReviewComment  *PRLink `json:"review_comment,omitempty"`
   105  	Commits        *PRLink `json:"commits,omitempty"`
   106  	Statuses       *PRLink `json:"statuses,omitempty"`
   107  }
   108  
   109  // PullRequestBranch represents a base or head branch in a GitHub pull request.
   110  type PullRequestBranch struct {
   111  	Label *string     `json:"label,omitempty"`
   112  	Ref   *string     `json:"ref,omitempty"`
   113  	SHA   *string     `json:"sha,omitempty"`
   114  	Repo  *Repository `json:"repo,omitempty"`
   115  	User  *User       `json:"user,omitempty"`
   116  }
   117  
   118  // PullRequestListOptions specifies the optional parameters to the
   119  // PullRequestsService.List method.
   120  type PullRequestListOptions struct {
   121  	// State filters pull requests based on their state. Possible values are:
   122  	// open, closed, all. Default is "open".
   123  	State string `url:"state,omitempty"`
   124  
   125  	// Head filters pull requests by head user and branch name in the format of:
   126  	// "user:ref-name".
   127  	Head string `url:"head,omitempty"`
   128  
   129  	// Base filters pull requests by base branch name.
   130  	Base string `url:"base,omitempty"`
   131  
   132  	// Sort specifies how to sort pull requests. Possible values are: created,
   133  	// updated, popularity, long-running. Default is "created".
   134  	Sort string `url:"sort,omitempty"`
   135  
   136  	// Direction in which to sort pull requests. Possible values are: asc, desc.
   137  	// If Sort is "created" or not specified, Default is "desc", otherwise Default
   138  	// is "asc"
   139  	Direction string `url:"direction,omitempty"`
   140  
   141  	ListOptions
   142  }
   143  
   144  // List the pull requests for the specified repository.
   145  //
   146  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#list-pull-requests
   147  //
   148  //meta:operation GET /repos/{owner}/{repo}/pulls
   149  func (s *PullRequestsService) List(ctx context.Context, owner string, repo string, opts *PullRequestListOptions) ([]*PullRequest, *Response, error) {
   150  	u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo)
   151  	u, err := addOptions(u, opts)
   152  	if err != nil {
   153  		return nil, nil, err
   154  	}
   155  
   156  	req, err := s.client.NewRequest("GET", u, nil)
   157  	if err != nil {
   158  		return nil, nil, err
   159  	}
   160  
   161  	var pulls []*PullRequest
   162  	resp, err := s.client.Do(ctx, req, &pulls)
   163  	if err != nil {
   164  		return nil, resp, err
   165  	}
   166  
   167  	return pulls, resp, nil
   168  }
   169  
   170  // ListPullRequestsWithCommit returns pull requests associated with a commit SHA.
   171  //
   172  // The results may include open and closed pull requests.
   173  // By default, the PullRequestListOptions State filters for "open".
   174  //
   175  // GitHub API docs: https://docs.github.com/rest/commits/commits#list-pull-requests-associated-with-a-commit
   176  //
   177  //meta:operation GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls
   178  func (s *PullRequestsService) ListPullRequestsWithCommit(ctx context.Context, owner, repo, sha string, opts *ListOptions) ([]*PullRequest, *Response, error) {
   179  	u := fmt.Sprintf("repos/%v/%v/commits/%v/pulls", owner, repo, sha)
   180  	u, err := addOptions(u, opts)
   181  	if err != nil {
   182  		return nil, nil, err
   183  	}
   184  
   185  	req, err := s.client.NewRequest("GET", u, nil)
   186  	if err != nil {
   187  		return nil, nil, err
   188  	}
   189  
   190  	// TODO: remove custom Accept header when this API fully launches.
   191  	req.Header.Set("Accept", mediaTypeListPullsOrBranchesForCommitPreview)
   192  	var pulls []*PullRequest
   193  	resp, err := s.client.Do(ctx, req, &pulls)
   194  	if err != nil {
   195  		return nil, resp, err
   196  	}
   197  
   198  	return pulls, resp, nil
   199  }
   200  
   201  // Get a single pull request.
   202  //
   203  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#get-a-pull-request
   204  //
   205  //meta:operation GET /repos/{owner}/{repo}/pulls/{pull_number}
   206  func (s *PullRequestsService) Get(ctx context.Context, owner string, repo string, number int) (*PullRequest, *Response, error) {
   207  	u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number)
   208  	req, err := s.client.NewRequest("GET", u, nil)
   209  	if err != nil {
   210  		return nil, nil, err
   211  	}
   212  
   213  	pull := new(PullRequest)
   214  	resp, err := s.client.Do(ctx, req, pull)
   215  	if err != nil {
   216  		return nil, resp, err
   217  	}
   218  
   219  	return pull, resp, nil
   220  }
   221  
   222  // GetRaw gets a single pull request in raw (diff or patch) format.
   223  //
   224  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#get-a-pull-request
   225  //
   226  //meta:operation GET /repos/{owner}/{repo}/pulls/{pull_number}
   227  func (s *PullRequestsService) GetRaw(ctx context.Context, owner string, repo string, number int, opts RawOptions) (string, *Response, error) {
   228  	u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number)
   229  	req, err := s.client.NewRequest("GET", u, nil)
   230  	if err != nil {
   231  		return "", nil, err
   232  	}
   233  
   234  	switch opts.Type {
   235  	case Diff:
   236  		req.Header.Set("Accept", mediaTypeV3Diff)
   237  	case Patch:
   238  		req.Header.Set("Accept", mediaTypeV3Patch)
   239  	default:
   240  		return "", nil, fmt.Errorf("unsupported raw type %d", opts.Type)
   241  	}
   242  
   243  	var buf bytes.Buffer
   244  	resp, err := s.client.Do(ctx, req, &buf)
   245  	if err != nil {
   246  		return "", resp, err
   247  	}
   248  
   249  	return buf.String(), resp, nil
   250  }
   251  
   252  // NewPullRequest represents a new pull request to be created.
   253  type NewPullRequest struct {
   254  	Title *string `json:"title,omitempty"`
   255  	// The name of the branch where your changes are implemented. For
   256  	// cross-repository pull requests in the same network, namespace head with
   257  	// a user like this: username:branch.
   258  	Head     *string `json:"head,omitempty"`
   259  	HeadRepo *string `json:"head_repo,omitempty"`
   260  	// The name of the branch you want the changes pulled into. This should be
   261  	// an existing branch on the current repository. You cannot submit a pull
   262  	// request to one repository that requests a merge to a base of another
   263  	// repository.
   264  	Base                *string `json:"base,omitempty"`
   265  	Body                *string `json:"body,omitempty"`
   266  	Issue               *int    `json:"issue,omitempty"`
   267  	MaintainerCanModify *bool   `json:"maintainer_can_modify,omitempty"`
   268  	Draft               *bool   `json:"draft,omitempty"`
   269  }
   270  
   271  // Create a new pull request on the specified repository.
   272  //
   273  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#create-a-pull-request
   274  //
   275  //meta:operation POST /repos/{owner}/{repo}/pulls
   276  func (s *PullRequestsService) Create(ctx context.Context, owner string, repo string, pull *NewPullRequest) (*PullRequest, *Response, error) {
   277  	u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo)
   278  	req, err := s.client.NewRequest("POST", u, pull)
   279  	if err != nil {
   280  		return nil, nil, err
   281  	}
   282  
   283  	p := new(PullRequest)
   284  	resp, err := s.client.Do(ctx, req, p)
   285  	if err != nil {
   286  		return nil, resp, err
   287  	}
   288  
   289  	return p, resp, nil
   290  }
   291  
   292  // PullRequestBranchUpdateOptions specifies the optional parameters to the
   293  // PullRequestsService.UpdateBranch method.
   294  type PullRequestBranchUpdateOptions struct {
   295  	// ExpectedHeadSHA specifies the most recent commit on the pull request's branch.
   296  	// Default value is the SHA of the pull request's current HEAD ref.
   297  	ExpectedHeadSHA *string `json:"expected_head_sha,omitempty"`
   298  }
   299  
   300  // PullRequestBranchUpdateResponse specifies the response of pull request branch update.
   301  type PullRequestBranchUpdateResponse struct {
   302  	Message *string `json:"message,omitempty"`
   303  	URL     *string `json:"url,omitempty"`
   304  }
   305  
   306  // UpdateBranch updates the pull request branch with latest upstream changes.
   307  //
   308  // This method might return an AcceptedError and a status code of
   309  // 202. This is because this is the status that GitHub returns to signify that
   310  // it has now scheduled the update of the pull request branch in a background task.
   311  // A follow up request, after a delay of a second or so, should result
   312  // in a successful request.
   313  //
   314  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#update-a-pull-request-branch
   315  //
   316  //meta:operation PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch
   317  func (s *PullRequestsService) UpdateBranch(ctx context.Context, owner, repo string, number int, opts *PullRequestBranchUpdateOptions) (*PullRequestBranchUpdateResponse, *Response, error) {
   318  	u := fmt.Sprintf("repos/%v/%v/pulls/%d/update-branch", owner, repo, number)
   319  
   320  	req, err := s.client.NewRequest("PUT", u, opts)
   321  	if err != nil {
   322  		return nil, nil, err
   323  	}
   324  
   325  	// TODO: remove custom Accept header when this API fully launches.
   326  	req.Header.Set("Accept", mediaTypeUpdatePullRequestBranchPreview)
   327  
   328  	p := new(PullRequestBranchUpdateResponse)
   329  	resp, err := s.client.Do(ctx, req, p)
   330  	if err != nil {
   331  		return nil, resp, err
   332  	}
   333  
   334  	return p, resp, nil
   335  }
   336  
   337  type pullRequestUpdate struct {
   338  	Title               *string `json:"title,omitempty"`
   339  	Body                *string `json:"body,omitempty"`
   340  	State               *string `json:"state,omitempty"`
   341  	Base                *string `json:"base,omitempty"`
   342  	MaintainerCanModify *bool   `json:"maintainer_can_modify,omitempty"`
   343  }
   344  
   345  // Edit a pull request.
   346  // pull must not be nil.
   347  //
   348  // The following fields are editable: Title, Body, State, Base.Ref and MaintainerCanModify.
   349  // Base.Ref updates the base branch of the pull request.
   350  //
   351  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#update-a-pull-request
   352  //
   353  //meta:operation PATCH /repos/{owner}/{repo}/pulls/{pull_number}
   354  func (s *PullRequestsService) Edit(ctx context.Context, owner string, repo string, number int, pull *PullRequest) (*PullRequest, *Response, error) {
   355  	if pull == nil {
   356  		return nil, nil, errors.New("pull must be provided")
   357  	}
   358  
   359  	u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number)
   360  
   361  	update := &pullRequestUpdate{
   362  		Title:               pull.Title,
   363  		Body:                pull.Body,
   364  		State:               pull.State,
   365  		MaintainerCanModify: pull.MaintainerCanModify,
   366  	}
   367  	// avoid updating the base branch when closing the Pull Request
   368  	// - otherwise the GitHub API server returns a "Validation Failed" error:
   369  	// "Cannot change base branch of closed pull request".
   370  	if pull.Base != nil && pull.GetState() != "closed" {
   371  		update.Base = pull.Base.Ref
   372  	}
   373  
   374  	req, err := s.client.NewRequest("PATCH", u, update)
   375  	if err != nil {
   376  		return nil, nil, err
   377  	}
   378  
   379  	p := new(PullRequest)
   380  	resp, err := s.client.Do(ctx, req, p)
   381  	if err != nil {
   382  		return nil, resp, err
   383  	}
   384  
   385  	return p, resp, nil
   386  }
   387  
   388  // ListCommits lists the commits in a pull request.
   389  //
   390  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#list-commits-on-a-pull-request
   391  //
   392  //meta:operation GET /repos/{owner}/{repo}/pulls/{pull_number}/commits
   393  func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, repo string, number int, opts *ListOptions) ([]*RepositoryCommit, *Response, error) {
   394  	u := fmt.Sprintf("repos/%v/%v/pulls/%d/commits", owner, repo, number)
   395  	u, err := addOptions(u, opts)
   396  	if err != nil {
   397  		return nil, nil, err
   398  	}
   399  
   400  	req, err := s.client.NewRequest("GET", u, nil)
   401  	if err != nil {
   402  		return nil, nil, err
   403  	}
   404  
   405  	var commits []*RepositoryCommit
   406  	resp, err := s.client.Do(ctx, req, &commits)
   407  	if err != nil {
   408  		return nil, resp, err
   409  	}
   410  
   411  	return commits, resp, nil
   412  }
   413  
   414  // ListFiles lists the files in a pull request.
   415  //
   416  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#list-pull-requests-files
   417  //
   418  //meta:operation GET /repos/{owner}/{repo}/pulls/{pull_number}/files
   419  func (s *PullRequestsService) ListFiles(ctx context.Context, owner string, repo string, number int, opts *ListOptions) ([]*CommitFile, *Response, error) {
   420  	u := fmt.Sprintf("repos/%v/%v/pulls/%d/files", owner, repo, number)
   421  	u, err := addOptions(u, opts)
   422  	if err != nil {
   423  		return nil, nil, err
   424  	}
   425  
   426  	req, err := s.client.NewRequest("GET", u, nil)
   427  	if err != nil {
   428  		return nil, nil, err
   429  	}
   430  
   431  	var commitFiles []*CommitFile
   432  	resp, err := s.client.Do(ctx, req, &commitFiles)
   433  	if err != nil {
   434  		return nil, resp, err
   435  	}
   436  
   437  	return commitFiles, resp, nil
   438  }
   439  
   440  // IsMerged checks if a pull request has been merged.
   441  //
   442  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#check-if-a-pull-request-has-been-merged
   443  //
   444  //meta:operation GET /repos/{owner}/{repo}/pulls/{pull_number}/merge
   445  func (s *PullRequestsService) IsMerged(ctx context.Context, owner string, repo string, number int) (bool, *Response, error) {
   446  	u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number)
   447  	req, err := s.client.NewRequest("GET", u, nil)
   448  	if err != nil {
   449  		return false, nil, err
   450  	}
   451  
   452  	resp, err := s.client.Do(ctx, req, nil)
   453  	merged, err := parseBoolResponse(err)
   454  	return merged, resp, err
   455  }
   456  
   457  // PullRequestMergeResult represents the result of merging a pull request.
   458  type PullRequestMergeResult struct {
   459  	SHA     *string `json:"sha,omitempty"`
   460  	Merged  *bool   `json:"merged,omitempty"`
   461  	Message *string `json:"message,omitempty"`
   462  }
   463  
   464  // PullRequestOptions lets you define how a pull request will be merged.
   465  type PullRequestOptions struct {
   466  	CommitTitle string // Title for the automatic commit message. (Optional.)
   467  	SHA         string // SHA that pull request head must match to allow merge. (Optional.)
   468  
   469  	// The merge method to use. Possible values include: "merge", "squash", and "rebase" with the default being merge. (Optional.)
   470  	MergeMethod string
   471  
   472  	// If false, an empty string commit message will use the default commit message. If true, an empty string commit message will be used.
   473  	DontDefaultIfBlank bool
   474  }
   475  
   476  type pullRequestMergeRequest struct {
   477  	CommitMessage *string `json:"commit_message,omitempty"`
   478  	CommitTitle   string  `json:"commit_title,omitempty"`
   479  	MergeMethod   string  `json:"merge_method,omitempty"`
   480  	SHA           string  `json:"sha,omitempty"`
   481  }
   482  
   483  // Merge a pull request.
   484  // commitMessage is an extra detail to append to automatic commit message.
   485  //
   486  // GitHub API docs: https://docs.github.com/rest/pulls/pulls#merge-a-pull-request
   487  //
   488  //meta:operation PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge
   489  func (s *PullRequestsService) Merge(ctx context.Context, owner string, repo string, number int, commitMessage string, options *PullRequestOptions) (*PullRequestMergeResult, *Response, error) {
   490  	u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number)
   491  
   492  	pullRequestBody := &pullRequestMergeRequest{}
   493  	if commitMessage != "" {
   494  		pullRequestBody.CommitMessage = &commitMessage
   495  	}
   496  	if options != nil {
   497  		pullRequestBody.CommitTitle = options.CommitTitle
   498  		pullRequestBody.MergeMethod = options.MergeMethod
   499  		pullRequestBody.SHA = options.SHA
   500  		if options.DontDefaultIfBlank && commitMessage == "" {
   501  			pullRequestBody.CommitMessage = &commitMessage
   502  		}
   503  	}
   504  	req, err := s.client.NewRequest("PUT", u, pullRequestBody)
   505  	if err != nil {
   506  		return nil, nil, err
   507  	}
   508  
   509  	mergeResult := new(PullRequestMergeResult)
   510  	resp, err := s.client.Do(ctx, req, mergeResult)
   511  	if err != nil {
   512  		return nil, resp, err
   513  	}
   514  
   515  	return mergeResult, resp, nil
   516  }