This repository has been archived by the owner on Nov 30, 2023. It is now read-only.
forked from grezar/go-circleci
-
Notifications
You must be signed in to change notification settings - Fork 0
/
circleci.go
229 lines (192 loc) · 4.1 KB
/
circleci.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
package circleci
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"github.com/google/go-querystring/query"
)
const (
userAgent = "go-circleci"
DefaultAddress = "https://circleci.com"
DefaultBasePath = "/api/v2/"
)
type Config struct {
Address string
BasePath string
Token string
Headers http.Header
HTTPClient *http.Client
}
func DefaultConfig() *Config {
config := &Config{
Address: DefaultAddress,
BasePath: DefaultBasePath,
Token: os.Getenv("CIRCLECI_TOKEN"),
Headers: make(http.Header),
HTTPClient: &http.Client{},
}
config.Headers.Set("User-Agent", userAgent)
return config
}
type Client struct {
baseURL *url.URL
token string
headers http.Header
http *http.Client
Contexts Contexts
Projects Projects
Users Users
Workflows Workflows
Pipelines Pipelines
Jobs Jobs
Insights Insights
}
func NewClient(cfg *Config) (*Client, error) {
config := DefaultConfig()
if cfg != nil {
if cfg.Address != "" {
config.Address = cfg.Address
}
if cfg.BasePath != "" {
config.BasePath = cfg.BasePath
}
if cfg.Token != "" {
config.Token = cfg.Token
}
for k, v := range cfg.Headers {
config.Headers[k] = v
}
if cfg.HTTPClient != nil {
config.HTTPClient = cfg.HTTPClient
}
}
baseURL, err := url.Parse(config.Address)
if err != nil {
return nil, fmt.Errorf("invalid address: %v", err)
}
baseURL.Path = config.BasePath
if !strings.HasSuffix(baseURL.Path, "/") {
baseURL.Path += "/"
}
if config.Token == "" {
return nil, fmt.Errorf("API token is required")
}
client := &Client{
baseURL: baseURL,
token: config.Token,
headers: config.Headers,
http: config.HTTPClient,
}
client.Contexts = &contexts{client: client}
client.Projects = &projects{client: client}
client.Users = &users{client: client}
client.Workflows = &workflows{client: client}
client.Pipelines = &pipelines{client: client}
client.Jobs = &jobs{client: client}
client.Insights = &insights{client: client}
return client, nil
}
func (c *Client) newRequest(method string, path string, v interface{}) (*http.Request, error) {
u, err := c.baseURL.Parse(path)
if err != nil {
return nil, err
}
reqHeaders := make(http.Header)
reqHeaders.Set("Circle-Token", c.token)
reqHeaders.Set("Accept", "application/json")
var body interface{}
switch method {
case "GET":
if v != nil {
q, err := query.Values(v)
if err != nil {
return nil, err
}
u.RawQuery = q.Encode()
}
case "DELETE", "PATCH", "POST", "PUT":
reqHeaders.Set("Content-Type", "application/json")
body = v
}
var buf io.ReadWriter
if body != nil {
buf = &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
for k, v := range c.headers {
req.Header[k] = v
}
for k, v := range reqHeaders {
req.Header[k] = v
}
return req, nil
}
func (c *Client) do(ctx context.Context, req *http.Request, v interface{}) error {
reqWithCtx := req.WithContext(ctx)
resp, err := c.http.Do(reqWithCtx)
if err != nil {
select {
case <-ctx.Done():
return ctx.Err()
default:
return err
}
}
defer resp.Body.Close()
if err := checkResponseCode(resp); err != nil {
return err
}
if v == nil {
return nil
}
switch v := v.(type) {
case nil:
case io.Writer:
_, err = io.Copy(v, resp.Body)
default:
decErr := json.NewDecoder(resp.Body).Decode(v)
if decErr == io.EOF {
decErr = nil
}
if decErr != nil {
err = decErr
}
}
return err
}
type ErrorResponse struct {
Message string `json:"message"`
}
func checkResponseCode(r *http.Response) error {
if r.StatusCode >= 200 && r.StatusCode <= 299 {
return nil
}
switch r.StatusCode {
case 401:
return ErrUnauthorized
case 404:
return ErrNotFound
}
var errResponse ErrorResponse
err := json.NewDecoder(r.Body).Decode(&errResponse)
if err != nil || errResponse.Message == "" {
return errors.New(r.Status)
}
return errors.New(errResponse.Message)
}