forked from plouc/go-gitlab-client
/
gitlab.go
290 lines (237 loc) · 6.08 KB
/
gitlab.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
// Package github implements a simple client to consume gitlab API.
package gitlab
import (
"bytes"
"crypto/tls"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/google/go-querystring/query"
)
const (
DashboardFeedPath = "/dashboard.atom"
)
type Gitlab struct {
BaseUrl string
ApiPath string
RepoFeedPath string
Token string
Client *http.Client
}
type PaginationOptions struct {
Page int `url:"page,omitempty"`
PerPage int `url:"per_page,omitempty"`
}
type SortDirection string
const (
SortDirectionAsc SortDirection = "asc"
SortDirectionDesc SortDirection = "desc"
)
type SortOptions struct {
OrderBy string `url:"order_by,omitempty"`
Sort SortDirection `url:"sort,omitempty"`
}
type ResponseWithMessage struct {
Message string `json:"message"`
}
type ResponseMeta struct {
Method string
Url string
StatusCode int
RequestId string
Page int
PerPage int
PrevPage int
NextPage int
TotalPages int
Total int
Runtime float64
}
const (
dateLayout = "2006-01-02T15:04:05-07:00"
)
var (
skipCertVerify = flag.Bool("gitlab.skip-cert-check", false,
`If set to true, gitlab client will skip certificate checking for https, possibly exposing your system to MITM attack.`)
)
// NewGitlab generates a new gitlab service
func NewGitlab(baseUrl, apiPath, token string) *Gitlab {
config := &tls.Config{InsecureSkipVerify: *skipCertVerify}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: config,
}
client := &http.Client{Transport: tr}
return &Gitlab{
BaseUrl: baseUrl,
ApiPath: apiPath,
Token: token,
Client: client,
}
}
// ResourceUrl builds an url for given resource path.
//
// It replaces path placeholders with values from `params`:
//
// /whatever/:id => /whatever/1
//
func (g *Gitlab) ResourceUrl(path string, params map[string]string) *url.URL {
if params != nil {
for key, val := range params {
path = strings.Replace(path, key, val, -1)
}
}
u, err := url.Parse(g.BaseUrl + g.ApiPath + path)
if err != nil {
panic("Error while building gitlab url, unable to parse generated url")
}
return u
}
// ResourceUrlQ generates an url and appends a query string to it if available
func (g *Gitlab) ResourceUrlQ(path string, params map[string]string, qs interface{}) *url.URL {
u := g.ResourceUrl(path, params)
if qs != nil {
v, err := query.Values(qs)
if err != nil {
panic("Error while building gitlab url, unable to set query string")
}
u.RawQuery = v.Encode()
}
return u
}
func (g *Gitlab) execRequest(method, url string, body []byte) (*http.Response, error) {
var req *http.Request
var err error
if body != nil {
reader := bytes.NewReader(body)
req, err = http.NewRequest(method, url, reader)
} else {
req, err = http.NewRequest(method, url, nil)
}
req.Header.Add("Private-Token", g.Token)
if method == "POST" || method == "PUT" {
req.Header.Add("Content-Type", "application/json")
}
if err != nil {
panic("Error while building gitlab request")
}
resp, err := g.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("Client.Do error: %q", err)
}
if resp.StatusCode >= http.StatusBadRequest {
err = fmt.Errorf("*Gitlab.buildAndExecRequest failed: <%d> %s %s", resp.StatusCode, req.Method, req.URL)
}
return resp, err
}
func buildResponseMeta(resp *http.Response, method, u string) ResponseMeta {
meta := ResponseMeta{}
meta.Method = method
meta.Url = u
meta.StatusCode = resp.StatusCode
requestId := resp.Header.Get("X-Request-Id")
if requestId != "" {
meta.RequestId = requestId
}
page := resp.Header.Get("X-Page")
if page != "" {
pageInt, err := strconv.Atoi(page)
if err == nil {
meta.Page = pageInt
}
}
perPage := resp.Header.Get("X-Per-Page")
if perPage != "" {
perPageInt, err := strconv.Atoi(perPage)
if err == nil {
meta.PerPage = perPageInt
}
}
prevPage := resp.Header.Get("X-Prev-Page")
if prevPage != "" {
prevPageInt, err := strconv.Atoi(prevPage)
if err == nil {
meta.PrevPage = prevPageInt
}
}
nextPage := resp.Header.Get("X-Next-Page")
if nextPage != "" {
nextPageInt, err := strconv.Atoi(nextPage)
if err == nil {
meta.NextPage = nextPageInt
}
}
totalPages := resp.Header.Get("X-Total-Pages")
if totalPages != "" {
totalPagesInt, err := strconv.Atoi(totalPages)
if err == nil {
meta.TotalPages = totalPagesInt
}
}
total := resp.Header.Get("X-Total")
if total != "" {
totalInt, err := strconv.Atoi(total)
if err == nil {
meta.Total = totalInt
}
}
runtime := resp.Header.Get("X-Runtime")
if total != "" {
runtimeFloat, err := strconv.ParseFloat(runtime, 64)
if err == nil {
meta.Runtime = runtimeFloat
}
}
return meta
}
func (g *Gitlab) buildAndExecRequest(method, u string, body []byte) ([]byte, *ResponseMeta, error) {
resp, err := g.execRequest(method, u, body)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
}
meta := buildResponseMeta(resp, method, u)
return contents, &meta, err
}
func (g *Gitlab) buildAndExecRequestRaw(method, u, opaque string, body []byte) ([]byte, *ResponseMeta, error) {
var req *http.Request
var err error
if body != nil {
reader := bytes.NewReader(body)
req, err = http.NewRequest(method, u, reader)
} else {
req, err = http.NewRequest(method, u, nil)
}
req.Header.Add("Private-Token", g.Token)
if method == "POST" || method == "PUT" {
req.Header.Add("Content-Type", "application/json")
}
if err != nil {
panic("Error while building gitlab request")
}
if len(opaque) > 0 {
req.URL.Opaque = opaque
}
resp, err := g.Client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("Client.Do error: %q", err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
}
if resp.StatusCode >= http.StatusBadRequest {
err = fmt.Errorf("*Gitlab.buildAndExecRequestRaw failed: <%d> %s %s", resp.StatusCode, req.Method, req.URL)
}
meta := buildResponseMeta(resp, method, u)
return contents, &meta, err
}