-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
231 lines (215 loc) · 6.66 KB
/
main.go
File metadata and controls
231 lines (215 loc) · 6.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package main
import (
"context"
"encoding/json"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type BaseData struct {
Text string
}
func handleGithubError(resp *github.Response, err error, s string) {
if err != nil {
log.Println(s)
log.Println(err, resp)
}
}
func pullRequestHandler(w http.ResponseWriter, r *http.Request, client *github.Client, ctx *context.Context) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
var p github.PullRequestEvent
err = json.Unmarshal(body, &p)
if err != nil {
panic(err)
}
// now handle p
switch act := *p.Action; act {
case "opened":
comment := &github.IssueComment{
Body: github.String("Hi, I am helpbot, I will be managing this PR!"),
}
tail := strings.TrimPrefix(*p.PullRequest.URL, "https://api.github.com/repos/")
owner := strings.Split(tail, "/")[0]
repo := strings.Split(tail, "/")[1]
number, _ := strconv.ParseInt(strings.Split(tail, "/")[3], 10, 64)
_, resp, err := client.Issues.CreateComment(*ctx, owner, repo, int(number), comment)
handleGithubError(resp, err, "cannot create initial comment")
default:
return
}
}
// Look for /merge in text
func commentMerge(s string) bool {
var mergeRegExp = regexp.MustCompile(`\/merge`)
matched := mergeRegExp.MatchString(s)
return matched
}
func commentForceMerge(s string) bool {
var mergeRegExp = regexp.MustCompile(`\/forcemerge`)
matched := mergeRegExp.MatchString(s)
return matched
}
// Get type of comment author
type CommentAuthor struct {
Comment struct {
AuthorAssociation string `json:"author_association"`
} `json:"comment"`
}
func commentLabel(s string, labels []*github.Label) []string {
var ret []string
var lab github.Label
for i := 0; i < len(labels); i++ {
lab = *labels[i]
var mergeRegExp = regexp.MustCompile(`\/` + *lab.Name)
matched := mergeRegExp.MatchString(s)
if matched {
ret = append(ret, *lab.Name)
}
}
return ret
}
func handleLabels(s string, client *github.Client, ctx *context.Context, owner string, repo string, number int64) {
repLabels, resp, err := client.Issues.ListLabels(*ctx, owner, repo, nil)
handleGithubError(resp, err, "Issue listing labels")
labels := commentLabel(s, repLabels)
client.Issues.AddLabelsToIssue(*ctx, owner, repo, int(number), labels)
}
func handleReviews(s string, client *github.Client, ctx *context.Context, owner string, repo string, number int64) {
var regExp = regexp.MustCompile(`\/review@(\w+)`)
res := regExp.FindAllString(s, -1)
var users []string
for i := 0; i < len(res); i++ {
users = append(users, strings.ToLower(strings.Split(res[i], "@")[1]))
}
if len(users) > 0 {
var gUsers []string
var bUsers []string
collabs, resp, err := client.Repositories.ListCollaborators(*ctx, owner, repo, nil)
handleGithubError(resp, err, "error getting collaborators")
if len(collabs) > 0 {
for i := 0; i < len(collabs); i++ {
found := false
ele := collabs[i]
name := strings.ToLower(*ele.Login)
for j := 0; j < len(users); j++ {
if name == users[j] {
gUsers = append(gUsers, *ele.Login)
found = true
}
}
if found != true {
bUsers = append(bUsers, name)
}
}
// now request reviews
reviewers := github.ReviewersRequest{Reviewers: gUsers}
if len(reviewers.Reviewers) > 0 {
_, resp, err := client.PullRequests.RequestReviewers(*ctx, owner, repo, int(number), reviewers)
handleGithubError(resp, err, "problem adding reviewers")
}
}
}
}
// query for tests passing, get status of last commit to PR
func testState(client *github.Client, ctx *context.Context, owner string, repo string, number int64) string {
commits, resp, err := client.PullRequests.ListCommits(*ctx, owner, repo, int(number), nil)
handleGithubError(resp, err, "problem getting pull requests")
commit := commits[len(commits)-1]
statuses, resp, err := client.Repositories.ListStatuses(*ctx, owner, repo, *commit.SHA, nil)
handleGithubError(resp, err, "could not get status")
status := statuses[0]
return *status.State
}
func pullCommentHandler(w http.ResponseWriter, r *http.Request, client *github.Client, ctx *context.Context) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
var p github.IssueCommentEvent
err = json.Unmarshal(body, &p)
if err != nil {
panic(err)
}
// now handle p
act := *p.Action
if act != "deleted" {
tail := strings.TrimPrefix(*p.Issue.URL, "https://api.github.com/repos/")
owner := strings.Split(tail, "/")[0]
repo := strings.Split(tail, "/")[1]
number, _ := strconv.ParseInt(strings.Split(tail, "/")[3], 10, 64)
// handle merge here as special case
merg := commentMerge(*p.Comment.Body)
forceMerge := commentForceMerge(*p.Comment.Body)
var auth CommentAuthor
err = json.Unmarshal(body, &auth)
if err != nil {
log.Println(err)
}
if forceMerge {
if auth.Comment.AuthorAssociation == "OWNER" {
message := "Merging away, authorized by " + *p.Comment.User.Login
client.PullRequests.Merge(*ctx, owner, repo, int(number), message, nil)
merg = false
}
}
// only merge if request from proper person
if merg {
switch auth.Comment.AuthorAssociation {
case
"OWNER",
"COLLABORATOR",
"MEMBER":
message := "Merging away, authorized by " + *p.Comment.User.Login
status := testState(client, ctx, owner, repo, number)
if status == "success" {
client.PullRequests.Merge(*ctx, owner, repo, int(number), message, nil)
} else {
comment := &github.IssueComment{
Body: github.String("Cannot merge until tests pass"),
}
_, resp, err := client.Issues.CreateComment(*ctx, owner, repo, int(number), comment)
handleGithubError(resp, err, "cannot create initial comment")
}
}
}
handleLabels(*p.Comment.Body, client, ctx, owner, repo, number)
// now handle reviews
handleReviews(*p.Comment.Body, client, ctx, owner, repo, number)
}
}
func baseHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/base.html"))
t := BaseData{Text: "Hello, this is just a webpage"}
tmpl.Execute(w, t)
}
func main() {
var token = os.Getenv("TOKEN")
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
http.HandleFunc("/", baseHandler)
http.HandleFunc("/pull_request", func(w http.ResponseWriter, r *http.Request) {
pullRequestHandler(w, r, client, &ctx)
})
http.HandleFunc("/issue_comment", func(w http.ResponseWriter, r *http.Request) {
pullCommentHandler(w, r, client, &ctx)
})
var port = os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.ListenAndServe(":"+port, nil)
}