-
Notifications
You must be signed in to change notification settings - Fork 965
Expand file tree
/
Copy pathresource_github_repository_autolink_reference.go
More file actions
199 lines (174 loc) · 6.43 KB
/
resource_github_repository_autolink_reference.go
File metadata and controls
199 lines (174 loc) · 6.43 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
package github
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/google/go-github/v85/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceGithubRepositoryAutolinkReference() *schema.Resource {
return &schema.Resource{
Create: resourceGithubRepositoryAutolinkReferenceCreate,
Read: resourceGithubRepositoryAutolinkReferenceRead,
Delete: resourceGithubRepositoryAutolinkReferenceDelete,
Importer: &schema.ResourceImporter{
StateContext: func(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
parts := strings.Split(d.Id(), "/")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid ID specified: supplied ID must be written as <repository>/<autolink_reference_id>")
}
repository := parts[0]
id := parts[1]
// If the second part of the provided ID isn't an integer, assume that the
// caller provided the key prefix for the autolink reference, and look up
// the autolink by the key prefix.
_, err := strconv.Atoi(id)
if err != nil {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
autolink, err := getAutolinkByKeyPrefix(ctx, client, owner, repository, id)
if err != nil {
return nil, err
}
id = strconv.FormatInt(*autolink.ID, 10)
}
if err = d.Set("repository", repository); err != nil {
return nil, err
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
},
},
SchemaVersion: 1,
Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The repository name",
},
"key_prefix": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "This prefix appended by a number will generate a link any time it is found in an issue, pull request, or commit",
},
"target_url_template": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The template of the target URL used for the links; must be a valid URL and contain `<num>` for the reference number",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringMatch(regexp.MustCompile(`^http[s]?:\/\/[a-z0-9-.]*(:[0-9]+)?\/.*?<num>.*?$`), "must be a valid URL and contain <num> token")),
},
"is_alphanumeric": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: true,
Description: "Whether this autolink reference matches alphanumeric characters. If false, this autolink reference only matches numeric characters.",
},
"etag": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceGithubRepositoryAutolinkReferenceCreate(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Get("repository").(string)
keyPrefix := d.Get("key_prefix").(string)
targetURLTemplate := d.Get("target_url_template").(string)
isAlphanumeric := d.Get("is_alphanumeric").(bool)
ctx := context.Background()
// Check if an autolink with this key prefix already exists.
// The GitHub API returns 422 when attempting to create a duplicate, so we
// handle it ourselves: import the existing one if its settings match, or
// delete and recreate it if they differ.
existing, err := getAutolinkByKeyPrefix(ctx, client, owner, repoName, keyPrefix)
if err == nil {
if existing.GetURLTemplate() == targetURLTemplate && existing.GetIsAlphanumeric() == isAlphanumeric {
log.Printf("[INFO] Autolink reference with key prefix %q already exists in %s/%s (id=%d), importing it",
keyPrefix, owner, repoName, existing.GetID())
d.SetId(strconv.FormatInt(existing.GetID(), 10))
return resourceGithubRepositoryAutolinkReferenceRead(d, meta)
}
// Settings differ – delete the existing autolink so we can recreate it below.
log.Printf("[INFO] Autolink reference with key prefix %q already exists in %s/%s (id=%d) but with different settings, replacing it",
keyPrefix, owner, repoName, existing.GetID())
if _, delErr := client.Repositories.DeleteAutolink(ctx, owner, repoName, existing.GetID()); delErr != nil {
return delErr
}
}
opts := &github.AutolinkOptions{
KeyPrefix: &keyPrefix,
URLTemplate: &targetURLTemplate,
IsAlphanumeric: &isAlphanumeric,
}
autolinkRef, _, err := client.Repositories.AddAutolink(ctx, owner, repoName, opts)
if err != nil {
return err
}
d.SetId(strconv.FormatInt(autolinkRef.GetID(), 10))
return resourceGithubRepositoryAutolinkReferenceRead(d, meta)
}
func resourceGithubRepositoryAutolinkReferenceRead(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Get("repository").(string)
autolinkRefID, err := strconv.ParseInt(d.Id(), 10, 64)
if err != nil {
return unconvertibleIdErr(d.Id(), err)
}
ctx := context.WithValue(context.Background(), ctxId, d.Id())
if !d.IsNewResource() {
ctx = context.WithValue(ctx, ctxEtag, d.Get("etag").(string))
}
autolinkRef, _, err := client.Repositories.GetAutolink(ctx, owner, repoName, autolinkRefID)
if err != nil {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[INFO] Removing autolink reference for repository %s/%s from state because it no longer exists in GitHub",
owner, repoName)
d.SetId("")
return nil
}
}
return err
}
// Set resource fields
d.SetId(strconv.FormatInt(autolinkRef.GetID(), 10))
if err = d.Set("repository", repoName); err != nil {
return err
}
if err = d.Set("key_prefix", autolinkRef.KeyPrefix); err != nil {
return err
}
if err = d.Set("target_url_template", autolinkRef.URLTemplate); err != nil {
return err
}
if err = d.Set("is_alphanumeric", autolinkRef.IsAlphanumeric); err != nil {
return err
}
return nil
}
func resourceGithubRepositoryAutolinkReferenceDelete(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Get("repository").(string)
autolinkRefID, err := strconv.ParseInt(d.Id(), 10, 64)
if err != nil {
return unconvertibleIdErr(d.Id(), err)
}
ctx := context.WithValue(context.Background(), ctxId, d.Id())
_, err = client.Repositories.DeleteAutolink(ctx, owner, repoName, autolinkRefID)
return err
}