-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
208 lines (174 loc) · 4.87 KB
/
client.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
package jira
import (
"bytes"
"encoding/json"
"fmt"
"github.com/bitrise-io/go-utils/colorstring"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/urlutil"
"io/ioutil"
"net/http"
"net/http/httputil"
)
const (
apiEndPoint = "/rest/api/2/issue/"
)
// Client ...
type Client struct {
token string
client *http.Client
headers map[string]string
baseURL string
}
// Comment ...
type Comment struct {
Content string
IssuKey string
}
type response struct {
issueKey string
err error
}
func (resp response) String() string {
respValue := map[bool]string{true: colorstring.Green("SUCCES"), false: colorstring.Red("FAILED")}[resp.err == nil]
return fmt.Sprintf("Posting comment to - %s - : %s", resp.issueKey, respValue)
}
// -------------------------------------
// -- Public methods
// NewClient ...
func NewClient(token, baseURL string) *Client {
return &Client{
token: token,
client: &http.Client{},
headers: map[string]string{
"Authorization": `Basic ` + token,
"Content-Type": "application/json",
},
baseURL: baseURL,
}
}
// PostIssueAddLabel ...
func (client *Client) PostIssueAddLabel(comments []Comment, AdditionalLabel string) error {
if len(comments) == 0 {
return fmt.Errorf("no comment has been added")
}
ch := make(chan response, len(comments))
for _, comment := range comments {
go client.postIssueLabel(comment, AdditionalLabel, ch)
}
counter := 0
var respErrors []response
for resp := range ch {
counter++
log.Printf(resp.String())
if resp.err != nil {
respErrors = append(respErrors, resp)
}
if counter >= len(comments) {
break
}
}
if len(respErrors) > 0 {
fmt.Println()
log.Infof("Errors during posting comments:")
for _, respErr := range respErrors {
log.Warnf("Error during posting comment to - %s - : %s", respErr.issueKey, respErr.err.Error())
}
fmt.Println()
}
return map[bool]error{true: fmt.Errorf("some comments were failed to be posted at Jira")}[len(respErrors) > 0]
}
// -------------------------------------
// -- Private methods
type TransitionRequest struct {
Update Update `json:"update"`
}
type Labels struct {
Add string `json:"add"`
}
type Set struct {
Name string `json:"name"`
}
type Update struct {
Labels []Labels `json:"labels"`
}
func (client *Client) postIssueLabel(comment Comment, AdditionalLabel string, ch chan response) {
requestURL, err := urlutil.Join(client.baseURL, apiEndPoint, comment.IssuKey)
if err != nil {
ch <- response{comment.IssuKey, err}
return
}
newFields := &TransitionRequest{
Update{
Labels: []Labels{{Add: AdditionalLabel}},
},
}
request, err := createRequest(http.MethodPut, requestURL, client.headers, newFields)
if err != nil {
ch <- response{comment.IssuKey, err}
return
}
requestBytes, err := httputil.DumpRequest(request, true)
if err != nil {
ch <- response{comment.IssuKey, err}
return
}
log.Debugf("Request: %v", string(requestBytes))
// Perform request
_, body, err := client.performRequest(request, nil)
log.Debugf("Body: %s", string(body))
ch <- response{comment.IssuKey, err}
}
func createRequest(requestMethod string, url string, headers map[string]string, fields *TransitionRequest) (*http.Request, error) {
var jsonContent []byte
var err error
if jsonContent, err = json.Marshal(fields); err != nil {
return nil, err
}
req, err := http.NewRequest(requestMethod, url, bytes.NewBuffer(jsonContent))
if err != nil {
return nil, err
}
addHeaders(req, headers)
return req, nil
}
func (client *Client) performRequest(req *http.Request, requestResponse interface{}) (interface{}, []byte, error) {
response, err := client.client.Do(req)
if err != nil {
// On error, any Response can be ignored
return nil, nil, fmt.Errorf("failed to perform request, error: %s", err)
}
// The client must close the response body when finished with it
defer func() {
if cerr := response.Body.Close(); cerr != nil {
log.Warnf("Failed to close response body, error: %s", cerr)
}
}()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body, error: %s", err)
}
if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusMultipleChoices {
return nil, nil, fmt.Errorf("Response status: %d - Body: %s", response.StatusCode, string(body))
}
// Parse JSON body
if requestResponse != nil {
if err := json.Unmarshal([]byte(body), &requestResponse); err != nil {
return nil, nil, fmt.Errorf("failed to unmarshal response (%s), error: %s", body, err)
}
logDebugPretty(&requestResponse)
}
return requestResponse, body, nil
}
func addHeaders(req *http.Request, headers map[string]string) {
for key, value := range headers {
req.Header.Set(key, value)
}
}
func logDebugPretty(v interface{}) {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
fmt.Println("error:", err)
}
log.Debugf("Response: %+v\n", string(b))
}