-
Notifications
You must be signed in to change notification settings - Fork 960
Expand file tree
/
Copy pathresource_github_repository_custom_properties.go
More file actions
334 lines (276 loc) · 10 KB
/
resource_github_repository_custom_properties.go
File metadata and controls
334 lines (276 loc) · 10 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
package github
import (
"context"
"fmt"
"github.com/google/go-github/v84/github"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceGithubRepositoryCustomProperties() *schema.Resource {
return &schema.Resource{
Description: "Manages custom properties for a GitHub repository. This resource allows you to set multiple custom property values on a single repository in a single resource block, with in-place updates when values change.",
CreateContext: resourceGithubRepositoryCustomPropertiesCreate,
ReadContext: resourceGithubRepositoryCustomPropertiesRead,
UpdateContext: resourceGithubRepositoryCustomPropertiesUpdate,
DeleteContext: resourceGithubRepositoryCustomPropertiesDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceGithubRepositoryCustomPropertiesImport,
},
CustomizeDiff: customdiff.All(
diffRepository,
),
Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Required: true,
Description: "Name of the repository.",
},
"repository_id": {
Type: schema.TypeInt,
Computed: true,
Description: "The ID of the GitHub repository.",
},
"property": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
Description: "Set of custom property values for this repository.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of the custom property (must be defined at the organization level).",
},
"value": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
Description: "Value(s) of the custom property. For multi_select properties, multiple values can be specified.",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
Set: resourceGithubRepositoryCustomPropertiesHash,
},
},
}
}
// resourceGithubRepositoryCustomPropertiesHash creates a hash for a property block
// using only the property name, so that value changes are detected as in-place
// updates rather than remove+add within the set.
func resourceGithubRepositoryCustomPropertiesHash(v any) int {
raw := v.(map[string]any)
name := raw["name"].(string)
return schema.HashString(name)
}
func resourceGithubRepositoryCustomPropertiesApply(ctx context.Context, d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Get("repository").(string)
properties := d.Get("property").(*schema.Set).List()
// Get all organization custom property definitions to determine types
orgProperties, _, err := client.Organizations.GetAllCustomProperties(ctx, owner)
if err != nil {
return fmt.Errorf("error reading organization custom property definitions: %w", err)
}
// Create a map of property names to their types
propertyTypes := make(map[string]github.PropertyValueType)
for _, prop := range orgProperties {
if prop.PropertyName != nil {
propertyTypes[*prop.PropertyName] = prop.ValueType
}
}
// Build custom property values for this repository
customProperties := make([]*github.CustomPropertyValue, 0, len(properties))
for _, propBlock := range properties {
propMap := propBlock.(map[string]any)
propertyName := propMap["name"].(string)
propertyValues := expandStringList(propMap["value"].(*schema.Set).List())
propertyType, ok := propertyTypes[propertyName]
if !ok {
return fmt.Errorf("custom property %q is not defined at the organization level", propertyName)
}
customProperty := &github.CustomPropertyValue{
PropertyName: propertyName,
}
switch propertyType {
case github.PropertyValueTypeMultiSelect:
customProperty.Value = propertyValues
case github.PropertyValueTypeString, github.PropertyValueTypeSingleSelect,
github.PropertyValueTypeTrueFalse, github.PropertyValueTypeURL:
if len(propertyValues) > 0 {
customProperty.Value = propertyValues[0]
}
default:
return fmt.Errorf("unsupported property type %q for property %q", propertyType, propertyName)
}
customProperties = append(customProperties, customProperty)
}
_, err = client.Repositories.CreateOrUpdateCustomProperties(ctx, owner, repoName, customProperties)
if err != nil {
return fmt.Errorf("error setting custom properties for repository %s/%s: %w", owner, repoName, err)
}
return nil
}
func resourceGithubRepositoryCustomPropertiesCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
err := checkOrganization(meta)
if err != nil {
return diag.FromErr(err)
}
owner := meta.(*Owner).name
client := meta.(*Owner).v3client
repoName := d.Get("repository").(string)
if err := resourceGithubRepositoryCustomPropertiesApply(ctx, d, meta); err != nil {
return diag.FromErr(err)
}
id, err := buildID(owner, repoName)
if err != nil {
return diag.FromErr(err)
}
d.SetId(id)
repo, _, err := client.Repositories.Get(ctx, owner, repoName)
if err != nil {
return diag.FromErr(err)
}
if err := d.Set("repository_id", int(repo.GetID())); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceGithubRepositoryCustomPropertiesUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
err := checkOrganization(meta)
if err != nil {
return diag.FromErr(err)
}
if err := resourceGithubRepositoryCustomPropertiesApply(ctx, d, meta); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceGithubRepositoryCustomPropertiesRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
err := checkOrganization(meta)
if err != nil {
return diag.FromErr(err)
}
ctx = tflog.SetField(ctx, "id", d.Id())
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
_, repoName, err := parseID2(d.Id())
if err != nil {
return diag.FromErr(err)
}
// Get current properties from state to know which ones we're managing.
// On import this will be empty, which is handled below.
propertiesFromState := d.Get("property").(*schema.Set).List()
managedPropertyNames := make(map[string]bool)
for _, propBlock := range propertiesFromState {
propMap := propBlock.(map[string]any)
managedPropertyNames[propMap["name"].(string)] = true
}
isImport := len(managedPropertyNames) == 0
// Read actual properties from GitHub
allCustomProperties, _, err := client.Repositories.GetAllCustomPropertyValues(ctx, owner, repoName)
if err != nil {
return diag.FromErr(fmt.Errorf("error reading custom properties for repository %s/%s: %w", owner, repoName, err))
}
managedProperties, err := filterManagedCustomProperties(allCustomProperties, managedPropertyNames, isImport)
if err != nil {
return diag.FromErr(fmt.Errorf("error processing custom properties for repository %s/%s: %w", owner, repoName, err))
}
// If no properties exist, remove resource from state
if len(managedProperties) == 0 {
tflog.Warn(ctx, "No custom properties found, removing from state", map[string]any{"owner": owner, "repository": repoName})
d.SetId("")
return nil
}
if err := d.Set("repository", repoName); err != nil {
return diag.FromErr(err)
}
if err := d.Set("property", managedProperties); err != nil {
return diag.FromErr(err)
}
return nil
}
// filterManagedCustomProperties builds the property set from GitHub API results,
// filtering to only managed properties (or all properties during import).
func filterManagedCustomProperties(allProps []*github.CustomPropertyValue, managed map[string]bool, isImport bool) ([]any, error) {
result := make([]any, 0)
for _, prop := range allProps {
if !isImport && !managed[prop.PropertyName] {
continue
}
if prop.Value == nil {
continue
}
propertyValue, err := parseRepositoryCustomPropertyValueToStringSlice(prop)
if err != nil {
return nil, fmt.Errorf("error parsing property %q: %w", prop.PropertyName, err)
}
if len(propertyValue) == 0 {
continue
}
result = append(result, map[string]any{
"name": prop.PropertyName,
"value": propertyValue,
})
}
return result, nil
}
func resourceGithubRepositoryCustomPropertiesDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
err := checkOrganization(meta)
if err != nil {
return diag.FromErr(err)
}
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
_, repoName, err := parseID2(d.Id())
if err != nil {
return diag.FromErr(err)
}
properties := d.Get("property").(*schema.Set).List()
if len(properties) == 0 {
return nil
}
// Set all managed properties to nil (removes them)
customProperties := make([]*github.CustomPropertyValue, 0, len(properties))
for _, propBlock := range properties {
propMap := propBlock.(map[string]any)
customProperties = append(customProperties, &github.CustomPropertyValue{
PropertyName: propMap["name"].(string),
Value: nil,
})
}
_, err = client.Repositories.CreateOrUpdateCustomProperties(ctx, owner, repoName, customProperties)
if err != nil {
return diag.FromErr(fmt.Errorf("error deleting custom properties for repository %s/%s: %w", owner, repoName, err))
}
return nil
}
func resourceGithubRepositoryCustomPropertiesImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
// Import ID format: <repository> — owner is inferred from the provider config.
// On import, Read will detect empty state and import ALL properties.
repoName := d.Id()
owner := meta.(*Owner).name
client := meta.(*Owner).v3client
id, err := buildID(owner, repoName)
if err != nil {
return nil, err
}
d.SetId(id)
if err := d.Set("repository", repoName); err != nil {
return nil, err
}
repo, _, err := client.Repositories.Get(ctx, owner, repoName)
if err != nil {
return nil, fmt.Errorf("failed to retrieve repository %s: %w", repoName, err)
}
if err := d.Set("repository_id", int(repo.GetID())); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, nil
}