-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.go
More file actions
329 lines (273 loc) · 8.78 KB
/
Copy pathlib.go
File metadata and controls
329 lines (273 loc) · 8.78 KB
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
package kittycad
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"strings"
"time"
)
// DefaultServerURL is the default server URL for the KittyCad API.
const DefaultServerURL = "https://api.zoo.dev"
// TokenEnvVar is the environment variable that contains the token.
const TokenEnvVar = "ZOO_API_TOKEN"
type service struct {
client *Client
}
// NewClient creates a new client for the KittyCad API.
// You need to pass in your API token to create the client.
func NewClient(token, userAgent string) (*Client, error) {
if token == "" {
return nil, fmt.Errorf("you need to pass in an API token to create the client. Create a token at https://zoo.dev/account")
}
client := &Client{
server: DefaultServerURL,
token: token,
}
// Ensure the server URL always has a trailing slash.
if !strings.HasSuffix(client.server, "/") {
client.server += "/"
}
uat := userAgentTransport{
base: http.DefaultTransport,
userAgent: userAgent,
client: client,
}
client.client = &http.Client{
Transport: uat,
// We want a longer timeout since some of the files might take a bit.
Timeout: 600 * time.Second,
}
// Add the services to our client.
client.APICall = &APICallService{client: client}
client.APIToken = &APITokenService{client: client}
client.App = &AppService{client: client}
client.Beta = &BetaService{client: client}
client.Constant = &ConstantService{client: client}
client.Executor = &ExecutorService{client: client}
client.Factory = &FactoryService{client: client}
client.File = &FileService{client: client}
client.Hidden = &HiddenService{client: client}
client.Meta = &MetaService{client: client}
client.Ml = &MlService{client: client}
client.Modeling = &ModelingService{client: client}
client.Oauth2 = &Oauth2Service{client: client}
client.Org = &OrgService{client: client}
client.Payment = &PaymentService{client: client}
client.Project = &ProjectService{client: client}
client.ServiceAccount = &ServiceAccountService{client: client}
client.Shortlink = &ShortlinkService{client: client}
client.Store = &StoreService{client: client}
client.Unit = &UnitService{client: client}
client.User = &UserService{client: client}
return client, nil
}
// NewClientFromEnv creates a new client for the KittyCad API, using the token
// stored in the environment variable `KITTYCAD_API_TOKEN` or `ZOO_API_TOKEN`.
// Optionally, you can pass in a different base url from the default with `ZOO_HOST`. But that
// is not recommended, unless you know what you are doing or you are hosting
// your own instance of the KittyCAD API.
func NewClientFromEnv(userAgent string) (*Client, error) {
token := os.Getenv(TokenEnvVar)
if token == "" {
// Try the old environment variable name.
token = os.Getenv("KITTYCAD_API_TOKEN")
if token == "" {
return nil, fmt.Errorf("the environment variable %s must be set with your API token. Create a token at https://zoo.dev/account", TokenEnvVar)
}
}
host := os.Getenv("ZOO_HOST")
if host == "" {
host = DefaultServerURL
}
c, err := NewClient(token, userAgent)
if err != nil {
return nil, err
}
c.WithBaseURL(host)
return c, nil
}
// WithBaseURL overrides the baseURL.
func (c *Client) WithBaseURL(baseURL string) error {
newBaseURL, err := url.Parse(baseURL)
if err != nil {
return err
}
c.server = newBaseURL.String()
// Ensure the server URL always has a trailing slash.
if !strings.HasSuffix(c.server, "/") {
c.server += "/"
}
return nil
}
// WithToken overrides the token used for authentication.
func (c *Client) WithToken(token string) {
c.token = token
}
type userAgentTransport struct {
userAgent string
base http.RoundTripper
client *Client
}
// MultipartForm builds multipart/form-data request bodies for generated endpoints.
type MultipartForm struct {
buffer *bytes.Buffer
writer *multipart.Writer
closed bool
}
// NewMultipartForm creates a new multipart/form-data body.
func NewMultipartForm() *MultipartForm {
buffer := new(bytes.Buffer)
return &MultipartForm{
buffer: buffer,
writer: multipart.NewWriter(buffer),
}
}
func (f *MultipartForm) ensureWritable() error {
if f == nil {
return errors.New("multipart form is nil")
}
if f.writer == nil {
return errors.New("multipart form writer is nil")
}
if f.closed {
return errors.New("multipart form is closed")
}
return nil
}
// WriteJSONField adds a JSON field to the multipart body.
func (f *MultipartForm) WriteJSONField(field string, value any) error {
if err := f.ensureWritable(); err != nil {
return err
}
payload, err := json.Marshal(value)
if err != nil {
return fmt.Errorf("marshalling multipart JSON field %q failed: %v", field, err)
}
header := make(textproto.MIMEHeader)
header.Set("Content-Disposition", fmt.Sprintf(`form-data; name=%q; filename=%q`, field, field+".json"))
header.Set("Content-Type", "application/json")
part, err := f.writer.CreatePart(header)
if err != nil {
return fmt.Errorf("creating multipart JSON field %q failed: %v", field, err)
}
if _, err := part.Write(payload); err != nil {
return fmt.Errorf("writing multipart JSON field %q failed: %v", field, err)
}
return nil
}
// WriteFile adds a binary file part to the multipart body.
func (f *MultipartForm) WriteFile(field, filename string, body []byte) error {
return f.WriteFilePart(field, filename, "application/octet-stream", body)
}
// WriteFilePart adds a file part with a custom content type.
func (f *MultipartForm) WriteFilePart(field, filename, contentType string, body []byte) error {
if err := f.ensureWritable(); err != nil {
return err
}
if contentType == "" {
contentType = "application/octet-stream"
}
header := make(textproto.MIMEHeader)
header.Set("Content-Disposition", fmt.Sprintf(`form-data; name=%q; filename=%q`, field, filename))
header.Set("Content-Type", contentType)
part, err := f.writer.CreatePart(header)
if err != nil {
return fmt.Errorf("creating multipart file field %q failed: %v", field, err)
}
if _, err := part.Write(body); err != nil {
return fmt.Errorf("writing multipart file field %q failed: %v", field, err)
}
return nil
}
// Close finalizes the multipart body.
func (f *MultipartForm) Close() error {
if f == nil || f.closed {
return nil
}
f.closed = true
return f.writer.Close()
}
// ContentType returns the multipart/form-data content type with boundary.
func (f *MultipartForm) ContentType() string {
if f == nil || f.writer == nil {
return ""
}
return f.writer.FormDataContentType()
}
func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.base == nil {
return nil, errors.New("RoundTrip: no Transport specified")
}
newReq := *req
newReq.Header = make(http.Header)
for k, vv := range req.Header {
newReq.Header[k] = vv
}
// Add the user agent header.
newReq.Header["User-Agent"] = []string{t.userAgent}
// Default JSON requests should not clobber caller-provided content types.
if newReq.Header.Get("Content-Type") == "" {
newReq.Header["Content-Type"] = []string{"application/json"}
}
// Add the authorization header.
newReq.Header["Authorization"] = []string{fmt.Sprintf("Bearer %s", t.client.token)}
return t.base.RoundTrip(&newReq)
}
// HTTPError is an error returned by a failed API call.
type HTTPError struct {
// URL is the URL that was being accessed when the error occurred.
// It will always be populated.
URL *url.URL
// StatusCode is the HTTP response status code and will always be populated.
StatusCode int
// Message is the server response message and is only populated when
// explicitly referenced by the JSON server response.
Message string
// Body is the raw response returned by the server.
// It is often but not always JSON, depending on how the request fails.
Body string
// Header contains the response header fields from the server.
Header http.Header
}
// Error converts the Error type to a readable string.
func (err HTTPError) Error() string {
if err.Message != "" {
return fmt.Sprintf("HTTP %d: %s (%s)", err.StatusCode, err.Message, err.URL)
}
return fmt.Sprintf("HTTP %d (%s) BODY -> %v", err.StatusCode, err.URL, err.Body)
}
// checkResponse returns an error (of type *HTTPError) if the response
// status code is not 2xx.
func checkResponse(res *http.Response) error {
if res.StatusCode >= 200 && res.StatusCode <= 299 {
return nil
}
slurp, err := io.ReadAll(res.Body)
if err == nil {
var jerr Error
// Try to decode the body as an ErrorMessage.
if err := json.Unmarshal(slurp, &jerr); err == nil {
return &HTTPError{
URL: res.Request.URL,
StatusCode: res.StatusCode,
Message: jerr.Message,
Body: string(slurp),
Header: res.Header,
}
}
}
return &HTTPError{
URL: res.Request.URL,
StatusCode: res.StatusCode,
Body: string(slurp),
Header: res.Header,
Message: "",
}
}