forked from sqlc-dev/sqlc
/
upload.go
99 lines (91 loc) · 2.24 KB
/
upload.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
package bundler
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httputil"
"os"
"github.com/hrz8/sqlc/internal/config"
)
type Uploader struct {
token string
configPath string
config *config.Config
dir string
}
func NewUploader(configPath, dir string, conf *config.Config) *Uploader {
return &Uploader{
token: os.Getenv("SQLC_AUTH_TOKEN"),
configPath: configPath,
config: conf,
dir: dir,
}
}
func (up *Uploader) Validate() error {
if up.config.Project.ID == "" {
return fmt.Errorf("project.id is not set")
}
if up.token == "" {
return fmt.Errorf("SQLC_AUTH_TOKEN environment variable is not set")
}
return nil
}
func (up *Uploader) buildRequest(ctx context.Context, result map[string]string) (*http.Request, error) {
body := bytes.NewBuffer([]byte{})
w := multipart.NewWriter(body)
if err := writeInputs(w, up.configPath, up.config); err != nil {
return nil, err
}
if err := writeOutputs(w, up.dir, result); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
req, err := http.NewRequest("POST", "https://api.sqlc.dev/upload", body)
if err != nil {
return nil, err
}
// Set sqlc-version header
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", up.token))
return req.WithContext(ctx), nil
}
func (up *Uploader) DumpRequestOut(ctx context.Context, result map[string]string) error {
req, err := up.buildRequest(ctx, result)
if err != nil {
return err
}
dump, err := httputil.DumpRequest(req, true)
if err != nil {
return err
}
os.Stdout.Write(dump)
return nil
}
func (up *Uploader) Upload(ctx context.Context, result map[string]string) error {
if err := up.Validate(); err != nil {
return err
}
req, err := up.buildRequest(ctx, result)
if err != nil {
return err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode >= 400 {
body, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return fmt.Errorf("upload error: endpoint returned non-200 status code: %d", resp.StatusCode)
}
return fmt.Errorf("upload error: %d: %s", resp.StatusCode, string(body))
}
return nil
}