-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcodeship.go
277 lines (231 loc) · 6.94 KB
/
codeship.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
package codeship
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
)
// ErrRateLimitExceeded occurs when Codeship returns 403 Forbidden response
var ErrRateLimitExceeded = errors.New("rate limit exceeded")
// ErrNotFound occurs when Codeship returns a 404 Not Found response
type ErrNotFound struct {
apiErrors
}
// ErrBadRequest occurs when Codeship returns a 400 Bad Request response
type ErrBadRequest struct {
apiErrors
}
type apiErrors struct {
Errors []string `json:"errors"`
}
func (e apiErrors) Error() string {
return strings.Join(e.Errors, ", ")
}
// Organization holds the configuration for the current API client scoped to the Organization. Should not
// be modified concurrently
type Organization struct {
UUID string
Name string
Scopes []string
client *Client
}
// Response is a Codeship response. This wraps the standard http.Response returned from Codeship.
type Response struct {
*http.Response
// Links that were returned with the response. These are parsed from the Link header.
Links
}
var (
urlRegex = regexp.MustCompile(`\s*<(.+)>`)
relRegex = regexp.MustCompile(`\s*rel="(\w+)"`)
)
func newResponse(r *http.Response) Response {
response := Response{Response: r}
if linkText := r.Header.Get("Link"); linkText != "" {
linkMap := make(map[string]string)
// one chunk: <url>; rel="foo"
for _, chunk := range strings.Split(linkText, ",") {
pieces := strings.Split(chunk, ";")
urlMatch := urlRegex.FindStringSubmatch(pieces[0])
relMatch := relRegex.FindStringSubmatch(pieces[1])
if len(relMatch) > 1 && len(urlMatch) > 1 {
linkMap[relMatch[1]] = urlMatch[1]
}
}
response.Links.First = linkMap["first"]
response.Links.Last = linkMap["last"]
response.Links.Next = linkMap["next"]
response.Links.Previous = linkMap["prev"]
}
return response
}
const apiURL = "https://api.codeship.com/v2"
// StdLogger allows you to bring your own log implementation for logging
type StdLogger interface {
Println(...interface{})
}
// Won't compile if StdLogger can't be realized by a log.Logger
var _ StdLogger = &log.Logger{}
// Client holds information necessary to make a request to the Codeship API
type Client struct {
baseURL string
authenticator Authenticator
authentication Authentication
headers http.Header
httpClient *http.Client
logger StdLogger
verbose bool
}
// New creates a new Codeship API client
func New(auth Authenticator, opts ...Option) (*Client, error) {
if auth == nil {
return nil, errors.New("no authenticator provided")
}
client := &Client{
authenticator: auth,
baseURL: apiURL,
headers: make(http.Header),
}
if err := client.parseOptions(opts...); err != nil {
return nil, errors.Wrap(err, "options parsing failed")
}
// Fall back to http.DefaultClient if the user does not provide
// their own
if client.httpClient == nil {
client.httpClient = &http.Client{
Timeout: time.Second * 30,
}
}
// Fall back to default log.Logger (STDOUT) if the user does not provide
// their own
if client.logger == nil {
logger := &log.Logger{}
logger.SetOutput(os.Stdout)
client.logger = logger
}
return client, nil
}
// Organization scopes a client to a single Organization, allowing the user to make calls to the API
func (c *Client) Organization(ctx context.Context, name string) (*Organization, error) {
if name == "" {
return nil, errors.New("no organization name provided")
}
if c.AuthenticationRequired() {
if _, err := c.Authenticate(ctx); err != nil {
return nil, errors.Wrap(err, "authentication failed")
}
}
for _, org := range c.authentication.Organizations {
if org.Name == strings.ToLower(name) {
return &Organization{
UUID: org.UUID,
Name: org.Name,
Scopes: org.Scopes,
client: c,
}, nil
}
}
return nil, ErrUnauthorized(fmt.Sprintf("organization %q not authorized. Authorized organizations: %v", name, c.authentication.Organizations))
}
// Authentication returns the client's current Authentication object
func (c *Client) Authentication() Authentication {
return c.authentication
}
// AuthenticationRequired determines if a client must authenticate before making a request
func (c *Client) AuthenticationRequired() bool {
return c.authentication.AccessToken == "" || c.authentication.ExpiresAt <= time.Now().Unix()
}
func (c *Client) request(ctx context.Context, method, path string, params interface{}) ([]byte, Response, error) {
url := c.baseURL + path
// Replace nil with a JSON object if needed
var reqBody io.Reader
if params != nil {
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(params); err != nil {
return nil, Response{}, err
}
reqBody = buf
}
if c.AuthenticationRequired() {
if _, err := c.Authenticate(ctx); err != nil {
return nil, Response{}, err
}
}
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
return nil, Response{}, errors.Wrap(err, "HTTP request creation failed")
}
// Apply any user-defined headers first
req.Header = cloneHeader(c.headers)
req.Header.Set("Authorization", "Bearer "+c.authentication.AccessToken)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
return c.do(req.WithContext(ctx))
}
func (c *Client) do(req *http.Request) ([]byte, Response, error) {
if c.verbose {
dumpReq, _ := httputil.DumpRequest(req, true)
c.logger.Println(string(dumpReq))
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, Response{}, errors.Wrap(err, "HTTP request failed")
}
if c.verbose {
dumpResp, _ := httputil.DumpResponse(resp, true)
c.logger.Println(string(dumpResp))
}
defer func() {
_ = resp.Body.Close()
}()
response := newResponse(resp)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, response, errors.Wrap(err, "could not read response body")
}
code := resp.StatusCode
if code < 400 {
return body, response, nil
}
switch code {
case http.StatusBadRequest:
var e ErrBadRequest
if err = json.Unmarshal(body, &e); err != nil {
return nil, response, ErrBadRequest{}
}
return nil, response, e
case http.StatusNotFound:
var e ErrNotFound
if err = json.Unmarshal(body, &e); err != nil {
return nil, response, ErrNotFound{}
}
return nil, response, e
case http.StatusUnauthorized:
return nil, response, ErrUnauthorized("invalid credentials")
case http.StatusForbidden, http.StatusTooManyRequests:
return nil, response, ErrRateLimitExceeded
}
if len(body) > 0 {
return nil, response, fmt.Errorf("HTTP status: %d; content %q", resp.StatusCode, string(body))
}
return nil, response, fmt.Errorf("HTTP status: %d", resp.StatusCode)
}
// cloneHeader returns a shallow copy of the header.
// copied from https://godoc.org/github.com/golang/gddo/httputil/header#Copy
func cloneHeader(header http.Header) http.Header {
h := make(http.Header)
for k, vs := range header {
h[k] = vs
}
return h
}