-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathgitlab.go
1922 lines (1656 loc) · 49 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
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package gitlab is an internal wrapper for the go-gitlab package
//
// Most functions serve to expose debug logging if set and accept a project
// name string over an ID.
package gitlab
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
gitlab "github.com/xanzy/go-gitlab"
"github.com/zaquestion/lab/internal/git"
"github.com/zaquestion/lab/internal/logger"
)
// Get internal lab logger instance
var log = logger.GetInstance()
// 100 is the maximum allowed by the API
const maxItemsPerPage = 100
var (
// ErrActionRepeated is returned when a GitLab action is executed again. For example
// this can be returned when an MR is approved twice.
ErrActionRepeated = errors.New("GitLab action repeated")
// ErrNotModified is returned when adding an already existing item to a Todo list
ErrNotModified = errors.New("Not Modified")
// ErrProjectNotFound is returned when a GitLab project cannot be found.
ErrProjectNotFound = errors.New("GitLab project not found, verify you have access to the requested resource")
// ErrStatusForbidden is returned when attempting to access a GitLab project with insufficient permissions
ErrStatusForbidden = errors.New("Insufficient permissions for GitLab project")
)
var (
lab *gitlab.Client
host string
user string
token string
)
// Host exposes the GitLab scheme://hostname used to interact with the API
func Host() string {
return host
}
// User exposes the configured GitLab user
func User() string {
return user
}
// UserID get the current user ID from gitlab server
func UserID() (int, error) {
u, _, err := lab.Users.CurrentUser()
if err != nil {
return 0, err
}
return u.ID, nil
}
func initGitlabClient(ctx context.Context, _host, _user, _token string, tlsConfig *tls.Config) {
if len(_host) > 0 && _host[len(_host)-1] == '/' {
_host = _host[:len(_host)-1]
}
host = _host
user = _user
token = _token
tp := http.DefaultTransport.(*http.Transport).Clone()
tp.TLSClientConfig = tlsConfig
httpClient := &http.Client{
Transport: tp,
}
lab, _ = gitlab.NewClient(token,
gitlab.WithHTTPClient(httpClient),
gitlab.WithBaseURL(host+"/api/v4"),
gitlab.WithCustomLeveledLogger(log),
gitlab.WithRequestOptions(gitlab.WithContext(ctx)),
)
}
// Init initializes a gitlab client for use throughout lab.
func Init(ctx context.Context, _host, _user, _token string, allowInsecure bool) {
initGitlabClient(ctx, _host, _user, _token, &tls.Config{
InsecureSkipVerify: allowInsecure,
})
}
// InitWithCustomCA open the HTTP client using a custom CA file (a self signed
// one for instance) instead of relying only on those installed in the current
// system database
func InitWithCustomCA(ctx context.Context, _host, _user, _token, caFile string) error {
if len(_host) > 0 && _host[len(_host)-1] == '/' {
_host = _host[:len(_host)-1]
}
host = _host
user = _user
token = _token
caCert, err := os.ReadFile(caFile)
if err != nil {
return err
}
// use system cert pool as a baseline
caCertPool, err := x509.SystemCertPool()
if err != nil {
return err
}
caCertPool.AppendCertsFromPEM(caCert)
initGitlabClient(ctx, _host, _user, _token, &tls.Config{
RootCAs: caCertPool,
})
return nil
}
func parseID(id interface{}) (string, error) {
var strID string
switch v := id.(type) {
case int:
strID = strconv.Itoa(v)
case string:
strID = v
default:
return "", fmt.Errorf("unknown id type %#v", id)
}
return strID, nil
}
// Defines filepath for default GitLab templates
const (
TmplMR = "merge_request_templates/default.md"
TmplIssue = "issue_templates/default.md"
)
// LoadGitLabTmpl loads gitlab templates for use in creating Issues and MRs
//
// https://gitlab.com/help/user/project/description_templates.md#setting-a-default-template-for-issues-and-merge-requests
func LoadGitLabTmpl(tmplName string) string {
wd, err := git.WorkingDir()
if err != nil {
log.Fatal(err)
}
tmplFile := filepath.Join(wd, ".gitlab", tmplName)
content, err := ioutil.ReadFile(tmplFile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return ""
}
log.Fatal(err)
}
return strings.TrimSpace(string(content))
}
var localProjects map[string]*gitlab.Project = make(map[string]*gitlab.Project)
// GetProject looks up a Gitlab project by ID.
func GetProject(projID interface{}) (*gitlab.Project, error) {
target, resp, err := lab.Projects.GetProject(projID, nil)
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil, ErrProjectNotFound
}
if err != nil {
return nil, err
}
return target, nil
}
// FindProject looks up the Gitlab project. If the namespace is not provided in
// the project string it will search for projects in the users namespace
func FindProject(projID interface{}) (*gitlab.Project, error) {
var (
id string
search string
)
switch v := projID.(type) {
case int:
// If the project number is used directly, don't "guess" anything
id = strconv.Itoa(v)
search = id
case string:
id = v
search = id
// If the project name is used, check if it already has the
// namespace (already have a slash '/' in the name) or try to guess
// it's on user's own namespace.
if !strings.Contains(id, "/") {
search = user + "/" + id
}
}
if target, ok := localProjects[id]; ok {
return target, nil
}
target, err := GetProject(search)
if err != nil {
return nil, err
}
// fwiw, I feel bad about this
localProjects[id] = target
return target, nil
}
// Fork creates a user fork of a GitLab project using the specified protocol
func Fork(projID interface{}, opts *gitlab.ForkProjectOptions, useHTTP bool, wait bool) (string, error) {
var id string
switch v := projID.(type) {
case int:
// If numeric ID, we need the complete name with namespace
p, err := FindProject(v)
if err != nil {
return "", err
}
id = p.NameWithNamespace
case string:
id = v
// Check if the ID passed already contains the namespace/path that
// we need.
if !strings.Contains(id, "/") {
// Is it a numeric ID passed as string?
if _, err := strconv.Atoi(id); err != nil {
return "", errors.New("remote must include namespace")
}
// Do the same as done in 'case int' for numeric ID passed as
// string
p, err := FindProject(id)
if err != nil {
return "", err
}
id = p.NameWithNamespace
}
}
parts := strings.Split(id, "/")
// See if a fork already exists in the destination
name := parts[len(parts)-1]
namespace := ""
if opts != nil {
var (
optName = *(opts.Name)
optNamespace = *(opts.Namespace)
optPath = *(opts.Path)
)
if optNamespace != "" {
namespace = optNamespace + "/"
}
// Project name takes precedence over path for finding a project
// on Gitlab through API
if optName != "" {
name = optName
} else if optPath != "" {
name = optPath
} else {
opts.Name = gitlab.String(name)
}
}
target, err := FindProject(namespace + name)
if err == nil {
// Check if it isn't the same project being requested
if target.PathWithNamespace == projID {
errMsg := "not possible to fork a project from the same namespace and name"
return "", errors.New(errMsg)
}
// Check if it isn't a non-fork project, meaning the user has
// access to a project with same namespace/name
if target.ForkedFromProject == nil {
errMsg := fmt.Sprintf("\"%s\" project already taken\n", target.PathWithNamespace)
return "", errors.New(errMsg)
}
// Check if it isn't already a fork for another project
if target.ForkedFromProject != nil &&
target.ForkedFromProject.PathWithNamespace != projID {
errMsg := fmt.Sprintf("\"%s\" fork already taken for a different project",
target.PathWithNamespace)
return "", errors.New(errMsg)
}
// Project already forked and found
urlToRepo := target.SSHURLToRepo
if useHTTP {
urlToRepo = target.HTTPURLToRepo
}
return urlToRepo, nil
} else if err != nil && err != ErrProjectNotFound {
return "", err
}
target, err = FindProject(projID)
if err != nil {
return "", err
}
// Now that we have the "wait" opt, don't let the user in the hope that
// something is running.
fmt.Printf("Forking %s project...\n", projID)
fork, _, err := lab.Projects.ForkProject(target.ID, opts)
if err != nil {
return "", err
}
// Busy-wait approach for checking the import_status of the fork.
// References:
// https://docs.gitlab.com/ce/api/projects.html#fork-project
// https://docs.gitlab.com/ee/api/project_import_export.html#import-status
status, _, err := lab.ProjectImportExport.ImportStatus(fork.ID, nil)
if err != nil {
log.Infof("Impossible to get fork status: %s\n", err)
} else {
if wait {
for {
if status.ImportStatus == "finished" {
break
}
status, _, err = lab.ProjectImportExport.ImportStatus(fork.ID, nil)
if err != nil {
log.Fatal(err)
}
time.Sleep(2 * time.Second)
}
} else if status.ImportStatus != "finished" {
err = errors.New("not finished")
}
}
urlToRepo := fork.SSHURLToRepo
if useHTTP {
urlToRepo = fork.HTTPURLToRepo
}
return urlToRepo, err
}
// MRCreate opens a merge request on GitLab
func MRCreate(projID interface{}, opts *gitlab.CreateMergeRequestOptions) (string, error) {
mr, _, err := lab.MergeRequests.CreateMergeRequest(projID, opts)
if err != nil {
return "", err
}
return mr.WebURL, nil
}
// MRCreateDiscussion creates a discussion on a merge request on GitLab
func MRCreateDiscussion(projID interface{}, id int, opts *gitlab.CreateMergeRequestDiscussionOptions) (string, error) {
discussion, _, err := lab.Discussions.CreateMergeRequestDiscussion(projID, id, opts)
if err != nil {
return "", err
}
// Unlike MR, Note has no WebURL property, so we have to create it
// ourselves from the project, noteable id and note id
note := discussion.Notes[0]
p, err := FindProject(projID)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/-/merge_requests/%d#note_%d", p.WebURL, note.NoteableIID, note.ID), nil
}
// MRUpdate edits an merge request on a GitLab project
func MRUpdate(projID interface{}, id int, opts *gitlab.UpdateMergeRequestOptions) (string, error) {
mr, _, err := lab.MergeRequests.UpdateMergeRequest(projID, id, opts)
if err != nil {
return "", err
}
return mr.WebURL, nil
}
// MRDelete deletes an merge request on a GitLab project
func MRDelete(projID interface{}, id int) error {
resp, err := lab.MergeRequests.DeleteMergeRequest(projID, id)
if resp != nil && resp.StatusCode == http.StatusForbidden {
return ErrStatusForbidden
}
if err != nil {
return err
}
return nil
}
// MRCreateNote adds a note to a merge request on GitLab
func MRCreateNote(projID interface{}, id int, opts *gitlab.CreateMergeRequestNoteOptions) (string, error) {
note, _, err := lab.Notes.CreateMergeRequestNote(projID, id, opts)
if err != nil {
return "", err
}
// Unlike MR, Note has no WebURL property, so we have to create it
// ourselves from the project, noteable id and note id
p, err := FindProject(projID)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/-/merge_requests/%d#note_%d", p.WebURL, note.NoteableIID, note.ID), nil
}
// MRGet retrieves the merge request from GitLab project
func MRGet(projID interface{}, id int) (*gitlab.MergeRequest, error) {
mr, _, err := lab.MergeRequests.GetMergeRequest(projID, id, nil)
if err != nil {
return nil, err
}
return mr, nil
}
// MRList lists the MRs on a GitLab project
func MRList(projID interface{}, opts gitlab.ListProjectMergeRequestsOptions, n int) ([]*gitlab.MergeRequest, error) {
var list []*gitlab.MergeRequest
for true {
opts.PerPage = maxItemsPerPage
if n != -1 {
opts.PerPage = n - len(list)
if opts.PerPage > maxItemsPerPage {
opts.PerPage = maxItemsPerPage
}
}
mrs, resp, err := lab.MergeRequests.ListProjectMergeRequests(projID, &opts)
if err != nil {
return nil, err
}
list = append(list, mrs...)
if len(list) == n {
break
}
var ok bool
if opts.Page, ok = hasNextPage(resp); !ok {
break
}
}
return list, nil
}
// MRClose closes an mr on a GitLab project
func MRClose(projID interface{}, id int) error {
mr, _, err := lab.MergeRequests.GetMergeRequest(projID, id, nil)
if err != nil {
return err
}
if mr.State == "closed" {
return fmt.Errorf("mr already closed")
}
_, _, err = lab.MergeRequests.UpdateMergeRequest(projID, int(id), &gitlab.UpdateMergeRequestOptions{
StateEvent: gitlab.String("close"),
})
if err != nil {
return err
}
return nil
}
// MRReopen reopen an already close mr on a GitLab project
func MRReopen(projID interface{}, id int) error {
mr, _, err := lab.MergeRequests.GetMergeRequest(projID, id, nil)
if err != nil {
return err
}
if mr.State == "opened" {
return fmt.Errorf("mr not closed")
}
_, _, err = lab.MergeRequests.UpdateMergeRequest(projID, int(id), &gitlab.UpdateMergeRequestOptions{
StateEvent: gitlab.String("reopen"),
})
if err != nil {
return err
}
return nil
}
// MRListDiscussions retrieves the discussions (aka notes & comments) for a merge request
func MRListDiscussions(projID interface{}, id int) ([]*gitlab.Discussion, error) {
discussions := []*gitlab.Discussion{}
opt := &gitlab.ListMergeRequestDiscussionsOptions{
// 100 is the maximum allowed by the API
PerPage: maxItemsPerPage,
}
for {
// get a page of discussions from the API ...
d, resp, err := lab.Discussions.ListMergeRequestDiscussions(projID, id, opt)
if err != nil {
return nil, err
}
// ... and add them to our collection of discussions
discussions = append(discussions, d...)
// if we've seen all the pages, then we can break here.
// otherwise, update the page number to get the next page.
var ok bool
if opt.Page, ok = hasNextPage(resp); !ok {
break
}
}
return discussions, nil
}
// MRRebase merges an mr on a GitLab project
func MRRebase(projID interface{}, id int) error {
_, err := lab.MergeRequests.RebaseMergeRequest(projID, int(id))
if err != nil {
return err
}
return nil
}
// MRMerge merges an mr on a GitLab project
func MRMerge(projID interface{}, id int, opts *gitlab.AcceptMergeRequestOptions) error {
_, _, err := lab.MergeRequests.AcceptMergeRequest(projID, int(id), opts)
if err != nil {
return err
}
return nil
}
// MRApprove approves an mr on a GitLab project
func MRApprove(projID interface{}, id int) error {
_, resp, err := lab.MergeRequestApprovals.ApproveMergeRequest(projID, id, &gitlab.ApproveMergeRequestOptions{})
if resp != nil && resp.StatusCode == http.StatusForbidden {
return ErrStatusForbidden
}
if resp != nil && resp.StatusCode == http.StatusUnauthorized {
// returns 401 if the MR has already been approved
return ErrActionRepeated
}
if err != nil {
return err
}
return nil
}
// MRUnapprove Unapproves a previously approved mr on a GitLab project
func MRUnapprove(projID interface{}, id int) error {
resp, err := lab.MergeRequestApprovals.UnapproveMergeRequest(projID, id, nil)
if resp != nil && resp.StatusCode == http.StatusForbidden {
return ErrStatusForbidden
}
if resp != nil && resp.StatusCode == http.StatusNotFound {
// returns 404 if the MR has already been unapproved
return ErrActionRepeated
}
if err != nil {
return err
}
return nil
}
// MRSubscribe subscribes to an mr on a GitLab project
func MRSubscribe(projID interface{}, id int) error {
_, resp, err := lab.MergeRequests.SubscribeToMergeRequest(projID, id, nil)
if resp != nil && resp.StatusCode == http.StatusNotModified {
return errors.New("Already subscribed")
}
if err != nil {
return err
}
return nil
}
// MRUnsubscribe unsubscribes from a previously mr on a GitLab project
func MRUnsubscribe(projID interface{}, id int) error {
_, resp, err := lab.MergeRequests.UnsubscribeFromMergeRequest(projID, id, nil)
if resp != nil && resp.StatusCode == http.StatusNotModified {
return errors.New("Not subscribed")
}
if err != nil {
return err
}
return nil
}
// MRThumbUp places a thumb up/down on a merge request
func MRThumbUp(projID interface{}, id int) error {
_, _, err := lab.AwardEmoji.CreateMergeRequestAwardEmoji(projID, id, &gitlab.CreateAwardEmojiOptions{
Name: "thumbsup",
})
if err != nil {
return err
}
return nil
}
// MRThumbDown places a thumb up/down on a merge request
func MRThumbDown(projID interface{}, id int) error {
_, _, err := lab.AwardEmoji.CreateMergeRequestAwardEmoji(projID, id, &gitlab.CreateAwardEmojiOptions{
Name: "thumbsdown",
})
if err != nil {
return err
}
return nil
}
// IssueCreate opens a new issue on a GitLab project
func IssueCreate(projID interface{}, opts *gitlab.CreateIssueOptions) (string, error) {
mr, _, err := lab.Issues.CreateIssue(projID, opts)
if err != nil {
return "", err
}
return mr.WebURL, nil
}
// IssueUpdate edits an issue on a GitLab project
func IssueUpdate(projID interface{}, id int, opts *gitlab.UpdateIssueOptions) (string, error) {
issue, _, err := lab.Issues.UpdateIssue(projID, id, opts)
if err != nil {
return "", err
}
return issue.WebURL, nil
}
// IssueCreateNote creates a new note on an issue and returns the note URL
func IssueCreateNote(projID interface{}, id int, opts *gitlab.CreateIssueNoteOptions) (string, error) {
note, _, err := lab.Notes.CreateIssueNote(projID, id, opts)
if err != nil {
return "", err
}
// Unlike Issue, Note has no WebURL property, so we have to create it
// ourselves from the project, noteable id and note id
p, err := FindProject(projID)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/-/issues/%d#note_%d", p.WebURL, note.NoteableIID, note.ID), nil
}
// IssueGet retrieves the issue information from a GitLab project
func IssueGet(projID interface{}, id int) (*gitlab.Issue, error) {
issue, _, err := lab.Issues.GetIssue(projID, id)
if err != nil {
return nil, err
}
return issue, nil
}
// IssueList gets a list of issues on a GitLab Project
func IssueList(projID interface{}, opts gitlab.ListProjectIssuesOptions, n int) ([]*gitlab.Issue, error) {
var list []*gitlab.Issue
for true {
opts.PerPage = maxItemsPerPage
if n != -1 {
opts.PerPage = n - len(list)
if opts.PerPage > maxItemsPerPage {
opts.PerPage = maxItemsPerPage
}
}
issues, resp, err := lab.Issues.ListProjectIssues(projID, &opts)
if err != nil {
return nil, err
}
list = append(list, issues...)
if len(list) == n {
break
}
var ok bool
if opts.Page, ok = hasNextPage(resp); !ok {
break
}
}
return list, nil
}
// IssueClose closes an issue on a GitLab project
func IssueClose(projID interface{}, id int) error {
issue, _, err := lab.Issues.GetIssue(projID, id)
if err != nil {
return err
}
if issue.State == "closed" {
return fmt.Errorf("issue already closed")
}
_, _, err = lab.Issues.UpdateIssue(projID, id, &gitlab.UpdateIssueOptions{
StateEvent: gitlab.String("close"),
})
if err != nil {
return err
}
return nil
}
// IssueDuplicate closes an issue as duplicate of another
func IssueDuplicate(projID interface{}, id int, dupID interface{}) error {
dID, err := parseID(dupID)
if err != nil {
return err
}
// Not exposed in API, go through quick action
body := "/duplicate " + dID
_, _, err = lab.Notes.CreateIssueNote(projID, id, &gitlab.CreateIssueNoteOptions{
Body: &body,
})
if err != nil {
return errors.Errorf("Failed to close issue #%d as duplicate of %s", id, dID)
}
issue, _, err := lab.Issues.GetIssue(projID, id)
if issue == nil || issue.State != "closed" {
return errors.Errorf("Failed to close issue #%d as duplicate of %s", id, dID)
}
return nil
}
// IssueReopen reopens a closed issue
func IssueReopen(projID interface{}, id int) error {
issue, _, err := lab.Issues.GetIssue(projID, id)
if err != nil {
return err
}
if issue.State == "opened" {
return fmt.Errorf("issue not closed")
}
_, _, err = lab.Issues.UpdateIssue(projID, id, &gitlab.UpdateIssueOptions{
StateEvent: gitlab.String("reopen"),
})
if err != nil {
return err
}
return nil
}
// IssueListDiscussions retrieves the discussions (aka notes & comments) for an issue
func IssueListDiscussions(projID interface{}, id int) ([]*gitlab.Discussion, error) {
discussions := []*gitlab.Discussion{}
opt := &gitlab.ListIssueDiscussionsOptions{
// 100 is the maximum allowed by the API
PerPage: maxItemsPerPage,
}
for {
// get a page of discussions from the API ...
d, resp, err := lab.Discussions.ListIssueDiscussions(projID, id, opt)
if err != nil {
return nil, err
}
// ... and add them to our collection of discussions
discussions = append(discussions, d...)
// if we've seen all the pages, then we can break here.
// otherwise, update the page number to get the next page.
var ok bool
if opt.Page, ok = hasNextPage(resp); !ok {
break
}
}
return discussions, nil
}
// IssueSubscribe subscribes to an issue on a GitLab project
func IssueSubscribe(projID interface{}, id int) error {
_, resp, err := lab.Issues.SubscribeToIssue(projID, id, nil)
if resp != nil && resp.StatusCode == http.StatusNotModified {
return errors.New("Already subscribed")
}
if err != nil {
return err
}
return nil
}
// IssueUnsubscribe unsubscribes from an issue on a GitLab project
func IssueUnsubscribe(projID interface{}, id int) error {
_, resp, err := lab.Issues.UnsubscribeFromIssue(projID, id, nil)
if resp != nil && resp.StatusCode == http.StatusNotModified {
return errors.New("Not subscribed")
}
if err != nil {
return err
}
return nil
}
// GetCommit returns top Commit by ref (hash, branch or tag).
func GetCommit(projID interface{}, ref string) (*gitlab.Commit, error) {
c, _, err := lab.Commits.GetCommit(projID, ref)
if err != nil {
return nil, err
}
return c, nil
}
// LabelList gets a list of labels on a GitLab Project
func LabelList(projID interface{}) ([]*gitlab.Label, error) {
labels := []*gitlab.Label{}
opt := &gitlab.ListLabelsOptions{
ListOptions: gitlab.ListOptions{
PerPage: maxItemsPerPage,
},
}
for {
l, resp, err := lab.Labels.ListLabels(projID, opt)
if err != nil {
return nil, err
}
labels = append(labels, l...)
// if we've seen all the pages, then we can break here
// otherwise, update the page number to get the next page.
var ok bool
if opt.Page, ok = hasNextPage(resp); !ok {
break
}
}
return labels, nil
}
// LabelCreate creates a new project label
func LabelCreate(projID interface{}, opts *gitlab.CreateLabelOptions) error {
_, _, err := lab.Labels.CreateLabel(projID, opts)
return err
}
// LabelDelete removes a project label
func LabelDelete(projID, name string) error {
_, err := lab.Labels.DeleteLabel(projID, name, &gitlab.DeleteLabelOptions{
Name: &name,
})
return err
}
// BranchList get all branches from the project that somehow matches the
// requested options
func BranchList(projID interface{}, opts *gitlab.ListBranchesOptions) ([]*gitlab.Branch, error) {
branches := []*gitlab.Branch{}
for {
bList, resp, err := lab.Branches.ListBranches(projID, opts)
if err != nil {
return nil, err
}
branches = append(branches, bList...)
var ok bool
if opts.Page, ok = hasNextPage(resp); !ok {
break
}
}
return branches, nil
}
// MilestoneGet get a specific milestone from the list of available ones
func MilestoneGet(projID interface{}, name string) (*gitlab.Milestone, error) {
opts := &gitlab.ListMilestonesOptions{
Title: &name,
}
milestones, _ := MilestoneList(projID, opts)
switch len(milestones) {
case 1:
return milestones[0], nil
case 0:
return nil, errors.Errorf("Milestone '%s' not found", name)
default:
return nil, errors.Errorf("Milestone '%s' is ambiguous", name)
}
}
// MilestoneList gets a list of milestones on a GitLab Project
func MilestoneList(projID interface{}, opt *gitlab.ListMilestonesOptions) ([]*gitlab.Milestone, error) {
milestones := []*gitlab.Milestone{}
for {
m, resp, err := lab.Milestones.ListMilestones(projID, opt)
if err != nil {
return nil, err
}
milestones = append(milestones, m...)
// if we've seen all the pages, then we can break here.
// otherwise, update the page number to get the next page.
var ok bool
if opt.Page, ok = hasNextPage(resp); !ok {
break
}
}
p, err := FindProject(projID)
if err != nil {
return nil, err
}
if p.Namespace.Kind != "group" {
return milestones, nil
}
// get inherited milestones from group; in the future, we'll be able to use the
// IncludeParentMilestones option with ListMilestones()
includeParents := true
gopt := &gitlab.ListGroupMilestonesOptions{
IIDs: opt.IIDs,
Title: opt.Title,
State: opt.State,
Search: opt.Search,
IncludeParentMilestones: &includeParents,
}
for {
groupMilestones, resp, err := lab.GroupMilestones.ListGroupMilestones(p.Namespace.ID, gopt)
if err != nil {
return nil, err
}
for _, m := range groupMilestones {
milestones = append(milestones, &gitlab.Milestone{
ID: m.ID,
IID: m.IID,
Title: m.Title,
Description: m.Description,
StartDate: m.StartDate,
DueDate: m.DueDate,
State: m.State,
UpdatedAt: m.UpdatedAt,
CreatedAt: m.CreatedAt,
Expired: m.Expired,
})
}
// if we've seen all the pages, then we can break here
// otherwise, update the page number to get the next page.
var ok bool
if gopt.Page, ok = hasNextPage(resp); !ok {
break
}
}
return milestones, nil
}
// MilestoneCreate creates a new project milestone
func MilestoneCreate(projID interface{}, opts *gitlab.CreateMilestoneOptions) error {
_, _, err := lab.Milestones.CreateMilestone(projID, opts)
return err
}
// MilestoneDelete deletes a project milestone
func MilestoneDelete(projID, name string) error {
milestone, err := MilestoneGet(projID, name)
if err != nil {
return err
}
_, err = lab.Milestones.DeleteMilestone(milestone.ProjectID, milestone.ID)
return err
}
// ProjectSnippetCreate creates a snippet in a project
func ProjectSnippetCreate(projID interface{}, opts *gitlab.CreateProjectSnippetOptions) (*gitlab.Snippet, error) {
snip, _, err := lab.ProjectSnippets.CreateSnippet(projID, opts)
if err != nil {
return nil, err
}
return snip, nil
}
// ProjectSnippetDelete deletes a project snippet
func ProjectSnippetDelete(projID interface{}, id int) error {
_, err := lab.ProjectSnippets.DeleteSnippet(projID, id)