/
main.go
280 lines (251 loc) · 6.14 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/nlopes/slack"
)
const (
jiraURL = "JIRA_URL"
jiraUser = "JIRA_USER"
jiraPassword = "JIRA_PASSWORD"
jiraIcon = "https://globus.atlassian.net/images/64jira.png"
slackToken = "SLACK_TOKEN"
issueURL = "/rest/api/2/issue/"
projectsURL = "/rest/api/2/project"
yellow = "#FFD442"
green = "#048A25"
blue = "#496686"
)
type (
// Project Jira project
Project struct {
ID string `json:"id"`
KEY string `json:"key"`
}
// JiraClient http client for connecting to the Jira server
JiraClient struct {
username string
password string
baseURL *url.URL
httpClient *http.Client
}
//Issue Jira issue
Issue struct {
Key string
Fields *IssueFields
}
//IssueFields fields for Jira issue
IssueFields struct {
IssueType *IssueType
Summary string
Creator *Creator
Assignee *Assignee
Priority *Priority
Status *Status
}
//IssueType Jira issue type e.g Task,Bug etc
IssueType struct {
IconURL string
Name string
}
//Creator Jira issue creator
Creator struct {
DisplayName string
}
//Assignee Jira issue assignee
Assignee struct {
DisplayName string
}
//Priority Jira issue priority
Priority struct {
Name string
IconURL string
}
//Status Jira issue status, e.g open closed
Status struct {
Name string
IconURL string
}
)
var (
//Pattern hold the issue regex
Pattern *regexp.Regexp
//Projects all of the Jira projects
Projects = []Project{}
//Slack slack client
Slack *slack.Client
//Client JiraClient
Client JiraClient
jiraHostURL string
jiraUserName string
jiraiUserPassword string
slackAPIToken string
)
//NewClient new jira client
func NewClient(username, password string, baseURL *url.URL) JiraClient {
return JiraClient{
username: username,
password: password,
baseURL: baseURL,
httpClient: &http.Client{Timeout: 10 * time.Second},
}
}
//GetProjects returns a representation of a Jira project for the given project key. An example of a key is MYPROJ.
func (client JiraClient) GetProjects() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s%s", client.baseURL, projectsURL), nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(client.username, client.password)
responseCode, data, err := client.consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
return fmt.Errorf("error getting project. Status code: %d.\n", responseCode)
}
if err := json.Unmarshal(data, &Projects); err != nil {
return err
}
return nil
}
//GetIssue serach jira for an issue
func (client JiraClient) GetIssue(issuekey string) (Issue, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s%s%s", client.baseURL, issueURL, issuekey), nil)
var issue Issue
if err != nil {
return issue, err
}
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(client.username, client.password)
responseCode, data, err := client.consumeResponse(req)
if err != nil {
return issue, err
}
if responseCode != http.StatusOK {
return issue, fmt.Errorf("error getting project. Status code: %d.\n", responseCode)
}
if err := json.Unmarshal(data, &issue); err != nil {
return issue, err
}
if issue.Key == "" {
return issue, errors.New("No Issue were found")
}
if issue.Fields.Assignee == nil {
issue.Fields.Assignee = &Assignee{"Unassigned"}
}
return issue, nil
}
func (client JiraClient) consumeResponse(req *http.Request) (rc int, buffer []byte, err error) {
response, err := client.httpClient.Do(req)
if err != nil {
return response.StatusCode, nil, err
}
defer response.Body.Close()
if data, err := ioutil.ReadAll(response.Body); err == nil {
return response.StatusCode, data, nil
}
return response.StatusCode, nil, err
}
func buildPattern() {
pattern := `(?:\W|^)((`
for _, p := range Projects {
pattern += p.KEY
pattern += "|"
}
pattern += `)-\d+)(\+)?|$`
Pattern = regexp.MustCompile(pattern)
}
func getColor(status string) (color string) {
switch status {
case "Open":
color = blue
case "Reopened":
color = blue
case "To Do":
color = blue
case "Resolved":
color = green
case "Closed":
color = green
case "Done":
color = green
default:
color = yellow
}
return color
}
func sendMessage(issue Issue, channel string) error {
params := slack.PostMessageParameters{}
text := fmt.Sprintf("*%s*\n\n *Assignee* %s *Priority* %s ", issue.Fields.Summary, issue.Fields.Assignee.DisplayName, issue.Fields.Priority.Name)
attachment := slack.Attachment{
Title: issue.Key,
TitleLink: fmt.Sprintf("%s/browse/%s", jiraHostURL, issue.Key),
Text: text,
Color: getColor(issue.Fields.Status.Name),
MarkdownIn: []string{"text", "pretext"},
}
params.Attachments = []slack.Attachment{attachment}
params.IconURL = jiraIcon
params.Username = "Jira"
_, _, err := Slack.PostMessage(channel, "", params)
if err != nil {
fmt.Printf("%s\n", err)
return err
}
return nil
}
func processEvents(text string, channel string, wg sync.WaitGroup) {
defer wg.Done()
matches := Pattern.FindStringSubmatch(text)
if matches != nil && matches[1] != "" {
issue, err := Client.GetIssue(strings.TrimSpace(matches[1]))
if err == nil {
sendMessage(issue, channel)
}
}
}
func main() {
var wg sync.WaitGroup
jiraHostURL = os.Getenv(jiraURL)
jiraUserName = os.Getenv(jiraUser)
jiraiUserPassword = os.Getenv(jiraPassword)
slackAPIToken = os.Getenv(slackToken)
url, _ := url.Parse(jiraHostURL)
Client = NewClient(jiraUserName, jiraiUserPassword, url)
Slack = slack.New(slackAPIToken)
Slack.SetDebug(false)
Client.GetProjects()
buildPattern()
rtm := Slack.NewRTM()
go rtm.ManageConnection()
Loop:
for {
select {
case msg := <-rtm.IncomingEvents:
switch ev := msg.Data.(type) {
case *slack.MessageEvent:
if ev.SubType != "bot_message" {
wg.Add(1)
go processEvents(ev.Text, ev.Channel, wg)
}
case *slack.InvalidAuthEvent:
fmt.Printf("Invalid credentials")
break Loop
default:
// Ignore other events..
}
}
}
wg.Wait()
}