/
github.go
465 lines (384 loc) · 12.3 KB
/
github.go
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
Copyright 2021 The CI/CD Operator Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package github
import (
"crypto/hmac"
"crypto/sha1"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/tmax-cloud/cd-operator/pkg/git"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// Client is a gitlab client struct
type Client struct {
GitAPIURL string
GitRepository string
GitToken string
GitWebhookSecret string
K8sClient client.Client
header map[string]string
}
// Init initiates the Client
func (c *Client) Init() error {
c.header = map[string]string{
"Accept": "application/vnd.github.v3+json",
}
if c.GitToken != "" {
c.header["Authorization"] = "token " + c.GitToken
}
return nil
}
// ParseWebhook parses a webhook body for github
func (c *Client) ParseWebhook(header http.Header, jsonString []byte) (*git.Webhook, error) {
var signature = strings.Replace(header.Get("x-hub-signature"), "sha1=", "", 1)
if err := Validate(c.GitWebhookSecret, signature, jsonString); err != nil {
return nil, err
}
eventType := git.EventType(header.Get("x-github-event"))
switch eventType {
case git.EventTypePullRequest:
return c.parsePullRequestWebhook(jsonString)
case git.EventTypePush:
return c.parsePushWebhook(jsonString)
case git.EventTypeIssueComment:
return c.parseIssueCommentWebhook(jsonString)
case git.EventTypePullRequestReview:
return c.parsePullRequestReviewWebhook(jsonString)
case git.EventTypePullRequestReviewComment:
return c.parsePullRequestReviewCommentWebhook(jsonString)
}
return nil, nil
}
// ListWebhook lists registered webhooks
func (c *Client) ListWebhook() ([]git.WebhookEntry, error) {
var apiURL = c.GitAPIURL + "/repos/" + c.GitRepository + "/hooks"
var entries []WebhookEntry
err := git.GetPaginatedRequest(apiURL, c.header, func() interface{} {
return &[]WebhookEntry{}
}, func(i interface{}) {
entries = append(entries, *i.(*[]WebhookEntry)...)
})
if err != nil {
return nil, err
}
var result []git.WebhookEntry
for _, e := range entries {
result = append(result, git.WebhookEntry{ID: e.ID, URL: e.Config.URL})
}
return result, nil
}
// RegisterWebhook registers our webhook server to the remote git server
func (c *Client) RegisterWebhook(url string) error {
var registrationBody RegistrationWebhookBody
var registrationConfig RegistrationWebhookBodyConfig
var apiURL = c.GitAPIURL + "/repos/" + c.GitRepository + "/hooks"
registrationBody.Name = "web"
registrationBody.Active = true
registrationBody.Events = []string{"*"}
registrationConfig.URL = url
registrationConfig.ContentType = "json"
registrationConfig.InsecureSsl = "0"
registrationConfig.Secret = c.GitWebhookSecret
registrationBody.Config = registrationConfig
if _, _, err := c.requestHTTP(http.MethodPost, apiURL, registrationBody); err != nil {
return err
}
return nil
}
// DeleteWebhook deletes registered webhook
func (c *Client) DeleteWebhook(id int) error {
var apiURL = c.GitAPIURL + "/repos/" + c.GitRepository + "/hooks/" + strconv.Itoa(id)
if _, _, err := c.requestHTTP(http.MethodDelete, apiURL, nil); err != nil {
return err
}
return nil
}
// ListCommitStatuses lists commit status of the specific commit
func (c *Client) ListCommitStatuses(ref string) ([]git.CommitStatus, error) {
apiURL := c.GitAPIURL + "/repos/" + c.GitRepository + "/commits/" + ref + "/statuses"
var statuses []CommitStatusResponse
err := git.GetPaginatedRequest(apiURL, c.header, func() interface{} {
return &[]CommitStatusResponse{}
}, func(i interface{}) {
statuses = append(statuses, *i.(*[]CommitStatusResponse)...)
})
if err != nil {
return nil, err
}
// Temp map for filtering duplicated contexts
tmp := map[string]struct{}{}
var resp []git.CommitStatus
for _, s := range statuses {
_, exist := tmp[s.Context]
if exist {
continue
}
tmp[s.Context] = struct{}{}
resp = append(resp, git.CommitStatus{
Context: s.Context,
State: git.CommitStatusState(s.State),
Description: s.Description,
TargetURL: s.TargetURL,
})
}
return resp, nil
}
// SetCommitStatus sets commit status for the specific commit
func (c *Client) SetCommitStatus(sha string, status git.CommitStatus) error {
var commitStatusBody CommitStatusRequest
// Don't set commit status if its' sha is a fake
if sha == git.FakeSha {
return nil
}
apiURL := c.GitAPIURL + "/repos/" + c.GitRepository + "/statuses/" + sha
commitStatusBody.State = string(status.State)
commitStatusBody.TargetURL = status.TargetURL
commitStatusBody.Description = status.Description
commitStatusBody.Context = status.Context
if _, _, err := c.requestHTTP(http.MethodPost, apiURL, commitStatusBody); err != nil {
return err
}
return nil
}
// GetUserInfo gets a user's information
func (c *Client) GetUserInfo(userName string) (*git.User, error) {
// userName is string!
apiURL := fmt.Sprintf("%s/users/%s", c.GitAPIURL, userName)
result, _, err := c.requestHTTP(http.MethodGet, apiURL, nil)
if err != nil {
return nil, err
}
var userInfo UserInfo
if err := json.Unmarshal(result, &userInfo); err != nil {
return nil, err
}
return &git.User{
ID: userInfo.ID,
Name: userInfo.UserName,
Email: userInfo.Email,
}, nil
}
// CanUserWriteToRepo decides if the user has write permission on the repo
func (c *Client) CanUserWriteToRepo(user git.User) (bool, error) {
// userName is string!
apiURL := fmt.Sprintf("%s/repos/%s/collaborators/%s/permission", c.GitAPIURL, c.GitRepository, user.Name)
result, _, err := c.requestHTTP(http.MethodGet, apiURL, nil)
if err != nil {
return false, err
}
var permission UserPermission
if err := json.Unmarshal(result, &permission); err != nil {
return false, err
}
return permission.Permission == "admin" || permission.Permission == "write", nil
}
// RegisterComment registers comment to an issue
func (c *Client) RegisterComment(_ git.IssueType, issueNo int, body string) error {
apiURL := fmt.Sprintf("%s/repos/%s/issues/%d/comments", c.GitAPIURL, c.GitRepository, issueNo)
commentBody := &CommentBody{Body: body}
if _, _, err := c.requestHTTP(http.MethodPost, apiURL, commentBody); err != nil {
return err
}
return nil
}
// ListPullRequests gets pull request list
func (c *Client) ListPullRequests(onlyOpen bool) ([]git.PullRequest, error) {
apiURL := fmt.Sprintf("%s/repos/%s/pulls", c.GitAPIURL, c.GitRepository)
if !onlyOpen {
apiURL += "?state=all"
}
var prs []PullRequest
err := git.GetPaginatedRequest(apiURL, c.header, func() interface{} {
return &[]PullRequest{}
}, func(i interface{}) {
prs = append(prs, *i.(*[]PullRequest)...)
})
if err != nil {
return nil, err
}
var result []git.PullRequest
for _, pr := range prs {
if !pr.Draft { // TODO - should it be here??
result = append(result, *convertPullRequestToShared(&pr))
}
}
return result, nil
}
// GetPullRequest gets PR given id
func (c *Client) GetPullRequest(id int) (*git.PullRequest, error) {
apiURL := fmt.Sprintf("%s/repos/%s/pulls/%d", c.GitAPIURL, c.GitRepository, id)
data, _, err := c.requestHTTP(http.MethodGet, apiURL, nil)
if err != nil {
return nil, err
}
pr := &PullRequest{}
if err := json.Unmarshal(data, &pr); err != nil {
return nil, err
}
return convertPullRequestToShared(pr), nil
}
// MergePullRequest merges a pull request
func (c *Client) MergePullRequest(id int, sha string, method git.MergeMethod, message string) error {
apiURL := fmt.Sprintf("%s/repos/%s/pulls/%d/merge", c.GitAPIURL, c.GitRepository, id)
tokens := strings.Split(message, "\n\n")
body := &MergeRequest{
CommitTitle: tokens[0],
MergeMethod: string(method),
Sha: sha,
}
if len(tokens) > 1 {
body.CommitMessage = strings.Join(tokens[1:], "\n\n")
}
_, _, err := c.requestHTTP(http.MethodPut, apiURL, body)
if err != nil {
return err
}
return nil
}
// GetPullRequestDiff gets diff of the pull request
func (c *Client) GetPullRequestDiff(id int) (*git.Diff, error) {
apiURL := fmt.Sprintf("%s/repos/%s/pulls/%d/files", c.GitAPIURL, c.GitRepository, id)
rawDiffs, _, err := c.requestHTTP(http.MethodGet, apiURL, nil)
if err != nil {
return nil, err
}
diffs := DiffFiles{}
if err := json.Unmarshal(rawDiffs, &diffs); err != nil {
return nil, err
}
var changes []git.Change
for _, d := range diffs {
prevName := d.PrevFilename
if prevName == "" {
prevName = d.Filename
}
changes = append(changes, git.Change{
Filename: d.Filename,
OldFilename: prevName,
Additions: d.Additions,
Deletions: d.Deletions,
Changes: d.Changes,
})
}
return &git.Diff{Changes: changes}, nil
}
// ListPullRequestCommits lists commits list of a pull request
func (c *Client) ListPullRequestCommits(id int) ([]git.Commit, error) {
apiURL := fmt.Sprintf("%s/repos/%s/pulls/%d/commits", c.GitAPIURL, c.GitRepository, id)
raw, _, err := c.requestHTTP(http.MethodGet, apiURL, nil)
if err != nil {
return nil, err
}
var resp []CommitResponse
if err := json.Unmarshal(raw, &resp); err != nil {
return nil, err
}
var commits []git.Commit
for _, commit := range resp {
commits = append(commits, git.Commit{
SHA: commit.SHA,
Message: commit.Commit.Message,
Author: git.User{
Name: commit.Commit.Author.Name,
Email: commit.Commit.Author.Email,
},
Committer: git.User{
Name: commit.Commit.Committer.Name,
Email: commit.Commit.Committer.Email,
},
})
}
return commits, nil
}
// SetLabel sets label to the issue id
func (c *Client) SetLabel(_ git.IssueType, id int, label string) error {
apiURL := fmt.Sprintf("%s/repos/%s/issues/%d/labels", c.GitAPIURL, c.GitRepository, id)
_, _, err := c.requestHTTP(http.MethodPost, apiURL, []LabelBody{{Name: label}})
if err != nil {
return err
}
return nil
}
// DeleteLabel deletes label from the issue id
func (c *Client) DeleteLabel(_ git.IssueType, id int, label string) error {
apiURL := fmt.Sprintf("%s/repos/%s/issues/%d/labels/%s", c.GitAPIURL, c.GitRepository, id, label)
_, _, err := c.requestHTTP(http.MethodDelete, apiURL, nil)
if err != nil {
return err
}
return nil
}
// GetBranch gets branch info
func (c *Client) GetBranch(branch string) (*git.Branch, error) {
apiURL := fmt.Sprintf("%s/repos/%s/branches/%s", c.GitAPIURL, c.GitRepository, branch)
raw, _, err := c.requestHTTP(http.MethodGet, apiURL, nil)
if err != nil {
return nil, err
}
resp := &BranchResponse{}
if err := json.Unmarshal(raw, resp); err != nil {
return nil, err
}
return &git.Branch{Name: resp.Name, CommitID: resp.Commit.Sha}, nil
}
func convertPullRequestToShared(pr *PullRequest) *git.PullRequest {
var labels []git.IssueLabel
for _, l := range pr.Labels {
labels = append(labels, git.IssueLabel{Name: l.Name})
}
return &git.PullRequest{
ID: pr.Number,
Title: pr.Title,
State: git.PullRequestState(pr.State),
Author: git.User{
ID: pr.User.ID,
Name: pr.User.Name,
},
URL: pr.URL,
Base: git.Base{Ref: pr.Base.Ref, Sha: pr.Base.Sha},
Head: git.Head{Ref: pr.Head.Ref, Sha: pr.Head.Sha},
Labels: labels,
Mergeable: pr.Mergeable,
}
}
func (c *Client) requestHTTP(method, apiURL string, data interface{}) ([]byte, http.Header, error) {
return git.RequestHTTP(method, apiURL, c.header, data)
}
// IsValidPayload validates the webhook payload
func IsValidPayload(secret, headerHash string, payload []byte) bool {
hash := HashPayload(secret, payload)
return hmac.Equal(
[]byte(hash),
[]byte(headerHash),
)
}
// HashPayload hashes the payload
func HashPayload(secret string, payloadBody []byte) string {
hm := hmac.New(sha1.New, []byte(secret))
_, err := hm.Write(payloadBody)
sum := hm.Sum(nil)
if err != nil {
return ""
}
return fmt.Sprintf("%x", sum)
}
// Validate validates the webhook payload
func Validate(secret, headerHash string, payload []byte) error {
if !IsValidPayload(secret, headerHash, payload) {
return fmt.Errorf("invalid request : X-Hub-Signature does not match secret")
}
return nil
}