/
gitlab.go
216 lines (190 loc) · 4.66 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
package vcs
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"time"
"go.opencensus.io/plugin/ochttp"
"github.com/epels/preport"
)
type Gitlab struct {
httpc *http.Client
baseURL, bearer string
}
type mergeRequestsResponse []mergeRequestResponse
type mergeRequestResponse struct {
Title string
WebURL string `json:"web_url"`
Author struct {
Username string
}
CreatedAt time.Time `json:"created_at"`
}
type (
Scope string
Sort string
State string
)
// GitlabOptions are parameters used to filter the pull requests; values with
// the respective type's zero values are discarded.
type GitlabOptions struct {
Scope Scope
State State
IsDraft *bool
HasAssignee *bool
HasBeenApproved *bool
HasReviewer *bool
Sort Sort
PerPage int
}
const (
ScopeCreatedByMe Scope = "created_by_me"
ScopeAssignedToMe Scope = "assigned_to_me"
ScopeAll Scope = "all"
SortAsc Sort = "asc"
SortDesc Sort = "desc"
StateClosed State = "closed"
StateLocked State = "locked"
StateMerged State = "merged"
StateOpened State = "opened"
)
var False = false
func NewGitlab(baseURL, bearer string) (*Gitlab, error) {
switch "" {
case baseURL:
return nil, errors.New("baseURL must not be empty")
case bearer:
return nil, errors.New("bearer must not be empty")
}
if u, err := url.Parse(baseURL); err != nil || (u.Scheme != "http" && u.Scheme != "https") {
return nil, errors.New("baseURL must be a valid http(s) URL")
}
return &Gitlab{
httpc: &http.Client{
Transport: &ochttp.Transport{},
// Timeout is a generous duration intended as a fallback for when
// the caller does not provide a context with a sensible deadline.
Timeout: 30 * time.Second,
},
baseURL: baseURL,
bearer: bearer,
}, nil
}
func (g *Gitlab) ListPullRequests(ctx context.Context, projectID string, opts GitlabOptions) ([]preport.PullRequest, error) {
vals, err := opts.toValues()
if err != nil {
return nil, fmt.Errorf("unable to validate GitlabOptions: %s", err)
}
u := fmt.Sprintf("%s/api/v4/projects/%s/merge_requests?%s", g.baseURL, projectID, vals.Encode())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, http.NoBody)
if err != nil {
return nil, fmt.Errorf("net/http: NewRequestWithContext: %s", err)
}
req.Header.Set("Authorization", "Bearer "+g.bearer)
res, err := g.httpc.Do(req)
if err != nil {
return nil, fmt.Errorf("net/http: Client.Do: %s", err)
}
defer func() {
if err := res.Body.Close(); err != nil {
log.Printf("%T: Close: %s", res.Body, err)
}
}()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", res.StatusCode)
}
var rs mergeRequestsResponse
if err := json.NewDecoder(res.Body).Decode(&rs); err != nil {
return nil, fmt.Errorf("encoding/json: Decoder.Decode: %s", err)
}
return rs.toPullRequests(), nil
}
func (rs mergeRequestsResponse) toPullRequests() []preport.PullRequest {
prs := make([]preport.PullRequest, 0, len(rs))
for _, r := range rs {
prs = append(prs, r.toPullRequest())
}
return prs
}
func (r mergeRequestResponse) toPullRequest() preport.PullRequest {
return preport.PullRequest{
Title: r.Title,
URL: r.WebURL,
Author: preport.Author{
Username: r.Author.Username,
},
CreatedAt: r.CreatedAt,
}
}
func (o GitlabOptions) validate() error {
switch o.Scope {
case "", ScopeCreatedByMe, ScopeAssignedToMe, ScopeAll:
default:
return fmt.Errorf("unexpected scope: %q", o.Scope)
}
switch o.Sort {
case "", SortAsc, SortDesc:
default:
return fmt.Errorf("unexpected sort: %q", o.Sort)
}
switch o.State {
case "", StateClosed, StateLocked, StateMerged, StateOpened:
default:
return fmt.Errorf("unexpected state: %q", o.State)
}
return nil
}
func (o GitlabOptions) toValues() (url.Values, error) {
if err := o.validate(); err != nil {
return nil, err
}
v := url.Values{}
if o.Scope != "" {
v.Set("scope", string(o.Scope))
}
if o.State != "" {
v.Set("state", string(o.State))
}
if o.Sort != "" {
v.Set("sort", string(o.Sort))
}
if o.IsDraft != nil {
wip := "no"
if *o.IsDraft {
wip = "yes"
}
v.Set("wip", wip)
}
if o.HasAssignee != nil {
assignee := "None"
if *o.HasAssignee {
assignee = "Any"
}
v.Set("assignee_id", assignee)
}
if o.HasBeenApproved != nil {
approvedBy := "None"
if *o.HasBeenApproved {
approvedBy = "Any"
}
v.Set("approved_by_ids", approvedBy)
}
if o.HasReviewer != nil {
reviewer := "None"
if *o.HasReviewer {
reviewer = "Any"
}
v.Set("reviewer_id", reviewer)
}
perPage := 100
if o.PerPage != 0 {
perPage = o.PerPage
}
v.Set("per_page", strconv.Itoa(perPage))
return v, nil
}