-
Notifications
You must be signed in to change notification settings - Fork 694
/
resource_github_branch_protection_v3_utils.go
354 lines (297 loc) · 9.83 KB
/
resource_github_branch_protection_v3_utils.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
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
package github
import (
"context"
"errors"
"fmt"
"github.com/google/go-github/v48/github"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"log"
"strings"
)
func buildProtectionRequest(d *schema.ResourceData) (*github.ProtectionRequest, error) {
req := &github.ProtectionRequest{
EnforceAdmins: d.Get("enforce_admins").(bool),
RequiredConversationResolution: github.Bool(d.Get("require_conversation_resolution").(bool)),
}
rsc, err := expandRequiredStatusChecks(d)
if err != nil {
return nil, err
}
req.RequiredStatusChecks = rsc
rprr, err := expandRequiredPullRequestReviews(d)
if err != nil {
return nil, err
}
req.RequiredPullRequestReviews = rprr
res, err := expandRestrictions(d)
if err != nil {
return nil, err
}
req.Restrictions = res
return req, nil
}
func flattenAndSetRequiredStatusChecks(d *schema.ResourceData, protection *github.Protection) error {
rsc := protection.GetRequiredStatusChecks()
if rsc != nil {
var checks []interface{}
// TODO: Remove once contexts is fully deprecated.
// Handle contexts as check objects while waiting for contexts to become deprecated
// Flatten contexts
for _, c := range rsc.Contexts {
chkMap := make(map[string]interface{})
chkMap["context"] = c
chkMap["app_id"] = -1
checks = append(checks, chkMap)
}
// Flatten checks
for _, chk := range rsc.Checks {
chkMap := make(map[string]interface{})
chkMap["context"] = chk.Context
chkMap["app_id"] = chk.AppID
checks = append(checks, chkMap)
}
return d.Set("required_status_checks", []interface{}{
map[string]interface{}{
"strict": rsc.Strict,
// TODO: As above, remove if unneeded
//"contexts": schema.NewSet(schema.HashString, contexts),
"check": checks,
},
})
}
return d.Set("required_status_checks", []interface{}{})
}
func requireSignedCommitsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
repoName, branch, err := parseTwoPartID(d.Id(), "repository", "branch")
if err != nil {
return err
}
orgName := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
if !d.IsNewResource() {
ctx = context.WithValue(ctx, ctxEtag, d.Get("etag").(string))
}
signedCommitStatus, _, err := client.Repositories.GetSignaturesProtectedBranch(ctx,
orgName, repoName, branch)
if err != nil {
log.Printf("[INFO] Not able to read signature protection: %s/%s (%s)", orgName, repoName, branch)
return nil
}
return d.Set("require_signed_commits", signedCommitStatus.Enabled)
}
func requireSignedCommitsUpdate(d *schema.ResourceData, meta interface{}) (err error) {
requiredSignedCommit := d.Get("require_signed_commits").(bool)
client := meta.(*Owner).v3client
repoName, branch, err := parseTwoPartID(d.Id(), "repository", "branch")
if err != nil {
return err
}
orgName := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
if !d.IsNewResource() {
ctx = context.WithValue(ctx, ctxEtag, d.Get("etag").(string))
}
if requiredSignedCommit {
_, _, err = client.Repositories.RequireSignaturesOnProtectedBranch(ctx, orgName, repoName, branch)
} else {
_, err = client.Repositories.OptionalSignaturesOnProtectedBranch(ctx, orgName, repoName, branch)
}
return err
}
func flattenAndSetRequiredPullRequestReviews(d *schema.ResourceData, protection *github.Protection) error {
rprr := protection.GetRequiredPullRequestReviews()
if rprr != nil {
var users, teams []interface{}
restrictions := rprr.GetDismissalRestrictions()
if restrictions != nil {
users = make([]interface{}, 0, len(restrictions.Users))
for _, u := range restrictions.Users {
if u.Login != nil {
users = append(users, *u.Login)
}
}
teams = make([]interface{}, 0, len(restrictions.Teams))
for _, t := range restrictions.Teams {
if t.Slug != nil {
teams = append(teams, *t.Slug)
}
}
}
return d.Set("required_pull_request_reviews", []interface{}{
map[string]interface{}{
"dismiss_stale_reviews": rprr.DismissStaleReviews,
"dismissal_users": schema.NewSet(schema.HashString, users),
"dismissal_teams": schema.NewSet(schema.HashString, teams),
"require_code_owner_reviews": rprr.RequireCodeOwnerReviews,
"required_approving_review_count": rprr.RequiredApprovingReviewCount,
},
})
}
return d.Set("required_pull_request_reviews", []interface{}{})
}
func flattenAndSetRestrictions(d *schema.ResourceData, protection *github.Protection) error {
restrictions := protection.GetRestrictions()
if restrictions != nil {
users := make([]interface{}, 0, len(restrictions.Users))
for _, u := range restrictions.Users {
if u.Login != nil {
users = append(users, *u.Login)
}
}
teams := make([]interface{}, 0, len(restrictions.Teams))
for _, t := range restrictions.Teams {
if t.Slug != nil {
teams = append(teams, *t.Slug)
}
}
apps := make([]interface{}, 0, len(restrictions.Apps))
for _, t := range restrictions.Apps {
if t.Slug != nil {
apps = append(apps, *t.Slug)
}
}
return d.Set("restrictions", []interface{}{
map[string]interface{}{
"users": schema.NewSet(schema.HashString, users),
"teams": schema.NewSet(schema.HashString, teams),
"apps": schema.NewSet(schema.HashString, apps),
},
})
}
return d.Set("restrictions", []interface{}{})
}
func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusChecks, error) {
if v, ok := d.GetOk("required_status_checks"); ok {
vL := v.([]interface{})
if len(vL) > 1 {
return nil, errors.New("cannot specify required_status_checks more than one time")
}
rsc := new(github.RequiredStatusChecks)
for _, v := range vL {
// List can only have one item, safe to early return here
if v == nil {
return nil, nil
}
m := v.(map[string]interface{})
rsc.Strict = m["strict"].(bool)
var rscChecks []*github.RequiredStatusCheck
// Iterate and parse contexts into checks objects as contexts is deprecated.
// TODO: Remove this code once contexts is fully deprecated
// Iterate and parse contexts
contexts := expandNestedSet(m, "contexts")
for _, c := range contexts {
appID := int64(-1) // Default
rscChecks = append(rscChecks, &github.RequiredStatusCheck{
Context: c,
AppID: &appID,
})
}
// Iterate and parse checks
checks := m["check"].([]interface{})
for _, c := range checks {
chk := c.(map[string]interface{})
var cContext string
if cContext, ok = chk["context"].(string); !ok {
return nil, errors.New("could not parse 'context' for required_status_checks check")
}
var cAppId int
if cAppId, ok = chk["app_id"].(int); !ok {
log.Printf("[DEBUG] app_id value: %v", chk["app_id"].(int))
return nil, errors.New("could not parse 'app_id' for required_status_checks check")
}
rscAppId := int64(cAppId)
rscChecks = append(rscChecks, &github.RequiredStatusCheck{
Context: cContext,
AppID: &rscAppId,
})
}
// Assign after looping both checks and contexts
rsc.Checks = rscChecks
}
return rsc, nil
}
return nil, nil
}
func expandRequiredPullRequestReviews(d *schema.ResourceData) (*github.PullRequestReviewsEnforcementRequest, error) {
if v, ok := d.GetOk("required_pull_request_reviews"); ok {
vL := v.([]interface{})
if len(vL) > 1 {
return nil, errors.New("cannot specify required_pull_request_reviews more than one time")
}
rprr := new(github.PullRequestReviewsEnforcementRequest)
drr := new(github.DismissalRestrictionsRequest)
for _, v := range vL {
// List can only have one item, safe to early return here
if v == nil {
return nil, nil
}
m := v.(map[string]interface{})
users := expandNestedSet(m, "dismissal_users")
if len(users) > 0 {
drr.Users = &users
}
teams := expandNestedSet(m, "dismissal_teams")
if len(teams) > 0 {
drr.Teams = &teams
}
rprr.DismissalRestrictionsRequest = drr
rprr.DismissStaleReviews = m["dismiss_stale_reviews"].(bool)
rprr.RequireCodeOwnerReviews = m["require_code_owner_reviews"].(bool)
rprr.RequiredApprovingReviewCount = m["required_approving_review_count"].(int)
}
return rprr, nil
}
return nil, nil
}
func expandRestrictions(d *schema.ResourceData) (*github.BranchRestrictionsRequest, error) {
if v, ok := d.GetOk("restrictions"); ok {
vL := v.([]interface{})
if len(vL) > 1 {
return nil, errors.New("cannot specify restrictions more than one time")
}
restrictions := new(github.BranchRestrictionsRequest)
for _, v := range vL {
// Restrictions only have set attributes nested, need to return nil values for these.
// The API won't initialize these as nil
if v == nil {
restrictions.Users = []string{}
restrictions.Teams = []string{}
restrictions.Apps = []string{}
return restrictions, nil
}
m := v.(map[string]interface{})
users := expandNestedSet(m, "users")
restrictions.Users = users
teams := expandNestedSet(m, "teams")
restrictions.Teams = teams
apps := expandNestedSet(m, "apps")
restrictions.Apps = apps
}
return restrictions, nil
}
return nil, nil
}
func checkBranchRestrictionsUsers(actual *github.BranchRestrictions, expected *github.BranchRestrictionsRequest) error {
if expected == nil {
return nil
}
expectedUsers := expected.Users
if actual == nil {
return fmt.Errorf("unable to add users in restrictions: %s", strings.Join(expectedUsers, ", "))
}
actualLoopUp := make(map[string]struct{}, len(actual.Users))
for _, a := range actual.Users {
actualLoopUp[a.GetLogin()] = struct{}{}
}
notFounds := make([]string, 0, len(actual.Users))
for _, e := range expectedUsers {
if _, ok := actualLoopUp[e]; !ok {
notFounds = append(notFounds, e)
}
}
if len(notFounds) == 0 {
return nil
}
return fmt.Errorf("unable to add users in restrictions: %s", strings.Join(notFounds, ", "))
}