forked from rtCamp/action-slack-notify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
391 lines (355 loc) · 10 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"strings"
)
const (
EnvSlackWebhook = "SLACK_WEBHOOK"
EnvSlackCustom = "SLACK_CUSTOM_PAYLOAD"
EnvSlackIcon = "SLACK_ICON"
EnvSlackIconEmoji = "SLACK_ICON_EMOJI"
EnvSlackChannel = "SLACK_CHANNEL"
EnvSlackTitle = "SLACK_TITLE"
EnvSlackMessage = "SLACK_MESSAGE"
EnvSlackOnSuccess = "SLACK_MESSAGE_ON_SUCCESS"
EnvSlackOnFailure = "SLACK_MESSAGE_ON_FAILURE"
EnvSlackOnCancel = "SLACK_MESSAGE_ON_CANCEL"
EnvSlackColor = "SLACK_COLOR"
EnvSlackUserName = "SLACK_USERNAME"
EnvSlackFooter = "SLACK_FOOTER"
EnvGithubActor = "GITHUB_ACTOR"
EnvGithubRun = "GITHUB_RUN"
EnvSiteName = "SITE_NAME"
EnvHostName = "HOST_NAME"
EnvMinimal = "MSG_MINIMAL"
EnvSlackLinkNames = "SLACK_LINK_NAMES"
EnvThreadTs = "SLACK_THREAD_TS"
EnvSlackUpload = "SLACK_FILE_UPLOAD"
EnvMessageMode = "MSG_MODE"
)
type Webhook struct {
Text string `json:"text,omitempty"`
UserName string `json:"username,omitempty"`
IconURL string `json:"icon_url,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
Channel string `json:"channel,omitempty"`
LinkNames string `json:"link_names,omitempty"`
UnfurlLinks bool `json:"unfurl_links"`
Attachments []Attachment `json:"attachments,omitempty"`
ThreadTs string `json:"thread_ts,omitempty"`
}
type Attachment struct {
Fallback string `json:"fallback"`
Pretext string `json:"pretext,omitempty"`
Color string `json:"color,omitempty"`
AuthorName string `json:"author_name,omitempty"`
AuthorLink string `json:"author_link,omitempty"`
AuthorIcon string `json:"author_icon,omitempty"`
Footer string `json:"footer,omitempty"`
Fields []Field `json:"fields,omitempty"`
}
type Field struct {
Title string `json:"title,omitempty"`
Value string `json:"value,omitempty"`
Short bool `json:"short,omitempty"`
}
func main() {
endpoint := getEnv(EnvSlackWebhook)
custom_payload := envOr(EnvSlackCustom, "")
if endpoint == "" {
if getEnv(EnvSlackChannel) == "" {
fmt.Fprintln(os.Stderr, "Channel is required for sending message using a token")
os.Exit(1)
}
if getEnv(EnvMessageMode) == "TOKEN" {
endpoint = "https://slack.com/api/chat.postMessage"
} else {
fmt.Fprintln(os.Stderr, "URL is required")
os.Exit(2)
}
}
if custom_payload != "" {
if err := send_raw(endpoint, []byte(custom_payload)); err != nil {
fmt.Fprintf(os.Stderr, "Error sending message: %s\n", err)
os.Exit(2)
}
} else {
text := getEnv(EnvSlackMessage)
if text == "" {
fmt.Fprintln(os.Stderr, "Message is required")
os.Exit(3)
}
if strings.HasPrefix(getEnv("GITHUB_WORKFLOW"), ".github") {
err := os.Setenv("GITHUB_WORKFLOW", "Link to action run.yaml")
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to update the workflow's variables: %s\n\n", err)
os.Exit(4)
}
}
long_sha := getEnv("GITHUB_SHA")
commit_sha := long_sha[0:6]
color := ""
switch strings.ToLower(getEnv(EnvSlackColor)) {
case "success":
color = "good"
// If exists, override with on success
success_msg := envOr(EnvSlackOnSuccess, "")
if success_msg != "" {
text = success_msg
}
case "cancelled":
color = "#808080"
// If exists, override with on cancel
cancel_msg := envOr(EnvSlackOnCancel, "")
if cancel_msg != "" {
text = cancel_msg
}
case "failure":
color = "danger"
// If exists, override with on failure
failure_msg := envOr(EnvSlackOnFailure, "")
if failure_msg != "" {
text = failure_msg
}
default:
color = envOr(EnvSlackColor, "good")
}
if text == "" {
text = "EOM"
}
minimal := getEnv(EnvMinimal)
fields := []Field{}
if minimal == "true" {
mainFields := []Field{
{
Title: getEnv(EnvSlackTitle),
Value: text,
Short: false,
},
}
fields = append(mainFields, fields...)
} else if minimal != "" {
requiredFields := strings.Split(minimal, ",")
mainFields := []Field{
{
Title: getEnv(EnvSlackTitle),
Value: text,
Short: false,
},
}
for _, requiredField := range requiredFields {
switch strings.ToLower(requiredField) {
case "ref":
field := []Field{
{
Title: "Ref",
Value: getEnv("GITHUB_REF"),
Short: true,
},
}
mainFields = append(field, mainFields...)
case "event":
field := []Field{
{
Title: "Event",
Value: getEnv("GITHUB_EVENT_NAME"),
Short: true,
},
}
mainFields = append(field, mainFields...)
case "actions url":
field := []Field{
{
Title: "Actions URL",
Value: "<" + getEnv("GITHUB_SERVER_URL") + "/" + getEnv("GITHUB_REPOSITORY") + "/commit/" + getEnv("GITHUB_SHA") + "/checks|" + getEnv("GITHUB_WORKFLOW") + ">",
Short: true,
},
}
mainFields = append(field, mainFields...)
case "commit":
field := []Field{
{
Title: "Commit",
Value: "<" + getEnv("GITHUB_SERVER_URL") + "/" + getEnv("GITHUB_REPOSITORY") + "/commit/" + getEnv("GITHUB_SHA") + "|" + commit_sha + ">",
Short: true,
},
}
mainFields = append(field, mainFields...)
}
}
fields = append(mainFields, fields...)
} else {
mainFields := []Field{
{
Title: "Ref",
Value: getEnv("GITHUB_REF"),
Short: true,
}, {
Title: "Event",
Value: getEnv("GITHUB_EVENT_NAME"),
Short: true,
},
{
Title: "Actions URL",
Value: "<" + getEnv("GITHUB_SERVER_URL") + "/" + getEnv("GITHUB_REPOSITORY") + "/commit/" + getEnv("GITHUB_SHA") + "/checks|" + getEnv("GITHUB_WORKFLOW") + ">",
Short: true,
},
{
Title: "Commit",
Value: "<" + getEnv("GITHUB_SERVER_URL") + "/" + getEnv("GITHUB_REPOSITORY") + "/commit/" + getEnv("GITHUB_SHA") + "|" + commit_sha + ">",
Short: true,
},
{
Title: getEnv(EnvSlackTitle),
Value: text,
Short: false,
},
}
fields = append(mainFields, fields...)
}
hostName := getEnv(EnvHostName)
if hostName != "" {
newfields := []Field{
{
Title: getEnv("SITE_TITLE"),
Value: getEnv(EnvSiteName),
Short: true,
},
{
Title: getEnv("HOST_TITLE"),
Value: getEnv(EnvHostName),
Short: true,
},
}
fields = append(newfields, fields...)
}
msg := Webhook{
UserName: getEnv(EnvSlackUserName),
IconURL: getEnv(EnvSlackIcon),
IconEmoji: getEnv(EnvSlackIconEmoji),
Channel: getEnv(EnvSlackChannel),
LinkNames: getEnv(EnvSlackLinkNames),
ThreadTs: getEnv(EnvThreadTs),
Attachments: []Attachment{
{
Fallback: envOr(EnvSlackMessage, "GITHUB_ACTION="+getEnv("GITHUB_ACTION")+" \n GITHUB_ACTOR="+getEnv("GITHUB_ACTOR")+" \n GITHUB_EVENT_NAME="+getEnv("GITHUB_EVENT_NAME")+" \n GITHUB_REF="+getEnv("GITHUB_REF")+" \n GITHUB_REPOSITORY="+getEnv("GITHUB_REPOSITORY")+" \n GITHUB_WORKFLOW="+getEnv("GITHUB_WORKFLOW")),
Color: color,
AuthorName: envOr(EnvGithubActor, ""),
AuthorLink: getEnv("GITHUB_SERVER_URL") + "/" + getEnv(EnvGithubActor),
AuthorIcon: getEnv("GITHUB_SERVER_URL") + "/" + getEnv(EnvGithubActor) + ".png?size=32",
Footer: envOr(EnvSlackFooter, "<https://github.com/rtCamp/github-actions-library|Powered By rtCamp's GitHub Actions Library> | <"+getEnv(EnvGithubRun)+"|Triggered on this workflow run>"),
Fields: fields,
},
},
}
if err := send(endpoint, msg); err != nil {
fmt.Fprintf(os.Stderr, "Error sending message: %s\n", err)
os.Exit(1)
}
}
fmt.Fprintf(os.Stdout, "Successfully sent the message!")
}
func getEnv(name string) string {
return strings.TrimSpace(os.Getenv(name))
}
func envOr(name, def string) string {
if d, ok := os.LookupEnv(name); ok {
return strings.TrimSpace(d)
}
return def
}
func send(endpoint string, msg Webhook) error {
enc, err := json.Marshal(msg)
if err != nil {
return err
}
return send_raw(endpoint, enc)
}
func send_raw(endpoint string, payload []byte) error {
b := bytes.NewBuffer(payload)
var res *http.Response
var err error
switch getEnv(EnvMessageMode) {
case "WEBHOOK":
res, err = http.Post(endpoint, "application/json", b)
case "TOKEN":
req, err := http.NewRequest("POST", endpoint, b)
if err != nil {
return fmt.Errorf("Error creating request: %s\n", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+getEnv("SLACK_TOKEN"))
client := &http.Client{}
res, err = client.Do(req)
default:
fmt.Fprintf(os.Stderr, "Invalid message mode: %s\n", getEnv(EnvMessageMode))
os.Exit(6)
}
if err != nil {
return err
}
if res.StatusCode >= 299 {
return fmt.Errorf("Error on message: %s\n", res.Status)
}
if os.Getenv(EnvSlackUpload) != "" {
err = sendFile(os.Getenv(EnvSlackUpload), "", os.Getenv(EnvSlackChannel), os.Getenv(EnvThreadTs))
if err != nil {
return err
}
}
return nil
}
func sendFile(filename string, message string, channel string, thread_ts string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
fileData := &bytes.Buffer{}
writer := multipart.NewWriter(fileData)
part, err := writer.CreateFormFile("file", filename)
if err != nil {
return err
}
_, err = io.Copy(part, file)
err = writer.WriteField("initial_comment", message)
if err != nil {
return err
}
err = writer.WriteField("channels", channel)
if err != nil {
return err
}
if thread_ts != "" {
err = writer.WriteField("thread_ts", thread_ts)
if err != nil {
return err
}
}
err = writer.Close()
if err != nil {
return err
}
req, err := http.NewRequest("POST", "https://slack.com/api/files.upload", fileData)
if err != nil {
return err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+os.Getenv("SLACK_TOKEN"))
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return err
}
if res.StatusCode >= 299 {
return fmt.Errorf("Error on message: %s\n", res.Status)
}
fmt.Println(res.Status)
return nil
}