forked from databricks/terraform-provider-databricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_repo.go
263 lines (238 loc) · 7.83 KB
/
resource_repo.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
package repos
import (
"context"
"fmt"
"net/url"
"path"
"regexp"
"strings"
"github.com/databricks/terraform-provider-databricks/common"
"github.com/databricks/terraform-provider-databricks/workspace"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
// ReposAPI exposes the Repos API
type ReposAPI struct {
client *common.DatabricksClient
context context.Context
}
// NewReposAPI creates ReposAPI instance from provider meta
func NewReposAPI(ctx context.Context, m any) ReposAPI {
return ReposAPI{m.(*common.DatabricksClient), ctx}
}
type ReposSparseCheckout struct {
Patterns []string `json:"patterns"`
}
// ReposInformation provides information about given repository
type ReposInformation struct {
ID int64 `json:"id"`
Url string `json:"url" tf:"force_new"`
Provider string `json:"provider,omitempty" tf:"computed,alias:git_provider,force_new"`
SparseCheckout *ReposSparseCheckout `json:"sparse_checkout,omitempty" tf:"force_new"`
Path string `json:"path,omitempty" tf:"computed,force_new"` // TODO: remove force_new after the Update API will support changing the path
Branch string `json:"branch,omitempty" tf:"computed"`
HeadCommitID string `json:"head_commit_id,omitempty" tf:"computed,alias:commit_hash"`
}
// RepoID returns job id as string
func (r ReposInformation) RepoID() string {
return fmt.Sprintf("%d", r.ID)
}
type reposCreateRequest struct {
Url string `json:"url"`
Provider string `json:"provider"`
Path string `json:"path,omitempty"`
SparseCheckout *ReposSparseCheckout `json:"sparse_checkout,omitempty"`
}
func (a ReposAPI) Create(r reposCreateRequest) (ReposInformation, error) {
var resp ReposInformation
if r.Provider == "" { // trying to infer Git Provider from the URL
r.Provider = GetGitProviderFromUrl(r.Url)
}
if r.Provider == "" {
return resp, fmt.Errorf("git_provider isn't specified and we can't detect provider from URL")
}
if r.Path != "" {
p := path.Dir(strings.TrimSuffix(r.Path, "/"))
if err := workspace.NewNotebooksAPI(a.context, a.client).Mkdirs(p); err != nil {
return resp, err
}
}
err := a.client.Post(a.context, "/repos", r, &resp)
return resp, err
}
func (a ReposAPI) Delete(id string) error {
return a.client.Delete(a.context, fmt.Sprintf("/repos/%s", id), nil)
}
func (a ReposAPI) Update(id string, r map[string]any) error {
if len(r) == 0 {
return nil
}
// TODO: update may change ONE OF (url AND provider (optional)), (path), or (branch OR tag).
// for URL/provider force re-create as there are limits on what could be done for changing URL/provider
if path, ok := r["path"]; ok {
err := a.client.Patch(a.context, fmt.Sprintf("/repos/%s", id), map[string]any{"path": path})
if err != nil {
return err
}
delete(r, "path")
}
return a.client.Patch(a.context, fmt.Sprintf("/repos/%s", id), r)
}
func (a ReposAPI) Read(id string) (ReposInformation, error) {
var resp ReposInformation
err := a.client.Get(a.context, fmt.Sprintf("/repos/%s", id), nil, &resp)
return resp, err
}
type ReposListResponse struct {
NextPageToken string `json:"next_page_token,omitempty"`
Repos []ReposInformation `json:"repos"`
}
func (a ReposAPI) List(prefix string) ([]ReposInformation, error) {
req := map[string]string{}
if prefix != "" {
req["path_prefix"] = prefix
}
reposList := []ReposInformation{}
for {
var resp ReposListResponse
err := a.client.Get(a.context, "/repos", req, &resp)
if err != nil {
return nil, err
}
reposList = append(reposList, resp.Repos...)
if resp.NextPageToken == "" {
break
}
req["next_page_token"] = resp.NextPageToken
}
return reposList, nil
}
func (a ReposAPI) ListAll() ([]ReposInformation, error) {
return a.List("")
}
var (
gitProvidersMap = map[string]string{
"github.com": "gitHub",
"dev.azure.com": "azureDevOpsServices",
"gitlab.com": "gitLab",
"bitbucket.org": "bitbucketCloud",
}
awsCodeCommitRegex = regexp.MustCompile(`^git-codecommit\.[^.]+\.amazonaws\.com$`)
)
func GetGitProviderFromUrl(uri string) string {
provider := ""
u, err := url.Parse(uri)
if err == nil {
lhost := strings.ToLower(u.Host)
provider = gitProvidersMap[lhost]
if provider == "" && awsCodeCommitRegex.FindStringSubmatch(lhost) != nil {
provider = "awsCodeCommit"
}
}
return provider
}
func validatePath(i interface{}, k string) (_ []string, errors []error) {
v := i.(string)
if v != "" {
if !strings.HasPrefix(v, "/Repos/") {
errors = append(errors, fmt.Errorf("should start with /Repos/, got '%s'", v))
return
}
v = strings.TrimSuffix(v, "/")
parts := strings.Split(v, "/")
if len(parts) != 4 { // we require 3 path parts + starting /
errors = append(errors, fmt.Errorf("should have 3 components (/Repos/<directory>/<repo>), got %d", len(parts)-1))
return
}
}
return
}
func ResourceRepo() common.Resource {
s := common.StructToSchema(ReposInformation{}, func(s map[string]*schema.Schema) map[string]*schema.Schema {
s["url"].ValidateFunc = validation.IsURLWithScheme([]string{"https", "http"})
s["git_provider"].DiffSuppressFunc = common.EqualFoldDiffSuppress
s["branch"].ConflictsWith = []string{"tag"}
s["branch"].ValidateFunc = validation.StringIsNotWhiteSpace
s["path"].ValidateFunc = validatePath
s["tag"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"branch"},
ValidateFunc: validation.StringIsNotWhiteSpace,
}
s["workspace_path"] = &schema.Schema{
Type: schema.TypeString,
Computed: true,
}
delete(s, "id")
return s
})
return common.Resource{
Schema: s,
SchemaVersion: 1,
Create: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
reposAPI := NewReposAPI(ctx, c)
var repo ReposInformation
common.DataToStructPointer(d, s, &repo)
req := reposCreateRequest{Path: repo.Path, Provider: repo.Provider,
Url: repo.Url, SparseCheckout: repo.SparseCheckout}
resp, err := reposAPI.Create(req)
if err != nil {
return err
}
d.SetId(resp.RepoID())
branch := d.Get("branch").(string)
tag := d.Get("tag").(string)
updateReq := map[string]any{}
if tag != "" {
updateReq["tag"] = tag
} else if branch != "" && branch != resp.Branch {
updateReq["branch"] = branch
}
return reposAPI.Update(d.Id(), updateReq)
},
Read: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
reposAPI := NewReposAPI(ctx, c)
resp, err := reposAPI.Read(d.Id())
if err != nil {
return err
}
err = common.StructToData(resp, s, d)
if err != nil {
return err
}
d.Set("workspace_path", "/Workspace"+resp.Path)
return nil
},
Update: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
var repo ReposInformation
common.DataToStructPointer(d, s, &repo)
reposAPI := NewReposAPI(ctx, c)
req := map[string]any{}
// Not working yet, wait until API is ready
// if d.HasChange("path") {
// req["path"] = d.Get("path").(string)
// }
if d.HasChange("tag") {
req["tag"] = d.Get("tag").(string)
d.Set("branch", "")
} else if d.HasChange("branch") {
req["branch"] = repo.Branch
d.Set("tag", "")
} else {
if repo.Branch != "" {
req["branch"] = repo.Branch
} else if v := d.Get("tag").(string); v != "" {
req["tag"] = v
}
}
if repo.SparseCheckout != nil {
req["sparse_checkout"] = map[string]any{"patterns": repo.SparseCheckout.Patterns}
}
return reposAPI.Update(d.Id(), req)
},
Delete: func(ctx context.Context, d *schema.ResourceData, c *common.DatabricksClient) error {
return NewReposAPI(ctx, c).Delete(d.Id())
},
}
}