forked from drone-plugins/drone-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
126 lines (110 loc) · 2.15 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
package main
import (
"fmt"
"strings"
"github.com/bluele/slack"
)
type (
Repo struct {
Owner string
Name string
}
Build struct {
Tag string
Event string
Number int
Commit string
Ref string
Branch string
Author string
Message string
Status string
Link string
Started int64
Created int64
}
Config struct {
Webhook string
Channel string
Recipient string
Username string
Template string
ImageURL string
IconURL string
IconEmoji string
}
Job struct {
Started int64
}
Plugin struct {
Repo Repo
Build Build
Config Config
Job Job
}
)
func (p Plugin) Exec() error {
attachment := slack.Attachment{
Text: message(p.Repo, p.Build),
Fallback: fallback(p.Repo, p.Build),
Color: color(p.Build),
MarkdownIn: []string{"text", "fallback"},
ImageURL: p.Config.ImageURL,
}
payload := slack.WebHookPostPayload{}
payload.Username = p.Config.Username
payload.Attachments = []*slack.Attachment{&attachment}
payload.IconUrl = p.Config.IconURL
payload.IconEmoji = p.Config.IconEmoji
if p.Config.Recipient != "" {
payload.Channel = prepend("@", p.Config.Recipient)
} else if p.Config.Channel != "" {
payload.Channel = prepend("#", p.Config.Channel)
}
if p.Config.Template != "" {
txt, err := RenderTrim(p.Config.Template, p)
if err != nil {
return err
}
attachment.Text = txt
}
client := slack.NewWebHook(p.Config.Webhook)
return client.PostMessage(&payload)
}
func message(repo Repo, build Build) string {
return fmt.Sprintf("*%s* <%s|%s/%s#%s> (%s) by %s",
build.Status,
build.Link,
repo.Owner,
repo.Name,
build.Commit[:8],
build.Branch,
build.Author,
)
}
func fallback(repo Repo, build Build) string {
return fmt.Sprintf("%s %s/%s#%s (%s) by %s",
build.Status,
repo.Owner,
repo.Name,
build.Commit[:8],
build.Branch,
build.Author,
)
}
func color(build Build) string {
switch build.Status {
case "success":
return "good"
case "failure", "error", "killed":
return "danger"
default:
return "warning"
}
}
func prepend(prefix, s string) string {
if !strings.HasPrefix(s, prefix) {
return prefix + s
}
return s
}