-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
api.go
319 lines (269 loc) · 9.02 KB
/
api.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
/*
Copyright 2019 The Tekton 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 pullrequest
import (
"context"
"fmt"
"io"
"strconv"
"github.com/hashicorp/go-multierror"
"github.com/jenkins-x/go-scm/scm"
"go.uber.org/zap"
)
// Handler handles interactions with the GitHub API.
type Handler struct {
client *scm.Client
repo string
prNum int
logger *zap.SugaredLogger
}
// NewHandler initializes a new handler for interacting with SCM
// resources.
func NewHandler(logger *zap.SugaredLogger, client *scm.Client, repo string, pr int) *Handler {
return &Handler{
logger: logger,
client: client,
repo: repo,
prNum: pr,
}
}
// Download fetches and stores the desired pull request.
func (h *Handler) Download(ctx context.Context) (*Resource, error) {
// Pull Request
h.logger.Info("finding pr")
pr, _, err := h.client.PullRequests.Find(ctx, h.repo, h.prNum)
if err != nil {
return nil, fmt.Errorf("finding pr %d: %w", h.prNum, err)
}
// Statuses
h.logger.Info("finding combined status")
status, out, err := h.client.Repositories.ListStatus(ctx, h.repo, pr.Sha, &scm.ListOptions{})
if err != nil {
body, _ := io.ReadAll(out.Body)
defer out.Body.Close()
h.logger.Warnf("%v: %s", err, string(body))
return nil, fmt.Errorf("finding combined status for pr %d: %w", h.prNum, err)
}
// Comments
// TODO: Pagination.
h.logger.Info("finding comments: %v", h)
comments, _, err := h.client.PullRequests.ListComments(ctx, h.repo, h.prNum, &scm.ListOptions{})
if err != nil {
return nil, fmt.Errorf("finding comments for pr %d: %w", h.prNum, err)
}
h.logger.Info("found comments: %v", comments)
labels, _, err := h.client.PullRequests.ListLabels(ctx, h.repo, h.prNum, &scm.ListOptions{})
if err != nil {
return nil, fmt.Errorf("finding labels for pr %d: %w", h.prNum, err)
}
pr.Labels = labels
r := &Resource{
PR: pr,
Statuses: status,
Comments: comments,
}
populateManifest(r)
return r, nil
}
func populateManifest(r *Resource) {
labels := make(Manifest)
for _, l := range r.PR.Labels {
labels[l.Name] = true
}
comments := make(Manifest)
for _, c := range r.Comments {
comments[strconv.Itoa(c.ID)] = true
}
r.Manifests = map[string]Manifest{
"labels": labels,
"comments": comments,
}
}
// Upload takes files stored on the filesystem and uploads new changes to
// GitHub.
func (h *Handler) Upload(ctx context.Context, r *Resource) error {
h.logger.Infof("Syncing resource: %+v", r)
var merr error
if err := h.uploadLabels(ctx, r.Manifests["labels"], r.PR.Labels); err != nil {
merr = multierror.Append(merr, err)
}
if err := h.uploadStatuses(ctx, r.Statuses, r.PR.Sha); err != nil {
merr = multierror.Append(merr, err)
}
if err := h.uploadComments(ctx, r.Manifests["comments"], r.Comments); err != nil {
merr = multierror.Append(merr, err)
}
return merr
}
func (h *Handler) uploadLabels(ctx context.Context, manifest Manifest, raw []*scm.Label) error {
// Convert requested labels to a map. This ensures that there are no
// duplicates and makes it easier to query which labels are being requested.
labels := make(map[string]bool)
for _, l := range raw {
labels[l.Name] = true
}
// Fetch current labels associated to the PR. We'll need to keep track of
// which labels are new and should not be modified.
currentLabels, _, err := h.client.PullRequests.ListLabels(ctx, h.repo, h.prNum, &scm.ListOptions{})
if err != nil {
return fmt.Errorf("listing labels for pr %d: %w", h.prNum, err)
}
current := make(map[string]bool)
for _, l := range currentLabels {
current[l.Name] = true
}
h.logger.Debugf("Current labels: %v", current)
var merr error
// Create new labels that are missing from the PR.
create := []string{}
for l := range labels {
if !current[l] {
create = append(create, l)
}
}
h.logger.Debugf("Creating labels %v for PR %d", create, h.prNum)
for _, l := range create {
if _, err := h.client.PullRequests.AddLabel(ctx, h.repo, h.prNum, l); err != nil {
merr = multierror.Append(merr, fmt.Errorf("adding label %s: %w", l, err))
}
}
// Remove labels that no longer exist in the workspace and were present in
// the manifest.
for l := range current {
if !labels[l] && manifest[l] {
h.logger.Debugf("Removing label %s for PR %d", l, h.prNum)
if _, err := h.client.PullRequests.DeleteLabel(ctx, h.repo, h.prNum, l); err != nil {
merr = multierror.Append(merr, fmt.Errorf("finding pr %d: %w", h.prNum, err))
}
}
}
return merr
}
func (h *Handler) uploadComments(ctx context.Context, manifest Manifest, comments []*scm.Comment) error {
h.logger.Infof("Setting comments for PR %d to: %v", h.prNum, comments)
// Sort comments into whether they are new or existing comments (based on
// whether there is an ID defined).
existingComments := map[int]*scm.Comment{}
newComments := []*scm.Comment{}
for _, c := range comments {
if c.ID != 0 {
existingComments[c.ID] = c
} else {
newComments = append(newComments, c)
}
}
var merr error
if err := h.maybeDeleteComments(ctx, manifest, existingComments); err != nil {
merr = multierror.Append(merr, fmt.Errorf("deleting comments %v: %w", existingComments, err))
}
if err := h.createNewComments(ctx, newComments); err != nil {
merr = multierror.Append(merr, fmt.Errorf("creating comments %v: %s", newComments, err))
}
return merr
}
// maybeDeleteComments deletes a comment iif it no longer exists in the remote
// SCM and exists in the manifest (therefore was present during resource
// initialization).
func (h *Handler) maybeDeleteComments(ctx context.Context, manifest Manifest, comments map[int]*scm.Comment) error {
currentComments, _, err := h.client.PullRequests.ListComments(ctx, h.repo, h.prNum, &scm.ListOptions{})
if err != nil {
return err
}
var merr error
for _, ec := range currentComments {
if _, ok := comments[ec.ID]; ok {
// Comment already exists. Carry on
continue
}
// Current comment does not exist in the current resource.
// Check if we were aware of the comment when the resource was
// initialized.
if _, ok := manifest[strconv.Itoa(ec.ID)]; !ok {
// Comment did not exist when resource created, so this was created
// recently. To not modify this comment.
h.logger.Debugf("Not tracking comment %d. Skipping.", ec.ID)
continue
}
// Comment existed beforehand, user intentionally deleted. Remove from
// upstream source.
h.logger.Infof("Deleting comment %d for PR %d", ec.ID, h.prNum)
if _, err := h.client.PullRequests.DeleteComment(ctx, h.repo, h.prNum, ec.ID); err != nil {
merr = multierror.Append(merr, fmt.Errorf("deleting comment %d: %w", ec.ID, err))
continue
}
}
return merr
}
func (h *Handler) createNewComments(ctx context.Context, comments []*scm.Comment) error {
var merr error
for _, dc := range comments {
c := &scm.CommentInput{
Body: dc.Body,
}
h.logger.Infof("Creating comment %s for PR %d", c.Body, h.prNum)
if _, _, err := h.client.PullRequests.CreateComment(ctx, h.repo, h.prNum, c); err != nil {
merr = multierror.Append(merr, fmt.Errorf("creating comment %v: %w", c, err))
}
}
return merr
}
func validateStatuses(statuses []*scm.Status) error {
var merr error
for _, s := range statuses {
if s.Label == "" {
merr = multierror.Append(merr, fmt.Errorf("invalid status: \"Label\" should not be empty: %v", *s))
}
if s.State.String() == scm.StateUnknown.String() {
merr = multierror.Append(merr, fmt.Errorf("invalid status: \"State\" is empty or has invalid value: %v", *s))
}
}
return merr
}
func (h *Handler) uploadStatuses(ctx context.Context, statuses []*scm.Status, sha string) error {
if statuses == nil {
h.logger.Info("Skipping statuses, nothing to set.")
return nil
}
if err := validateStatuses(statuses); err != nil {
return err
}
h.logger.Infof("Looking for existing status on %s", sha)
cs, _, err := h.client.Repositories.ListStatus(ctx, h.repo, sha, &scm.ListOptions{})
if err != nil {
return err
}
// Index the statuses so we can avoid sending them if they already exist.
csMap := map[string]scm.State{}
for _, s := range cs {
csMap[s.Label] = s.State
}
var merr error
for _, s := range statuses {
if csMap[s.Label] == s.State {
h.logger.Infof("Skipping setting %s because it already matches", s.Label)
continue
}
si := &scm.StatusInput{
Label: s.Label,
State: s.State,
Desc: s.Desc,
Target: s.Target,
}
h.logger.Infof("Creating status %s on %s", si.Label, sha)
if _, _, err := h.client.Repositories.CreateStatus(ctx, h.repo, sha, si); err != nil {
merr = multierror.Append(merr, fmt.Errorf("creating status %q: %w", si.Label, err))
continue
}
}
return merr
}