Repository navigation
Expand file tree
/
Copy pathclient_pull_request.go
More file actions
293 lines (258 loc) · 8.7 KB
/
Copy pathclient_pull_request.go
File metadata and controls
293 lines (258 loc) · 8.7 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
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
package github
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"github.com/rockbears/log"
"github.com/ovh/cds/engine/cache"
"github.com/ovh/cds/sdk"
)
func (g *githubClient) PullRequest(ctx context.Context, fullname string, id string) (sdk.VCSPullRequest, error) {
var pr PullRequest
cachePullRequestKey := cache.Key("vcs", "github", "pullrequests", g.OAuthToken, fmt.Sprintf("/repos/%s/pulls/%s", fullname, id))
opts := []getArgFunc{withETag}
for {
url := fmt.Sprintf("/repos/%s/pulls/%s", fullname, id)
status, body, _, err := g.get(ctx, url, opts...)
if err != nil {
if err := g.Cache.Delete(cachePullRequestKey); err != nil {
log.Error(ctx, "githubclient.PullRequest > unable to delete cache key %v: %v", cachePullRequestKey, err)
}
return sdk.VCSPullRequest{}, err
}
if status >= 400 {
if err := g.Cache.Delete(cachePullRequestKey); err != nil {
log.Error(ctx, "githubclient.PullRequest > unable to delete cache key %v: %v", cachePullRequestKey, err)
}
if status > 500 {
return sdk.VCSPullRequest{}, sdk.NewError(sdk.ErrUnknownError, errorAPI(body))
} else {
return sdk.VCSPullRequest{}, sdk.NewError(sdk.ErrNotFound, errorAPI(body))
}
}
//Github may return 304 status because we are using conditional request with ETag based headers
if status == http.StatusNotModified {
//If repos aren't updated, lets get them from cache
find, err := g.Cache.Get(cachePullRequestKey, &pr)
if err != nil {
log.Error(ctx, "cannot get from cache %s: %v", cachePullRequestKey, err)
}
if !find {
opts = []getArgFunc{withoutETag}
log.Error(ctx, "Unable to get pullrequest (%s) from the cache", strings.ReplaceAll(cachePullRequestKey, g.OAuthToken, ""))
continue
}
} else {
if err := sdk.JSONUnmarshal(body, &pr); err != nil {
log.Warn(ctx, "githubClient.PullRequest> Unable to parse github pullrequest: %s", err)
return sdk.VCSPullRequest{}, sdk.WithStack(err)
}
}
if strconv.Itoa(pr.Number) != id {
log.Warn(ctx, "githubClient.PullRequest> Cannot find pullrequest %s", id)
if err := g.Cache.Delete(cachePullRequestKey); err != nil {
log.Error(ctx, "githubclient.PullRequest > unable to delete cache key %v: %v", cachePullRequestKey, err)
}
return sdk.VCSPullRequest{}, sdk.WithStack(fmt.Errorf("cannot find pullrequest %s", id))
}
//Put the body on cache for one hour and one minute
if err := g.Cache.SetWithTTL(cachePullRequestKey, pr, 61*60); err != nil {
log.Error(ctx, "cannot SetWithTTL: %s: %v", cachePullRequestKey, err)
}
break
}
return pr.ToVCSPullRequest(), nil
}
// PullRequests fetch all the pull request for a repository
func (g *githubClient) PullRequests(ctx context.Context, fullname string, opts sdk.VCSPullRequestOptions) ([]sdk.VCSPullRequest, error) {
var pullRequests = []PullRequest{}
cacheKey := cache.Key("vcs", "github", "pullrequests", g.OAuthToken, "/repos/"+fullname+"/pulls")
githubOpts := []getArgFunc{withETag}
var nextPage = "/repos/" + fullname + "/pulls"
for nextPage != "" {
if ctx.Err() != nil {
break
}
status, body, headers, err := g.get(ctx, nextPage, githubOpts...)
if err != nil {
log.Warn(ctx, "githubClient.PullRequests> Error %s", err)
return nil, err
}
if status >= 400 {
return nil, sdk.NewError(sdk.ErrUnknownError, errorAPI(body))
}
githubOpts[0] = withETag
nextPullRequests := []PullRequest{}
//Github may return 304 status because we are using conditional request with ETag based headers
if status == http.StatusNotModified {
//If repos aren't updated, lets get them from cache
find, err := g.Cache.Get(cacheKey, &pullRequests)
if err != nil {
log.Error(ctx, "cannot get from cache %s: %v", cacheKey, err)
}
if !find {
githubOpts[0] = withoutETag
log.Error(ctx, "Unable to get pullrequest (%s) from the cache", strings.ReplaceAll(cacheKey, g.OAuthToken, ""))
continue
}
break
} else {
if err := sdk.JSONUnmarshal(body, &nextPullRequests); err != nil {
log.Warn(ctx, "githubClient.Branches> Unable to parse github branches: %s", err)
return nil, err
}
}
pullRequests = append(pullRequests, nextPullRequests...)
nextPage = getNextPage(headers)
}
//Put the body on cache for one hour and one minute
k := cache.Key("vcs", "github", "pullrequests", g.OAuthToken, "/repos/"+fullname+"/pulls")
if err := g.Cache.SetWithTTL(k, pullRequests, 61*60); err != nil {
log.Error(ctx, "cannot SetWithTTL: %s: %v", k, err)
}
prResults := []sdk.VCSPullRequest{}
for _, pullr := range pullRequests {
// If a state is given we want to filter PRs
switch opts.State {
case sdk.VCSPullRequestStateOpen:
if pullr.State == "closed" || pullr.Merged {
continue
}
case sdk.VCSPullRequestStateMerged:
if !pullr.Merged {
continue
}
case sdk.VCSPullRequestStateClosed:
if pullr.State != "closed" || pullr.Merged {
continue
}
}
pr := pullr.ToVCSPullRequest()
prResults = append(prResults, pr)
}
return prResults, nil
}
// PullRequestComment push a new comment on a pull request
func (g *githubClient) PullRequestComment(ctx context.Context, repo string, prReq sdk.VCSPullRequestCommentRequest) error {
if g.DisableStatus {
log.Warn(ctx, "github.PullRequestComment> ⚠ Github statuses are disabled")
return nil
}
canWrite, err := g.UserHasWritePermission(ctx, repo)
if err != nil {
return err
}
if !canWrite {
if err := g.GrantWritePermission(ctx, repo); err != nil {
return err
}
}
path := fmt.Sprintf("/repos/%s/issues/%d/comments", repo, prReq.ID)
payload := map[string]string{
"body": prReq.Message,
}
values, _ := json.Marshal(payload)
res, err := g.post(ctx, path, "application/json", bytes.NewReader(values), nil, &postOptions{skipDefaultBaseURL: false, asUser: true})
if err != nil {
return sdk.WrapError(err, "Unable to post status")
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return sdk.WrapError(err, "Unable to read body")
}
log.Debug(ctx, "%v", string(body))
if res.StatusCode != 201 {
return sdk.WrapError(err, "Unable to create status on github. Status code : %d - Body: %s", res.StatusCode, body)
}
return nil
}
func (g *githubClient) PullRequestCreate(ctx context.Context, repo string, pr sdk.VCSPullRequest) (sdk.VCSPullRequest, error) {
canWrite, err := g.UserHasWritePermission(ctx, repo)
if err != nil {
return sdk.VCSPullRequest{}, err
}
if !canWrite {
if err := g.GrantWritePermission(ctx, repo); err != nil {
return sdk.VCSPullRequest{}, err
}
}
path := fmt.Sprintf("/repos/%s/pulls", repo)
payload := map[string]string{
"title": pr.Title,
"head": pr.Head.Branch.DisplayID,
"base": pr.Base.Branch.DisplayID,
}
values, _ := json.Marshal(payload)
res, err := g.post(ctx, path, "application/json", bytes.NewReader(values), nil, &postOptions{skipDefaultBaseURL: false, asUser: true})
if err != nil {
return sdk.VCSPullRequest{}, sdk.WrapError(err, "Unable to post status")
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return sdk.VCSPullRequest{}, sdk.WrapError(err, "Unable to read body")
}
var prResponse PullRequest
if err := sdk.JSONUnmarshal(body, &prResponse); err != nil {
return sdk.VCSPullRequest{}, sdk.WrapError(err, "Unable to unmarshal pullrequest %s", string(body))
}
return prResponse.ToVCSPullRequest(), nil
}
func (pullr PullRequest) ToVCSPullRequest() sdk.VCSPullRequest {
return sdk.VCSPullRequest{
ID: pullr.Number,
Base: sdk.VCSPushEvent{
Repo: pullr.Base.Repo.FullName,
Branch: sdk.VCSBranch{
ID: pullr.Base.Ref,
DisplayID: pullr.Base.Ref,
LatestCommit: pullr.Base.Sha,
},
CloneURL: pullr.Base.Repo.CloneURL,
Commit: sdk.VCSCommit{
Author: sdk.VCSAuthor{
Avatar: pullr.Base.User.AvatarURL,
DisplayName: pullr.Base.User.Login,
Name: pullr.Base.User.Name,
},
Hash: pullr.Base.Sha,
Message: pullr.Base.Label,
Timestamp: pullr.UpdatedAt.Unix(),
},
},
Head: sdk.VCSPushEvent{
Repo: pullr.Head.Repo.FullName,
Branch: sdk.VCSBranch{
ID: pullr.Head.Ref,
DisplayID: pullr.Head.Ref,
LatestCommit: pullr.Head.Sha,
},
CloneURL: pullr.Head.Repo.CloneURL,
Commit: sdk.VCSCommit{
Author: sdk.VCSAuthor{
Avatar: pullr.Head.User.AvatarURL,
DisplayName: pullr.Head.User.Login,
Name: pullr.Head.User.Name,
},
Hash: pullr.Head.Sha,
Message: pullr.Head.Label,
Timestamp: pullr.UpdatedAt.Unix(),
},
},
URL: pullr.HTMLURL,
User: sdk.VCSAuthor{
Avatar: pullr.User.AvatarURL,
DisplayName: pullr.User.Login,
Name: pullr.User.Name,
},
Closed: pullr.State == "closed",
Merged: pullr.Merged,
Updated: pullr.UpdatedAt,
}
}