forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
384 lines (322 loc) · 10.4 KB
/
util.go
File metadata and controls
384 lines (322 loc) · 10.4 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package github
import (
"context"
"crypto/md5"
"errors"
"fmt"
"log"
"net/http"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"github.com/google/go-github/v82/github"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
const (
idSeparator = ":"
idSeparatorEscaped = `??`
)
// https://developer.github.com/guides/traversing-with-pagination/#basics-of-pagination
var maxPerPage = 100
// escapeIDPart escapes any idSeparator characters in a string.
func escapeIDPart(part string) string {
return strings.ReplaceAll(part, idSeparator, idSeparatorEscaped)
}
// unescapeIDPart unescapes any escaped idSeparator characters in a string.
func unescapeIDPart(part string) string {
return strings.ReplaceAll(part, idSeparatorEscaped, idSeparator)
}
// buildID joins the parts with the idSeparator.
func buildID(parts ...string) (string, error) {
l := len(parts)
if l == 0 {
return "", fmt.Errorf("no parts provided to build id")
}
for i, p := range parts {
if i < l-1 && strings.Contains(p, idSeparator) {
return "", fmt.Errorf("unescaped separator in non-final part %q", p)
}
}
id := strings.Join(parts, idSeparator)
return id, nil
}
// parseID splits the id by the idSeparator checking the count.
func parseID(id string, count int) ([]string, error) {
if len(id) == 0 {
return nil, fmt.Errorf("id is empty")
}
parts := strings.SplitN(id, idSeparator, count)
if len(parts) != count {
return nil, fmt.Errorf("unexpected ID format (%q); expected %d parts separated by %q", id, count, idSeparator)
}
return parts, nil
}
// parseID2 splits the id by the idSeparator into two parts.
func parseID2(id string) (string, string, error) {
parts, err := parseID(id, 2)
if err != nil {
return "", "", err
}
return parts[0], parts[1], nil
}
// parseID3 splits the id by the idSeparator into three parts.
func parseID3(id string) (string, string, string, error) {
parts, err := parseID(id, 3)
if err != nil {
return "", "", "", err
}
return parts[0], parts[1], parts[2], nil
}
// parseID4 splits the id by the idSeparator into four parts.
func parseID4(id string) (string, string, string, string, error) {
parts, err := parseID(id, 4)
if err != nil {
return "", "", "", "", err
}
return parts[0], parts[1], parts[2], parts[3], nil
}
func checkOrganization(meta any) error {
if !meta.(*Owner).IsOrganization {
return fmt.Errorf("this resource can only be used in the context of an organization, %q is a user", meta.(*Owner).name)
}
return nil
}
func caseInsensitive() schema.SchemaDiffSuppressFunc {
return func(k, o, n string, d *schema.ResourceData) bool {
return strings.EqualFold(o, n)
}
}
// wrapErrors is provided to easily turn errors into diag.Diagnostics
// until we go through the provider and replace error usage.
func wrapErrors(errs []error) diag.Diagnostics {
var diags diag.Diagnostics
for _, err := range errs {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: "Error",
Detail: err.Error(),
})
}
return diags
}
// toDiagFunc is a helper that operates on Hashicorp's helper/validation functions
// and converts them to the diag.Diagnostic format
// --> nolint: oldFunc needs to be schema.SchemaValidateFunc to keep compatibility with
// the old code until all uses of schema.SchemaValidateFunc are gone.
func toDiagFunc(oldFunc schema.SchemaValidateFunc, keyName string) schema.SchemaValidateDiagFunc { //nolint:staticcheck
return func(i any, path cty.Path) diag.Diagnostics {
warnings, errors := oldFunc(i, keyName)
var diags diag.Diagnostics
for _, err := range errors {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: err.Error(),
})
}
for _, warn := range warnings {
diags = append(diags, diag.Diagnostic{
Severity: diag.Warning,
Summary: warn,
})
}
return diags
}
}
func validateValueFunc(values []string) schema.SchemaValidateDiagFunc {
return func(v any, k cty.Path) diag.Diagnostics {
errs := make([]error, 0)
value := v.(string)
valid := slices.Contains(values, value)
if !valid {
errs = append(errs, fmt.Errorf("%s is an invalid value for argument %s", value, k))
}
return wrapErrors(errs)
}
}
// return the pieces of id `left:right` as left, right.
func parseTwoPartID(id, left, right string) (string, string, error) {
parts := strings.SplitN(id, ":", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("unexpected ID format (%q); expected %s:%s", id, left, right)
}
return parts[0], parts[1], nil
}
// format the strings into an id `a:b`.
func buildTwoPartID(a, b string) string {
return fmt.Sprintf("%s:%s", a, b)
}
// return the pieces of id `left:center:right` as left, center, right.
func parseThreePartID(id, left, center, right string) (string, string, string, error) {
parts := strings.SplitN(id, ":", 3)
if len(parts) != 3 {
return "", "", "", fmt.Errorf("unexpected ID format (%q). Expected %s:%s:%s", id, left, center, right)
}
return parts[0], parts[1], parts[2], nil
}
// format the strings into an id `a:b:c`.
func buildThreePartID(a, b, c string) string {
return fmt.Sprintf("%s:%s:%s", a, b, c)
}
func buildChecksumID(v []string) string {
sort.Strings(v)
h := md5.New()
// Hash.Write never returns an error. See https://pkg.go.dev/hash#Hash
_, _ = h.Write([]byte(strings.Join(v, "")))
bs := h.Sum(nil)
return fmt.Sprintf("%x", bs)
}
func expandStringList(configured []any) []string {
vs := make([]string, 0, len(configured))
for _, v := range configured {
val, ok := v.(string)
if ok && val != "" {
vs = append(vs, val)
}
}
return vs
}
func flattenStringList(v []string) []any {
c := make([]any, 0, len(v))
for _, s := range v {
c = append(c, s)
}
return c
}
func unconvertibleIdErr(id string, err error) *unconvertibleIdError {
return &unconvertibleIdError{OriginalId: id, OriginalError: err}
}
type unconvertibleIdError struct {
OriginalId string
OriginalError error
}
func (e *unconvertibleIdError) Error() string {
return fmt.Sprintf("Unexpected ID format (%q), expected numerical ID. %s",
e.OriginalId, e.OriginalError.Error())
}
func splitRepoFilePath(path string) (string, string) {
parts := strings.Split(path, "/")
return parts[0], strings.Join(parts[1:], "/")
}
func getTeamID(teamIDString string, meta any) (int64, error) {
// Given a string that is either a team id or team slug, return the
// id of the team it is referring to.
ctx := context.Background()
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
teamId, parseIntErr := strconv.ParseInt(teamIDString, 10, 64)
if parseIntErr == nil {
return teamId, nil
}
// The given id not an integer, assume it is a team slug
team, _, slugErr := client.Teams.GetTeamBySlug(ctx, orgName, teamIDString)
if slugErr != nil {
return -1, errors.New(parseIntErr.Error() + slugErr.Error())
}
return team.GetID(), nil
}
func getTeamSlug(teamIDString string, meta any) (string, error) {
ctx := context.Background()
return getTeamSlugContext(ctx, teamIDString, meta)
}
func getTeamSlugContext(ctx context.Context, teamIDString string, meta any) (string, error) {
// Given a string that is either a team id or team slug, return the
// team slug it is referring to.
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
orgId := meta.(*Owner).id
teamId, parseIntErr := strconv.ParseInt(teamIDString, 10, 64)
if parseIntErr != nil {
// The given id not an integer, assume it is a team slug
team, _, slugErr := client.Teams.GetTeamBySlug(ctx, orgName, teamIDString)
if slugErr != nil {
return "", errors.New(parseIntErr.Error() + slugErr.Error())
}
return team.GetSlug(), nil
}
// The given id is an integer, assume it is a team id
team, _, teamIdErr := client.Teams.GetTeamByID(ctx, orgId, teamId)
if teamIdErr != nil {
// There isn't a team with the given ID, assume it is a teamslug
team, _, slugErr := client.Teams.GetTeamBySlug(ctx, orgName, teamIDString)
if slugErr != nil {
return "", errors.New(teamIdErr.Error() + slugErr.Error())
}
return team.GetSlug(), nil
}
return team.GetSlug(), nil
}
// https://docs.github.com/en/actions/reference/encrypted-secrets#naming-your-secrets
var secretNameRegexp = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
func validateSecretNameFunc(v any, path cty.Path) diag.Diagnostics {
errs := make([]error, 0)
name, ok := v.(string)
if !ok {
return wrapErrors([]error{fmt.Errorf("expected type of %s to be string", path)})
}
if !secretNameRegexp.MatchString(name) {
errs = append(errs, errors.New("secret names can only contain alphanumeric characters or underscores and must not start with a number"))
}
if strings.HasPrefix(strings.ToUpper(name), "GITHUB_") {
errs = append(errs, errors.New("secret names must not start with the GITHUB_ prefix"))
}
return wrapErrors(errs)
}
// deleteResourceOn404AndSwallow304OtherwiseReturnError will log and delete resource if error is 404 which indicates resource (or any of its ancestors)
// doesn't exist.
// resourceDescription represents a formatting string that represents the resource
// args will be passed to resourceDescription in `log.Printf`.
func deleteResourceOn404AndSwallow304OtherwiseReturnError(err error, d *schema.ResourceData, resourceDescription string, args ...any) error {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
if ghErr.Response.StatusCode == http.StatusNotModified {
return nil
}
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[INFO] Removing "+resourceDescription+" from state because it no longer exists in GitHub",
args...)
d.SetId("")
return nil
}
}
return err
}
// Helper function to safely convert interface{} to int, handling both int and float64.
func toInt(v any) int {
switch val := v.(type) {
case int:
return val
case float64:
return int(val)
case int64:
return int(val)
default:
return 0
}
}
// Helper function to safely convert interface{} to int64, handling both int and float64.
func toInt64(v any) int64 {
switch val := v.(type) {
case int:
return int64(val)
case int64:
return val
case float64:
return int64(val)
default:
return 0
}
}
// lookupTeamID looks up the ID of a team by its slug.
func lookupTeamID(ctx context.Context, meta *Owner, slug string) (int64, error) {
client := meta.v3client
owner := meta.name
team, _, err := client.Teams.GetTeamBySlug(ctx, owner, slug)
if err != nil {
return 0, err
}
return team.GetID(), nil
}