-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
792 lines (686 loc) · 27.6 KB
/
main.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
// What it can do
// - Message into slack per tracked PR per channel to alert the wider team
// - Further messages in relation to that PR to be sent as a thread message
// - Daily reminders of all tracked active PRs per channel
// - Notifactions on any new comments made since the last check
// - Notifactions on any new reviewers, or reviewers changing their review
// - Delete all thread messages + parent message once PR is no longer active
// - If a user has requested to track a PR that is already being tracked, it will @ them in slack with any new updates
// Future plans
// - prefix all message with PR ID ---- DONE
// - functionality to collect all PRs tracked per channel and send a morning reminder for remaining active PRs ---- DONE
// - Check if PR is still active here, if not, send message to thread to confirm PR has been completed or abandoned ---- DONE
// - Ensure the same PR can't be added twice ---- DONE
// - If the person has requested a already existing tracked PR, add them to the @ list ---- DONE
// - Update cron to be passed in via var and see if there's a cron to exclude weekends "0 0 9 * * 1-5". ---- DONE
// - Fetch when someone approves the PR ---- added to check if PR has been declined / approved with suggestions also. Needs to check if reviewer has changed their review still ---- DONE
// - Delete first message sent that hosts all thread messages on choice. Have to delete thread messages first ---- (conversation messages also count the parent) ---- DONE
// - Only check unresolved comments. Do we message the comment author that they've had responses? How do we link Azure Devops authers back to slack?
// - A /bump command to push a notifaction to the channel containing all your PRs
// - functionality around comparing comments. If the author has responded to the new comment, dont alert.
// - Add automatic PRs to be posted to a channel through Azure Devops Webhooks
// - Get project using ID from resource > repo > project. Use ID https://dev.azure.com/kieranjamess/_apis/projects/<ID> and check name. If name matches key, move on ----- DONE
// - If the name matches, get the PRID from resource > repo > pullRequestId, get the userID from key.WhoToMessage and channel from key.ChannelId ----- DONE
// - Send a message to channel ID, that PR has been created by DisplayName.FirstName. Add PR to activePrs and start the go process ----- DONE
// - Message should look somewhat like "@<WhoToMessage> A new PR <PR_TITLE>|<Link> has been created in <key> by <FirstName>//""" ----- DONE
// - Add a catch on eventType for webhook != "git.pullrequest.created"
// - Add an option to allow an array of repos to get sent to an array of channels. So repo1,repo2 = channel1. Repo3, repo4 = channel2 and all other repos within project goes to channel 5 ---- DONE
// - Add support if the automatic_prs.json file is missing, to continue
// - Add functions to check if the PR has a build. Post build results to slack.
// - Support no mention lists if no one should be mentioned ---- DONE
// - Add a /track command on the tread messages to add user to the updates
// Not Possible Ideas
// - Add a thread message if the PR is ready to be merged ---- NOT POSSIBLE (if its just approvers, the merge status is still 'succeeded' even if not all people have approved)
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/robfig/cron/v3"
"github.com/slack-go/slack"
"github.com/tkanos/gonfig"
)
const (
slackVerificationToken = ""
slackAccessToken = ""
personalAccessToken = ""
cronTimer = "0 0 9 * * 1-5" // At 9AM, on a weekday
deleteFirstMessage = false // Delete the first message with all the thread messages once PR is no longer active.
)
var azureDevOpsOrganization string
var azureDevOpsProject string
var repositoryName string
var activeMonitoring = make(map[string]bool) // key: "PRID_channelID", value: true/false
var mutex sync.Mutex // Mutex for safe concurrent access to the map
var cronOnce sync.Once
var isCronRunning bool
var interestedUsers = make(map[string][]string) // key: PRID, value: list of user IDs
type WebhookData struct {
Resource struct {
Repository struct {
Project struct {
Name string `json:"name"`
} `json:"project"`
WebURL string `json:"webUrl"`
Name string `json:"name"`
} `json:"repository"`
PullRequestID int `json:"pullRequestId"`
PrTitle string `json:"title"`
CreatedBy struct {
DisplayName string `json:"displayName"`
} `json:"createdBy"`
} `json:"resource"`
}
type AutomaticPrMessages struct {
Projects map[string]ProjectInfo `json:"AutomaticPrMessages"`
}
type ProjectInfo struct {
ChannelIds []string `json:"ChannelIds"`
SlackUserIDs []string `json:"SlackUserIds"`
SpecificRepos map[string]SpecificRepos `json:"SpecificRepos"`
}
type SpecificRepos struct {
ChannelIds []string `json:"ChannelIds"`
SlackUserIDs []string `json:"SlackUserIds"`
}
type Author struct {
DisplayName string `json:"displayName"`
}
type Comment struct {
ID int `json:"id"`
Content string `json:"content"`
Author Author `json:"author"`
CommentType string `json:"commentType"`
}
type CommentThread struct {
Comments []Comment `json:"comments"`
}
type CommentResponse struct {
Value []CommentThread `json:"value"`
}
type Reviewer struct {
DisplayName string `json:"displayName"`
UniqueName string `json:"uniqueName"`
Vote int `json:"vote"`
}
type PullRequest struct {
ID int `json:"pullRequestId"`
Title string `json:"title"`
Status string `json:"status"`
Reviewers []Reviewer `json:"reviewers"`
}
func fetchCommentsFromAzureDevOps(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID string) ([]Comment, error) {
azureDevOpsURL := fmt.Sprintf(
"https://dev.azure.com/%s/%s/_apis/git/repositories/%s/pullRequests/%s/threads?api-version=6.1",
azureDevOpsOrganization,
azureDevOpsProject,
repositoryName,
prID,
)
req, err := http.NewRequest("GET", azureDevOpsURL, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(personalAccessToken, "")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var commentResponse CommentResponse
err = json.Unmarshal(body, &commentResponse)
if err != nil {
return nil, err
}
var comments []Comment
for _, thread := range commentResponse.Value {
for _, comment := range thread.Comments {
if comment.CommentType != "system" { // Check if CommentType is not "system". System comments count as reviewrs approving / declined / rejecting etc
comments = append(comments, comment)
}
}
}
return comments, nil
}
func getPullRequest(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID string) (*PullRequest, error) {
azureDevOpsURL := fmt.Sprintf(
"https://dev.azure.com/%s/%s/_apis/git/repositories/%s/pullRequests/%s?api-version=6.1",
azureDevOpsOrganization,
azureDevOpsProject,
repositoryName,
prID,
)
req, err := http.NewRequest("GET", azureDevOpsURL, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth("", personalAccessToken)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var pr PullRequest
err = json.Unmarshal(body, &pr)
if err != nil {
return nil, err
}
return &pr, nil
}
func getPullRequestStatus(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID string) (status string) {
pr, err := getPullRequest(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
if err != nil {
fmt.Println("Error:", err)
return
}
// return error also from other function and check there isn't an error in loop when marking as completed.
return pr.Status
}
func getPullRequestReviewers(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID string) (reviewers []Reviewer) {
pr, err := getPullRequest(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
if err != nil {
fmt.Println("Error:", err)
return
}
// return error also from other function and check there isn't an error in loop when marking as completed.
return pr.Reviewers
}
func handleSlackSlashCommand(w http.ResponseWriter, r *http.Request) {
prLink := r.FormValue("text")
fmt.Println("-------------------\nPR Link received from slack:", prLink)
// Verify that the request is coming from Slack by checking the token
token := r.FormValue("token")
if token != slackVerificationToken {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Println("Token Authorised")
w.WriteHeader(http.StatusOK)
// Split the URL by "/" to get the parts
parts := strings.Split(prLink, "/")
// Find the index of "_git" and use it to split azureDevOpsOrganization, azureDevOpsProject, and repositoryName
gitIndex := -1
for i, part := range parts {
if part == "_git" {
gitIndex = i
break
}
}
if gitIndex == -1 || gitIndex+3 >= len(parts) {
fmt.Println("Invalid URL format")
return
}
azureDevOpsOrganization = parts[gitIndex-2]
azureDevOpsProject := parts[gitIndex-1]
repositoryName := parts[gitIndex+1]
fmt.Println("Organization:", azureDevOpsOrganization)
fmt.Println("Project:", azureDevOpsProject)
fmt.Println("Repo:", repositoryName)
// Extract PR link from Slack command
prTemplate := fmt.Sprintf(
"https://dev.azure.com/%s/%s/_git/%s/pullrequest",
azureDevOpsOrganization,
azureDevOpsProject,
repositoryName,
)
prID := strings.TrimPrefix(prLink, prTemplate)
prID = strings.TrimSuffix(prID, "/")
prID = strings.TrimPrefix(prID, "/")
channelID := r.FormValue("channel_id")
key := fmt.Sprintf("%s_%s", prID, channelID)
mutex.Lock()
if activeMonitoring[key] {
// PR is already being monitored, add user to interested users if not already added
userAlreadyInterested := false
for _, userID := range interestedUsers[prID] {
if userID == r.FormValue("user_id") {
userAlreadyInterested = true
fmt.Println("Submitted from:", r.FormValue("user_name"), "\nChannel: ", r.FormValue("channel_name"), "/", r.FormValue("channel_id"), "\nPR is already being tracked by user...\n-------------------")
w.Write([]byte("You are already tracking this PR"))
return
}
}
if !userAlreadyInterested {
interestedUsers[prID] = append(interestedUsers[prID], r.FormValue("user_id"))
w.Write([]byte("This PR is already being tracked. You're now interested in this PR, and will be notified of updates."))
}
fmt.Println("Submitted from:", r.FormValue("user_name"), "\nChannel: ", r.FormValue("channel_name"), "/", r.FormValue("channel_id"), "\nPR is already being monitored, attempting to add user to monitoring list...\n-------------------")
mutex.Unlock()
return
} else {
// Add the first requestee as interested in the PR
userAlreadyInterested := false
for _, userID := range interestedUsers[prID] {
if userID == r.FormValue("user_id") {
userAlreadyInterested = true
}
}
if !userAlreadyInterested {
interestedUsers[prID] = append(interestedUsers[prID], r.FormValue("user_id"))
}
// Mark the PR monitoring as active for this PR and channel
activeMonitoring[key] = true
mutex.Unlock()
fmt.Println("PRID:", prID)
// Prepare the response message
pr, err := getPullRequest(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
if err != nil {
fmt.Println("Error:", err)
return
}
if getPullRequestStatus(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID) != "active" {
// Send message back to slack only visible to user to alert the user that PR isnt active.
fmt.Println("PR isn't active...")
w.Write([]byte("Please submit an active PR"))
return
}
w.Write([]byte("Processing your request..."))
firstMessage := fmt.Sprintf("New PR '<%s|*%s*>', created by <@%s>. Tracking PR...",
prLink,
pr.Title,
r.FormValue("user_id"),
)
parentMessageTs := sendSlackMessage(slackAccessToken, r.FormValue("channel_id"), firstMessage, "", "", false)
fmt.Println("Submitted from:", r.FormValue("user_name"), "\nChannel: ", r.FormValue("channel_name"), "/", r.FormValue("channel_id"), "\nParentMessageTs:", parentMessageTs, "\n-------------------")
// Only start cron if it's not running.
if !isCronRunning {
cronOnce.Do(func() {
startCron(azureDevOpsOrganization, azureDevOpsProject, repositoryName)
})
}
// loop until PR isn't active anymore
stopChannel := make(chan struct{})
go monitorPr(azureDevOpsOrganization, azureDevOpsProject, repositoryName, parentMessageTs, prID, prLink, r.FormValue("channel_id"), stopChannel)
}
}
func monitorPr(azureDevOpsOrganization, azureDevOpsProject, repositoryName, parentMessageTs, prID, prLink, channelId string, stopChannel chan struct{}) {
// Set a timer for each minute
ticker := time.NewTicker(1 * time.Minute)
// Setup vars
uniqueAuthors := make(map[string]bool)
reviewersApproved := make(map[string]bool)
reviewersDeclined := make(map[string]bool)
prefix := fmt.Sprintf("[%s - %s]", channelId, prID)
var approvedChanged bool
var declinedChanged bool
// Fetch comments
comments, _ := fetchCommentsFromAzureDevOps(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
currentCommentCount := len(comments)
// Fetch reviews
reviews := getPullRequestReviewers(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
currentReviewsCount := len(reviews)
for range ticker.C {
approvedChanged = false
declinedChanged = false
interestedUserIDs := interestedUsers[prID]
mentionText := ""
for _, userID := range interestedUserIDs {
mentionText += fmt.Sprintf("<@%s>", userID)
mentionText = strings.ReplaceAll(mentionText, "<@>", "")
}
fmt.Println(prefix, "Checking for changes")
// Check if PR is still active here, if not, send message to thread to confirm PR has been completed
if status := getPullRequestStatus(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID); status != "active" {
close(stopChannel)
mutex.Lock()
key := fmt.Sprintf("%s_%s", prID, channelId)
delete(activeMonitoring, key)
mutex.Unlock()
fmt.Println(fmt.Sprintf("%s PR isn't active, PR state is %s. Removing from being tracked and sending message to thread", prefix, status))
if deleteFirstMessage {
fmt.Println(fmt.Sprintf("%s Deleting messages relating to this tracked PR", prefix))
// Get all thread messages, delete thread messages and then delete master message
threadMessages, err := getThreadMessages(slackAccessToken, channelId, parentMessageTs)
if err != nil {
fmt.Printf(prefix, "Error retrieving thread messages:", err)
return
}
if err := deleteThreadMessages(slackAccessToken, channelId, threadMessages); err != nil {
fmt.Printf(prefix, "Error deleting thread messages:", err)
return
}
} else {
// Send message to thread confirming the new state of the PR to the mention list
statusMessage := fmt.Sprintf("%s The <%s|PR> has been marked as %s and will no longer be tracked.", mentionText, prLink, status)
sendSlackMessage(slackAccessToken, channelId, statusMessage, parentMessageTs, "", false)
}
break
}
newComments, err := fetchCommentsFromAzureDevOps(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
if err != nil {
fmt.Println(prefix, "Error fetching comments:", err)
continue
}
// Compare new comments with the existing comments
newCommentsCount := len(newComments)
if newCommentsCount > currentCommentCount {
fmt.Println(fmt.Sprintf("%s New comments found! Current Comments: %d, New Comments: %d", prefix, currentCommentCount, newCommentsCount))
for i := currentCommentCount; i < newCommentsCount; i++ {
names := strings.Fields(newComments[i].Author.DisplayName)
if len(names) > 0 {
firstName := names[0]
uniqueAuthors[firstName] = true
}
}
var uniqueAuthorsString string
for firstName := range uniqueAuthors {
uniqueAuthorsString += fmt.Sprintf("%s, ", firstName)
}
uniqueAuthorsString = strings.TrimSuffix(uniqueAuthorsString, ", ")
threadMessage := fmt.Sprintf("%s There's *%d* new comment(s) on the <%s|PR> left by %s.",
mentionText,
newCommentsCount-currentCommentCount,
prLink,
uniqueAuthorsString,
)
sendSlackMessage(slackAccessToken, channelId, threadMessage, parentMessageTs, "", false)
// Update the current comment count with the new count
currentCommentCount = newCommentsCount
}
newReviews := getPullRequestReviewers(azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
newReviewsCount := len(newReviews)
// Run both newReviews and currentReviews at the same time at each index, compare the vote at each index.
for i := 0; i < newReviewsCount && i < currentReviewsCount; i++ {
newReview := newReviews[i]
currentReview := reviews[i]
if newReview.UniqueName == currentReview.UniqueName {
if newReview.Vote != currentReview.Vote {
if newReview.Vote >= 5 {
reviewersApproved[newReview.DisplayName] = true
delete(reviewersDeclined, newReview.DisplayName)
approvedChanged = true
} else if newReview.Vote == -10 {
reviewersDeclined[newReview.DisplayName] = true
delete(reviewersApproved, newReview.DisplayName)
declinedChanged = true
}
}
}
}
for i := currentReviewsCount; i < newReviewsCount; i++ {
newReview := newReviews[i]
// Process the new review without comparing it to any current review
if newReview.Vote >= 5 { // Approved with suggestions OR Approved
reviewersApproved[newReview.DisplayName] = true
approvedChanged = true
} else if newReview.Vote == -10 { // Declined
reviewersDeclined[newReview.DisplayName] = true
declinedChanged = true
}
}
if approvedChanged || declinedChanged {
approvedReviewers := reviewersToString(reviewersApproved)
declinedReviewers := reviewersToString(reviewersDeclined)
var reviewersThreadMessage string
if approvedReviewers != "" && declinedReviewers != "" {
reviewersThreadMessage = fmt.Sprintf("%s There's some new reviews on your <%s|PR>. It has been *approved* by %s and *declined* by %s",
mentionText,
prLink,
approvedReviewers,
declinedReviewers,
)
} else if approvedReviewers == "" && declinedReviewers != "" {
reviewersThreadMessage = fmt.Sprintf("%s There's some new reviews on your <%s|PR>. It has been *declined* by %s",
mentionText,
prLink,
declinedReviewers,
)
} else {
reviewersThreadMessage = fmt.Sprintf("%s There's some new reviews on your <%s|PR>. It has been *approved* by %s",
mentionText,
prLink,
approvedReviewers,
)
}
fmt.Println(prefix, "Some new reviewers found. Approvers:", approvedReviewers, ",Decliners:", declinedReviewers)
sendSlackMessage(slackAccessToken, channelId, reviewersThreadMessage, parentMessageTs, "", false)
}
// Update the current review
reviews = newReviews
currentReviewsCount = newReviewsCount
}
}
func sendSlackMessage(slackAccessToken, channelID, message, messageTs, userId string, postEphemeral bool) (message_ts string) {
api := slack.New(slackAccessToken)
if postEphemeral {
message_ts, err := api.PostEphemeral(channelID, userId, slack.MsgOptionText(message, false))
if err != nil {
log.Fatalf("Error sending message: %v", err)
}
return message_ts
} else {
_, message_ts, err := api.PostMessage(channelID, slack.MsgOptionText(message, false), slack.MsgOptionTS(messageTs))
if err != nil {
log.Fatalf("Error sending message: %v", err)
}
return message_ts
}
}
func getThreadMessages(slackAccessToken, channelID, parentTimestamp string) ([]slack.Message, error) {
api := slack.New(slackAccessToken)
params := slack.GetConversationRepliesParameters{
ChannelID: channelID,
Timestamp: parentTimestamp,
}
messages, _, _, err := api.GetConversationReplies(¶ms)
if err != nil {
return nil, err
}
return messages, nil
}
func deleteThreadMessages(slackAccessToken, channelID string, messages []slack.Message) error {
api := slack.New(slackAccessToken)
for _, msg := range messages {
_, _, err := api.DeleteMessage(channelID, msg.Timestamp)
if err != nil {
return err
}
}
return nil
}
func postActivePRsMessage(activePrs map[string]bool, azureDevOpsOrganization, azureDevOpsProject, repositoryName string) {
channelMessage := make(map[string]string)
for key, value := range activePrs {
if value {
// Key is in the format "prID_channelID", so split it to get prID and channelID
parts := strings.Split(key, "_")
if len(parts) == 2 {
prID := parts[0]
channelID := parts[1]
azureDevOpsURL := fmt.Sprintf(
"\nhttps://dev.azure.com/%s/%s/_git/%s/pullrequest/%s",
azureDevOpsOrganization,
azureDevOpsProject,
repositoryName,
prID,
)
// Check if the channelID already exists in the channelMessage map
if existingMessage, ok := channelMessage[channelID]; ok {
// If the channelID exists, append the new PR URL to the existing message
channelMessage[channelID] = existingMessage + ", " + azureDevOpsURL
} else {
// If the channelID doesn't exist, set the new PR URL as the message
channelMessage[channelID] = fmt.Sprintf("The follow tracked PRs are still active! Please can we get a review on them today.%s", azureDevOpsURL)
}
}
}
}
// Post messages to each channel for a combined message of every PR. Only post if there are still active PRs
if len(channelMessage) > 0 {
for channelID, message := range channelMessage {
sendSlackMessage(slackAccessToken, channelID, message, "", "", false)
fmt.Println("[GLOBAL] Posting active PRs to", channelID)
}
}
}
func startCron(azureDevOpsOrganization, azureDevOpsProject, repositoryName string) {
cron := cron.New(cron.WithSeconds())
cron.AddFunc(cronTimer, func() {
postActivePRsMessage(activeMonitoring, azureDevOpsOrganization, azureDevOpsProject, repositoryName)
})
cron.Start()
fmt.Println("[GLOBAL] Starting cron")
isCronRunning = true
}
func reviewersToString(reviewers map[string]bool) string {
reviewerList := make([]string, 0)
for reviewer := range reviewers {
reviewerList = append(reviewerList, reviewer)
}
return strings.Join(reviewerList, ", ")
}
func handleAzureDevopsWebhook(w http.ResponseWriter, r *http.Request, configuration AutomaticPrMessages) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
var data WebhookData
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "Failed to parse JSON", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
// Extract the desired information
fmt.Println("[GLOBAL] Received webhook from Azure Devops matching Project:", data.Resource.Repository.Project)
projectName := data.Resource.Repository.Project.Name
// Iterate through the project keys and check if the project name matches
for key, project := range configuration.Projects {
if projectName == key {
fmt.Printf("[GLOBAL] Project name matched with %s: %+v\n", key, project)
parts := strings.Split(data.Resource.Repository.WebURL, "/")
azureDevOpsOrganization := parts[3]
azureDevOpsProject := parts[4]
repositoryName := parts[6]
prID := strconv.Itoa(data.Resource.PullRequestID)
prLink := fmt.Sprintf("https://dev.azure.com/%s/%s/_git/%s/pullrequest/%s", azureDevOpsOrganization, azureDevOpsProject, repositoryName, prID)
if len(project.ChannelIds) != 0 {
if len(project.SpecificRepos) == 0 {
azureWebhookIterateOverChannelsAndUsers(project.ChannelIds, project.SlackUserIDs, azureDevOpsOrganization, azureDevOpsProject, prLink, data.Resource.PrTitle, prID, projectName, data.Resource.Repository.Name, data.Resource.CreatedBy.DisplayName)
} else {
for key, repo := range project.SpecificRepos {
if key == repositoryName {
azureWebhookIterateOverChannelsAndUsers(repo.ChannelIds, repo.SlackUserIDs, azureDevOpsOrganization, azureDevOpsProject, prLink, data.Resource.PrTitle, prID, projectName, data.Resource.Repository.Name, data.Resource.CreatedBy.DisplayName)
} else {
azureWebhookIterateOverChannelsAndUsers(project.ChannelIds, project.SlackUserIDs, azureDevOpsOrganization, azureDevOpsProject, prLink, data.Resource.PrTitle, prID, projectName, data.Resource.Repository.Name, data.Resource.CreatedBy.DisplayName)
}
}
}
} else {
if len(project.SpecificRepos) != 0 {
for key, repo := range project.SpecificRepos {
if key == repositoryName {
azureWebhookIterateOverChannelsAndUsers(repo.ChannelIds, repo.SlackUserIDs, azureDevOpsOrganization, azureDevOpsProject, prLink, data.Resource.PrTitle, prID, projectName, data.Resource.Repository.Name, data.Resource.CreatedBy.DisplayName)
} else {
fmt.Println(fmt.Sprintf("[GLOBAL] PR passed in on repo; %s, but no matching key was found", repositoryName))
}
}
} else {
fmt.Println("[GLOBAL] No specific repos or default channel ID set")
}
}
}
}
}
func azureWebhookIterateOverChannelsAndUsers(channels []string, users []string, azureDevOpsOrganization string, azureDevOpsProject string, prlink string, prtitle string, prid string, projectname string, reponame string, createdby string) {
mentions := makeMentionList(users)
for _, channel := range channels {
key := fmt.Sprintf("%s_%s", prid, channel)
mutex.Lock()
activeMonitoring[key] = true
mutex.Unlock()
for _, user := range users {
userAlreadyInterested := false
for _, user_ID := range interestedUsers[prid] {
if user_ID == user {
userAlreadyInterested = true
}
}
if !userAlreadyInterested {
interestedUsers[prid] = append(interestedUsers[prid], user)
}
}
var firstmessage string
if mentions == "" {
firstmessage = fmt.Sprintf("%s New PR '<%s|*%s*>' has been created in *%s/%s* by %s",
mentions,
prlink,
prtitle,
projectname,
reponame,
createdby,
)
} else {
firstmessage = fmt.Sprintf("New PR '<%s|*%s*>' has been created in *%s/%s* by %s",
prlink,
prtitle,
projectname,
reponame,
createdby,
)
}
parentMessageTs := sendSlackMessage(slackAccessToken, channel, firstmessage, "", "", false)
if !isCronRunning {
cronOnce.Do(func() {
startCron(azureDevOpsOrganization, azureDevOpsProject, reponame)
})
}
// loop until PR isn't active anymore
stopChannel := make(chan struct{})
go monitorPr(azureDevOpsOrganization, azureDevOpsProject, reponame, parentMessageTs, prid, prlink, channel, stopChannel)
}
}
func makeMentionList(users []string) string {
var list strings.Builder
for _, user := range users {
user = fmt.Sprintf("<@%s>", user)
list.WriteString(user)
}
return list.String()
}
func main() {
configuration := AutomaticPrMessages{}
err := gonfig.GetConf("automatic_prs.json", &configuration)
if err != nil {
fmt.Println("Error loading configuration:", err)
os.Exit(1)
}
if len(configuration.Projects) > 0 {
fmt.Println("-------------------\n[GLOBAL] Automatic PR configuration below")
for key, value := range configuration.Projects {
fmt.Println("-------------------\nProject:", key)
fmt.Println("ChannelIds:", value.ChannelIds)
fmt.Println("SlackUserIDs:", value.SlackUserIDs)
for key, value := range value.SpecificRepos {
fmt.Println("Repo:", key)
fmt.Println("-ChannelIds:", value.ChannelIds)
fmt.Println("-SlackUserIds:", value.SlackUserIDs)
}
}
fmt.Println("-------------------")
} else {
fmt.Println("[GLOBAL] No automatic PR configuration")
}
http.HandleFunc("/azuredevops", func(w http.ResponseWriter, r *http.Request) {
handleAzureDevopsWebhook(w, r, configuration)
})
http.HandleFunc("/slack/pr", handleSlackSlashCommand)
fmt.Println("[GLOBAL] Server listening on port 80...")
http.ListenAndServe(":80", nil)
}