-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.go
407 lines (335 loc) · 12.1 KB
/
event.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
package bitbucketrunpipeline
import (
"fmt"
"github.com/pkg/errors"
"github.com/sharovik/devbot/internal/container"
"github.com/sharovik/devbot/internal/database"
"github.com/sharovik/devbot/internal/dto"
"github.com/sharovik/devbot/internal/dto/databasedto"
"github.com/sharovik/devbot/internal/log"
"github.com/sharovik/devbot/internal/service"
"github.com/sharovik/devbot/internal/service/message"
"github.com/sharovik/devbot/internal/service/message/conversation"
"github.com/sharovik/orm/clients"
"github.com/sharovik/orm/query"
"regexp"
"strconv"
"strings"
"time"
)
const (
//EventName the name of the event
EventName = "bitbucket_run_pipeline"
VariablesScenario = "bitbucket_run_pipeline_variables"
//EventVersion the version of the event
EventVersion = "2.0.0"
pipelineRegex = `(?im)(?:start|run)(?:\s+)([a-z-_0-9]+)`
prRegexp = `(?im)https:\/\/bitbucket.org\/(?P<workspace>.+)\/(?P<repository_slug>.+)\/pull-requests\/(?P<pull_request_id>\d+)`
repositoryRegex = `(?im)((?:repository)\s+([a-z-_0-9]+))`
urlRegex = `(?m)([\w+]+\:\/\/)?([\w\d-]+\.)*[\w-]+[\.\:]\w+([\/\?\=\&\#\.]?[\w-]+)*\/?`
helpMessage = "Send me message ```start {YOUR_CUSTOM_PIPELINE} {BITBUCKET_PULL_REQUEST_URL_1} {BITBUCKET_PULL_REQUEST_URL_2} ...{BITBUCKET_PULL_REQUEST_URL_N}``` to run the pipeline for selected pull-request.\nYou can also trigger pipeline for one or more repositories, just write ```start {YOUR_CUSTOM_PIPELINE} repository {YOUR_REPOSITORY_NAME}```. In case when you specify the repository, the default main branch will be used(for example: `master`)."
pipelineRefTypeBranch = "branch"
pipelineTargetTypePipelineRefTarget = "pipeline_ref_target"
pipelineSelectorTypeCustom = "custom"
defaultScenarioAnswer = "Ok, give me a min"
stepWhatDestination = "For which `pull-requests` or `repositories` should I trigger the pipeline?"
stepWhatPipeline = "What pipeline should I run? Please, write the pipeline name. Eg: my-custom-pipeline"
)
// PullRequest the pull-request item
type PullRequest struct {
ID int64
RepositorySlug string
Workspace string
Title string
Description string
Branch string
}
func (r PullRequest) GetURL() string {
return fmt.Sprintf("https://bitbucket.org/%s/%s/pull-requests/%d", r.Workspace, r.RepositorySlug, r.ID)
}
// EventStruct the struct for the event object
type EventStruct struct {
}
var (
//Event - object which is ready to use
Event = EventStruct{}
)
func (e EventStruct) Help() string {
return helpMessage
}
func (e EventStruct) Alias() string {
return EventName
}
func (e EventStruct) Execute(message dto.BaseChatMessage) (dto.BaseChatMessage, error) {
if !isAllVariablesDefined(message) {
return triggerVariablesScenario(message)
}
pullRequests, pipeline, repositories, err := getVariables(message)
if err != nil {
log.Logger().AddError(err).Msg("Failed to extract information from this conversation")
return message, err
}
log.Logger().Info().
Str("workspace", container.C.Config.BitBucketConfig.DefaultWorkspace).
Str("main_branch", container.C.Config.BitBucketConfig.DefaultMainBranch).
Str("pipeline", pipeline).
Interface("pull_requests", pullRequests).
Interface("repositories", repositories).
Msg("Triggered pipeline run")
for _, pr := range pullRequests {
if err = runPipelineForPullRequest(message, pipeline, pr); err != nil {
log.Logger().
AddError(err).
Str("pipeline", pipeline).
Interface("pull_request", pr).
Msg("Failed to trigger pipeline for selected pull-request")
}
}
for _, repository := range repositories {
if err = runPipelineForRepository(message, pipeline, repository); err != nil {
log.Logger().
AddError(err).
Str("pipeline", pipeline).
Interface("repository", repository).
Msg("Failed to trigger pipeline for selected repository")
}
}
message.Text = "Done"
return message, nil
}
func runPipelineForRepository(message dto.BaseChatMessage, pipeline string, repository string) error {
response, err := container.C.BibBucketClient.RunPipeline(container.C.Config.BitBucketConfig.DefaultWorkspace, repository, dto.BitBucketRequestRunPipeline{
Target: dto.PipelineTarget{
RefName: container.C.Config.BitBucketConfig.DefaultMainBranch,
RefType: pipelineRefTypeBranch,
Selector: dto.PipelineTargetSelector{
Type: pipelineSelectorTypeCustom,
Pattern: pipeline,
},
Type: pipelineTargetTypePipelineRefTarget,
},
})
if err != nil {
return errors.Wrap(err, "Failed to trigger pipeline for selected repository")
}
buildURL := fmt.Sprintf("https://bitbucket.org/%s/%s/addon/pipelines/home#!/results/%d", container.C.Config.BitBucketConfig.DefaultWorkspace, repository, response.BuildNumber)
_, _, err = container.C.MessageClient.SendMessage(dto.BaseChatMessage{
Channel: message.Channel,
Text: fmt.Sprintf("Pipeline `%s` for repository `%s` was triggered against `%s` branch. Here is the build url: %s", pipeline, repository, container.C.Config.BitBucketConfig.DefaultMainBranch, buildURL),
AsUser: true,
Ts: time.Now(),
DictionaryMessage: dto.DictionaryMessage{},
OriginalMessage: dto.BaseOriginalMessage{},
})
if err != nil {
return errors.Wrap(err, "Failed to send notification to the channel.")
}
return nil
}
func runPipelineForPullRequest(message dto.BaseChatMessage, pipeline string, pullRequest PullRequest) error {
info, err := container.C.BibBucketClient.PullRequestInfo(pullRequest.Workspace, pullRequest.RepositorySlug, pullRequest.ID)
if err != nil {
return errors.Wrap(err, "Failed to retrieve information about this pull-pullRequest.")
}
replacer := strings.NewReplacer("\\", "")
pullRequest.Title = info.Title
pullRequest.Description = replacer.Replace(info.Description)
pullRequest.Branch = info.Source.Branch.Name
response, err := container.C.BibBucketClient.RunPipeline(pullRequest.Workspace, pullRequest.RepositorySlug, dto.BitBucketRequestRunPipeline{
Target: dto.PipelineTarget{
RefName: pullRequest.Branch,
RefType: pipelineRefTypeBranch,
Selector: dto.PipelineTargetSelector{
Type: pipelineSelectorTypeCustom,
Pattern: pipeline,
},
Type: pipelineTargetTypePipelineRefTarget,
},
})
if err != nil {
_, _, err = container.C.MessageClient.SendMessage(dto.BaseChatMessage{
Channel: message.Channel,
Text: fmt.Sprintf("Failed to run `%s` pipeline for %s because of next error: ``` %s ```", pipeline, pullRequest.GetURL(), err.Error()),
AsUser: true,
Ts: time.Now(),
DictionaryMessage: dto.DictionaryMessage{},
OriginalMessage: dto.BaseOriginalMessage{},
})
if err != nil {
return errors.Wrap(err, "Failed to send notification to the channel.")
}
return errors.Wrap(err, "Failed to trigger pipeline for selected pull-request.")
}
buildURL := fmt.Sprintf("https://bitbucket.org/%s/%s/addon/pipelines/home#!/results/%d", pullRequest.Workspace, pullRequest.RepositorySlug, response.BuildNumber)
_, _, err = container.C.MessageClient.SendMessage(dto.BaseChatMessage{
Channel: message.Channel,
Text: fmt.Sprintf("Pipeline `%s` for pull-request `%s` was triggered. Here is the build url: %s", pipeline, pullRequest.GetURL(), buildURL),
AsUser: true,
Ts: time.Now(),
DictionaryMessage: dto.DictionaryMessage{},
OriginalMessage: dto.BaseOriginalMessage{},
})
if err != nil {
return errors.Wrap(err, "Failed to send notification to the channel.")
}
return nil
}
func triggerVariablesScenario(msg dto.BaseChatMessage) (dto.BaseChatMessage, error) {
scenarioID, err := getVariablesScenarioID()
if err != nil {
msg.Text = "Failed to trigger the main questions for the schedule scenario"
return msg, err
}
//We prepare the scenario, with our event name, to make sure we execute the right at the end
scenario, err := service.PrepareScenario(scenarioID, EventName)
if err != nil {
msg.Text = "Failed to get the scenario"
return msg, err
}
if err = message.TriggerScenario(msg.Channel, scenario, false); err != nil {
msg.Text = "Failed to ask scenario questions"
return msg, err
}
msg.Text = ""
return msg, nil
}
func getVariablesScenarioID() (int64, error) {
//We are getting scenario
q := new(clients.Query).Select(databasedto.ScenariosModel.GetColumns()).
From(databasedto.ScenariosModel).
Where(query.Where{
First: "name",
Operator: "=",
Second: query.Bind{
Field: "name",
Value: VariablesScenario,
},
})
res, err := container.C.Dictionary.GetDBClient().Execute(q)
if err != nil {
return 0, err
}
if len(res.Items()) == 0 {
return 0, errors.New("Failed to find the variables scenario")
}
return int64(res.Items()[0].GetField("id").Value.(int)), nil
}
func isAllVariablesDefined(message dto.BaseChatMessage) bool {
receivedPullRequests, pipeline, repositories, err := getVariables(message)
if err != nil {
log.Logger().AddError(err).Msg("Failed to parse pull-request, pipeline and repository information from string.")
return false
}
if pipeline == "" {
return false
}
if len(receivedPullRequests) != 0 {
return true
}
if len(repositories) != 0 {
return true
}
return false
}
func getVariables(message dto.BaseChatMessage) (pullRequests []PullRequest, pipeline string, repositories []string, err error) {
if conv := conversation.GetConversation(message.Channel); conv.Scenario.ID != int64(0) {
return extractInfoFromConversationVariables(message)
}
return extractInfoFromString(message.OriginalMessage.Text)
}
func getAllUrls(text string) (urls []string, err error) {
re, err := regexp.Compile(urlRegex)
if err != nil {
log.Logger().AddError(err).Msg("Error during the Find Matches operation")
return
}
matches := re.FindAllStringSubmatch(text, -1)
if len(matches) == 0 {
return
}
for _, url := range matches {
urls = append(urls, url[0])
}
return
}
func findAllPullRequestsInText(subject string) (list []PullRequest, err error) {
urls, err := getAllUrls(subject)
if err != nil {
return list, errors.Wrap(err, "Failed to parse urls")
}
for _, url := range urls {
re, err := regexp.Compile(prRegexp)
if err != nil {
return list, errors.Wrap(err, "Failed to parse pull-request")
}
matches := re.FindAllStringSubmatch(url, -1)
if len(matches) == 0 {
return list, nil
}
for _, id := range matches {
if id[1] == "" {
continue
}
item := PullRequest{}
item.Workspace = id[1]
item.RepositorySlug = id[2]
item.ID, err = strconv.ParseInt(id[3], 10, 64)
if err != nil {
return list, errors.Wrap(err, "Failed to parse pull-request ID")
}
list = append(list, item)
}
}
return list, nil
}
func getFromVariable(message dto.BaseChatMessage, variableQuestion string) (value string) {
conv := conversation.GetConversation(message.Channel)
//If we already have opened conversation, we will try to get the answer from the required variables
if conv.Scenario.ID != int64(0) {
for _, variable := range conv.Scenario.RequiredVariables {
if variableQuestion == variable.Question {
return strings.TrimSpace(variable.Value)
}
}
}
return ""
}
// Install method for installation of event
func (e EventStruct) Install() error {
log.Logger().Debug().
Str("event_name", EventName).
Str("event_version", EventVersion).
Msg("Triggered event installation")
err := container.C.Dictionary.InstallNewEventScenario(database.EventScenario{
EventName: EventName,
ScenarioName: fmt.Sprintf("%s_initial", EventName),
EventVersion: EventVersion,
Questions: []database.Question{
{
Question: "start",
Answer: defaultScenarioAnswer,
QuestionRegex: "(?i)(start)",
},
},
})
if err != nil {
return err
}
return container.C.Dictionary.InstallNewEventScenario(database.EventScenario{
EventName: EventName,
ScenarioName: VariablesScenario,
EventVersion: EventVersion,
RequiredVariables: []database.ScenarioVariable{
{
Question: stepWhatDestination,
},
{
Question: stepWhatPipeline,
},
},
})
}
// Update for event update actions
func (e EventStruct) Update() error {
return container.C.MigrationService.RunMigrations()
}