/
stash.go
825 lines (721 loc) · 22.9 KB
/
stash.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// Atlassian Stash API package.
// Stash API Reference: https://developer.atlassian.com/static/rest/stash/3.0.1/stash-rest.html
package stash
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"runtime"
"strings"
"time"
"github.com/ae6rt/retry"
)
var Log *log.Logger = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile)
type (
Stash interface {
CreateRepository(projectKey, slug string) (Repository, error)
GetRepositories() (map[int]Repository, error)
GetBranches(projectKey, repositorySlug string) (map[string]Branch, error)
GetTags(projectKey, repositorySlug string) (map[string]Tag, error)
CreateBranchRestriction(projectKey, repositorySlug, branch, user string) (BranchRestriction, error)
GetBranchRestrictions(projectKey, repositorySlug string) (BranchRestrictions, error)
DeleteBranchRestriction(projectKey, repositorySlug string, id int) error
GetRepository(projectKey, repositorySlug string) (Repository, error)
GetPullRequests(projectKey, repositorySlug, state string) ([]PullRequest, error)
GetRawFile(projectKey, repositorySlug, branch, filePath string) ([]byte, error)
CreatePullRequest(projectKey, repositorySlug, title, description, fromRef, toRef string, reviewers []string) (PullRequest, error)
DeleteBranch(projectKey, repositorySlug, branchName string) error
}
Client struct {
userName string
password string
baseURL *url.URL
Stash
}
Page struct {
IsLastPage bool `json:"isLastPage"`
Size int `json:"size"`
Start int `json:"start"`
NextPageStart int `json:"nextPageStart"`
}
Repositories struct {
IsLastPage bool `json:"isLastPage"`
Size int `json:"size"`
Start int `json:"start"`
NextPageStart int `json:"nextPageStart"`
Repository []Repository `json:"values"`
}
Repository struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Project Project `json:"project"`
ScmID string `json:"scmId"`
Links Links `json:"links"`
}
Project struct {
Key string `json:"key"`
}
Links struct {
Clones []Clone `json:"clone"`
}
Clone struct {
HREF string `json:"href"`
Name string `json:"name"`
}
Branches struct {
IsLastPage bool `json:"isLastPage"`
Size int `json:"size"`
Start int `json:"start"`
NextPageStart int `json:"nextPageStart"`
Branch []Branch `json:"values"`
}
Branch struct {
ID string `json:"id"`
DisplayID string `json:"displayId"`
LatestChangeSet string `json:"latestChangeset"`
IsDefault bool `json:"isDefault"`
}
Tags struct {
Page
Tags []Tag `json:"values"`
}
Tag struct {
ID string `json:"id"`
DisplayID string `json:"displayId"`
}
BranchRestrictions struct {
BranchRestriction []BranchRestriction `json:"values"`
}
BranchRestriction struct {
Id int `json:"id"`
Branch Branch `json:"branch"`
}
BranchPermission struct {
Type string `json:"type"`
Branch string `json:"value"`
Users []string `json:"users"`
Groups []string `json:"groups"`
}
PullRequests struct {
Page
PullRequests []PullRequest `json:"values"`
}
PullRequest struct {
ID int `id:"closed"`
Closed bool `json:"closed"`
Open bool `json:"open"`
State string `json:"state"`
Title string `json:"title"`
Description string `json:"description"`
FromRef Ref `json:"fromRef"`
ToRef Ref `json:"toRef"`
}
Ref struct {
DisplayID string `json:"displayId"`
}
errorResponse struct {
StatusCode int
Reason string
error
}
// Pull Request Types
User struct {
Name string `json:"name"`
}
Reviewer struct {
User User `json:"user"`
}
PullRequestProject struct {
Key string `json:"key"`
}
PullRequestRepository struct {
Slug string `json:"slug"`
Name string `json:"name,omitempty"`
Project PullRequestProject `json:"project"`
}
PullRequestRef struct {
Id string `json:"id"`
Repository PullRequestRepository `json:"repository"`
}
PullRequestResource struct {
Title string `json:"title"`
Description string `json:"description"`
FromRef PullRequestRef `json:"fromRef"`
ToRef PullRequestRef `json:"toRef"`
Reviewers []Reviewer `json:"reviewers"`
}
)
const (
stashPageLimit int = 25
)
var (
httpTransport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
)
var (
httpClient *http.Client = &http.Client{Timeout: 10 * time.Second, Transport: httpTransport}
)
func (e errorResponse) Error() string {
return fmt.Sprintf("%s (%d)", e.Reason, e.StatusCode)
}
func NewClient(userName, password string, baseURL *url.URL) Stash {
return Client{userName: userName, password: password, baseURL: baseURL}
}
func (client Client) CreateRepository(projectKey, projectSlug string) (Repository, error) {
slug := fmt.Sprintf(`{"name": "%s", "scmId": "git"}`, projectSlug)
req, err := http.NewRequest("POST", fmt.Sprintf("%s/rest/api/1.0/projects/%s/repos", client.baseURL.String(), projectKey), bytes.NewBuffer([]byte(slug)))
if err != nil {
return Repository{}, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-type", "application/json")
req.SetBasicAuth(client.userName, client.password)
responseCode, data, err := consumeResponse(req)
if err != nil {
return Repository{}, err
}
if responseCode != http.StatusCreated {
var reason string = "unknown reason"
switch {
case responseCode == http.StatusBadRequest:
reason = "The repository was not created due to a validation error."
case responseCode == http.StatusUnauthorized:
reason = "The currently authenticated user has insufficient permissions to create a repository."
case responseCode == http.StatusNotFound:
reason = "The resource was not found. Does the project key exist?"
case responseCode == http.StatusConflict:
reason = "A repository with same name already exists."
}
return Repository{}, errorResponse{StatusCode: responseCode, Reason: reason}
}
var t Repository
err = json.Unmarshal(data, &t)
if err != nil {
return Repository{}, err
}
return t, nil
}
// GetRepositories returns a map of repositories indexed by repository URL.
func (client Client) GetRepositories() (map[int]Repository, error) {
start := 0
repositories := make(map[int]Repository)
morePages := true
for morePages {
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
var data []byte
work := func() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/api/1.0/repos?start=%d&limit=%d", client.baseURL.String(), start, stashPageLimit), nil)
if err != nil {
return err
}
Log.Printf("stash.GetRepositories URL %s\n", req.URL)
req.Header.Set("Accept", "application/json")
// use credentials if we have them. If not, the repository must be public.
if client.userName != "" && client.password != "" {
req.SetBasicAuth(client.userName, client.password)
}
var responseCode int
responseCode, data, err = consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusBadRequest:
reason = "Bad request."
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
return nil
}
if err := retry.Try(work); err != nil {
return nil, err
}
var r Repositories
err := json.Unmarshal(data, &r)
if err != nil {
return nil, err
}
for _, repo := range r.Repository {
repositories[repo.ID] = repo
}
morePages = !r.IsLastPage
start = r.NextPageStart
}
return repositories, nil
}
// GetBranches returns a map of branches indexed by branch display name for the given repository.
func (client Client) GetBranches(projectKey, repositorySlug string) (map[string]Branch, error) {
start := 0
branches := make(map[string]Branch)
morePages := true
for morePages {
var data []byte
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
workit := func() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/api/1.0/projects/%s/repos/%s/branches?start=%d&limit=%d", client.baseURL.String(), projectKey, repositorySlug, start, stashPageLimit), nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(client.userName, client.password)
var responseCode int
responseCode, data, err = consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusNotFound:
reason = "Not found"
case responseCode == http.StatusUnauthorized:
reason = "Unauthorized"
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
return nil
}
if err := retry.Try(workit); err != nil {
return nil, err
}
var r Branches
if err := json.Unmarshal(data, &r); err != nil {
return nil, err
}
for _, branch := range r.Branch {
branches[branch.DisplayID] = branch
}
morePages = !r.IsLastPage
start = r.NextPageStart
}
return branches, nil
}
// GetTags returns a map of tags indexed by tag display name for the given repository.
func (client Client) GetTags(projectKey, repositorySlug string) (map[string]Tag, error) {
start := 0
tags := make(map[string]Tag)
morePages := true
for morePages {
var data []byte
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
work := func() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/api/1.0/projects/%s/repos/%s/tags?start=%d&limit=%d", client.baseURL.String(), projectKey, repositorySlug, start, stashPageLimit), nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
// use credentials if we have them. If not, the repository must be public.
if client.userName != "" && client.password != "" {
req.SetBasicAuth(client.userName, client.password)
}
var responseCode int
responseCode, data, err = consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusNotFound:
reason = "Not found"
case responseCode == http.StatusUnauthorized:
reason = "Unauthorized"
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
return nil
}
if err := retry.Try(work); err != nil {
return nil, err
}
var r Tags
if err := json.Unmarshal(data, &r); err != nil {
return nil, err
}
for _, tag := range r.Tags {
tags[tag.DisplayID] = tag
}
morePages = !r.IsLastPage
start = r.NextPageStart
}
return tags, nil
}
// GetRepository returns a repository representation for the given Stash Project key and repository slug.
func (client Client) GetRepository(projectKey, repositorySlug string) (Repository, error) {
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
var r Repository
work := func() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/api/1.0/projects/%s/repos/%s", client.baseURL.String(), projectKey, repositorySlug), nil)
if err != nil {
return err
}
Log.Printf("stash.GetRepository %s\n", req.URL)
req.Header.Set("Accept", "application/json")
// use credentials if we have them. If not, the repository must be public.
if client.userName != "" && client.password != "" {
req.SetBasicAuth(client.userName, client.password)
}
responseCode, data, err := consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusNotFound:
reason = "Not found"
case responseCode == http.StatusUnauthorized:
reason = "Unauthorized"
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
err = json.Unmarshal(data, &r)
if err != nil {
return err
}
return nil
}
return r, retry.Try(work)
}
func (client Client) CreateBranchRestriction(projectKey, repositorySlug, branch, user string) (BranchRestriction, error) {
branchPermission := BranchPermission{
Type: "BRANCH",
Branch: branch,
Users: []string{user},
Groups: []string{},
}
data, err := json.Marshal(branchPermission)
if err != nil {
return BranchRestriction{}, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/rest/branch-permissions/1.0/projects/%s/repos/%s/restricted", client.baseURL.String(), projectKey, repositorySlug), bytes.NewReader(data))
if err != nil {
return BranchRestriction{}, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-type", "application/json")
req.SetBasicAuth(client.userName, client.password)
responseCode, data, err := consumeResponse(req)
if err != nil {
return BranchRestriction{}, err
}
if responseCode != http.StatusOK {
var reason string = "unknown reason"
switch {
case responseCode == http.StatusBadRequest:
reason = "The branch restriction was not created due to a validation error."
case responseCode == http.StatusUnauthorized:
reason = "The currently authenticated user has insufficient permissions to create a branch restriction."
case responseCode == http.StatusNotFound:
reason = "The resource was not found. Does the project key exist? What about the repo? The user? The branch?"
case responseCode == http.StatusConflict:
reason = "A branch restriction with same name already exists."
}
return BranchRestriction{}, errorResponse{StatusCode: responseCode, Reason: reason}
}
var t BranchRestriction
err = json.Unmarshal(data, &t)
if err != nil {
return BranchRestriction{}, err
}
return t, nil
}
func (client Client) GetBranchRestrictions(projectKey, repositorySlug string) (BranchRestrictions, error) {
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
var branchRestrictions BranchRestrictions
work := func() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/branch-permissions/1.0/projects/%s/repos/%s/restricted", client.baseURL.String(), projectKey, repositorySlug), nil)
if err != nil {
return err
}
Log.Printf("stash.GetBranchRestrictions %s\n", req.URL)
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(client.userName, client.password)
responseCode, data, err := consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusNotFound:
reason = "Not found"
case responseCode == http.StatusUnauthorized:
reason = "Unauthorized"
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
err = json.Unmarshal(data, &branchRestrictions)
if err != nil {
return err
}
return nil
}
return branchRestrictions, retry.Try(work)
}
// GetRepository returns a repository representation for the given Stash Project key and repository slug.
func (client Client) DeleteBranchRestriction(projectKey, repositorySlug string, id int) error {
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
work := func() error {
req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/rest/branch-permissions/1.0/projects/%s/repos/%s/restricted/%d", client.baseURL.String(), projectKey, repositorySlug, id), nil)
if err != nil {
return err
}
Log.Printf("stash.DeleteBranchRestriction %s\n", req.URL)
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(client.userName, client.password)
responseCode, _, err := consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusNoContent {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusNotFound:
reason = "Not found"
case responseCode == http.StatusUnauthorized:
reason = "Unauthorized"
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
return nil
}
return retry.Try(work)
}
// GetPullRequests returns a list of pull requests for a project / slug.
func (client Client) GetPullRequests(projectKey, projectSlug, state string) ([]PullRequest, error) {
start := 0
pullRequests := make([]PullRequest, 0)
morePages := true
for morePages {
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
var data []byte
work := func() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/api/1.0/projects/%s/repos/%s/pull-requests?state=%s&start=%d&limit=%d", client.baseURL.String(), projectKey, projectSlug, state, start, stashPageLimit), nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(client.userName, client.password)
var responseCode int
responseCode, data, err = consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusBadRequest:
reason = "Bad request."
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
return nil
}
if err := retry.Try(work); err != nil {
return nil, err
}
var r PullRequests
err := json.Unmarshal(data, &r)
if err != nil {
return nil, err
}
for _, pr := range r.PullRequests {
pullRequests = append(pullRequests, pr)
}
morePages = !r.IsLastPage
start = r.NextPageStart
}
return pullRequests, nil
}
// CreatePullRequest creates a pull request between branches.
func (client Client) CreatePullRequest(projectKey, repositorySlug, title, description, fromRef, toRef string, reviewers []string) (PullRequest, error) {
var revs []Reviewer
for _, rev := range reviewers {
revs = append(revs, Reviewer{
User: User{Name: rev},
})
}
pullRequestResource := PullRequestResource{
Title: title,
Description: description,
FromRef: PullRequestRef{
Id: fromRef,
Repository: PullRequestRepository{
Slug: repositorySlug,
Project: PullRequestProject{
Key: projectKey,
},
},
},
ToRef: PullRequestRef{
Id: toRef,
Repository: PullRequestRepository{
Slug: repositorySlug,
Project: PullRequestProject{
Key: projectKey,
},
},
},
Reviewers: revs,
}
reqBody, err := json.Marshal(pullRequestResource)
if err != nil {
return PullRequest{}, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/rest/api/1.0/projects/%s/repos/%s/pull-requests", client.baseURL.String(), projectKey, repositorySlug), bytes.NewBuffer(reqBody))
if err != nil {
return PullRequest{}, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-type", "application/json")
req.SetBasicAuth(client.userName, client.password)
responseCode, data, err := consumeResponse(req)
if err != nil {
return PullRequest{}, err
}
if responseCode != http.StatusCreated {
var reason string = "unknown reason"
switch {
case responseCode == http.StatusBadRequest:
reason = "The repository was not created due to a validation error."
case responseCode == http.StatusUnauthorized:
reason = "The currently authenticated user has insufficient permissions to create a repository."
case responseCode == http.StatusNotFound:
reason = "The resource was not found. Does the project key exist?"
case responseCode == http.StatusConflict:
reason = "A repository with same name already exists."
}
return PullRequest{}, errorResponse{StatusCode: responseCode, Reason: reason}
}
var t PullRequest
err = json.Unmarshal(data, &t)
if err != nil {
return PullRequest{}, err
}
return t, nil
}
func (client Client) DeleteBranch(projectKey, repositorySlug, branchName string) error {
work := func() error {
buffer := bytes.NewBufferString((fmt.Sprintf(`{"name":"refs/heads/%s","dryRun":false}`, branchName)))
req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/rest/branch-utils/1.0/projects/%s/repos/%s/branches", client.baseURL.String(), projectKey, repositorySlug), buffer)
if err != nil {
return err
}
req.Header.Set("Content-type", "application/json")
req.SetBasicAuth(client.userName, client.password)
responseCode, _, err := consumeResponse(req)
if err != nil {
return err
}
switch responseCode {
case http.StatusNoContent:
return nil
case http.StatusBadRequest:
return errorResponse{StatusCode: responseCode, Reason: "Bad Requeest"}
case http.StatusUnauthorized:
return errorResponse{StatusCode: responseCode, Reason: "Unauthorized"}
default:
return errorResponse{StatusCode: responseCode, Reason: "(unhandled reason)"}
}
}
return retry.New(3*time.Second, 3, retry.DefaultBackoffFunc).Try(work)
}
func (client Client) GetRawFile(repositoryProjectKey, repositorySlug, filePath, branch string) ([]byte, error) {
retry := retry.New(3*time.Second, 3, retry.DefaultBackoffFunc)
var data []byte
work := func() error {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/projects/%s/repos/%s/browse/%s?at=%s&raw", client.baseURL.String(), strings.ToLower(repositoryProjectKey), strings.ToLower(repositorySlug), filePath, branch), nil)
if err != nil {
return err
}
Log.Printf("stash.GetRawFile %s\n", req.URL)
req.SetBasicAuth(client.userName, client.password)
var responseCode int
responseCode, data, err = consumeResponse(req)
if err != nil {
return err
}
if responseCode != http.StatusOK {
var reason string = "unhandled reason"
switch {
case responseCode == http.StatusNotFound:
reason = "Not found"
case responseCode == http.StatusUnauthorized:
reason = "Unauthorized"
}
return errorResponse{StatusCode: responseCode, Reason: reason}
}
return nil
}
return data, retry.Try(work)
}
func HasRepository(repositories map[int]Repository, url string) (Repository, bool) {
for _, repo := range repositories {
for _, clone := range repo.Links.Clones {
if clone.HREF == url {
return repo, true
}
}
}
return Repository{}, false
}
func IsRepositoryExists(err error) bool {
if err == nil {
return false
}
if response, ok := err.(errorResponse); ok {
return response.StatusCode == http.StatusConflict
}
return false
}
func IsRepositoryNotFound(err error) bool {
if err == nil {
return false
}
if response, ok := err.(errorResponse); ok {
return response.StatusCode == http.StatusNotFound
}
return false
}
func consumeResponse(req *http.Request) (rc int, buffer []byte, err error) {
response, err := httpClient.Do(req)
defer func() {
if response != nil && response.Body != nil {
response.Body.Close()
}
if e := recover(); e != nil {
trace := make([]byte, 10*1024)
_ = runtime.Stack(trace, false)
Log.Printf("%s", trace)
err = fmt.Errorf("%v", e)
}
}()
if err != nil {
panic(err)
}
if data, err := ioutil.ReadAll(response.Body); err != nil {
panic(err)
} else {
return response.StatusCode, data, nil
}
}
// SshUrl extracts the SSH-based URL from the repository metadata.
func (repo Repository) SshUrl() string {
for _, clone := range repo.Links.Clones {
if clone.Name == "ssh" {
return clone.HREF
}
}
return ""
}