Skip to content

Commit

Permalink
Add PullRequestResource functionality for updating labels and comments.
Browse files Browse the repository at this point in the history
Missing from this change:
* Statuses, since this might involve more discussion on the set of statuses
  that we want to support.
* Updating from changes to the raw payloads. Unclear how we want to
  handle these at the moment. Punting on this for now.

First step for supporting #778.

Co-authored-by: Dan Lorenc <[email protected]>
Co-authored-by: Billy Lynch <[email protected]>
  • Loading branch information
wlynch and dlorenc committed Jun 19, 2019
1 parent fc6ef39 commit b8b43ed
Show file tree
Hide file tree
Showing 132 changed files with 50,740 additions and 121 deletions.
54 changes: 54 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions cmd/pullrequest-init/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# pullrequest-init

pullrequest-init fetches pull request data from the given URL and places it in
the provided path.

This binary outputs a generic pull request object into `pr.json`, as well as
provider specific payloads.

Currently supported providers:

* GitHub

## Generic pull request payload

The payload generated by default aims to abstract the base features of any pull
request provider. Since there is no one true spec for pull requests, not every
feature may be available. The payload is output to `$PATH/pr.json` and looks
like:

```json
{
"Type": "github",
"ID": 188184279,
"Head": {
"Repo": "https://github.com/wlynch/test.git",
"Branch": "dev",
"SHA": "9bcde245572c74329827acdcab88792ebb84d578"
},
"Base": {
"Repo": "https://github.com/wlynch/test.git",
"Branch": "master",
"SHA": "1e80c83ed01e187669b836096335d1c8a2c57182"
},
"Comments": [
{
"Text": "test comment",
"Author": "wlynch",
"ID": 494418247,
"Raw": "/tmp/prtest/github/comments/494418247.json"
}
],
"Labels": [
{
"Text": "my-label"
}
],
"Raw": "/tmp/prtest/github/pr.json"
}
```

## GitHub

GitHub pull requests will output these additional files:

* `$PATH/github/pr.json`: The raw GitHub payload as specified by
https://developer.github.com/v3/pulls/#get-a-single-pull-request
* `$PATH/github/comments/#.json`: Comments associated to the PR as specified
by https://developer.github.com/v3/issues/comments/#get-a-single-comment

For now, these files are *read-only*.

The binary will look for GitHub credentials in the `${GITHUBTOKEN}` environment
variable. This should generally be specified as a secret with the field name
`githubToken` in the `PullRequestResource` definition.
232 changes: 232 additions & 0 deletions cmd/pullrequest-init/fake_github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
package main

import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"

"github.com/google/go-github/github"
"github.com/gorilla/mux"
)

const (
// ErrorKeyword is a magic const used to denote PRs/Comments that should
// return errors to the client to simulate issues communicating with GitHub.
ErrorKeyword = "~~ERROR~~"
)

// key defines keys for associating data to PRs/issues in the fake server.
type key struct {
owner string
repo string
id int64
}

// FakeGitHub is a fake GitHub server for use in tests.
type FakeGitHub struct {
*mux.Router

pr map[key]*github.PullRequest
// GitHub references comments in 2 ways:
// 1) List by issue (PR) ID.
// 2) Get by comment ID.
// We need to store references to both to emulate the API properly.
prComments map[key][]*github.IssueComment
comments map[key]*github.IssueComment
}

// NewFakeGitHub returns a new FakeGitHub.
func NewFakeGitHub() *FakeGitHub {
s := &FakeGitHub{
Router: mux.NewRouter(),
pr: make(map[key]*github.PullRequest),
prComments: make(map[key][]*github.IssueComment),
comments: make(map[key]*github.IssueComment),
}
s.HandleFunc("/repos/{owner}/{repo}/pulls/{number}", s.getPullRequest).Methods(http.MethodGet)
s.HandleFunc("/repos/{owner}/{repo}/issues/{number}/comments", s.getComments).Methods(http.MethodGet)
s.HandleFunc("/repos/{owner}/{repo}/issues/{number}/comments", s.createComment).Methods(http.MethodPost)
s.HandleFunc("/repos/{owner}/{repo}/issues/comments/{number}", s.updateComment).Methods(http.MethodPatch)
s.HandleFunc("/repos/{owner}/{repo}/issues/comments/{number}", s.deleteComment).Methods(http.MethodDelete)
s.HandleFunc("/repos/{owner}/{repo}/issues/{number}/labels", s.updateLabels).Methods(http.MethodPut)

return s
}

