-
Notifications
You must be signed in to change notification settings - Fork 15
/
main_pullrequest.go
414 lines (367 loc) · 11.5 KB
/
main_pullrequest.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
package main
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/go-github/v28/github"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
clientgithub "github.com/mendersoftware/integration-test-runner/client/github"
)
var (
changelogPrefix = "Merging these commits will result in the following changelog entries:\n\n"
warningHeader = "\n\n## Warning\n\nGenerating changelogs also resulted in these warnings:\n\n"
msgDetailsKubernetesLog = "see <a href=\"https://console.cloud.google.com/kubernetes/" +
"deployment/us-east1/company-websites/default/test-runner-mender-io/logs?" +
"project=gp-kubernetes-269000\">logs</a> for details."
)
type retryParams struct {
retryFunc func() error
compFunc func(error) bool
}
const (
doRetry bool = true
noRetry = false
)
func retryOnError(args retryParams) error {
var maxBackoff int = 8 * 8
err := args.retryFunc()
i := 1
for i <= maxBackoff && args.compFunc(err) {
err = args.retryFunc()
i = i * 2
time.Sleep(time.Duration(i) * time.Second)
}
return err
}
func processGitHubPullRequest(
ctx *gin.Context,
pr *github.PullRequestEvent,
githubClient clientgithub.Client,
conf *config,
) error {
var (
prRef string
err error
action = pr.GetAction()
)
log := getCustomLoggerFromContext(ctx).
WithField("pull", pr.GetNumber()).
WithField("action", action)
req := pr.GetPullRequest()
// Do not run if the PR is a draft
if req.GetDraft() {
log.Infof(
"The PR: %s/%d is a draft. Do not run tests",
pr.GetRepo().GetName(),
pr.GetNumber(),
)
return nil
}
log.Debugf("Processing pull request action %s", action)
switch action {
case "opened", "reopened", "synchronize", "ready_for_review":
// We always create a pr_* branch
if prRef, err = syncPullRequestBranch(log, pr, conf); err != nil {
log.Errorf("Could not create PR branch: %s", err.Error())
msg := "There was an error syncing branches, " + msgDetailsKubernetesLog
postGitHubMessage(ctx, pr, log, msg)
}
//and we run a pipeline only for the pr_* branch
if prRef != "" {
prNum := strconv.Itoa(pr.GetNumber())
prBranchName := "pr_" + prNum
isOrgMember := func() bool {
return githubClient.IsOrganizationMember(
ctx,
conf.githubOrganization,
pr.Sender.GetLogin(),
)
}
err = retryOnError(retryParams{
retryFunc: func() error {
return startPRPipeline(log, prBranchName, pr, conf, isOrgMember)
},
compFunc: func(compareError error) bool {
re := regexp.MustCompile("Missing CI config file|" +
"No stages / jobs for this pipeline")
switch {
case compareError == nil:
return noRetry
case re.MatchString(compareError.Error()):
log.Infof("start pipeline for PR '%d' is skipped", pr.Number)
return noRetry
default:
log.Errorf("failed to start pipeline for PR: %s", compareError)
return doRetry
}
},
})
if err != nil {
msg := "There was an error running your pipeline, " + msgDetailsKubernetesLog
postGitHubMessage(ctx, pr, log, msg)
}
}
handleChangelogComments(log, ctx, githubClient, pr, conf)
case "closed":
// Delete merged pr branches in GitLab
if err := deleteStaleGitlabPRBranch(log, pr, conf); err != nil {
log.Errorf(
"Failed to delete the stale PR branch after the PR: %v was merged or closed. "+
"Error: %v",
pr,
err,
)
}
// If the pr was merged, suggest cherry-picks
if err := suggestCherryPicks(log, pr, githubClient, conf); err != nil {
log.Errorf("Failed to suggest cherry picks for the pr %v. Error: %v", pr, err)
}
}
// Continue to the integration Pipeline only for organization members
if member := githubClient.IsOrganizationMember(
ctx,
conf.githubOrganization,
pr.Sender.GetLogin(),
); !member {
log.Warnf(
"%s is making a pullrequest, but he/she is not a member of our organization, ignoring",
pr.Sender.GetLogin(),
)
return nil
}
// First check if the PR has been merged. If so, stop
// the pipeline, and do nothing else.
if err := stopBuildsOfStalePRs(log, pr, conf); err != nil {
log.Errorf(
"Failed to stop a stale build after the PR: %v was merged or closed. Error: %v",
pr,
err,
)
}
// Keep the OS and Enterprise repos in sync
if err := syncIfOSHasEnterpriseRepo(log, conf, pr); err != nil {
log.Errorf("Failed to sync the OS and Enterprise repos: %s", err.Error())
}
// get the list of builds
builds := parsePullRequest(log, conf, action, pr)
log.Infof("%s:%d would trigger %d builds", pr.GetRepo().GetName(), pr.GetNumber(), len(builds))
// do not start the builds, inform the user about the `start pipeline` command instead
if len(builds) > 0 {
// Only comment, if not already commented on a PR
botCommentString := ", Let me know if you want to start the integration pipeline by " +
"mentioning me and the command \""
if getFirstMatchingBotCommentInPR(log, githubClient, pr, botCommentString, conf) == nil {
msg := "@" + pr.GetSender().GetLogin() + botCommentString + commandStartPipeline + "\"."
msg += `
---
<details>
<summary>my commands and options</summary>
<br />
You can trigger a pipeline on multiple prs with:
- mentioning me and ` + "`" + `start pipeline --pr mender/127 --pr mender-connect/255` + "`" + `
You can start a fast pipeline, disabling full integration tests with:
- mentioning me and ` + "`" + `start pipeline --fast` + "`" + `
You can trigger GitHub->GitLab branch sync with:
- mentioning me and ` + "`" + `sync` + "`" + `
You can cherry pick to a given branch or branches with:
- mentioning me and:
` + "```" + `
cherry-pick to:
* 1.0.x
* 2.0.x
` + "```" + `
</details>
`
postGitHubMessage(ctx, pr, log, msg)
} else {
log.Infof(
"I have already commented on the pr: %s/%d, no need to keep on nagging",
pr.GetRepo().GetName(), pr.GetNumber())
}
}
return nil
}
func postGitHubMessage(
ctx *gin.Context,
pr *github.PullRequestEvent,
log *logrus.Entry,
msg string,
) {
if err := githubClient.CreateComment(
ctx,
pr.GetOrganization().GetLogin(),
pr.GetRepo().GetName(),
pr.GetNumber(),
&github.IssueComment{Body: github.String(msg)},
); err != nil {
log.Infof("Failed to comment on the pr: %v, Error: %s", pr, err.Error())
}
}
func getFirstMatchingBotCommentInPR(
log *logrus.Entry,
githubClient clientgithub.Client,
pr *github.PullRequestEvent,
botComment string,
conf *config,
) *github.IssueComment {
comments, err := githubClient.ListComments(
context.Background(),
conf.githubOrganization,
pr.GetRepo().GetName(),
pr.GetNumber(),
&github.IssueListCommentsOptions{
Sort: "created",
Direction: "asc",
})
if err != nil {
log.Errorf("Failed to list the comments on PR: %s/%d, err: '%s'",
pr.GetRepo().GetName(), pr.GetNumber(), err)
return nil
}
for _, comment := range comments {
if comment.Body != nil &&
strings.Contains(*comment.Body, botComment) &&
comment.User != nil &&
comment.User.Login != nil &&
*comment.User.Login == githubBotName {
return comment
}
}
return nil
}
func handleChangelogComments(
log *logrus.Entry,
ctx *gin.Context,
githubClient clientgithub.Client,
pr *github.PullRequestEvent,
conf *config,
) {
// It would be semantically correct to update the integration repo
// here. However, this step is carried out on every PR update, causing a
// big amount of "git fetch" requests, which both reduces performance,
// and could result in rate limiting. Instead, we assume that the
// integration repo is recent enough, since it is still updated when
// doing mender-qa builds.
//
// // First update integration repo.
// err := updateIntegrationRepo(conf)
// if err != nil {
// log.Errorf("Could not update integration repo: %s", err.Error())
// // Should still be safe to continue though.
// }
// Only do changelog commenting for mendersoftware repositories.
if pr.GetPullRequest().GetBase().GetRepo().GetOwner().GetLogin() != "mendersoftware" {
log.Info("Not a mendersoftware repository. Ignoring.")
return
}
changelogText, warningText, err := fetchChangelogTextForPR(log, pr, conf)
if err != nil {
log.Errorf("Error while fetching changelog text: %s", err.Error())
return
}
updatePullRequestChangelogComments(log, ctx, githubClient, pr, conf,
changelogText, warningText)
}
func fetchChangelogTextForPR(
log *logrus.Entry,
pr *github.PullRequestEvent,
conf *config,
) (string, string, error) {
repo := pr.GetPullRequest().GetBase().GetRepo().GetName()
baseSHA := pr.GetPullRequest().GetBase().GetSHA()
headSHA := pr.GetPullRequest().GetHead().GetSHA()
baseRef := pr.GetPullRequest().GetBase().GetRef()
headRef := pr.GetPullRequest().GetHead().GetRef()
versionRange := fmt.Sprintf(
"%s..%s",
baseSHA,
headSHA,
)
log.Debugf("Getting changelog for repo (%s) and range (%s)", repo, versionRange)
// Generate the changelog text for this PR.
changelogText, warningText, err := getChangelogText(
repo, versionRange, conf)
if err != nil {
err = errors.Wrap(err, "Not able to get changelog text")
}
// Replace SHAs with the original ref names, so that the changelog text
// does not change on every commit amend. The reason we did not use ref
// names to begin with is that they may live in personal forks, so it
// complicates the fetching mechanism. SHAs however, are always present
// in the repository you are merging into.
//
// Fetching changelogs online from personal forks is pretty unlikely to
// be useful outside of the integration-test-runner niche (better to use
// the local version), therefore we do this replacement instead of
// making the changelog-generator "fork aware".
changelogText = strings.ReplaceAll(changelogText, baseSHA, baseRef)
changelogText = strings.ReplaceAll(changelogText, headSHA, headRef)
log.Debugf("Prepared changelog text: %s", changelogText)
log.Debugf("Got warning text: %s", warningText)
return changelogText, warningText, err
}
func assembleCommentText(changelogText, warningText string) string {
commentText := changelogPrefix + changelogText
if warningText != "" {
commentText += warningHeader + warningText
}
return commentText
}
func updatePullRequestChangelogComments(
log *logrus.Entry,
ctx *gin.Context,
githubClient clientgithub.Client,
pr *github.PullRequestEvent,
conf *config,
changelogText string,
warningText string,
) {
var err error
commentText := assembleCommentText(changelogText, warningText)
emptyChangelog := (changelogText == "" ||
strings.HasSuffix(changelogText, "### Changelogs\n\n"))
comment := getFirstMatchingBotCommentInPR(log, githubClient, pr, changelogPrefix, conf)
if comment != nil {
// There is a previous comment about changelog.
if *comment.Body == commentText {
log.Debugf("The changelog hasn't changed (comment ID: %d). Leave it alone.",
comment.ID)
return
} else {
log.Debugf("Deleting old changelog comment (comment ID: %d).",
comment.ID)
err = githubClient.DeleteComment(
ctx,
conf.githubOrganization,
pr.GetRepo().GetName(),
*comment.ID,
)
if err != nil {
log.Errorf("Could not delete changelog comment: %s",
err.Error())
}
}
} else if emptyChangelog {
log.Info("Changelog is empty, and there is no previous changelog comment. Stay silent.")
return
}
commentBody := &github.IssueComment{
Body: &commentText,
}
err = githubClient.CreateComment(
ctx,
conf.githubOrganization,
pr.GetRepo().GetName(),
pr.GetNumber(),
commentBody,
)
if err != nil {
log.Errorf("Could not post changelog comment: %s. Comment text: %s",
err.Error(), commentText)
}
}