Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
228 lines (196 loc) · 7.03 KB
/
Copy pathconfig.go
File metadata and controls
228 lines (196 loc) · 7.03 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
package github
import (
"context"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/google/go-github/v92/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
)
type Config struct {
AppID *string
AppInstallationID *string
AppPEM []byte
BaseURL *url.URL
IsGHES bool
CachePath string
Insecure bool
LegacyClient bool
MaxRetries int
Owner string
ParallelRequests bool
ReadDelay time.Duration
RetryableErrors map[int]bool
RetryDelay time.Duration
Token string
WriteDelay time.Duration
MaxPerPage int
}
type Owner struct {
name string
id int64
v3client *github.Client
v4client *githubv4.Client
StopContext context.Context
IsOrganization bool
maxPerPage int
}
const (
// DotComAPIURL is the base API URL for github.com.
DotComAPIURL = "https://api.github.com/"
// DotComHost is the hostname for github.com.
DotComHost = "github.com"
// DotComAPIHost is the API hostname for github.com.
DotComAPIHost = "api.github.com"
// RESTAPIPath is the rest api path for api.github.com & ghe.com.
RESTAPIPath = "/"
// GraphQLAPIPath is the graphql api path for api.github.com & ghe.com.
GraphQLAPIPath = "/graphql"
// GHESRESTAPISuffix is the rest api suffix for GitHub Enterprise Server.
GHESRESTAPIPath = "api/v3/"
// GHESGraphQLAPISuffix is the GraphQL api suffix for GitHub Enterprise Server.
GHESGraphQLAPIPath = "api/graphql"
)
var (
// GHECHostMatch is a regex to match GitHub Enterprise Cloud hosts.
GHECHostMatch = regexp.MustCompile(`\.ghe\.com$`)
// GHECAPIHostMatch is a regex to match GitHub Enterprise Cloud API hosts.
GHECAPIHostMatch = regexp.MustCompile(`^api\.[a-zA-Z0-9-]+\.ghe\.com$`)
)
func RateLimitedHTTPClient(client *http.Client, writeDelay, readDelay, retryDelay time.Duration, parallelRequests bool, retryableErrors map[int]bool, maxRetries int) *http.Client {
client.Transport = NewEtagTransport(client.Transport)
client.Transport = NewRateLimitTransport(client.Transport, WithWriteDelay(writeDelay), WithReadDelay(readDelay), WithParallelRequests(parallelRequests))
client.Transport = logging.NewLoggingHTTPTransport(client.Transport)
client.Transport = newPreviewHeaderInjectorTransport(map[string]string{
// TODO: remove when Stone Crop preview is moved to general availability in the GraphQL API
"Accept": "application/vnd.github.stone-crop-preview+json",
}, client.Transport)
if maxRetries > 0 {
client.Transport = NewRetryTransport(client.Transport, WithRetryDelay(retryDelay), WithRetryableErrors(retryableErrors), WithMaxRetries(maxRetries))
}
return client
}
func (c *Config) AuthenticatedHTTPClient() *http.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: c.Token},
)
client := oauth2.NewClient(ctx, ts)
return RateLimitedHTTPClient(client, c.WriteDelay, c.ReadDelay, c.RetryDelay, c.ParallelRequests, c.RetryableErrors, c.MaxRetries)
}
func (c *Config) Anonymous() bool {
return c.AppID == nil && c.Token == ""
}
func (c *Config) AnonymousHTTPClient() *http.Client {
client := &http.Client{Transport: http.DefaultTransport.(*http.Transport).Clone()}
return RateLimitedHTTPClient(client, c.WriteDelay, c.ReadDelay, c.RetryDelay, c.ParallelRequests, c.RetryableErrors, c.MaxRetries)
}
func (c *Config) NewGraphQLClient(client *http.Client) (*githubv4.Client, error) {
pathSuffix := GraphQLAPIPath
if c.IsGHES {
pathSuffix = GHESGraphQLAPIPath
}
return githubv4.NewEnterpriseClient(c.BaseURL.JoinPath(pathSuffix).String(), client), nil
}
func (c *Config) NewRESTClient(client *http.Client) (*github.Client, error) {
pathSuffix := RESTAPIPath
if c.IsGHES {
pathSuffix = GHESRESTAPIPath
}
return github.NewClient(github.WithHTTPClient(client), github.WithURLs(new(c.BaseURL.JoinPath(pathSuffix).String()), nil))
}
// Deprecated: This is no longer required as [configureProviderMeta] is now used to configure the provider meta parameter with the necessary clients and owner information. Use [configureProviderMeta] instead.
func (c *Config) ConfigureOwner(owner *Owner) (*Owner, error) {
ctx := context.Background()
owner.name = c.Owner
if owner.name == "" {
if c.Anonymous() {
return owner, nil
}
// Discover authenticated user
user, _, err := owner.v3client.Users.Get(ctx, "")
if err != nil {
return nil, err
}
owner.name = user.GetLogin()
} else {
remoteOrg, _, err := owner.v3client.Organizations.Get(ctx, owner.name)
if err == nil {
if remoteOrg != nil {
owner.id = remoteOrg.GetID()
owner.IsOrganization = true
}
}
}
return owner, nil
}
// Meta returns the meta parameter that is passed into subsequent resources
// https://godoc.org/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema#ConfigureFunc
// Deprecated: Use [configureProviderMeta] instead.
func (c *Config) Meta() (any, error) {
return configureProviderMeta(context.Background(), "", c)
}
type previewHeaderInjectorTransport struct {
rt http.RoundTripper
previewHeaders map[string]string
}
func newPreviewHeaderInjectorTransport(headers map[string]string, rt http.RoundTripper) *previewHeaderInjectorTransport {
return &previewHeaderInjectorTransport{
rt: rt,
previewHeaders: headers,
}
}
func (injector *previewHeaderInjectorTransport) RoundTrip(req *http.Request) (*http.Response, error) {
for name, value := range injector.previewHeaders {
header := req.Header.Get(name)
if header == "" {
header = value
// NOTE: Some API endpoints expect a single Accept: application/octet-stream header.
// If one has been set, it's necessary to preserve it as-is, without
// appending previewHeaders value.
// See https://github.com/google/go-github/pull/3392
} else if strings.ToLower(name) != "accept" || header != "application/octet-stream" {
header = strings.Join([]string{header, value}, ",")
}
req.Header.Set(name, header)
}
return injector.rt.RoundTrip(req)
}
// getBaseURL returns a correctly configured base URL and a bool as to if this is GitHub Enterprise Server.
func getBaseURL(s string) (*url.URL, bool, error) {
if s == "" {
return nil, false, fmt.Errorf("base url must not be empty")
}
u, err := url.Parse(s)
if err != nil {
return nil, false, err
}
if !u.IsAbs() {
return nil, false, fmt.Errorf("base url must be absolute")
}
u = u.JoinPath("/")
switch {
case u.Host == DotComAPIHost:
case u.Host == DotComHost:
u.Host = DotComAPIHost
case GHECAPIHostMatch.MatchString(u.Host):
case GHECHostMatch.MatchString(u.Host):
u.Host = fmt.Sprintf("api.%s", u.Host)
default:
u.Path = strings.TrimSuffix(u.Path, GHESRESTAPIPath)
return u, true, nil
}
if u.Scheme != "https" {
return nil, false, fmt.Errorf("base url for github.com or ghe.com must use the https scheme")
}
if len(u.Path) > 1 {
return nil, false, fmt.Errorf("base url for github.com or ghe.com must not contain a path, got %s", u.Path)
}
u.Path = "/"
return u, false, nil
}