-
Notifications
You must be signed in to change notification settings - Fork 16
/
plugin.go
314 lines (266 loc) · 6.86 KB
/
plugin.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/drone/drone-template-lib/template"
"github.com/nlopes/slack"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type (
// MessageOptions contains the slack message.
MessageOptions struct {
Icon string
Username string
Template string
ImageAttachments []string
}
// Repo information.
Repo struct {
FullName string
Owner string
Name string
Link string
}
// Build information.
Build struct {
Commit string
Branch string
Ref string
Link string
Message string
Author string
Email string
Number int
Status string
Event string
Deploy string
BuildLink string
}
// Config for the plugin.
Config struct {
Token string
Channel string
Mapping string
Success MessageOptions
Failure MessageOptions
}
// Plugin values.
Plugin struct {
Repo Repo
Build Build
BuildLast Build
Config Config
User *slack.User
}
// searchFunc determines how to search for a slack user.
searchFunc func(*slack.User, string) bool
)
// Exec executes the plugin.
func (p Plugin) Exec() error {
// create the API
api := slack.New(p.Config.Token)
// verify the connection
authResponse, err := api.AuthTest()
if err != nil {
return errors.Wrap(err, "failed to test auth")
}
logrus.WithFields(logrus.Fields{
"team": authResponse.Team,
"user": authResponse.User,
}).Info("Successfully authenticated with Slack API")
// get the user
p.User, _ = p.findSlackUser(api)
// get the associated @ string
messageOptions := p.createMessage()
var userAt string
if p.User != nil {
userAt = fmt.Sprintf("@%s", p.User.Name)
_, _, err := api.PostMessage(userAt, messageOptions)
if err == nil {
logrus.WithFields(logrus.Fields{
"username": p.User.Name,
}).Info("Notified user")
} else {
logrus.WithFields(logrus.Fields{
"username": p.User.Name,
}).Error("Could not notify user")
}
} else {
userAt = p.Build.Author
logrus.WithFields(logrus.Fields{
"author": userAt,
}).Error("Could not find author")
}
if p.Config.Channel != "" {
if !strings.HasPrefix(p.Config.Channel, "#") {
p.Config.Channel = "#" + p.Config.Channel
}
_, _, err := api.PostMessage(p.Config.Channel, messageOptions)
if err == nil {
logrus.WithFields(logrus.Fields{
"channel": p.Config.Channel,
}).Info("Channel notified")
} else {
logrus.WithFields(logrus.Fields{
"channel": p.Config.Channel,
}).Error("Unable to notify channel")
}
}
return nil
}
// createMessage generates the message to post to Slack.
func (p Plugin) createMessage() slack.MsgOption {
// This is currently deprecated
var messageOptions MessageOptions
var color string
var messageTitle string
// Determine if the build was a success
if p.Build.Status == "success" {
messageOptions = p.Config.Success
color = "good"
messageTitle = "Build succeeded"
} else {
messageOptions = p.Config.Failure
color = "danger"
messageTitle = "Build failed"
}
// setup the message
messageParams := slack.PostMessageParameters{
Username: messageOptions.Username,
}
if strings.HasPrefix(messageOptions.Icon, "http") {
logrus.Info("Icon is a URL")
messageParams.IconURL = messageOptions.Icon
} else {
logrus.Info("Icon is an emoji")
messageParams.IconEmoji = messageOptions.Icon
}
messageText, err := template.Render(messageOptions.Template, &p)
if err != nil {
logrus.Error("Could not parse template")
}
// create the attachment
attachment := slack.Attachment{
Color: color,
Text: messageText,
Title: messageTitle,
TitleLink: p.Build.Link,
}
// Add image if any are provided
imageCount := len(messageOptions.ImageAttachments)
if imageCount > 0 {
logrus.WithFields(logrus.Fields{
"count": imageCount,
}).Info("Choosing from images")
rand.Seed(time.Now().UTC().UnixNano())
attachment.ImageURL = messageOptions.ImageAttachments[rand.Intn(imageCount)]
}
return slack.MsgOptionCompose(
slack.MsgOptionPostMessageParameters(messageParams),
slack.MsgOptionAttachments(attachment),
)
}
// findSlackUser uses the slack API to find the user who made the commit that
// is being built.
func (p Plugin) findSlackUser(api *slack.Client) (*slack.User, error) {
// get the mapping
mapping := userMapping(p.Config.Mapping)
// determine the search function to use
var search searchFunc
var find string
if val, ok := mapping[p.Build.Email]; ok {
logrus.WithFields(logrus.Fields{
"username": val,
}).Info("Searching for user by name, using build.email as key")
search = checkUsername
find = val
} else if val, ok := mapping[p.Build.Author]; ok {
logrus.WithFields(logrus.Fields{
"username": val,
}).Info("Searching for user by name, using build.author as key")
search = checkUsername
find = val
} else {
logrus.WithFields(logrus.Fields{
"email": p.Build.Email,
}).Info("Searching for user by email")
search = checkEmail
find = p.Build.Email
}
if len(find) == 0 {
return nil, errors.New("No user to search for")
}
// search for the user
users, err := api.GetUsers()
if err != nil {
return nil, errors.Wrap(err, "failed to query users")
}
var blameUser *slack.User
for _, user := range users {
if search(&user, find) {
logrus.WithFields(logrus.Fields{
"username": user.Name,
"email": user.Profile.Email,
}).Info("Found user")
blameUser = &user
break
} else {
logrus.WithFields(logrus.Fields{
"username": user.Name,
"email": user.Profile.Email,
}).Debug("User")
}
}
return blameUser, nil
}
// userMapping gets the user mapping file.
func userMapping(value string) map[string]string {
mapping := []byte(contents(value))
// turn into a map
values := map[string]string{}
err := json.Unmarshal(mapping, &values)
if err != nil {
if len(mapping) != 0 {
logrus.WithFields(logrus.Fields{
"mapping": value,
"error": err,
}).Error("Could not parse mapping")
}
values = make(map[string]string)
}
return values
}
// contents gets the value referenced either in a local filem, a URL or the
// string value itself.
func contents(s string) string {
if _, err := os.Stat(s); err == nil {
o, _ := ioutil.ReadFile(s)
return os.ExpandEnv(string(o))
}
if _, err := url.Parse(s); err == nil {
resp, err := http.Get(s)
if err != nil {
return s
}
defer resp.Body.Close()
o, _ := ioutil.ReadAll(resp.Body)
return os.ExpandEnv(string(o))
}
return os.ExpandEnv(s)
}
// checkEmail sees if the email is used by the user.
func checkEmail(user *slack.User, email string) bool {
return strings.EqualFold(user.Profile.Email, email)
}
// checkUsername sees if the username is the same as the user.
func checkUsername(user *slack.User, name string) bool {
return user.Profile.DisplayName == name || user.RealName == name
}