-
Notifications
You must be signed in to change notification settings - Fork 961
Expand file tree
/
Copy pathresource_github_team_settings.go
More file actions
307 lines (273 loc) · 10.6 KB
/
resource_github_team_settings.go
File metadata and controls
307 lines (273 loc) · 10.6 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
package github
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/shurcooL/githubv4"
)
func resourceGithubTeamSettings() *schema.Resource {
return &schema.Resource{
Create: resourceGithubTeamSettingsCreate,
Read: resourceGithubTeamSettingsRead,
Update: resourceGithubTeamSettingsUpdate,
Delete: resourceGithubTeamSettingsDelete,
Importer: &schema.ResourceImporter{
State: resourceGithubTeamSettingsImport,
},
Schema: map[string]*schema.Schema{
"team_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The GitHub team id or the GitHub team slug.",
},
"team_slug": {
Type: schema.TypeString,
Computed: true,
Description: "The slug of the Team within the Organization.",
},
"team_uid": {
Type: schema.TypeString,
Computed: true,
Description: "The unique ID of the Team on GitHub. Corresponds to the ID of the 'github_team_settings' resource.",
},
"review_request_delegation": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Description: "The settings for delegating code reviews to individuals on behalf of the team. If this block is present, even without any fields, then review request delegation will be enabled for the team.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"algorithm": {
Type: schema.TypeString,
Optional: true,
Description: "The algorithm to use when assigning pull requests to team members. Supported values are 'ROUND_ROBIN' and 'LOAD_BALANCE'.",
Default: "ROUND_ROBIN",
ValidateDiagFunc: toDiagFunc(func(v any, key string) (we []string, errs []error) {
algorithm, ok := v.(string)
if !ok {
return nil, []error{fmt.Errorf("expected type of %s to be string", key)}
}
if algorithm != "ROUND_ROBIN" && algorithm != "LOAD_BALANCE" {
errs = append(errs, errors.New("review request delegation algorithm must be one of [\"ROUND_ROBIN\", \"LOAD_BALANCE\"]"))
}
return we, errs
}, "algorithm"),
},
"member_count": {
Type: schema.TypeInt,
Optional: true,
RequiredWith: []string{"review_request_delegation"},
Description: "The number of team members to assign to a pull request.",
ValidateDiagFunc: toDiagFunc(func(v any, key string) (we []string, errs []error) {
count, ok := v.(int)
if !ok {
return nil, []error{fmt.Errorf("expected type of %s to be an integer", key)}
}
if count <= 0 {
errs = append(errs, errors.New("review request delegation reviewer count must be a positive number"))
}
return we, errs
}, "member_count"),
},
"notify": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "whether to notify the entire team when at least one member is also assigned to the pull request.",
},
"excluded_team_member_node_ids": {
Type: schema.TypeSet,
Optional: true,
Description: "A list of team member node IDs to exclude from the PR review process.",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
}
}
func resourceGithubTeamSettingsCreate(d *schema.ResourceData, meta any) error {
err := checkOrganization(meta)
if err != nil {
return err
}
// Given a string that is either a team id or team slug, return the
// get the basic details of the team including node_id and slug
ctx := context.Background()
teamIDString, _ := d.Get("team_id").(string)
nodeId, slug, err := resolveTeamIDs(teamIDString, meta.(*Owner), ctx)
if err != nil {
return err
}
d.SetId(nodeId)
if err = d.Set("team_slug", slug); err != nil {
return err
}
if err = d.Set("team_uid", nodeId); err != nil {
return err
}
return resourceGithubTeamSettingsUpdate(d, meta)
}
func resourceGithubTeamSettingsRead(d *schema.ResourceData, meta any) error {
err := checkOrganization(meta)
if err != nil {
return err
}
graphql := meta.(*Owner).v4client
orgName := meta.(*Owner).name
teamSlug := d.Get("team_slug").(string)
query := queryTeamSettings{}
variables := map[string]any{
"slug": githubv4.String(teamSlug),
"login": githubv4.String(orgName),
}
e := graphql.Query(meta.(*Owner).StopContext, &query, variables)
if e != nil {
return e
}
if query.Organization.Team.ReviewRequestDelegation {
reviewRequestDelegation := make(map[string]any)
reviewRequestDelegation["algorithm"] = query.Organization.Team.ReviewRequestDelegationAlgorithm
reviewRequestDelegation["member_count"] = query.Organization.Team.ReviewRequestDelegationCount
reviewRequestDelegation["notify"] = query.Organization.Team.ReviewRequestDelegationNotifyAll
if err = d.Set("review_request_delegation", []any{reviewRequestDelegation}); err != nil {
return err
}
} else {
if err = d.Set("review_request_delegation", []any{}); err != nil {
return err
}
}
// NOTE: The exclusion list is not available via the GraphQL read query yet.
// The excluded_team_member_node_ids field can be set but cannot be read back from the GitHub API.
// This is because the GraphQL API for team review assignments is currently in preview.
return nil
}
func resourceGithubTeamSettingsUpdate(d *schema.ResourceData, meta any) error {
if d.HasChange("review_request_delegation") || d.IsNewResource() {
ctx := context.WithValue(context.Background(), ctxId, d.Id())
graphql := meta.(*Owner).v4client
if setting := d.Get("review_request_delegation").([]any); len(setting) == 0 {
var mutation struct {
UpdateTeamReviewAssignment struct {
ClientMutationId githubv4.ID `graphql:"clientMutationId"`
} `graphql:"updateTeamReviewAssignment(input:$input)"`
}
return graphql.Mutate(ctx, &mutation, defaultTeamReviewAssignmentSettings(d.Id()), nil)
} else {
settings := d.Get("review_request_delegation").([]any)[0].(map[string]any)
var mutation struct {
UpdateTeamReviewAssignment struct {
ClientMutationId githubv4.ID `graphql:"clientMutationId"`
} `graphql:"updateTeamReviewAssignment(input:$input)"`
}
exclusionList := make([]string, 0)
if excludedIDs, ok := settings["excluded_team_member_node_ids"]; ok && excludedIDs != nil {
for _, v := range excludedIDs.(*schema.Set).List() {
if v != nil {
exclusionList = append(exclusionList, v.(string))
}
}
}
return graphql.Mutate(ctx, &mutation, UpdateTeamReviewAssignmentInput{
TeamID: d.Id(),
ReviewRequestDelegation: true,
ReviewRequestDelegationAlgorithm: settings["algorithm"].(string),
ReviewRequestDelegationCount: settings["member_count"].(int),
ReviewRequestDelegationNotifyAll: settings["notify"].(bool),
ExcludedTeamMemberIds: exclusionList,
}, nil)
}
}
return resourceGithubTeamSettingsRead(d, meta)
}
func resourceGithubTeamSettingsDelete(d *schema.ResourceData, meta any) error {
ctx := context.WithValue(context.Background(), ctxId, d.Id())
graphql := meta.(*Owner).v4client
var mutation struct {
UpdateTeamReviewAssignment struct {
ClientMutationId githubv4.ID `graphql:"clientMutationId"`
} `graphql:"updateTeamReviewAssignment(input:$input)"`
}
return graphql.Mutate(ctx, &mutation, defaultTeamReviewAssignmentSettings(d.Id()), nil)
}
func resourceGithubTeamSettingsImport(d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
nodeId, slug, err := resolveTeamIDs(d.Id(), meta.(*Owner), context.Background())
if err != nil {
return nil, err
}
if err = d.Set("team_id", d.Id()); err != nil {
return nil, err
}
d.SetId(nodeId)
if err = d.Set("team_slug", slug); err != nil {
return nil, err
}
if err = d.Set("team_uid", nodeId); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, resourceGithubTeamSettingsRead(d, meta)
}
func resolveTeamIDs(idOrSlug string, meta *Owner, ctx context.Context) (nodeId, slug string, err error) {
client := meta.v3client
orgName := meta.name
orgId := meta.id
teamId, parseIntErr := strconv.ParseInt(idOrSlug, 10, 64)
if parseIntErr != nil {
// The given id not an integer, assume it is a team slug
team, _, slugErr := client.Teams.GetTeamBySlug(ctx, orgName, idOrSlug)
if slugErr != nil {
return "", "", errors.New(parseIntErr.Error() + slugErr.Error())
}
return team.GetNodeID(), team.GetSlug(), nil
} else {
// 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, idOrSlug)
if slugErr != nil {
return "", "", errors.New(teamIdErr.Error() + slugErr.Error())
}
return team.GetNodeID(), team.GetSlug(), nil
}
return team.GetNodeID(), team.GetSlug(), nil
}
}
type UpdateTeamReviewAssignmentInput struct {
ClientMutationID string `json:"clientMutationId,omitempty"`
TeamID string `graphql:"id" json:"id"`
ReviewRequestDelegation bool `graphql:"enabled" json:"enabled"`
ReviewRequestDelegationAlgorithm string `graphql:"algorithm" json:"algorithm"`
ReviewRequestDelegationCount int `graphql:"teamMemberCount" json:"teamMemberCount"`
ReviewRequestDelegationNotifyAll bool `graphql:"notifyTeam" json:"notifyTeam"`
ExcludedTeamMemberIds []string `graphql:"excludedTeamMemberIds" json:"excludedTeamMemberIds"`
}
func defaultTeamReviewAssignmentSettings(id string) UpdateTeamReviewAssignmentInput {
return UpdateTeamReviewAssignmentInput{
TeamID: id,
ReviewRequestDelegation: false,
ReviewRequestDelegationAlgorithm: "ROUND_ROBIN",
ReviewRequestDelegationCount: 1,
ReviewRequestDelegationNotifyAll: true,
}
}
type queryTeamSettings struct {
Organization struct {
Team struct {
Name string `graphql:"name"`
Slug string `graphql:"slug"`
ID string `graphql:"id"`
ReviewRequestDelegation bool `graphql:"reviewRequestDelegationEnabled"`
ReviewRequestDelegationAlgorithm string `graphql:"reviewRequestDelegationAlgorithm"`
ReviewRequestDelegationCount int `graphql:"reviewRequestDelegationMemberCount"`
ReviewRequestDelegationNotifyAll bool `graphql:"reviewRequestDelegationNotifyTeam"`
} `graphql:"team(slug:$slug)"`
} `graphql:"organization(login:$login)"`
}