-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgitlab.go
407 lines (324 loc) · 9.38 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type mergeRequest struct {
Id int `json:"id"`
Iid int `json:"iid"`
Title string `json:"title"`
Description string `json:"description"`
SourceBranch string `json:"source_branch"`
TargetBranch string `json:"target_branch"`
}
type mergeRequestCreateRequest struct {
SourceBranch string `json:"source_branch"`
TargetBranch string `json:"target_branch"`
Title string `json:"title"`
}
type session struct {
PrivateToken string `json:"private_token"`
}
type GitlabError []string
func (g GitlabError) Error() string {
return "Gitlab:\n\t - " + strings.Join(g, "\n\t -") + "\n"
}
// TODO: Handle advanced {"message": {...}} responses:
// https://github.com/gitlabhq/gitlabhq/tree/master/doc/api#data-validation-and-error-reporting
type errorResponse struct {
Errors []string `json:"error"` // An {"error": ["..."]} is returned, fx when creating a MR from master to master
Message json.RawMessage `json:"message"` // "message" kan be a string or a structure
}
type sessionRequest struct {
Login string `json:"login"`
Password string `json:"password"`
}
type gitlab struct {
scheme string
host string
apiPath string
token string
}
type activityFeed struct {
Title string `xml:"title"`
Entries []*feedCommit `xml:"entry"`
}
type feedCommit struct {
Title string `xml:"title"`
Updated time.Time `xml:"updated"`
}
const MERGE_REQUEST_STATE_OPENED string = "opened"
const DASHBOARD_FEED_PATH string = "/dashboard.atom"
func (g gitlab) getProjectUrl(path string) string {
return g.scheme + "://" + g.host + "/" + strings.TrimPrefix(path, "/")
}
func (g gitlab) getMergeRequestUrl(projectId string, mergeRequestId int) string {
projectId, _ = url.QueryUnescape(projectId)
projectId = strings.Trim(projectId, "/")
return g.scheme + "://" + g.host + "/" + projectId + "/merge_requests/" + strconv.Itoa(mergeRequestId)
}
func newGitlab(host string) gitlab {
return gitlab{"http", host, "/api/v3", ""}
}
func (g gitlab) getPrivateTokenUrl() string {
return g.scheme + "://" + g.host + "/profile/account"
}
func (g gitlab) getFeedUrl() string {
return g.scheme + "://" + g.host + DASHBOARD_FEED_PATH + "?private_token=" + g.token
}
func (g gitlab) buildFeed(method, url string, body []byte) ([]byte, 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)
}
if err != nil {
panic("Error while building gitlab request")
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return 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 >= 400 {
err = fmt.Errorf("buildFeed failed: <%d> %s", resp.StatusCode, req.URL)
}
return contents, err
}
func (g gitlab) getApiUrl(pathSegments ...string) string {
return g.getUnauthApiUrl(pathSegments...) + "?private_token=" + g.token
}
func (g gitlab) getUnauthApiUrl(pathSegments ...string) string {
return g.scheme + "://" + g.host + g.apiPath + "/" + strings.Join(pathSegments, "/")
}
func (g gitlab) getOpaqueApiUrl(pathSegments ...string) string {
return g.getUnauthOpaqueApiUrl(pathSegments...) + "?private_token=" + g.token
}
func (g gitlab) getUnauthOpaqueApiUrl(pathSegments ...string) string {
return "//" + g.host + g.apiPath + "/" + strings.Join(pathSegments, "/")
}
func (g gitlab) createMergeRequest(projectId, sourceBranch, targetBranch, title string) (*mergeRequest, error) {
requestBody := mergeRequestCreateRequest{
SourceBranch: sourceBranch,
TargetBranch: targetBranch,
Title: title,
}
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
err := encoder.Encode(requestBody)
if nil != err {
return nil, err
}
addr := g.getApiUrl("projects", url.QueryEscape(projectId), "merge_requests")
req, err := http.NewRequest("POST", addr, buffer)
req.URL = &url.URL{
Scheme: g.scheme,
Host: g.host,
// Use opaque url to preserve "%2F"
Opaque: g.getOpaqueApiUrl("projects", url.QueryEscape(projectId), "merge_requests"),
}
req.Header.Set("Content-Type", "application/json")
client := http.Client{}
resp, err := client.Do(req)
if nil != err {
return nil, err
}
if resp.StatusCode == 404 {
// Duplicate merge request, same source branch
return nil, fmt.Errorf("There already exists a merge request for: %s\n", sourceBranch)
}
if resp.StatusCode != 201 {
return nil, g.getErrorFromResponse(resp, 201)
}
responseDecoder := json.NewDecoder(resp.Body)
var newMergeRequest mergeRequest
err = responseDecoder.Decode(&newMergeRequest)
if nil != err {
return nil, err
}
return &newMergeRequest, nil
}
// Try getting gitlab error from gitlab http response
func (g gitlab) getErrorFromResponse(resp *http.Response, expectedStatusCode int) error {
// Try getting error response from gitlab
var err error
responseDecoder := json.NewDecoder(resp.Body)
var errorResp errorResponse
err = responseDecoder.Decode(&errorResp)
if nil == err {
// "error" member?
if len(errorResp.Errors) > 0 {
return GitlabError(errorResp.Errors)
}
// "message" string member?
var message string
err = json.Unmarshal(errorResp.Message, &message)
message = strings.TrimSpace(message)
if nil == err && "" != message {
return GitlabError([]string{message})
}
// "message" member other than string?
message = string(errorResp.Message)
if "" != message {
return GitlabError([]string{message})
}
}
return fmt.Errorf("Expected status %d, got %d\n", expectedStatusCode, resp.StatusCode)
}
/// Request session for private token
func (g gitlab) getSession(login, password string) (*session, error) {
requestBody := sessionRequest{
Login: login,
Password: password,
}
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
err := encoder.Encode(requestBody)
if nil != err {
return nil, err
}
addr := g.getUnauthApiUrl("session")
req, err := http.NewRequest("POST", addr, buffer)
req.URL = &url.URL{
Scheme: g.scheme,
Host: g.host,
// Use opaque url to preserve "%2F"
Opaque: g.getUnauthOpaqueApiUrl("session"),
}
req.Header.Set("Content-Type", "application/json")
client := http.Client{}
resp, err := client.Do(req)
if nil != err {
return nil, err
}
if resp.StatusCode != 201 {
return nil, errors.New(resp.Status)
}
responseDecoder := json.NewDecoder(resp.Body)
var session session
err = responseDecoder.Decode(&session)
if nil != err {
return nil, err
}
return &session, nil
}
func (g gitlab) queryMergeRequests(projectId string, state string) ([]mergeRequest, error) {
if state == "" {
state = MERGE_REQUEST_STATE_OPENED
}
addr := g.getApiUrl("projects", url.QueryEscape(projectId), "merge_requests") + "&state=" + state
req, err := http.NewRequest("GET", addr, nil)
req.URL = &url.URL{
Scheme: g.scheme,
Host: g.host,
// Use opaque url to preserve "%2F"
Opaque: g.getOpaqueApiUrl("projects", url.QueryEscape(projectId), "merge_requests") + "&state=" + state,
}
client := http.Client{}
resp, err := client.Do(req)
if nil != err {
return nil, err
}
if resp.StatusCode == 404 {
if g.token != "" {
addr = strings.Replace(addr, g.token, "***", -1)
}
return nil, fmt.Errorf("404: %s\n", addr)
}
if resp.StatusCode != 200 {
return nil, g.getErrorFromResponse(resp, 200)
}
var mergeRequests []mergeRequest
d := json.NewDecoder(resp.Body)
// Check for leading "<" -> "api 404"
err = d.Decode(&mergeRequests)
if nil != err {
return nil, err
}
return mergeRequests, nil
}
func (g gitlab) acceptMergeRequest(projectId string, mergeRequestId int) error {
addr := g.getApiUrl(
"projects",
url.QueryEscape(projectId),
"merge_request",
url.QueryEscape(strconv.Itoa(mergeRequestId)),
"merge",
)
req, err := http.NewRequest("PUT", addr, nil)
req.URL = &url.URL{
Scheme: g.scheme,
Host: g.host,
// Use opaque url to preserve "%2F"
Opaque: g.getOpaqueApiUrl("projects", url.QueryEscape(projectId), "merge_request", strconv.Itoa(mergeRequestId), "merge"),
}
client := http.Client{}
resp, err := client.Do(req)
if nil != err {
return err
}
if resp.StatusCode == 404 {
if g.token != "" {
addr = strings.Replace(addr, g.token, "***", -1)
}
return fmt.Errorf("404: %s %s\n", req.Method, addr)
}
if resp.StatusCode != 200 {
return g.getErrorFromResponse(resp, 200)
}
return nil
}
func (g gitlab) doApiRequest(method string, pathSegments ...string) (*http.Response, error) {
addr := g.getApiUrl(pathSegments...)
req, err := http.NewRequest(method, addr, nil)
if nil != err {
return nil, err
}
req.URL = &url.URL{
Scheme: g.scheme,
Host: g.host,
// Use opaque url to preserve "%2F"
Opaque: g.getOpaqueApiUrl(pathSegments...),
}
client := http.Client{}
return client.Do(req)
}
func (g gitlab) removeBranch(projectId string, branch string) error {
resp, err := g.doApiRequest(
"DELETE",
"projects",
url.QueryEscape(projectId),
"repository/branches",
url.QueryEscape(branch),
)
if nil != err {
return err
}
if resp.StatusCode == 404 {
return fmt.Errorf(
`Could not find branch: "%s" on project: "%s"`,
branch,
projectId,
)
}
if resp.StatusCode != 200 {
return g.getErrorFromResponse(resp, 200)
}
return nil
}