Repository navigation
Expand file tree
/
Copy pathutil.go
More file actions
265 lines (223 loc) · 6.67 KB
/
Copy pathutil.go
File metadata and controls
265 lines (223 loc) · 6.67 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
package github
import (
"crypto/md5"
"errors"
"fmt"
"log"
"net/http"
"regexp"
"slices"
"sort"
"strings"
"github.com/google/go-github/v92/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 = `??`
)
// 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 checkOrganizationOK(meta *Owner) (bool, diag.Diagnostics) {
if !meta.IsOrganization {
return false, diag.Errorf("this resource can only be used in the context of an organization, %q is a user", meta.name)
}
return true, 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)
}
}
func validateValueFunc(values []string) schema.SchemaValidateDiagFunc {
return func(v any, k cty.Path) diag.Diagnostics {
value := v.(string)
valid := slices.Contains(values, value)
if !valid {
return diag.Errorf("%s is an invalid value for argument %s", value, k)
}
return nil
}
}
// format the strings into an id `a:b`.
//
// Deprecated: use buildID instead.
func buildTwoPartID(a, b string) string {
return fmt.Sprintf("%s:%s", a, b)
}
// format the strings into an id `a:b:c`.
//
// Deprecated: use buildID instead.
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())
}
// 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 {
var diags diag.Diagnostics
name, ok := v.(string)
if !ok {
return diag.Errorf("expected type of %s to be string", path)
}
if !secretNameRegexp.MatchString(name) {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Detail: "secret names can only contain alphanumeric characters or underscores and must not start with a number",
Summary: "Error",
AttributePath: path,
})
}
if strings.HasPrefix(strings.ToUpper(name), "GITHUB_") {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Detail: "secret names must not start with the GITHUB_ prefix",
Summary: "Error",
AttributePath: path,
})
}
return diags
}
// 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 {
if ghErr, ok := errors.AsType[*github.ErrorResponse](err); ok {
if ghErr.Response.StatusCode == http.StatusNotModified {
log.Printf("[INFO] Resource %s not modified, skipping", resourceDescription)
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
}
}