func prKey(r *http.Request) (key, error) {
pr, err := strconv.ParseInt(mux.Vars(r)["number"], 10, 64)
if err != nil {
return key{}, err
}
return key{
owner: mux.Vars(r)["owner"],
repo: mux.Vars(r)["repo"],
id: pr,
}, nil
}

// AddPullRequest adds the given pull request to the fake GitHub server.
// This is done as a convenience over implementing PullReqests.Create in the
// GitHub server since that method takes in a different type (NewPullRequest).
func (g *FakeGitHub) AddPullRequest(pr *github.PullRequest) {
key := key{
owner: pr.GetBase().GetUser().GetLogin(),
repo: pr.GetBase().GetRepo().GetName(),
id: pr.GetID(),
}
g.pr[key] = pr
}

func (g *FakeGitHub) getPullRequest(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

pr, ok := g.pr[key]
if !ok {
http.Error(w, fmt.Sprintf("%v not found", key), http.StatusNotFound)
return
}

if err := json.NewEncoder(w).Encode(pr); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

func (g *FakeGitHub) getComments(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

comments, ok := g.prComments[key]
if !ok {
comments = []*github.IssueComment{}
}
if err := json.NewEncoder(w).Encode(comments); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

func (g *FakeGitHub) createComment(w http.ResponseWriter, r *http.Request) {
prKey, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
c := new(github.IssueComment)
if err := json.NewDecoder(r.Body).Decode(c); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if strings.Contains(c.GetBody(), ErrorKeyword) {
http.Error(w, "intentional error", http.StatusInternalServerError)
return
}

c.ID = github.Int64(int64(len(g.comments) + 1))

if _, ok := g.prComments[prKey]; !ok {
g.prComments[prKey] = []*github.IssueComment{}
}
g.prComments[prKey] = append(g.prComments[prKey], c)

commentKey := key{
owner: prKey.owner,
repo: prKey.repo,
id: c.GetID(),
}
g.comments[commentKey] = c

if err := json.NewEncoder(w).Encode(c); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

func (g *FakeGitHub) updateComment(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
update := new(github.IssueComment)
if err := json.NewDecoder(r.Body).Decode(update); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if strings.Contains(update.GetBody(), ErrorKeyword) {
http.Error(w, "intentional error", http.StatusInternalServerError)
return
}

existing, ok := g.comments[key]
if !ok {
http.Error(w, fmt.Sprintf("comment %+v not found", key), http.StatusNotFound)
return
}

*existing = *update
w.WriteHeader(http.StatusOK)
}

func (g *FakeGitHub) deleteComment(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

if _, ok := g.comments[key]; !ok {
http.Error(w, fmt.Sprintf("comment %+v not found", key), http.StatusNotFound)
return
}

// Remove comment from PR storage. Not particularly efficient, but we don't
// generally expect this to be used for large number of comments in unit
// tests.
for k := range g.prComments {
for i, c := range g.prComments[k] {
if c.GetID() == key.id {
g.prComments[k] = append(g.prComments[k][:i], g.prComments[k][i+1:]...)
break
}
}
}
delete(g.comments, key)

w.WriteHeader(http.StatusOK)
}

func (g *FakeGitHub) updateLabels(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

pr, ok := g.pr[key]
if !ok {
http.Error(w, "pull request not found", http.StatusNotFound)
return
}

payload := []string{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pr.Labels = make([]*github.Label, 0, len(payload))
for _, l := range payload {
pr.Labels = append(pr.Labels, &github.Label{
Name: github.String(l),
})
}

w.WriteHeader(http.StatusOK)
}
Loading

0 comments on commit b8b43ed

Please sign in to comment.