This repository has been archived by the owner on Oct 16, 2023. It is now read-only.
forked from afrase/gh-notify-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (154 loc) · 5.5 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/google/go-github/github"
"github.com/nlopes/slack"
)
const (
slackProdMsgText string = ":ship: New Production release for [*<%s|%s>*] `%s`"
slackStageMsgText string = ":construction: New Stage release for [*<%s|%s>*] `%s`"
slackDisplayUsername string = "Release Bot"
defaultFieldColor string = "36a64f"
circleCIProjectURL = "https://circleci.com/api/v1.1/project/github/%s/%s?circle-token=%s"
circleCIWorkflowURL = "https://circleci.com/workflow-run/%s"
)
var (
pullRequestRegexp = regexp.MustCompile(`#(\d+)`)
)
// Build struct for CircleCI response
type Build struct {
VcsTag string `json:"vcs_tag"`
Workflows Workflow `json:"workflows"`
}
// Workflow struct for CircleCI response
type Workflow struct {
WorkflowID string `json:"workflow_id"`
}
func getCircleCIBuilds(url string) ([]Build, error) {
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Accept", "application/json")
// Set a 60 second timeout.
client := &http.Client{Timeout: time.Second * 60}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var circleBuilds []Build
if err := json.Unmarshal(body, &circleBuilds); err != nil {
return nil, err
}
return circleBuilds, nil
}
func getCircleCIBuildURL(token, account, repo, tag string) (string, bool) {
if token == "" {
return "", false
}
url := fmt.Sprintf(circleCIProjectURL, account, repo, token)
// try 4 times to find the build url
for i := 1; i < 4; i++ {
builds, err := getCircleCIBuilds(url)
if err != nil {
break
}
for _, build := range builds {
if build.VcsTag == tag {
return fmt.Sprintf(circleCIWorkflowURL, build.Workflows.WorkflowID), true
}
}
time.Sleep(time.Duration(i*2) * time.Second)
}
return "", false
}
func parseReleaseBody(payload *github.ReleaseEvent) string {
pullRequestURL := fmt.Sprintf("<%s/pull/$1|#$1>", payload.Repo.GetHTMLURL())
return pullRequestRegexp.ReplaceAllString(payload.Release.GetBody(), pullRequestURL)
}
func buildAttachment(payload *github.ReleaseEvent, color string) slack.Attachment {
// If the author was a bot then use the sender which is the person who publishes the release.
var user *github.User
if payload.Release.Author.GetType() == "Bot" {
user = payload.Sender
} else {
user = payload.Release.Author
}
attachment := slack.Attachment{
Title: payload.Release.GetName(),
AuthorName: user.GetLogin(),
AuthorIcon: user.GetAvatarURL(),
AuthorLink: user.GetHTMLURL(),
Text: parseReleaseBody(payload),
Color: fmt.Sprintf("#%s", color),
Ts: json.Number(fmt.Sprintf("%d", payload.Release.GetPublishedAt().Unix())),
Fields: []slack.AttachmentField{
{
Title: "Tag",
Value: payload.Release.GetHTMLURL(),
Short: false,
},
},
}
repo := strings.Split(payload.Repo.GetFullName(), "/")
buildURL, ok := getCircleCIBuildURL(os.Getenv("CIRCLECI_TOKEN"), repo[0], repo[1], payload.Release.GetTagName())
// add the CircleCI link if it exists
if ok {
attachment.Fields = append(attachment.Fields, slack.AttachmentField{Title: "CircleCI", Value: buildURL, Short: false})
}
return attachment
}
func sendSlackMessage(event *github.ReleaseEvent, token, channel, color string) error {
attachment := buildAttachment(event, color)
username := slack.MsgOptionUsername(slackDisplayUsername)
var text string
if strings.Contains(event.Release.GetTagName(), "-rc") {
text = fmt.Sprintf(slackStageMsgText, event.Repo.GetHTMLURL(), event.Repo.GetName(), event.Release.GetTagName())
} else {
text = fmt.Sprintf(slackProdMsgText, event.Repo.GetHTMLURL(), event.Repo.GetName(), event.Release.GetTagName())
}
message := slack.MsgOptionText(text, false)
client := slack.New(token)
_, _, err := client.PostMessage(channel, message, username, slack.MsgOptionAttachments(attachment))
return err
}
// Handler is executed by AWS Lambda in the main function. Once the request
// is processed, it returns an Amazon API Gateway response object to AWS Lambda
func Handler(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
// Check the headers first because the body might not be in a format we expect.
eventType := req.Headers["X-GitHub-Event"]
// we only care about release events.
if eventType != "release" {
return events.APIGatewayProxyResponse{Body: "Skipping because event is not 'release'", StatusCode: 200}, nil
}
// Parse the body into a `github.ReleaseEvent` struct.
var payload github.ReleaseEvent
if err := json.Unmarshal([]byte(req.Body), &payload); err != nil {
return events.APIGatewayProxyResponse{StatusCode: 500, Body: "Unable to handle request"}, err
}
// New actions have been added to the 'release' event. Only look for the 'publish' action.
if *payload.Action != "published" {
return events.APIGatewayProxyResponse{Body: "Skipping because action is not 'published'", StatusCode: 200}, nil
}
// Get the color query param if it exists.
color, ok := req.QueryStringParameters["color"]
if !ok {
color = defaultFieldColor
}
err := sendSlackMessage(&payload, req.PathParameters["token"], req.PathParameters["channel"], color)
if err != nil {
return events.APIGatewayProxyResponse{StatusCode: 500, Body: "Failed to send slack message"}, err
}
return events.APIGatewayProxyResponse{Body: "Success", StatusCode: 200}, nil
}
func main() {
lambda.Start(Handler)
}