/
client.go
167 lines (149 loc) · 4.63 KB
/
client.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
package gh
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"time"
"github.com/aviator-co/av/internal/config"
"emperror.dev/errors"
"github.com/aviator-co/av/internal/utils/logutils"
"github.com/shurcooL/githubv4"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
)
type Client struct {
httpClient *http.Client
gh *githubv4.Client
}
const githubCloudApiBaseUrl = "https://api.github.com"
// NewClient creates a new GitHub client.
// It takes configuration from the global config.Av.GitHub variable.
func NewClient(token string) (*Client, error) {
if token == "" {
return nil, errors.Errorf("no GitHub token provided (do you need to configure one?)")
}
src := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
httpClient := oauth2.NewClient(context.Background(), src)
var gh *githubv4.Client
if config.Av.GitHub.BaseURL == "" {
gh = githubv4.NewClient(httpClient)
} else {
gh = githubv4.NewEnterpriseClient(config.Av.GitHub.BaseURL+"/api/graphql", httpClient)
}
return &Client{httpClient, gh}, nil
}
func (c *Client) query(ctx context.Context, query any, variables map[string]any) (reterr error) {
log := logrus.WithFields(logrus.Fields{
"variables": logutils.Format("%#+v", variables),
})
log.Debug("executing GitHub API query...")
startTime := time.Now()
defer func() {
log := log.WithFields(logrus.Fields{
"elapsed": time.Since(startTime),
"result": logutils.Format("%#+v", query),
})
if reterr != nil {
log.WithError(reterr).Debug("GitHub API query failed")
} else {
log.Debug("GitHub API query succeeded")
}
}()
return c.gh.Query(ctx, query, variables)
}
func (c *Client) mutate(
ctx context.Context,
mutation any,
input githubv4.Input,
variables map[string]any,
) (reterr error) {
log := logrus.WithFields(logrus.Fields{
"input": logutils.Format("%#+v", input),
})
log.Debug("executing GitHub API mutation...")
startTime := time.Now()
defer func() {
log := log.WithFields(logrus.Fields{
"elapsed": time.Since(startTime),
"result": logutils.Format("%#+v", mutation),
})
if reterr != nil {
log.WithError(reterr).Debug("GitHub API mutation failed")
} else {
log.Debug("GitHub API mutation succeeded")
}
}()
return c.gh.Mutate(ctx, mutation, input, variables)
}
// restPost executes a POST request to the endpoint (e.g., /repos/:owner/:repo/pulls).
// It unmarshals the response into the given result type (unless it's nil).
func (c *Client) restPost(
ctx context.Context,
endpoint string,
body interface{},
result interface{},
) error {
if endpoint[0] != '/' {
logrus.WithField("endpoint", endpoint).Panicf("malformed REST endpoint")
}
startTime := time.Now()
// GitHub cloud and GHES have different API URLs.
// For cloud, it's `https://api.github.com/repos/...`.
// For GHES, it's `https://github.mycompany.com/api/v3/repos/...`.
var url string
if config.Av.GitHub.BaseURL == "" {
url = githubCloudApiBaseUrl + endpoint
} else {
url = config.Av.GitHub.BaseURL + "/api/v3" + endpoint
}
log := logrus.WithFields(logrus.Fields{
"url": url,
"body": logutils.Format("%#+v", body),
})
bodyJson, err := json.Marshal(body)
if err != nil {
return errors.Wrap(err, "failed to marshal request body to JSON")
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(bodyJson))
if err != nil {
return errors.Wrap(err, "failed to create request")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/vnd.github.v3+json")
log.Debug("executing GitHub API request...")
res, err := c.httpClient.Do(req)
log.Debugf("header: %#+v", req.Header)
if err != nil {
return errors.Wrap(err, "failed to make API request")
}
defer res.Body.Close()
resBody, err := io.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "failed to read response body")
}
log.WithField("elapsed", time.Since(startTime)).Debug("GitHub API request completed")
if res.StatusCode != http.StatusOK {
log.WithFields(logrus.Fields{
"status": res.StatusCode,
"body": string(resBody),
}).Debug("GitHub API request failed")
return errors.Errorf("GitHub API request for %s failed: %s", endpoint, res.Status)
}
// Don't try to unmarshal into nil, it will return an error.
// NOTE: Go is weird with nil ("nil" can be typed or untyped) and this will
// only capture an untyped nil (i.e., where the result parameter is given as
// a nil literal), but that should be fine.
if result == nil {
return nil
}
if err := json.Unmarshal(resBody, result); err != nil {
return errors.Wrap(err, "failed to unmarshal response body")
}
return nil
}