Use Search API for Pull Requests with go-github

320 Views Asked by At

Scenario: I receive a status webhook event from GitHub. I want to find any Pull Requests associated with the commit.

The StatusEvent contains the commit .SHA and a .Repo (Respository) object. This appears to be sufficient to find applicable PRs.

Issue: If the status event is triggered in response to checks performed on a PR in a respository separate from the commit, there are problems...

Attempt 1: The go-github package contains a PullRequestsService with .ListPullRequestsWithCommit method calling this GitHub API method. Unfortunately, this only seems to return PRs within the repo containing the commit. Meaning, it appears to ignore PRs created with commits from forked repos.

1

There are 1 best solutions below

0
On

Attempt 2: go-github has a SearchService.Issues method which accepts a query parameter. Using parameters type:pr SHA:<sha>, you get the issue "backing" the PR (not sure the proper terminology) -- regardless of the originating repo.

Then, using the PullRequestsService.Get method, you can get the actual PullRequest data.

Prototype code (use at your own risk):

commitSha := event.GetCommit().GetSHA()
ownerLogin := repo.GetOwner().GetLogin()

issues, _, err := client.Search.Issues(ctx, fmt.Sprintf("type:pr SHA:%s", commitSha), &github.SearchOptions{})
// if err != nil { ??? }
// if len(issues.Issues) == 0 { ??? }
issue := issue.Issue[0]
pr, _, err := client.PullRequests.Get(ctx, ownerLogin, issue.GetNumber())
// if err != nil { ??? }