-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain_comment.go
310 lines (282 loc) · 8.71 KB
/
main_comment.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
package main
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gin-gonic/gin"
"github.com/google/go-github/v28/github"
"github.com/sirupsen/logrus"
gitlab "gitlab.com/gitlab-org/api/client-go"
clientgithub "github.com/mendersoftware/integration-test-runner/client/github"
clientgitlab "github.com/mendersoftware/integration-test-runner/client/gitlab"
)
// nolint: gocyclo
func processGitHubComment(
ctx *gin.Context,
comment *github.IssueCommentEvent,
githubClient clientgithub.Client,
conf *config,
) error {
log := getCustomLoggerFromContext(ctx)
// process created actions only, ignore the others
action := comment.GetAction()
if action != "created" {
log.Infof("Ignoring action %s on comment", action)
return nil
}
// accept commands only from organization members
if !githubClient.IsOrganizationMember(ctx, conf.githubOrganization, comment.Sender.GetLogin()) {
log.Warnf(
"%s commented, but he/she is not a member of our organization, ignoring",
comment.Sender.GetLogin(),
)
return nil
}
// but ignore comments from myself
if comment.Sender.GetLogin() == githubBotName {
log.Warnf("%s commented, probably giving instructions, ignoring", comment.Sender.GetLogin())
return nil
}
// filter comments mentioning the bot
commentBody := comment.Comment.GetBody()
if !strings.Contains(commentBody, "@"+githubBotName) {
log.Info("ignoring comment not mentioning me")
return nil
}
// retrieve the pull request
prLink := comment.Issue.GetPullRequestLinks().GetURL()
if prLink == "" {
log.Warnf("ignoring comment not on a pull request")
return nil
}
prLinkParts := strings.Split(prLink, "/")
prNumber, err := strconv.Atoi(prLinkParts[len(prLinkParts)-1])
if err != nil {
log.Errorf("Unable to retrieve the pull request: %s", err.Error())
return err
}
pr, err := githubClient.GetPullRequest(
ctx,
conf.githubOrganization,
comment.GetRepo().GetName(),
prNumber,
)
if err != nil {
log.Errorf("Unable to retrieve the pull request: %s", err.Error())
return err
}
// extract the command and check it is valid
switch {
case strings.Contains(commentBody, commandStartIntegrationPipeline):
prRequest := &github.PullRequestEvent{
Repo: comment.GetRepo(),
Number: github.Int(pr.GetNumber()),
PullRequest: pr,
}
build := getIntegrationBuild(log, conf, prRequest)
_, err = syncProtectedBranch(log, prRequest, conf, integrationPipelinePath)
if err != nil {
_ = say(ctx, "There was an error while syncing branches: {{.ErrorMessage}}",
struct {
ErrorMessage string
}{
ErrorMessage: err.Error(),
},
log,
conf,
prRequest)
return err
}
// start the build
if err := triggerIntegrationBuild(log, conf, &build, prRequest, nil); err != nil {
log.Errorf("Could not start build: %s", err.Error())
}
case strings.Contains(commentBody, commandStartClientPipeline):
buildOptions, err := parseBuildOptions(commentBody)
// get the list of builds
prRequest := &github.PullRequestEvent{
Repo: comment.GetRepo(),
Number: github.Int(pr.GetNumber()),
PullRequest: pr,
}
if err != nil {
_ = say(ctx, "There was an error while parsing arguments: {{.ErrorMessage}}",
struct {
ErrorMessage string
}{
ErrorMessage: err.Error(),
},
log,
conf,
prRequest)
return err
}
builds := parseClientPullRequest(log, conf, "opened", prRequest)
log.Infof(
"%s:%d will trigger %d builds",
comment.GetRepo().GetName(),
pr.GetNumber(),
len(builds),
)
// start the builds
for idx, build := range builds {
log.Infof("%d: "+spew.Sdump(build)+"\n", idx+1)
if build.repo == "meta-mender" && build.baseBranch == "master-next" {
log.Info("Skipping build targeting meta-mender:master-next")
continue
}
if err := triggerClientBuild(log, conf, &build, prRequest, buildOptions); err != nil {
log.Errorf("Could not start build: %s", err.Error())
}
}
case strings.Contains(commentBody, commandCherryPickBranch):
log.Infof("Attempting to cherry-pick the changes in PR: %s/%d",
comment.GetRepo().GetName(),
pr.GetNumber(),
)
err = cherryPickPR(log, comment, pr, conf, commentBody, githubClient)
if err != nil {
log.Error(err)
}
case strings.Contains(commentBody, commandConventionalCommit) &&
strings.Contains(pr.GetUser().GetLogin(), "dependabot"):
log.Infof(
"Attempting to make the PR: %s/%d and commit: %s a conventional commit",
comment.GetRepo().GetName(),
pr.GetNumber(),
pr.GetHead().GetSHA(),
)
err = conventionalComittifyDependabotPr(log, comment, pr, conf, commentBody, githubClient)
if err != nil {
log.Error(err)
}
case strings.Contains(commentBody, commandSyncRepos):
syncPRBranch(ctx, comment, pr, log, conf)
default:
log.Warnf("no command found: %s", commentBody)
return nil
}
return nil
}
func protectBranch(conf *config, branchName string, pipelinePath string) error {
// https://docs.gitlab.com/ee/api/protected_branches.html#protect-repository-branches
allow_force_push := false
opt := &gitlab.ProtectRepositoryBranchesOptions{
Name: &branchName,
AllowForcePush: &allow_force_push,
}
client, err := clientgitlab.NewGitLabClient(
conf.gitlabToken,
conf.gitlabBaseURL,
conf.dryRunMode,
)
if err != nil {
return err
}
_, err = client.ProtectRepositoryBranches(pipelinePath, opt)
if err != nil {
return fmt.Errorf("%v returned error: %s", err, err.Error())
}
return nil
}
func syncProtectedBranch(
log *logrus.Entry,
pr *github.PullRequestEvent,
conf *config,
pipelinePath string,
) (string, error) {
prBranchName := "pr_" + strconv.Itoa(pr.GetNumber()) + "_protected"
// check if we have a protected branch and try to delete it
response, err := deletePRBranch(pr, conf, prBranchName, log)
if err != nil {
// Don't return error if the branch doesn't exist
if response.StatusCode != 404 {
return "", fmt.Errorf("Got response: %d. Failed to delete PR branch: %s",
response.StatusCode, err.Error())
}
}
// Arbitrary sleep to ensure the branch and protection
// is fully deleted before we sync
time.Sleep(time.Duration(5) * time.Second)
if err := syncBranch(prBranchName, log, pr, conf); err != nil {
mainErrMsg := "There was an error syncing branches"
return "", fmt.Errorf("%v returned error: %s: %s", err, mainErrMsg, err.Error())
}
// Arbitrary sleep to ensure the branch is
// created before we protect it
time.Sleep(time.Duration(5) * time.Second)
if err := protectBranch(conf, prBranchName, pipelinePath); err != nil {
return "", fmt.Errorf("%v returned error: %s", err, err.Error())
}
return prBranchName, nil
}
func syncPRBranch(
ctx *gin.Context,
comment *github.IssueCommentEvent,
pr *github.PullRequest,
log *logrus.Entry,
conf *config,
) {
prEvent := &github.PullRequestEvent{
Repo: comment.GetRepo(),
Number: github.Int(pr.GetNumber()),
PullRequest: pr,
}
if _, err := syncPullRequestBranch(log, prEvent, conf); err != nil {
mainErrMsg := "There was an error syncing branches"
log.Errorf(mainErrMsg+": %s", err.Error())
msg := mainErrMsg + ", " + msgDetailsKubernetesLog
postGitHubMessage(ctx, prEvent, log, msg)
}
}
// parsing `start client pipeline --pr mender-connect/pull/88/head --pr deviceconnect/pull/12/head
// --pr mender/3.1.x --fast sugar pretty please`
//
// BuildOptions {
// Fast: true,
// PullRequests: map[string]string{
// "mender-connect": "pull/88/head",
// "deviceconnect": "pull/12/head",
// }
// }
func parseBuildOptions(commentBody string) (*BuildOptions, error) {
buildOptions := NewBuildOptions()
var err error
words := strings.Fields(commentBody)
tokensCount := len(words)
for id, word := range words {
if word == "--pr" && id < (tokensCount-1) {
userInput := strings.TrimSpace(words[id+1])
userInputParts := strings.Split(userInput, "/")
if len(userInput) > 0 {
var revision string
switch len(userInputParts) {
case 2: // we can have both deviceauth/1 and mender/3.1.x syntax
// repo/<pr_number> syntax
if _, err := strconv.Atoi(userInputParts[1]); err == nil {
revision = "pull/" + userInputParts[1] + "/head"
} else {
// feature branch
revision = userInputParts[1]
}
case 3: // deviceconnect/pull/12 syntax
revision = strings.Join(userInputParts[1:], "/") + "/head"
case 4: // deviceauth/pull/1/head syntax
revision = strings.Join(userInputParts[1:], "/")
default:
err = errors.New(
"parse error near '" + userInput + "', I need, e.g.: start client" +
" pipeline --pr somerepo/pull/12/head --pr somerepo/1.0.x ",
)
}
buildOptions.PullRequests[userInputParts[0]] = revision
}
} else if word == "--fast" {
buildOptions.Fast = true
}
}
return buildOptions, err
}