This repository has been archived by the owner on Jan 8, 2021. It is now read-only.
forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathresource_github_repository.go
481 lines (438 loc) · 14 KB
/
resource_github_repository.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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
package github
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"regexp"
"github.com/google/go-github/v32/github"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceGithubRepository() *schema.Resource {
return &schema.Resource{
Create: resourceGithubRepositoryCreate,
Read: resourceGithubRepositoryRead,
Update: resourceGithubRepositoryUpdate,
Delete: resourceGithubRepositoryDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
d.Set("auto_init", false)
return []*schema.ResourceData{d}, nil
},
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"homepage_url": {
Type: schema.TypeString,
Optional: true,
},
"private": {
Type: schema.TypeBool,
Computed: true, // is affected by "visibility"
Optional: true,
ConflictsWith: []string{"visibility"},
Deprecated: "use visibility instead",
},
"visibility": {
Type: schema.TypeString,
Optional: true,
Computed: true, // is affected by "private"
ValidateFunc: validation.StringInSlice([]string{"public", "private", "internal"}, false),
},
"has_issues": {
Type: schema.TypeBool,
Optional: true,
},
"has_projects": {
Type: schema.TypeBool,
Optional: true,
},
"has_downloads": {
Type: schema.TypeBool,
Optional: true,
},
"has_wiki": {
Type: schema.TypeBool,
Optional: true,
},
"is_template": {
Type: schema.TypeBool,
Optional: true,
},
"allow_merge_commit": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"allow_squash_merge": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"allow_rebase_merge": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"delete_branch_on_merge": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"auto_init": {
Type: schema.TypeBool,
Optional: true,
},
"default_branch": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Can only be set after initial repository creation, and only if the target branch exists",
Deprecated: "Use the github_branch_default resource instead",
},
"license_template": {
Type: schema.TypeString,
Optional: true,
},
"gitignore_template": {
Type: schema.TypeString,
Optional: true,
},
"archived": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"archive_on_destroy": {
Type: schema.TypeBool,
Optional: true,
},
"topics": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`), "must include only lowercase alphanumeric characters or hyphens and cannot start with a hyphen"),
},
},
"vulnerability_alerts": {
Type: schema.TypeBool,
Optional: true,
},
"full_name": {
Type: schema.TypeString,
Computed: true,
},
"html_url": {
Type: schema.TypeString,
Computed: true,
},
"ssh_clone_url": {
Type: schema.TypeString,
Computed: true,
},
"svn_url": {
Type: schema.TypeString,
Computed: true,
},
"git_clone_url": {
Type: schema.TypeString,
Computed: true,
},
"http_clone_url": {
Type: schema.TypeString,
Computed: true,
},
"etag": {
Type: schema.TypeString,
Computed: true,
},
"template": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"owner": {
Type: schema.TypeString,
Required: true,
},
"repository": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"node_id": {
Type: schema.TypeString,
Computed: true,
},
"repo_id": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func resourceGithubRepositoryObject(d *schema.ResourceData) *github.Repository {
return &github.Repository{
Name: github.String(d.Get("name").(string)),
Description: github.String(d.Get("description").(string)),
Homepage: github.String(d.Get("homepage_url").(string)),
Private: github.Bool(d.Get("private").(bool)),
Visibility: github.String(d.Get("visibility").(string)),
HasDownloads: github.Bool(d.Get("has_downloads").(bool)),
HasIssues: github.Bool(d.Get("has_issues").(bool)),
HasProjects: github.Bool(d.Get("has_projects").(bool)),
HasWiki: github.Bool(d.Get("has_wiki").(bool)),
IsTemplate: github.Bool(d.Get("is_template").(bool)),
AllowMergeCommit: github.Bool(d.Get("allow_merge_commit").(bool)),
AllowSquashMerge: github.Bool(d.Get("allow_squash_merge").(bool)),
AllowRebaseMerge: github.Bool(d.Get("allow_rebase_merge").(bool)),
DeleteBranchOnMerge: github.Bool(d.Get("delete_branch_on_merge").(bool)),
AutoInit: github.Bool(d.Get("auto_init").(bool)),
LicenseTemplate: github.String(d.Get("license_template").(string)),
GitignoreTemplate: github.String(d.Get("gitignore_template").(string)),
Archived: github.Bool(d.Get("archived").(bool)),
Topics: expandStringList(d.Get("topics").(*schema.Set).List()),
}
}
func resourceGithubRepositoryCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
if branchName, hasDefaultBranch := d.GetOk("default_branch"); hasDefaultBranch && (branchName != "main") {
return fmt.Errorf("Cannot set the default branch on a new repository to something other than 'main'.")
}
repoReq := resourceGithubRepositoryObject(d)
owner := meta.(*Owner).name
// Auth issues (403 You need admin access to the organization before adding a repository to it.)
// are encountered when the resources is created with the visibility parameter. As
// resourceGithubRepositoryUpdate is called immediately after, this is subsequently corrected.
repoReq.Visibility = nil
repoName := repoReq.GetName()
ctx := context.Background()
log.Printf("[DEBUG] Creating repository: %s/%s", owner, repoName)
if template, ok := d.GetOk("template"); ok {
templateConfigBlocks := template.([]interface{})
for _, templateConfigBlock := range templateConfigBlocks {
templateConfigMap, ok := templateConfigBlock.(map[string]interface{})
if !ok {
return errors.New("failed to unpack template configuration block")
}
templateRepo := templateConfigMap["repository"].(string)
templateRepoOwner := templateConfigMap["owner"].(string)
templateRepoReq := github.TemplateRepoRequest{
Name: &repoName,
Owner: &owner,
Description: github.String(d.Get("description").(string)),
Private: github.Bool(d.Get("private").(bool)),
}
repo, _, err := client.Repositories.CreateFromTemplate(ctx,
templateRepoOwner,
templateRepo,
&templateRepoReq,
)
if err != nil {
return err
}
d.SetId(*repo.Name)
}
} else {
// Create without a repository template
var repo *github.Repository
var err error
if meta.(*Owner).IsOrganization {
repo, _, err = client.Repositories.Create(ctx, owner, repoReq)
} else {
// Create repository within authenticated user's account
repo, _, err = client.Repositories.Create(ctx, "", repoReq)
}
if err != nil {
return err
}
d.SetId(repo.GetName())
}
topics := repoReq.Topics
if len(topics) > 0 {
_, _, err := client.Repositories.ReplaceAllTopics(ctx, owner, repoName, topics)
if err != nil {
return err
}
}
var alerts, private bool
if a, ok := d.GetOk("vulnerability_alerts"); ok {
alerts = a.(bool)
}
if p, ok := d.GetOk("private"); ok {
private = p.(bool)
}
var createVulnerabilityAlerts func(context.Context, string, string) (*github.Response, error)
if private && alerts {
createVulnerabilityAlerts = client.Repositories.EnableVulnerabilityAlerts
} else if !private && !alerts {
createVulnerabilityAlerts = client.Repositories.DisableVulnerabilityAlerts
}
if createVulnerabilityAlerts != nil {
_, err := createVulnerabilityAlerts(ctx, owner, repoName)
if err != nil {
return err
}
}
return resourceGithubRepositoryUpdate(d, meta)
}
func resourceGithubRepositoryRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Id()
log.Printf("[DEBUG] Reading repository: %s/%s", owner, repoName)
ctx := context.WithValue(context.Background(), ctxId, d.Id())
if !d.IsNewResource() {
ctx = context.WithValue(ctx, ctxEtag, d.Get("etag").(string))
}
repo, resp, err := client.Repositories.Get(ctx, owner, repoName)
if err != nil {
if ghErr, ok := err.(*github.ErrorResponse); ok {
if ghErr.Response.StatusCode == http.StatusNotModified {
return nil
}
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[WARN] Removing repository %s/%s from state because it no longer exists in GitHub",
owner, repoName)
d.SetId("")
return nil
}
}
return err
}
d.Set("etag", resp.Header.Get("ETag"))
d.Set("name", repoName)
d.Set("description", repo.GetDescription())
d.Set("homepage_url", repo.GetHomepage())
d.Set("private", repo.GetPrivate())
d.Set("visibility", repo.GetVisibility())
d.Set("has_issues", repo.GetHasIssues())
d.Set("has_projects", repo.GetHasProjects())
d.Set("has_wiki", repo.GetHasWiki())
d.Set("is_template", repo.GetIsTemplate())
d.Set("allow_merge_commit", repo.GetAllowMergeCommit())
d.Set("allow_squash_merge", repo.GetAllowSquashMerge())
d.Set("allow_rebase_merge", repo.GetAllowRebaseMerge())
d.Set("delete_branch_on_merge", repo.GetDeleteBranchOnMerge())
d.Set("has_downloads", repo.GetHasDownloads())
d.Set("full_name", repo.GetFullName())
d.Set("default_branch", repo.GetDefaultBranch())
d.Set("html_url", repo.GetHTMLURL())
d.Set("ssh_clone_url", repo.GetSSHURL())
d.Set("svn_url", repo.GetSVNURL())
d.Set("git_clone_url", repo.GetGitURL())
d.Set("http_clone_url", repo.GetCloneURL())
d.Set("archived", repo.GetArchived())
d.Set("topics", flattenStringList(repo.Topics))
d.Set("node_id", repo.GetNodeID())
d.Set("repo_id", repo.GetID())
if repo.TemplateRepository != nil {
d.Set("template", []interface{}{
map[string]interface{}{
"owner": repo.TemplateRepository.Owner.Login,
"repository": repo.TemplateRepository.Name,
},
})
} else {
d.Set("template", []interface{}{})
}
vulnerabilityAlerts, _, err := client.Repositories.GetVulnerabilityAlerts(ctx, owner, repoName)
if err != nil {
return fmt.Errorf("Error reading repository vulnerability alerts: %v", err)
}
d.Set("vulnerability_alerts", vulnerabilityAlerts)
return nil
}
func resourceGithubRepositoryUpdate(d *schema.ResourceData, meta interface{}) error {
// Can only update a repository if it is not archived or the update is to
// archive the repository (unarchiving is not supported by the Github API)
if d.Get("archived").(bool) && !d.HasChange("archived") {
log.Printf("[DEBUG] Skipping update of archived repository")
return nil
}
client := meta.(*Owner).v3client
repoReq := resourceGithubRepositoryObject(d)
// The endpoint will throw an error if trying to PATCH with a visibility value that is the same
if !d.HasChange("visibility") {
repoReq.Visibility = nil
}
// Can only set `default_branch` on an already created repository with the target branches ref already in-place
if v, ok := d.GetOk("default_branch"); ok {
branch := v.(string)
// If branch is "main", and the repository hasn't been initialized yet, setting this value will fail
if branch != "main" {
repoReq.DefaultBranch = &branch
}
}
repoName := d.Id()
owner := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
log.Printf("[DEBUG] Updating repository: %s/%s", owner, repoName)
repo, _, err := client.Repositories.Edit(ctx, owner, repoName, repoReq)
if err != nil {
return err
}
d.SetId(*repo.Name)
if d.HasChange("topics") {
topics := repoReq.Topics
_, _, err = client.Repositories.ReplaceAllTopics(ctx, owner, *repo.Name, topics)
if err != nil {
return err
}
d.SetId(*repo.Name)
if d.HasChange("topics") {
topics := repoReq.Topics
_, _, err = client.Repositories.ReplaceAllTopics(ctx, owner, *repo.Name, topics)
if err != nil {
return err
}
}
}
if !d.IsNewResource() && d.HasChange("vulnerability_alerts") {
updateVulnerabilityAlerts := client.Repositories.DisableVulnerabilityAlerts
if vulnerabilityAlerts, ok := d.GetOk("vulnerability_alerts"); ok && vulnerabilityAlerts.(bool) {
updateVulnerabilityAlerts = client.Repositories.EnableVulnerabilityAlerts
}
_, err = updateVulnerabilityAlerts(ctx, owner, repoName)
if err != nil {
return err
}
}
return resourceGithubRepositoryRead(d, meta)
}
func resourceGithubRepositoryDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
repoName := d.Id()
owner := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
archiveOnDestroy := d.Get("archive_on_destroy").(bool)
if archiveOnDestroy {
if d.Get("archived").(bool) {
log.Printf("[DEBUG] Repository already archived, nothing to do on delete: %s/%s", owner, repoName)
return nil
} else {
d.Set("archived", true)
repoReq := resourceGithubRepositoryObject(d)
log.Printf("[DEBUG] Archiving repository on delete: %s/%s", owner, repoName)
_, _, err := client.Repositories.Edit(ctx, owner, repoName, repoReq)
return err
}
}
log.Printf("[DEBUG] Deleting repository: %s/%s", owner, repoName)
_, err := client.Repositories.Delete(ctx, owner, repoName)
return err
}