From 4c0b3d0919241af2c88f990d062ff1aed8c5f3bd Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 13:10:22 +0200 Subject: [PATCH 01/11] better erroring --- bitbucket/resource_ssh_key.go | 98 ++++++++++++------------------ bitbucket/resource_ssh_key_test.go | 15 ++--- 2 files changed, 48 insertions(+), 65 deletions(-) diff --git a/bitbucket/resource_ssh_key.go b/bitbucket/resource_ssh_key.go index e659de05..2a9f1068 100644 --- a/bitbucket/resource_ssh_key.go +++ b/bitbucket/resource_ssh_key.go @@ -1,13 +1,12 @@ package bitbucket import ( - "bytes" - "encoding/json" "fmt" - "io/ioutil" "log" "strings" + "github.com/DrFaust92/bitbucket-go-client" + "github.com/antihax/optional" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -58,121 +57,104 @@ func resourceSshKey() *schema.Resource { } func resourceSshKeysCreate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + sshApi := c.ApiClient.SshApi sshKey := expandsshKey(d) - log.Printf("[DEBUG] SSH Key Request: %#v", sshKey) - bytedata, err := json.Marshal(sshKey) - if err != nil { - return err + sshKeyBody := &bitbucket.SshApiUsersSelectedUserSshKeysPostOpts{ + Body: optional.NewInterface(sshKey), } user := d.Get("user").(string) - sshKeyReq, err := client.Post(fmt.Sprintf("2.0/users/%s/ssh-keys", user), bytes.NewBuffer(bytedata)) - + sshKeyReq, _, err := sshApi.UsersSelectedUserSshKeysPost(c.AuthContext, user, sshKeyBody) if err != nil { - return err + return fmt.Errorf("error creating ssh key: %w", err) } - body, readerr := ioutil.ReadAll(sshKeyReq.Body) - if readerr != nil { - return readerr - } - - decodeerr := json.Unmarshal(body, &sshKey) - if decodeerr != nil { - return decodeerr - } - - d.SetId(string(fmt.Sprintf("%s/%s", user, sshKey.UUID))) + d.SetId(string(fmt.Sprintf("%s/%s", user, sshKeyReq.Uuid))) return resourceSshKeysRead(d, m) } func resourceSshKeysRead(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + sshApi := c.ApiClient.SshApi user, keyId, err := sshKeyId(d.Id()) if err != nil { return err } - sshKeysReq, _ := client.Get(fmt.Sprintf("2.0/users/%s/ssh-keys/%s", user, keyId)) - if sshKeysReq.StatusCode == 404 { + sshKeyReq, res, err := sshApi.UsersSelectedUserSshKeysKeyIdGet(c.AuthContext, keyId, user) + if err != nil { + return fmt.Errorf("error reading ssh key (%s): %w", d.Id(), err) + } + + if res.StatusCode == 404 { log.Printf("[WARN] SSH Key (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - if sshKeysReq.Body == nil { + if res.Body == nil { return fmt.Errorf("error getting SSH Key (%s): empty response", d.Id()) } - var sshKey *SshKey - body, readerr := ioutil.ReadAll(sshKeysReq.Body) - if readerr != nil { - return readerr - } - - log.Printf("[DEBUG] SSH Key Response JSON: %v", string(body)) - - decodeerr := json.Unmarshal(body, &sshKey) - if decodeerr != nil { - return decodeerr - } - - log.Printf("[DEBUG] SSH Key Response Decoded: %#v", sshKey) - d.Set("user", user) d.Set("key", d.Get("key").(string)) - d.Set("label", sshKey.Label) - d.Set("uuid", sshKey.UUID) - d.Set("comment", sshKey.Comment) + d.Set("label", sshKeyReq.Label) + d.Set("uuid", sshKeyReq.Uuid) + d.Set("comment", sshKeyReq.Comment) return nil } func resourceSshKeysUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + sshApi := c.ApiClient.SshApi sshKey := expandsshKey(d) - log.Printf("[DEBUG] SSH Key Request: %#v", sshKey) - bytedata, err := json.Marshal(sshKey) + sshKeyBody := &bitbucket.SshApiUsersSelectedUserSshKeysKeyIdPutOpts{ + Body: optional.NewInterface(sshKey), + } + + user, keyId, err := sshKeyId(d.Id()) if err != nil { return err } - _, err = client.Put(fmt.Sprintf("2.0/users/%s/ssh-keys/%s", - d.Get("user").(string), d.Get("uuid").(string)), bytes.NewBuffer(bytedata)) - + _, _, err = sshApi.UsersSelectedUserSshKeysKeyIdPut(c.AuthContext, keyId, user, sshKeyBody) if err != nil { - return err + return fmt.Errorf("error updating ssh key (%s): %w", d.Id(), err) } return resourceSshKeysRead(d, m) } func resourceSshKeysDelete(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + sshApi := c.ApiClient.SshApi user, keyId, err := sshKeyId(d.Id()) if err != nil { return err } - _, err = client.Delete(fmt.Sprintf("2.0/users/%s/ssh-keys/%s", user, keyId)) - + res, err := sshApi.UsersSelectedUserSshKeysKeyIdDelete(c.AuthContext, keyId, user) if err != nil { - return err + if res.StatusCode == 404 { + return nil + } + return fmt.Errorf("error deleting ssh key (%s): %w", d.Id(), err) } - return err + return nil } -func expandsshKey(d *schema.ResourceData) *SshKey { - key := &SshKey{ +func expandsshKey(d *schema.ResourceData) *bitbucket.SshAccountKey { + key := &bitbucket.SshAccountKey{ Key: d.Get("key").(string), Label: d.Get("label").(string), } diff --git a/bitbucket/resource_ssh_key_test.go b/bitbucket/resource_ssh_key_test.go index 213aeb13..aedf0fb1 100644 --- a/bitbucket/resource_ssh_key_test.go +++ b/bitbucket/resource_ssh_key_test.go @@ -2,7 +2,6 @@ package bitbucket import ( "fmt" - "net/url" "os" "testing" @@ -92,19 +91,21 @@ func TestAccBitbucketSshKey_label(t *testing.T) { } func testAccCheckBitbucketSshKeyDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(Clients).httpClient + client := testAccProvider.Meta().(Clients).genClient + sshApi := client.ApiClient.SshApi + for _, rs := range s.RootModule().Resources { if rs.Type != "bitbucket_ssh_key" { continue } - response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/ssh_keys/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["repository"], url.PathEscape(rs.Primary.Attributes["uuid"]))) - - if err == nil { - return fmt.Errorf("The resource was found should have errored") + user, keyId, err := sshKeyId(rs.Primary.ID) + if err != nil { + return err } - if response.StatusCode != 404 { + _, res, _ := sshApi.UsersSelectedUserSshKeysKeyIdGet(client.AuthContext, keyId, user) + if res.StatusCode != 404 { return fmt.Errorf("Ssh Key still exists") } From cc1aa2ac11ef6fa7fa9177986465554ccb88911b Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 13:39:48 +0200 Subject: [PATCH 02/11] pipe ssh key use gen client --- bitbucket/resource_pipeline_ssh_key.go | 62 +++++++-------------- bitbucket/resource_pipeline_ssh_key_test.go | 8 +-- 2 files changed, 24 insertions(+), 46 deletions(-) diff --git a/bitbucket/resource_pipeline_ssh_key.go b/bitbucket/resource_pipeline_ssh_key.go index a199106c..41180906 100644 --- a/bitbucket/resource_pipeline_ssh_key.go +++ b/bitbucket/resource_pipeline_ssh_key.go @@ -1,21 +1,14 @@ package bitbucket import ( - "bytes" - "encoding/json" "fmt" - "io/ioutil" "log" "strings" + "github.com/DrFaust92/bitbucket-go-client" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -type PiplineSshKey struct { - PrivateKey string `json:"private_key,omitempty"` - PublicKey string `json:"public_key,omitempty"` -} - func resourcePipelineSshKey() *schema.Resource { return &schema.Resource{ Create: resourcePipelineSshKeysPut, @@ -50,24 +43,18 @@ func resourcePipelineSshKey() *schema.Resource { } func resourcePipelineSshKeysPut(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + pipeApi := c.ApiClient.PipelinesApi pipeSshKey := expandPipelineSshKey(d) log.Printf("[DEBUG] Pipeline Ssh Key Request: %#v", pipeSshKey) - bytedata, err := json.Marshal(pipeSshKey) - - if err != nil { - return err - } repo := d.Get("repository").(string) workspace := d.Get("workspace").(string) - _, err = client.Put(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/key_pair", - workspace, repo), - bytes.NewBuffer(bytedata)) + _, _, err := pipeApi.UpdateRepositoryPipelineKeyPair(c.AuthContext, *pipeSshKey, workspace, repo) if err != nil { - return err + return fmt.Errorf("error creating pipeline ssh key: %w", err) } d.SetId(string(fmt.Sprintf("%s/%s", workspace, repo))) @@ -76,56 +63,47 @@ func resourcePipelineSshKeysPut(d *schema.ResourceData, m interface{}) error { } func resourcePipelineSshKeysRead(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + pipeApi := c.ApiClient.PipelinesApi workspace, repo, err := pipeSshKeyId(d.Id()) if err != nil { return err } - pipeSshKeysReq, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/key_pair", workspace, repo)) - if pipeSshKeysReq.StatusCode == 404 { + key, res, err := pipeApi.GetRepositoryPipelineSshKeyPair(c.AuthContext, workspace, repo) + if err != nil { + return fmt.Errorf("error reading Pipeline Ssh Key (%s): %w", d.Id(), err) + } + + if res.StatusCode == 404 { log.Printf("[WARN] Pipeline Ssh Key (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - if pipeSshKeysReq.Body == nil { + if res.Body == nil { return fmt.Errorf("error getting Pipeline Ssh Key (%s): empty response", d.Id()) } - var pipeSshKey *PiplineSshKey - body, readerr := ioutil.ReadAll(pipeSshKeysReq.Body) - if readerr != nil { - return readerr - } - - log.Printf("[DEBUG] Pipeline Ssh Key Response JSON: %v", string(body)) - - decodeerr := json.Unmarshal(body, &pipeSshKey) - if decodeerr != nil { - return decodeerr - } - - log.Printf("[DEBUG] Pipeline Ssh Key Response Decoded: %#v", pipeSshKey) - d.Set("repository", repo) d.Set("workspace", workspace) - d.Set("public_key", pipeSshKey.PublicKey) + d.Set("public_key", key.PublicKey) d.Set("private_key", d.Get("private_key").(string)) return nil } func resourcePipelineSshKeysDelete(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + pipeApi := c.ApiClient.PipelinesApi workspace, repo, err := pipeSshKeyId(d.Id()) if err != nil { return err } - _, err = client.Delete(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/key_pair", workspace, repo)) + _, err = pipeApi.DeleteRepositoryPipelineKeyPair(c.AuthContext, workspace, repo) if err != nil { return fmt.Errorf("error deleting Pipeline Ssh Key (%s): %w", d.Id(), err) @@ -134,8 +112,8 @@ func resourcePipelineSshKeysDelete(d *schema.ResourceData, m interface{}) error return err } -func expandPipelineSshKey(d *schema.ResourceData) *PiplineSshKey { - key := &PiplineSshKey{ +func expandPipelineSshKey(d *schema.ResourceData) *bitbucket.PipelineSshKeyPair { + key := &bitbucket.PipelineSshKeyPair{ PublicKey: d.Get("public_key").(string), PrivateKey: d.Get("private_key").(string), } diff --git a/bitbucket/resource_pipeline_ssh_key_test.go b/bitbucket/resource_pipeline_ssh_key_test.go index f0ca1903..ecd4b081 100644 --- a/bitbucket/resource_pipeline_ssh_key_test.go +++ b/bitbucket/resource_pipeline_ssh_key_test.go @@ -63,7 +63,8 @@ func TestAccBitbucketPipelineSshKey_basic(t *testing.T) { } func testAccCheckBitbucketPipelineSshKeyDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(Clients).httpClient + client := testAccProvider.Meta().(Clients).genClient + pipeApi := client.ApiClient.PipelinesApi for _, rs := range s.RootModule().Resources { if rs.Type != "bitbucket_pipeline_ssh_key" { continue @@ -74,14 +75,13 @@ func testAccCheckBitbucketPipelineSshKeyDestroy(s *terraform.State) error { return err } - response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/key_pair", - workspace, repo)) + _, res, err := pipeApi.GetRepositoryPipelineSshKeyPair(client.AuthContext, workspace, repo) if err == nil { return fmt.Errorf("The resource was found should have errored") } - if response.StatusCode != 404 { + if res.StatusCode != 404 { return fmt.Errorf("Pipeline Ssh Key Key still exists") } From 3038a17943773d38d6048b9aa62517c3e03026be Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 13:54:12 +0200 Subject: [PATCH 03/11] pipeline ssh known host use gen client --- bitbucket/resource_pipeline_ssh_key_test.go | 7 +- bitbucket/resource_pipeline_ssh_known_host.go | 107 ++++++------------ .../resource_pipeline_ssh_known_host_test.go | 14 +-- 3 files changed, 42 insertions(+), 86 deletions(-) diff --git a/bitbucket/resource_pipeline_ssh_key_test.go b/bitbucket/resource_pipeline_ssh_key_test.go index ecd4b081..b678280e 100644 --- a/bitbucket/resource_pipeline_ssh_key_test.go +++ b/bitbucket/resource_pipeline_ssh_key_test.go @@ -11,7 +11,6 @@ import ( ) func TestAccBitbucketPipelineSshKey_basic(t *testing.T) { - var pipelineSshKey PiplineSshKey resourceName := "bitbucket_pipeline_ssh_key.test" rName := acctest.RandomWithPrefix("tf-test") @@ -35,7 +34,7 @@ func TestAccBitbucketPipelineSshKey_basic(t *testing.T) { { Config: testAccBitbucketPipelineSshKeyConfig(owner, rName, publicKey, privateKey), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketPipelineSshKeyExists(resourceName, &pipelineSshKey), + testAccCheckBitbucketPipelineSshKeyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "workspace", "bitbucket_repository.test", "owner"), resource.TestCheckResourceAttrPair(resourceName, "repository", "bitbucket_repository.test", "name"), resource.TestCheckResourceAttr(resourceName, "public_key", publicKey), @@ -51,7 +50,7 @@ func TestAccBitbucketPipelineSshKey_basic(t *testing.T) { { Config: testAccBitbucketPipelineSshKeyConfig(owner, rName, publicKey2, privateKey2), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketPipelineSshKeyExists(resourceName, &pipelineSshKey), + testAccCheckBitbucketPipelineSshKeyExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "workspace", "bitbucket_repository.test", "owner"), resource.TestCheckResourceAttrPair(resourceName, "repository", "bitbucket_repository.test", "name"), resource.TestCheckResourceAttr(resourceName, "public_key", publicKey2), @@ -89,7 +88,7 @@ func testAccCheckBitbucketPipelineSshKeyDestroy(s *terraform.State) error { return nil } -func testAccCheckBitbucketPipelineSshKeyExists(n string, pipelineSshKey *PiplineSshKey) resource.TestCheckFunc { +func testAccCheckBitbucketPipelineSshKeyExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { diff --git a/bitbucket/resource_pipeline_ssh_known_host.go b/bitbucket/resource_pipeline_ssh_known_host.go index 0e0e6812..d5baef44 100644 --- a/bitbucket/resource_pipeline_ssh_known_host.go +++ b/bitbucket/resource_pipeline_ssh_known_host.go @@ -1,13 +1,11 @@ package bitbucket import ( - "bytes" - "encoding/json" "fmt" - "io/ioutil" "log" "strings" + "github.com/DrFaust92/bitbucket-go-client" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) @@ -85,49 +83,28 @@ func resourcePipelineSshKnownHost() *schema.Resource { } func resourcePipelineSshKnownHostsCreate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + pipeApi := c.ApiClient.PipelinesApi pipeSshKnownHost := expandPipelineSshKnownHost(d) log.Printf("[DEBUG] Pipeline Ssh Key Request: %#v", pipeSshKnownHost) - bytedata, err := json.Marshal(pipeSshKnownHost) - - if err != nil { - return err - } repo := d.Get("repository").(string) workspace := d.Get("workspace").(string) - resp, err := client.Post(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/known_hosts/", - workspace, repo), - bytes.NewBuffer(bytedata)) + host, _, err := pipeApi.CreateRepositoryPipelineKnownHost(c.AuthContext, *pipeSshKnownHost, workspace, repo) if err != nil { - return err - } - - body, readerr := ioutil.ReadAll(resp.Body) - if readerr != nil { - return readerr + return fmt.Errorf("error creating pipeline ssh known host: %w", err) } - log.Printf("[DEBUG] Pipeline Ssh Known Hosts Response JSON: %v", string(body)) - - var host PiplineSshKnownHost - - decodeerr := json.Unmarshal(body, &host) - if decodeerr != nil { - return decodeerr - } - - log.Printf("[DEBUG] Pipeline Ssh Known Host Pages Response Decoded: %#v", host) - - d.SetId(string(fmt.Sprintf("%s/%s/%s", workspace, repo, host.UUID))) + d.SetId(string(fmt.Sprintf("%s/%s/%s", workspace, repo, host.Uuid))) return resourcePipelineSshKnownHostsRead(d, m) } func resourcePipelineSshKnownHostsUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + pipeApi := c.ApiClient.PipelinesApi workspace, repo, uuid, err := pipeSshKnownHostId(d.Id()) if err != nil { @@ -136,77 +113,57 @@ func resourcePipelineSshKnownHostsUpdate(d *schema.ResourceData, m interface{}) pipeSshKnownHost := expandPipelineSshKnownHost(d) log.Printf("[DEBUG] Pipeline Ssh Key Request: %#v", pipeSshKnownHost) - bytedata, err := json.Marshal(pipeSshKnownHost) - - if err != nil { - return err - } - - _, err = client.Put(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/known_hosts/%s", - workspace, repo, uuid), - bytes.NewBuffer(bytedata)) + _, _, err = pipeApi.UpdateRepositoryPipelineKnownHost(c.AuthContext, *pipeSshKnownHost, workspace, repo, uuid) if err != nil { - return err + return fmt.Errorf("error updating pipeline ssh known host: %w", err) } return resourcePipelineSshKnownHostsRead(d, m) } func resourcePipelineSshKnownHostsRead(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + pipeApi := c.ApiClient.PipelinesApi workspace, repo, uuid, err := pipeSshKnownHostId(d.Id()) if err != nil { return err } - pipeSshKnownHostsReq, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/known_hosts/%s", - workspace, repo, uuid)) - if pipeSshKnownHostsReq.StatusCode == 404 { + host, res, err := pipeApi.GetRepositoryPipelineKnownHost(c.AuthContext, workspace, repo, uuid) + if err != nil { + return fmt.Errorf("error reading Pipeline Ssh Key (%s): %w", d.Id(), err) + } + + if res.StatusCode == 404 { log.Printf("[WARN] Pipeline Ssh Key (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - if pipeSshKnownHostsReq.Body == nil { + if res.Body == nil { return fmt.Errorf("error getting Pipeline Ssh Key (%s): empty response", d.Id()) } - var pipeSshKnownHost *PiplineSshKnownHost - body, readerr := ioutil.ReadAll(pipeSshKnownHostsReq.Body) - if readerr != nil { - return readerr - } - - log.Printf("[DEBUG] Pipeline Ssh Key Response JSON: %v", string(body)) - - decodeerr := json.Unmarshal(body, &pipeSshKnownHost) - if decodeerr != nil { - return decodeerr - } - - log.Printf("[DEBUG] Pipeline Ssh Key Response Decoded: %#v", pipeSshKnownHost) - d.Set("repository", repo) d.Set("workspace", workspace) - d.Set("hostname", pipeSshKnownHost.Hostname) - d.Set("uuid", pipeSshKnownHost.UUID) - d.Set("public_key", flattenPipelineSshKnownHost(pipeSshKnownHost.PublicKey)) + d.Set("hostname", host.Hostname) + d.Set("uuid", host.Uuid) + d.Set("public_key", flattenPipelineSshKnownHost(host.PublicKey)) return nil } func resourcePipelineSshKnownHostsDelete(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + pipeApi := c.ApiClient.PipelinesApi workspace, repo, uuid, err := pipeSshKnownHostId(d.Id()) if err != nil { return err } - - _, err = client.Delete(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/known_hosts/%s", - workspace, repo, uuid)) + _, err = pipeApi.DeleteRepositoryPipelineKnownHost(c.AuthContext, workspace, repo, uuid) if err != nil { return fmt.Errorf("error deleting Pipeline Ssh Key (%s): %w", d.Id(), err) @@ -215,8 +172,8 @@ func resourcePipelineSshKnownHostsDelete(d *schema.ResourceData, m interface{}) return err } -func expandPipelineSshKnownHost(d *schema.ResourceData) *PiplineSshKnownHost { - key := &PiplineSshKnownHost{ +func expandPipelineSshKnownHost(d *schema.ResourceData) *bitbucket.PipelineKnownHost { + key := &bitbucket.PipelineKnownHost{ Hostname: d.Get("hostname").(string), PublicKey: expandPipelineSshKnownHostKey(d.Get("public_key").([]interface{})), } @@ -224,10 +181,10 @@ func expandPipelineSshKnownHost(d *schema.ResourceData) *PiplineSshKnownHost { return key } -func expandPipelineSshKnownHostKey(pubKey []interface{}) *PiplineSshKnownHostPublicKey { +func expandPipelineSshKnownHostKey(pubKey []interface{}) *bitbucket.PipelineSshPublicKey { tfMap, _ := pubKey[0].(map[string]interface{}) - key := &PiplineSshKnownHostPublicKey{ + key := &bitbucket.PipelineSshPublicKey{ KeyType: tfMap["key_type"].(string), Key: tfMap["key"].(string), } @@ -235,7 +192,7 @@ func expandPipelineSshKnownHostKey(pubKey []interface{}) *PiplineSshKnownHostPub return key } -func flattenPipelineSshKnownHost(rp *PiplineSshKnownHostPublicKey) []interface{} { +func flattenPipelineSshKnownHost(rp *bitbucket.PipelineSshPublicKey) []interface{} { if rp == nil { return []interface{}{} } @@ -243,8 +200,8 @@ func flattenPipelineSshKnownHost(rp *PiplineSshKnownHostPublicKey) []interface{} m := map[string]interface{}{ "key_type": rp.KeyType, "key": rp.Key, - "md5_fingerprint": rp.MD5Fingerprint, - "sha256_fingerprint": rp.SHA256Fingerprint, + "md5_fingerprint": rp.Md5Fingerprint, + "sha256_fingerprint": rp.Sha256Fingerprint, } return []interface{}{m} diff --git a/bitbucket/resource_pipeline_ssh_known_host_test.go b/bitbucket/resource_pipeline_ssh_known_host_test.go index aae8e419..c1e53b52 100644 --- a/bitbucket/resource_pipeline_ssh_known_host_test.go +++ b/bitbucket/resource_pipeline_ssh_known_host_test.go @@ -11,7 +11,6 @@ import ( ) func TestAccBitbucketPipelineSshKnownHost_basic(t *testing.T) { - var pipelineSshKnownHost PiplineSshKnownHost resourceName := "bitbucket_pipeline_ssh_known_host.test" rName := acctest.RandomWithPrefix("tf-test") @@ -35,7 +34,7 @@ func TestAccBitbucketPipelineSshKnownHost_basic(t *testing.T) { { Config: testAccBitbucketPipelineSshKnownHostConfig(owner, rName, publicKey, "example.com"), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketPipelineSshKnownHostExists(resourceName, &pipelineSshKnownHost), + testAccCheckBitbucketPipelineSshKnownHostExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "workspace", "bitbucket_repository.test", "owner"), resource.TestCheckResourceAttrPair(resourceName, "repository", "bitbucket_repository.test", "name"), resource.TestCheckResourceAttr(resourceName, "hostname", "example.com"), @@ -67,7 +66,9 @@ func TestAccBitbucketPipelineSshKnownHost_basic(t *testing.T) { } func testAccCheckBitbucketPipelineSshKnownHostDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(Clients).httpClient + client := testAccProvider.Meta().(Clients).genClient + pipeApi := client.ApiClient.PipelinesApi + for _, rs := range s.RootModule().Resources { if rs.Type != "bitbucket_pipeline_ssh_known_host" { continue @@ -78,14 +79,13 @@ func testAccCheckBitbucketPipelineSshKnownHostDestroy(s *terraform.State) error return err } - response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config/ssh/known_hosts/%s", - workspace, repo, uuid)) + _, res, err := pipeApi.GetRepositoryPipelineKnownHost(client.AuthContext, workspace, repo, uuid) if err == nil { return fmt.Errorf("The resource was found should have errored") } - if response.StatusCode != 404 { + if res.StatusCode != 404 { return fmt.Errorf("Pipeline Ssh Known Host still exists") } @@ -93,7 +93,7 @@ func testAccCheckBitbucketPipelineSshKnownHostDestroy(s *terraform.State) error return nil } -func testAccCheckBitbucketPipelineSshKnownHostExists(n string, pipelineSshKnownHost *PiplineSshKnownHost) resource.TestCheckFunc { +func testAccCheckBitbucketPipelineSshKnownHostExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { From 8d5aec5084bb7171914cb3a2dc138838f8825d26 Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 14:54:29 +0200 Subject: [PATCH 04/11] repo use gen client --- bitbucket/resource_repository.go | 246 ++++++++++++-------------- bitbucket/resource_repository_test.go | 58 +++++- 2 files changed, 171 insertions(+), 133 deletions(-) diff --git a/bitbucket/resource_repository.go b/bitbucket/resource_repository.go index eba8efb5..a3ab9966 100644 --- a/bitbucket/resource_repository.go +++ b/bitbucket/resource_repository.go @@ -1,14 +1,13 @@ package bitbucket import ( - "bytes" - "encoding/json" "fmt" - "io/ioutil" "log" "strings" + "github.com/DrFaust92/bitbucket-go-client" + "github.com/antihax/optional" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) @@ -157,37 +156,40 @@ func resourceRepository() *schema.Resource { } } -func newRepositoryFromResource(d *schema.ResourceData) *Repository { - repo := &Repository{ - Name: d.Get("name").(string), - Slug: d.Get("slug").(string), +func newRepositoryFromResource(d *schema.ResourceData) *bitbucket.Repository { + repo := &bitbucket.Repository{ + Name: d.Get("name").(string), + // Slug: d.Get("slug").(string), Language: d.Get("language").(string), IsPrivate: d.Get("is_private").(bool), Description: d.Get("description").(string), ForkPolicy: d.Get("fork_policy").(string), HasWiki: d.Get("has_wiki").(bool), HasIssues: d.Get("has_issues").(bool), - SCM: d.Get("scm").(string), - Website: d.Get("website").(string), + Scm: d.Get("scm").(string), + // Website: d.Get("website").(string), } if v, ok := d.GetOk("link"); ok && len(v.([]interface{})) > 0 && v.([]interface{}) != nil { repo.Links = expandRepoLinks(v.([]interface{})) } - repo.Project.Key = d.Get("project_key").(string) + if v, ok := d.GetOk("project_key"); ok && v.(string) != "" { + project := &bitbucket.Project{ + Key: v.(string), + } + repo.Project = project + } + return repo } func resourceRepositoryUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient - repository := newRepositoryFromResource(d) - - var jsonbuffer []byte + c := m.(Clients).genClient + repoApi := c.ApiClient.RepositoriesApi + pipeApi := c.ApiClient.PipelinesApi - jsonpayload := bytes.NewBuffer(jsonbuffer) - enc := json.NewEncoder(jsonpayload) - enc.Encode(repository) + repository := newRepositoryFromResource(d) var repoSlug string repoSlug = d.Get("slug").(string) @@ -195,75 +197,60 @@ func resourceRepositoryUpdate(d *schema.ResourceData, m interface{}) error { repoSlug = d.Get("name").(string) } - _, err := client.Put(fmt.Sprintf("2.0/repositories/%s/%s", - d.Get("owner").(string), - repoSlug, - ), jsonpayload) + repoBody := &bitbucket.RepositoriesApiRepositoriesWorkspaceRepoSlugPutOpts{ + Body: optional.NewInterface(repository), + } + + workspace := d.Get("owner").(string) + _, _, err := repoApi.RepositoriesWorkspaceRepoSlugPut(c.AuthContext, repoSlug, workspace, repoBody) if err != nil { - return err + return fmt.Errorf("error updating repository (%s): %w", repoSlug, err) } pipelinesEnabled := d.Get("pipelines_enabled").(bool) - pipelinesConfig := &PipelinesEnabled{Enabled: pipelinesEnabled} + pipelinesConfig := &bitbucket.PipelinesConfig{Enabled: pipelinesEnabled} - bytedata, err := json.Marshal(pipelinesConfig) + _, _, err = pipeApi.UpdateRepositoryPipelineConfig(c.AuthContext, *pipelinesConfig, workspace, repoSlug) if err != nil { - return err + return fmt.Errorf("error enabling pipeline for repository (%s): %w", repoSlug, err) } - _, err = client.Put(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config", - d.Get("owner").(string), - repoSlug), bytes.NewBuffer(bytedata)) - - if err != nil { - return err - } return resourceRepositoryRead(d, m) } func resourceRepositoryCreate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + repoApi := c.ApiClient.RepositoriesApi + pipeApi := c.ApiClient.PipelinesApi repo := newRepositoryFromResource(d) - bytedata, err := json.Marshal(repo) - - if err != nil { - return err - } - var repoSlug string repoSlug = d.Get("slug").(string) if repoSlug == "" { repoSlug = d.Get("name").(string) } - _, err = client.Post(fmt.Sprintf("2.0/repositories/%s/%s", - d.Get("owner").(string), - repoSlug, - ), bytes.NewBuffer(bytedata)) + repoBody := &bitbucket.RepositoriesApiRepositoriesWorkspaceRepoSlugPostOpts{ + Body: optional.NewInterface(repo), + } + + workspace := d.Get("owner").(string) + _, _, err := repoApi.RepositoriesWorkspaceRepoSlugPost(c.AuthContext, repoSlug, workspace, repoBody) if err != nil { - return err + return fmt.Errorf("error creating repository (%s): %w", repoSlug, err) } d.SetId(string(fmt.Sprintf("%s/%s", d.Get("owner").(string), repoSlug))) pipelinesEnabled := d.Get("pipelines_enabled").(bool) - pipelinesConfig := &PipelinesEnabled{Enabled: pipelinesEnabled} + pipelinesConfig := &bitbucket.PipelinesConfig{Enabled: pipelinesEnabled} - bytedata, err = json.Marshal(pipelinesConfig) + _, _, err = pipeApi.UpdateRepositoryPipelineConfig(c.AuthContext, *pipelinesConfig, workspace, repoSlug) if err != nil { - return err - } - - _, err = client.Put(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config", - d.Get("owner").(string), - repoSlug), bytes.NewBuffer(bytedata)) - - if err != nil { - return err + return fmt.Errorf("error enabling pipeline for repository (%s): %w", repoSlug, err) } return resourceRepositoryRead(d, m) @@ -287,83 +274,55 @@ func resourceRepositoryRead(d *schema.ResourceData, m interface{}) error { repoSlug = d.Get("name").(string) } - owner := d.Get("owner").(string) - client := m.(Clients).httpClient - repoReq, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/%s", owner, repoSlug)) + workspace := d.Get("owner").(string) + c := m.(Clients).genClient + repoApi := c.ApiClient.RepositoriesApi + pipeApi := c.ApiClient.PipelinesApi + + repoRes, res, err := repoApi.RepositoriesWorkspaceRepoSlugGet(c.AuthContext, repoSlug, workspace) + if err != nil { + return fmt.Errorf("error reading repository (%s): %w", d.Id(), err) + } - if repoReq.StatusCode == 404 { + if res.StatusCode == 404 { log.Printf("[WARN] Repository (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - if repoReq.StatusCode == 200 { - - var repo Repository - - body, readerr := ioutil.ReadAll(repoReq.Body) - if readerr != nil { - return readerr - } - - log.Printf("[DEBUG] Repository Response JSON: %v", string(body)) - - decodeerr := json.Unmarshal(body, &repo) - if decodeerr != nil { - return decodeerr - } - - log.Printf("[DEBUG] Repository Response Decoded: %#v", repo) - - d.Set("scm", repo.SCM) - d.Set("is_private", repo.IsPrivate) - d.Set("has_wiki", repo.HasWiki) - d.Set("has_issues", repo.HasIssues) - d.Set("name", repo.Name) - if repo.Slug != "" && repo.Name != repo.Slug { - d.Set("slug", repo.Slug) - } - d.Set("language", repo.Language) - d.Set("fork_policy", repo.ForkPolicy) - d.Set("website", repo.Website) - d.Set("description", repo.Description) - d.Set("project_key", repo.Project.Key) - d.Set("uuid", repo.UUID) - - for _, cloneURL := range repo.Links.Clone { - if cloneURL.Name == "https" { - d.Set("clone_https", cloneURL.Href) - } else { - d.Set("clone_ssh", cloneURL.Href) - } - } - - d.Set("link", flattenRepoLinks(repo.Links)) - - pipelinesConfigReq, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/pipelines_config", owner, repoSlug)) - - // pipelines_config returns 404 if they've never been enabled for the project - if err != nil && pipelinesConfigReq.StatusCode != 404 { - return err + d.Set("scm", repoRes.Scm) + d.Set("is_private", repoRes.IsPrivate) + d.Set("has_wiki", repoRes.HasWiki) + d.Set("has_issues", repoRes.HasIssues) + d.Set("name", repoRes.Name) + d.Set("slug", repoRes.Name) + d.Set("language", repoRes.Language) + d.Set("fork_policy", repoRes.ForkPolicy) + // d.Set("website", repoRes.Website) + d.Set("description", repoRes.Description) + d.Set("project_key", repoRes.Project.Key) + d.Set("uuid", repoRes.Uuid) + + for _, cloneURL := range repoRes.Links.Clone { + if cloneURL.Name == "https" { + d.Set("clone_https", cloneURL.Href) + } else { + d.Set("clone_ssh", cloneURL.Href) } + } - if pipelinesConfigReq.StatusCode == 200 { - var pipelinesConfig PipelinesEnabled + d.Set("link", flattenRepoLinks(repoRes.Links)) - body, readerr := ioutil.ReadAll(pipelinesConfigReq.Body) - if readerr != nil { - return readerr - } + pipelinesConfigReq, res, err := pipeApi.GetRepositoryPipelineConfig(c.AuthContext, workspace, repoSlug) - decodeerr := json.Unmarshal(body, &pipelinesConfig) - if decodeerr != nil { - return decodeerr - } + if err != nil && res.StatusCode != 404 { + return err + } - d.Set("pipelines_enabled", pipelinesConfig.Enabled) - } else if pipelinesConfigReq.StatusCode == 404 { - d.Set("pipelines_enabled", false) - } + if res.StatusCode == 200 { + d.Set("pipelines_enabled", pipelinesConfigReq.Enabled) + } else if res.StatusCode == 404 { + d.Set("pipelines_enabled", false) } return nil @@ -377,13 +336,21 @@ func resourceRepositoryDelete(d *schema.ResourceData, m interface{}) error { repoSlug = d.Get("name").(string) } - client := m.(Clients).httpClient - _, err := client.Delete(fmt.Sprintf("2.0/repositories/%s/%s", d.Get("owner").(string), repoSlug)) + c := m.(Clients).genClient + repoApi := c.ApiClient.RepositoriesApi + + res, err := repoApi.RepositoriesWorkspaceRepoSlugDelete(c.AuthContext, repoSlug, d.Get("owner").(string), nil) + if err != nil { + if res.StatusCode == 404 { + return nil + } + return fmt.Errorf("error deleting repository (%s): %w", d.Id(), err) + } - return err + return nil } -func expandRepoLinks(l []interface{}) *RepoLinks { +func expandRepoLinks(l []interface{}) *bitbucket.RepositoryLinks { if len(l) == 0 || l[0] == nil { return nil } @@ -394,22 +361,43 @@ func expandRepoLinks(l []interface{}) *RepoLinks { return nil } - rp := &RepoLinks{} + rp := &bitbucket.RepositoryLinks{} if v, ok := tfMap["avatar"].([]interface{}); ok && len(v) > 0 { - rp.Avatar = expandProjectLink(v) + rp.Avatar = expandRepoLink(v) } return rp } -func flattenRepoLinks(rp *RepoLinks) []interface{} { +func flattenRepoLinks(rp *bitbucket.RepositoryLinks) []interface{} { if rp == nil { return []interface{}{} } m := map[string]interface{}{ - "avatar": flattenProjectLink(rp.Avatar), + "avatar": flattenRepoLink(rp.Avatar), + } + + return []interface{}{m} +} + +func expandRepoLink(l []interface{}) *bitbucket.Link { + + tfMap, _ := l[0].(map[string]interface{}) + + rp := &bitbucket.Link{} + + if v, ok := tfMap["href"].(string); ok { + rp.Href = v + } + + return rp +} + +func flattenRepoLink(rp *bitbucket.Link) []interface{} { + m := map[string]interface{}{ + "href": rp.Href, } return []interface{}{m} diff --git a/bitbucket/resource_repository_test.go b/bitbucket/resource_repository_test.go index 09194e43..5822a9bd 100644 --- a/bitbucket/resource_repository_test.go +++ b/bitbucket/resource_repository_test.go @@ -40,6 +40,37 @@ func TestAccBitbucketRepository_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "link.#", "1"), resource.TestCheckResourceAttr(resourceName, "link.0.avatar.#", "1"), resource.TestCheckResourceAttrSet(resourceName, "link.0.avatar.0.href"), + resource.TestCheckResourceAttrSet(resourceName, "project_key"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccBitbucketRepository_project(t *testing.T) { + var repo Repository + + rName := acctest.RandomWithPrefix("tf-test") + testUser := os.Getenv("BITBUCKET_TEAM") + resourceName := "bitbucket_repository.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBitbucketRepositoryDestroy, + Steps: []resource.TestStep{ + { + Config: testAccBitbucketRepoProjectConfig(testUser, rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckBitbucketRepositoryExists(resourceName, &repo), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "owner", testUser), + resource.TestCheckResourceAttrPair(resourceName, "project_key", "bitbucket_project.test", "key"), ), }, { @@ -129,6 +160,22 @@ resource "bitbucket_repository" "test" { `, testUser, rName) } +func testAccBitbucketRepoProjectConfig(testUser, rName string) string { + return fmt.Sprintf(` +resource "bitbucket_project" "test" { + owner = %[1]q + name = %[2]q + key = "AAAAAAA" +} + +resource "bitbucket_repository" "test" { + owner = %[1]q + name = %[2]q + project_key = bitbucket_project.test.key +} +`, testUser, rName) +} + func testAccBitbucketRepoAvatarConfig(testUser, rName string) string { return fmt.Sprintf(` resource "bitbucket_repository" "test" { @@ -155,18 +202,21 @@ resource "bitbucket_repository" "test" { } func testAccCheckBitbucketRepositoryDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(Clients).httpClient + client := testAccProvider.Meta().(Clients).genClient + repoApi := client.ApiClient.RepositoriesApi + for _, rs := range s.RootModule().Resources { if rs.Type != "bitbucket_repository" { continue } - response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["name"])) + _, res, err := repoApi.RepositoriesWorkspaceRepoSlugGet(client.AuthContext, + rs.Primary.Attributes["name"], rs.Primary.Attributes["owner"]) if err == nil { - return fmt.Errorf("The resource was found should have errored") + return fmt.Errorf("The repository was found should have errored") } - if response.StatusCode != 404 { + if res.StatusCode != 404 { return fmt.Errorf("Repository still exists") } } From cf36117c9d381e90b405f0651d4c3ed3dc64264f Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 14:59:09 +0200 Subject: [PATCH 05/11] remove unneeded structs --- bitbucket/resource_repository.go | 29 --------------------------- bitbucket/resource_repository_test.go | 18 +++++------------ 2 files changed, 5 insertions(+), 42 deletions(-) diff --git a/bitbucket/resource_repository.go b/bitbucket/resource_repository.go index a3ab9966..91dc3aff 100644 --- a/bitbucket/resource_repository.go +++ b/bitbucket/resource_repository.go @@ -12,35 +12,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -// PipelinesEnabled is the struct we send to turn on or turn off pipelines for a repository -type PipelinesEnabled struct { - Enabled bool `json:"enabled"` -} - -type RepoLinks struct { - Clone []Link `json:"clone,omitempty"` - Avatar Link `json:"avatar,omitempty"` -} - -// Repository is the struct we need to send off to the Bitbucket API to create a repository -type Repository struct { - SCM string `json:"scm,omitempty"` - HasWiki bool `json:"has_wiki,omitempty"` - HasIssues bool `json:"has_issues,omitempty"` - Website string `json:"website,omitempty"` - IsPrivate bool `json:"is_private,omitempty"` - ForkPolicy string `json:"fork_policy,omitempty"` - Language string `json:"language,omitempty"` - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - Slug string `json:"slug,omitempty"` - UUID string `json:"uuid,omitempty"` - Project struct { - Key string `json:"key,omitempty"` - } `json:"project,omitempty"` - Links *RepoLinks `json:"links,omitempty"` -} - func resourceRepository() *schema.Resource { return &schema.Resource{ Create: resourceRepositoryCreate, diff --git a/bitbucket/resource_repository_test.go b/bitbucket/resource_repository_test.go index 5822a9bd..f6d3765c 100644 --- a/bitbucket/resource_repository_test.go +++ b/bitbucket/resource_repository_test.go @@ -11,8 +11,6 @@ import ( ) func TestAccBitbucketRepository_basic(t *testing.T) { - var repo Repository - rName := acctest.RandomWithPrefix("tf-test") testUser := os.Getenv("BITBUCKET_TEAM") resourceName := "bitbucket_repository.test" @@ -25,7 +23,7 @@ func TestAccBitbucketRepository_basic(t *testing.T) { { Config: testAccBitbucketRepoConfig(testUser, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketRepositoryExists(resourceName, &repo), + testAccCheckBitbucketRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "owner", testUser), resource.TestCheckResourceAttr(resourceName, "scm", "git"), @@ -53,8 +51,6 @@ func TestAccBitbucketRepository_basic(t *testing.T) { } func TestAccBitbucketRepository_project(t *testing.T) { - var repo Repository - rName := acctest.RandomWithPrefix("tf-test") testUser := os.Getenv("BITBUCKET_TEAM") resourceName := "bitbucket_repository.test" @@ -67,7 +63,7 @@ func TestAccBitbucketRepository_project(t *testing.T) { { Config: testAccBitbucketRepoProjectConfig(testUser, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketRepositoryExists(resourceName, &repo), + testAccCheckBitbucketRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "owner", testUser), resource.TestCheckResourceAttrPair(resourceName, "project_key", "bitbucket_project.test", "key"), @@ -83,8 +79,6 @@ func TestAccBitbucketRepository_project(t *testing.T) { } func TestAccBitbucketRepository_avatar(t *testing.T) { - var repo Repository - rName := acctest.RandomWithPrefix("tf-test") testUser := os.Getenv("BITBUCKET_TEAM") resourceName := "bitbucket_repository.test" @@ -97,7 +91,7 @@ func TestAccBitbucketRepository_avatar(t *testing.T) { { Config: testAccBitbucketRepoAvatarConfig(testUser, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketRepositoryExists(resourceName, &repo), + testAccCheckBitbucketRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "link.#", "1"), resource.TestCheckResourceAttr(resourceName, "link.0.avatar.#", "1"), resource.TestCheckResourceAttrSet(resourceName, "link.0.avatar.0.href"), @@ -113,8 +107,6 @@ func TestAccBitbucketRepository_avatar(t *testing.T) { } func TestAccBitbucketRepository_camelcase(t *testing.T) { - var repo Repository - rName := acctest.RandomWithPrefix("tf-test") rName2 := acctest.RandomWithPrefix("tf-test-2") testUser := os.Getenv("BITBUCKET_TEAM") @@ -128,7 +120,7 @@ func TestAccBitbucketRepository_camelcase(t *testing.T) { { Config: testAccBitbucketRepoSlugConfig(testUser, rName, rName2), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketRepositoryExists(resourceName, &repo), + testAccCheckBitbucketRepositoryExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "owner", testUser), resource.TestCheckResourceAttr(resourceName, "scm", "git"), @@ -223,7 +215,7 @@ func testAccCheckBitbucketRepositoryDestroy(s *terraform.State) error { return nil } -func testAccCheckBitbucketRepositoryExists(n string, repository *Repository) resource.TestCheckFunc { +func testAccCheckBitbucketRepositoryExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { From 12a07b5eaad65d73aea8271c2a7f7d04ea7e3e18 Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 15:40:39 +0200 Subject: [PATCH 06/11] remove unneeded structs --- bitbucket/resource_repository.go | 4 +-- bitbucket/resource_repository_test.go | 37 --------------------------- 2 files changed, 1 insertion(+), 40 deletions(-) diff --git a/bitbucket/resource_repository.go b/bitbucket/resource_repository.go index 91dc3aff..629a070e 100644 --- a/bitbucket/resource_repository.go +++ b/bitbucket/resource_repository.go @@ -129,8 +129,7 @@ func resourceRepository() *schema.Resource { func newRepositoryFromResource(d *schema.ResourceData) *bitbucket.Repository { repo := &bitbucket.Repository{ - Name: d.Get("name").(string), - // Slug: d.Get("slug").(string), + Name: d.Get("name").(string), Language: d.Get("language").(string), IsPrivate: d.Get("is_private").(bool), Description: d.Get("description").(string), @@ -138,7 +137,6 @@ func newRepositoryFromResource(d *schema.ResourceData) *bitbucket.Repository { HasWiki: d.Get("has_wiki").(bool), HasIssues: d.Get("has_issues").(bool), Scm: d.Get("scm").(string), - // Website: d.Get("website").(string), } if v, ok := d.GetOk("link"); ok && len(v.([]interface{})) > 0 && v.([]interface{}) != nil { diff --git a/bitbucket/resource_repository_test.go b/bitbucket/resource_repository_test.go index f6d3765c..2e7b55dd 100644 --- a/bitbucket/resource_repository_test.go +++ b/bitbucket/resource_repository_test.go @@ -106,43 +106,6 @@ func TestAccBitbucketRepository_avatar(t *testing.T) { }) } -func TestAccBitbucketRepository_camelcase(t *testing.T) { - rName := acctest.RandomWithPrefix("tf-test") - rName2 := acctest.RandomWithPrefix("tf-test-2") - testUser := os.Getenv("BITBUCKET_TEAM") - resourceName := "bitbucket_repository.test" - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckBitbucketRepositoryDestroy, - Steps: []resource.TestStep{ - { - Config: testAccBitbucketRepoSlugConfig(testUser, rName, rName2), - Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketRepositoryExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "owner", testUser), - resource.TestCheckResourceAttr(resourceName, "scm", "git"), - resource.TestCheckResourceAttr(resourceName, "has_wiki", "false"), - resource.TestCheckResourceAttrSet(resourceName, "uuid"), - resource.TestCheckResourceAttr(resourceName, "fork_policy", "allow_forks"), - resource.TestCheckResourceAttr(resourceName, "language", ""), - resource.TestCheckResourceAttr(resourceName, "has_issues", "false"), - resource.TestCheckResourceAttr(resourceName, "slug", rName2), - resource.TestCheckResourceAttr(resourceName, "is_private", "true"), - resource.TestCheckResourceAttr(resourceName, "description", ""), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - func testAccBitbucketRepoConfig(testUser, rName string) string { return fmt.Sprintf(` resource "bitbucket_repository" "test" { From 1a46f0e17135c37cfb0100ca7f3d48cab49bf512 Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 16:45:58 +0200 Subject: [PATCH 07/11] link repo --- bitbucket/resource_repository.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/bitbucket/resource_repository.go b/bitbucket/resource_repository.go index 629a070e..0a20ff32 100644 --- a/bitbucket/resource_repository.go +++ b/bitbucket/resource_repository.go @@ -140,7 +140,7 @@ func newRepositoryFromResource(d *schema.ResourceData) *bitbucket.Repository { } if v, ok := d.GetOk("link"); ok && len(v.([]interface{})) > 0 && v.([]interface{}) != nil { - repo.Links = expandRepoLinks(v.([]interface{})) + repo.Links = expandLinks(v.([]interface{})) } if v, ok := d.GetOk("project_key"); ok && v.(string) != "" { @@ -280,7 +280,7 @@ func resourceRepositoryRead(d *schema.ResourceData, m interface{}) error { } } - d.Set("link", flattenRepoLinks(repoRes.Links)) + d.Set("link", flattenLinks(repoRes.Links)) pipelinesConfigReq, res, err := pipeApi.GetRepositoryPipelineConfig(c.AuthContext, workspace, repoSlug) @@ -319,7 +319,7 @@ func resourceRepositoryDelete(d *schema.ResourceData, m interface{}) error { return nil } -func expandRepoLinks(l []interface{}) *bitbucket.RepositoryLinks { +func expandLinks(l []interface{}) *bitbucket.RepositoryLinks { if len(l) == 0 || l[0] == nil { return nil } @@ -333,25 +333,25 @@ func expandRepoLinks(l []interface{}) *bitbucket.RepositoryLinks { rp := &bitbucket.RepositoryLinks{} if v, ok := tfMap["avatar"].([]interface{}); ok && len(v) > 0 { - rp.Avatar = expandRepoLink(v) + rp.Avatar = expandLink(v) } return rp } -func flattenRepoLinks(rp *bitbucket.RepositoryLinks) []interface{} { +func flattenLinks(rp *bitbucket.RepositoryLinks) []interface{} { if rp == nil { return []interface{}{} } m := map[string]interface{}{ - "avatar": flattenRepoLink(rp.Avatar), + "avatar": flattenLink(rp.Avatar), } return []interface{}{m} } -func expandRepoLink(l []interface{}) *bitbucket.Link { +func expandLink(l []interface{}) *bitbucket.Link { tfMap, _ := l[0].(map[string]interface{}) @@ -364,7 +364,7 @@ func expandRepoLink(l []interface{}) *bitbucket.Link { return rp } -func flattenRepoLink(rp *bitbucket.Link) []interface{} { +func flattenLink(rp *bitbucket.Link) []interface{} { m := map[string]interface{}{ "href": rp.Href, } From e8c97ccd0bcddc8b79425e5788da46f9ad2b3e84 Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 16:58:59 +0200 Subject: [PATCH 08/11] project use gen client --- bitbucket/resource_project.go | 155 ++++++++++------------------- bitbucket/resource_project_test.go | 20 ++-- go.mod | 3 +- go.sum | 19 ++-- 4 files changed, 71 insertions(+), 126 deletions(-) diff --git a/bitbucket/resource_project.go b/bitbucket/resource_project.go index 286b0332..d10e9af9 100644 --- a/bitbucket/resource_project.go +++ b/bitbucket/resource_project.go @@ -1,14 +1,13 @@ package bitbucket import ( - "bytes" - "encoding/json" "fmt" - "io/ioutil" "log" "strings" + "github.com/DrFaust92/bitbucket-go-client" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) // Project is the project data we need to send to create a project on the bitbucket api @@ -44,8 +43,9 @@ func resourceProject() *schema.Resource { Schema: map[string]*schema.Schema{ "key": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, }, "is_private": { Type: schema.TypeBool, @@ -57,12 +57,14 @@ func resourceProject() *schema.Resource { Optional: true, }, "owner": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, }, "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, }, "has_publicly_visible_repos": { Type: schema.TypeBool, @@ -102,8 +104,8 @@ func resourceProject() *schema.Resource { } } -func newProjectFromResource(d *schema.ResourceData) *Project { - project := &Project{ +func newProjectFromResource(d *schema.ResourceData) *bitbucket.Project { + project := &bitbucket.Project{ Name: d.Get("name").(string), IsPrivate: d.Get("is_private").(bool), Description: d.Get("description").(string), @@ -111,50 +113,37 @@ func newProjectFromResource(d *schema.ResourceData) *Project { } if v, ok := d.GetOk("link"); ok && len(v.([]interface{})) > 0 && v.([]interface{}) != nil { - project.ProjectLinks = expandProjectLinks(v.([]interface{})) + project.Links = expandProjectLinks(v.([]interface{})) } return project } func resourceProjectUpdate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + projectApi := c.ApiClient.ProjectsApi project := newProjectFromResource(d) - var jsonbuffer []byte - - jsonpayload := bytes.NewBuffer(jsonbuffer) - enc := json.NewEncoder(jsonpayload) - enc.Encode(project) - var projectKey string projectKey = d.Get("key").(string) if projectKey == "" { projectKey = d.Get("key").(string) } - _, err := client.Put(fmt.Sprintf("2.0/workspaces/%s/projects/%s", - d.Get("owner").(string), - projectKey, - ), jsonpayload) + _, _, err := projectApi.WorkspacesWorkspaceProjectsProjectKeyPut(c.AuthContext, *project, projectKey, d.Get("owner").(string)) if err != nil { - return err + return fmt.Errorf("error updating project (%s): %w", d.Id(), err) } return resourceProjectRead(d, m) } func resourceProjectCreate(d *schema.ResourceData, m interface{}) error { - client := m.(Clients).httpClient + c := m.(Clients).genClient + projectApi := c.ApiClient.ProjectsApi project := newProjectFromResource(d) - bytedata, err := json.Marshal(project) - - if err != nil { - return err - } - var projectKey string projectKey = d.Get("key").(string) if projectKey == "" { @@ -162,19 +151,15 @@ func resourceProjectCreate(d *schema.ResourceData, m interface{}) error { } owner := d.Get("owner").(string) - if owner == "" { - return fmt.Errorf("owner must not be a empty string") - } - _, err = client.Post(fmt.Sprintf("2.0/workspaces/%s/projects/", - d.Get("owner").(string), - ), bytes.NewBuffer(bytedata)) + log.Printf("haha %#v", project) + projRes, _, err := projectApi.WorkspacesWorkspaceProjectsPost(c.AuthContext, *project, owner) if err != nil { - return err + return fmt.Errorf("error creating project (%s): %w", projectKey, err) } - d.SetId(string(fmt.Sprintf("%s/%s", d.Get("owner").(string), projectKey))) + d.SetId(string(fmt.Sprintf("%s/%s", owner, projRes.Key))) return resourceProjectRead(d, m) } @@ -197,44 +182,27 @@ func resourceProjectRead(d *schema.ResourceData, m interface{}) error { projectKey = d.Get("key").(string) } - client := m.(Clients).httpClient - projectReq, _ := client.Get(fmt.Sprintf("2.0/workspaces/%s/projects/%s", - d.Get("owner").(string), - projectKey, - )) + c := m.(Clients).genClient + projectApi := c.ApiClient.ProjectsApi - if projectReq.StatusCode == 404 { + projRes, res, err := projectApi.WorkspacesWorkspaceProjectsProjectKeyGet(c.AuthContext, projectKey, d.Get("owner").(string)) + + if err != nil { + return fmt.Errorf("error reading project (%s): %w", d.Id(), err) + } + if res.StatusCode == 404 { log.Printf("[WARN] Project (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - if projectReq.StatusCode == 200 { - - var project Project - - body, readerr := ioutil.ReadAll(projectReq.Body) - if readerr != nil { - return readerr - } - - log.Printf("[DEBUG] Project Response JSON: %v", string(body)) - - decodeerr := json.Unmarshal(body, &project) - if decodeerr != nil { - return decodeerr - } - - log.Printf("[DEBUG] Project Response Decoded: %#v", project) - - d.Set("key", project.Key) - d.Set("is_private", project.IsPrivate) - d.Set("name", project.Name) - d.Set("description", project.Description) - d.Set("has_publicly_visible_repos", project.HasPubliclyVisibleRepos) - d.Set("uuid", project.UUID) - d.Set("link", flattenProjectLinks(project.ProjectLinks)) - } + d.Set("key", projRes.Key) + d.Set("is_private", projRes.IsPrivate) + d.Set("name", projRes.Name) + d.Set("description", projRes.Description) + d.Set("has_publicly_visible_repos", projRes.HasPubliclyVisibleRepos) + d.Set("uuid", projRes.Uuid) + d.Set("link", flattenProjectLinks(projRes.Links)) return nil } @@ -247,16 +215,18 @@ func resourceProjectDelete(d *schema.ResourceData, m interface{}) error { projectKey = d.Get("key").(string) } - client := m.(Clients).httpClient - _, err := client.Delete(fmt.Sprintf("2.0/workspaces/%s/projects/%s", - d.Get("owner").(string), - projectKey, - )) + c := m.(Clients).genClient + projectApi := c.ApiClient.ProjectsApi + + _, err := projectApi.WorkspacesWorkspaceProjectsProjectKeyDelete(c.AuthContext, projectKey, d.Get("owner").(string)) + if err != nil { + return fmt.Errorf("error deleting project (%s): %w", d.Id(), err) + } - return err + return nil } -func expandProjectLinks(l []interface{}) *ProjectLinks { +func expandProjectLinks(l []interface{}) *bitbucket.ProjectLinks { if len(l) == 0 || l[0] == nil { return nil } @@ -267,43 +237,22 @@ func expandProjectLinks(l []interface{}) *ProjectLinks { return nil } - rp := &ProjectLinks{} + rp := &bitbucket.ProjectLinks{} if v, ok := tfMap["avatar"].([]interface{}); ok && len(v) > 0 { - rp.Avatar = expandProjectLink(v) - } - - return rp -} - -func expandProjectLink(l []interface{}) Link { - - tfMap, _ := l[0].(map[string]interface{}) - - rp := Link{} - - if v, ok := tfMap["href"].(string); ok { - rp.Href = v + rp.Avatar = expandLink(v) } return rp } -func flattenProjectLinks(rp *ProjectLinks) []interface{} { +func flattenProjectLinks(rp *bitbucket.ProjectLinks) []interface{} { if rp == nil { return []interface{}{} } m := map[string]interface{}{ - "avatar": flattenProjectLink(rp.Avatar), - } - - return []interface{}{m} -} - -func flattenProjectLink(rp Link) []interface{} { - m := map[string]interface{}{ - "href": rp.Href, + "avatar": flattenLink(rp.Avatar), } return []interface{}{m} diff --git a/bitbucket/resource_project_test.go b/bitbucket/resource_project_test.go index e41ee119..1dfc9ae7 100644 --- a/bitbucket/resource_project_test.go +++ b/bitbucket/resource_project_test.go @@ -11,8 +11,6 @@ import ( ) func TestAccBitbucketProject_basic(t *testing.T) { - var project Project - resourceName := "bitbucket_project.test" testTeam := os.Getenv("BITBUCKET_TEAM") rName := acctest.RandomWithPrefix("tf-test") @@ -25,7 +23,7 @@ func TestAccBitbucketProject_basic(t *testing.T) { { Config: testAccBitbucketProjectConfig(testTeam, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketProjectExists(resourceName, &project), + testAccCheckBitbucketProjectExists(resourceName), resource.TestCheckResourceAttr(resourceName, "has_publicly_visible_repos", "false"), resource.TestCheckResourceAttr(resourceName, "key", "AAAAAA"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -48,8 +46,6 @@ func TestAccBitbucketProject_basic(t *testing.T) { } func TestAccBitbucketProject_avatar(t *testing.T) { - var project Project - resourceName := "bitbucket_project.test" testTeam := os.Getenv("BITBUCKET_TEAM") rName := acctest.RandomWithPrefix("tf-test") @@ -62,7 +58,7 @@ func TestAccBitbucketProject_avatar(t *testing.T) { { Config: testAccBitbucketProjectAvatarConfig(testTeam, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketProjectExists(resourceName, &project), + testAccCheckBitbucketProjectExists(resourceName), resource.TestCheckResourceAttr(resourceName, "link.#", "1"), resource.TestCheckResourceAttr(resourceName, "link.0.avatar.#", "1"), resource.TestCheckResourceAttrSet(resourceName, "link.0.avatar.0.href"), @@ -104,25 +100,29 @@ resource "bitbucket_project" "test" { } func testAccCheckBitbucketProjectDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(Clients).httpClient + client := testAccProvider.Meta().(Clients).genClient + projectApi := client.ApiClient.ProjectsApi + for _, rs := range s.RootModule().Resources { if rs.Type != "bitbucket_project" { continue } - response, err := client.Get(fmt.Sprintf("2.0/workspaces/%s/projects/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["name"])) + + _, res, err := projectApi.WorkspacesWorkspaceProjectsProjectKeyGet(client.AuthContext, + rs.Primary.Attributes["key"], rs.Primary.Attributes["owner"]) if err == nil { return fmt.Errorf("The resource was found should have errored") } - if response.StatusCode != 404 { + if res.StatusCode != 404 { return fmt.Errorf("Project still exists") } } return nil } -func testAccCheckBitbucketProjectExists(n string, project *Project) resource.TestCheckFunc { +func testAccCheckBitbucketProjectExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { diff --git a/go.mod b/go.mod index 12586d49..bd8fa8c9 100644 --- a/go.mod +++ b/go.mod @@ -1,7 +1,8 @@ module github.com/terraform-providers/terraform-provider-bitbucket require ( - github.com/DrFaust92/bitbucket-go-client v0.0.1 + github.com/DrFaust92/bitbucket-go-client v0.0.2 + github.com/antihax/optional v1.0.0 github.com/hashicorp/terraform-plugin-log v0.2.0 github.com/hashicorp/terraform-plugin-sdk/v2 v2.10.1 github.com/satori/go.uuid v1.2.0 diff --git a/go.sum b/go.sum index cd8f5aaf..19fe6e4b 100644 --- a/go.sum +++ b/go.sum @@ -11,9 +11,9 @@ cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6 cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.61.0 h1:NLQf5e1OMspfNT1RAHOB3ublr1TW3YTXO8OiWwVjK2U= cloud.google.com/go v0.61.0/go.mod h1:XukKJg4Y7QsUu0Hxg3qQKUWR4VuWivmyMK2+rUyxAqw= cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0 h1:Dg9iHVQfrhq82rUNu9ZxUDrJLaxFUe/HlCVaLyRruq8= cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= @@ -36,8 +36,8 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/DrFaust92/bitbucket-go-client v0.0.1 h1:fYnaLYnmrAYgszJQwv3BWoroFb1OJTEAktXeaFwHaKQ= -github.com/DrFaust92/bitbucket-go-client v0.0.1/go.mod h1:3UJtT6PmlsB7MCc1MbegmGlT2waRlIMIHtaQLTcd794= +github.com/DrFaust92/bitbucket-go-client v0.0.2 h1:xTSTA0SR59YcAbEiQkI0DKviV93+OcfaGa7LFRzy94I= +github.com/DrFaust92/bitbucket-go-client v0.0.2/go.mod h1:3UJtT6PmlsB7MCc1MbegmGlT2waRlIMIHtaQLTcd794= github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= @@ -406,7 +406,6 @@ golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= @@ -414,7 +413,6 @@ golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAG golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a h1:qfl7ob3DIEs3Ml9oLuPwY2N04gymzAW04WsUQHIClgM= golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= @@ -461,12 +459,11 @@ golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210502180810-71e4cd670f79/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -474,7 +471,6 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3 golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= @@ -518,15 +514,15 @@ golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed h1:+qzWo37K31KxduIYaBeMqJ8MUOyTayOQKpH9aDPLMSY= golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d h1:W07d4xkoAUSNOkOzdzXCdFGxT7o2rW4q8M34tB2i//k= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= @@ -542,8 +538,8 @@ google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/ google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0 h1:BaiDisFir8O4IJxvAabCGGkQ6yCJegNQqSVoYUNAnbk= google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0 h1:yfrXXP61wVuLb0vBcG6qaOoIoqYEzOQS8jum51jkv2w= google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -579,7 +575,6 @@ google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200711021454-869866162049 h1:YFTFpQhgvrLrmxtiIncJxFXeCyq84ixuKWVCaCAi9Oc= google.golang.org/genproto v0.0.0-20200711021454-869866162049/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= From 301a5d1db4a91b7e7b01827a50b903bda563a83c Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 17:06:51 +0200 Subject: [PATCH 09/11] hook events using gen client --- bitbucket/data_hook_types.go | 50 ++++++++---------------------------- 1 file changed, 10 insertions(+), 40 deletions(-) diff --git a/bitbucket/data_hook_types.go b/bitbucket/data_hook_types.go index 2cbb51dd..791fc862 100644 --- a/bitbucket/data_hook_types.go +++ b/bitbucket/data_hook_types.go @@ -1,29 +1,14 @@ package bitbucket import ( - "encoding/json" "fmt" - "io/ioutil" "log" "net/http" + "github.com/DrFaust92/bitbucket-go-client" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -type PaginatedHookTypes struct { - Values []HookType `json:"values,omitempty"` - Page int `json:"page,omitempty"` - Size int `json:"size,omitempty"` - Next string `json:"next,omitempty"` -} - -type HookType struct { - Event string `json:"event"` - Category string `json:"category"` - Label string `json:"label"` - Description string `json:"description"` -} - func dataHookTypes() *schema.Resource { return &schema.Resource{ Read: dataReadHookTypes, @@ -62,52 +47,37 @@ func dataHookTypes() *schema.Resource { } func dataReadHookTypes(d *schema.ResourceData, m interface{}) error { - c := m.(Clients).httpClient + c := m.(Clients).genClient + webhooksApi := c.ApiClient.WebhooksApi subjectType := d.Get("subject_type").(string) - hookTypes, err := c.Get(fmt.Sprintf("2.0/hook_events/%s", subjectType)) + hookTypes, res, err := webhooksApi.HookEventsSubjectTypeGet(c.AuthContext, subjectType) if err != nil { return err } - if hookTypes.StatusCode == http.StatusNotFound { + if res.StatusCode == http.StatusNotFound { return fmt.Errorf("user not found") } - if hookTypes.StatusCode >= http.StatusInternalServerError { + if res.StatusCode >= http.StatusInternalServerError { return fmt.Errorf("internal server error fetching hook types") } - body, readerr := ioutil.ReadAll(hookTypes.Body) - if readerr != nil { - return readerr - } - - log.Printf("[DEBUG] Hook Types Response JSON: %v", string(body)) - - var hookTypePages PaginatedHookTypes - - decodeerr := json.Unmarshal(body, &hookTypePages) - if decodeerr != nil { - return decodeerr - } - - log.Printf("[DEBUG] Hook Type Pages Response Decoded: %#v", hookTypePages) - d.SetId(subjectType) - d.Set("hook_types", flattenHookTypes(hookTypePages.Values)) + d.Set("hook_types", flattenHookTypes(hookTypes.Values)) return nil } -func flattenHookTypes(HookTypes []HookType) []interface{} { - if len(HookTypes) == 0 { +func flattenHookTypes(hookTypes []bitbucket.HookEvent) []interface{} { + if len(hookTypes) == 0 { return nil } var tfList []interface{} - for _, btRaw := range HookTypes { + for _, btRaw := range hookTypes { log.Printf("[DEBUG] HookType Response Decoded: %#v", btRaw) hookType := map[string]interface{}{ From 6c096de17fc810dac66758a5470b4ba7de590379 Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 17:37:31 +0200 Subject: [PATCH 10/11] branch restrict use code gen --- bitbucket/resource_branch_restriction.go | 151 ++++++++---------- bitbucket/resource_branch_restriction_test.go | 19 ++- 2 files changed, 78 insertions(+), 92 deletions(-) diff --git a/bitbucket/resource_branch_restriction.go b/bitbucket/resource_branch_restriction.go index 01a42a66..dae3931f 100644 --- a/bitbucket/resource_branch_restriction.go +++ b/bitbucket/resource_branch_restriction.go @@ -1,16 +1,14 @@ package bitbucket import ( - "bytes" "context" - "encoding/json" "fmt" - "io/ioutil" + "log" "net/url" "strings" - "github.com/hashicorp/terraform-plugin-log/tflog" + "github.com/DrFaust92/bitbucket-go-client" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -137,24 +135,38 @@ func resourceBranchRestriction() *schema.Resource { } } -func createBranchRestriction(d *schema.ResourceData) *BranchRestriction { +func createBranchRestriction(d *schema.ResourceData) *bitbucket.Branchrestriction { - users := make([]User, 0, len(d.Get("users").(*schema.Set).List())) + users := make([]bitbucket.Account, 0, d.Get("users").(*schema.Set).Len()) for _, item := range d.Get("users").(*schema.Set).List() { - users = append(users, User{Username: item.(string)}) + account := bitbucket.Account{ + Username: item.(string), + } + + users = append(users, account) } - groups := make([]Group, 0, len(d.Get("groups").(*schema.Set).List())) + groups := make([]bitbucket.Group, 0, d.Get("groups").(*schema.Set).Len()) for _, item := range d.Get("groups").(*schema.Set).List() { m := item.(map[string]interface{}) - groups = append(groups, Group{Owner: User{Username: m["owner"].(string)}, Slug: m["slug"].(string)}) + + account := &bitbucket.Account{ + Username: m["owner"].(string), + } + + group := bitbucket.Group{ + Owner: account, + Slug: m["slug"].(string), + } + + groups = append(groups, group) } - restict := &BranchRestriction{ + restict := &bitbucket.Branchrestriction{ Kind: d.Get("kind").(string), - Value: d.Get("value").(int), + Value: int32(d.Get("value").(int)), Users: users, Groups: groups, } @@ -168,7 +180,7 @@ func createBranchRestriction(d *schema.ResourceData) *BranchRestriction { } if v, ok := d.GetOk("branch_match_kind"); ok { - restict.BranchMatchkind = v.(string) + restict.BranchMatchKind = v.(string) } return restict @@ -176,92 +188,60 @@ func createBranchRestriction(d *schema.ResourceData) *BranchRestriction { } func resourceBranchRestrictionsCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(Clients).httpClient + c := m.(Clients).genClient + brApi := c.ApiClient.BranchRestrictionsApi branchRestriction := createBranchRestriction(d) - bytedata, err := json.Marshal(branchRestriction) + repo := d.Get("repository").(string) + workspace := d.Get("owner").(string) + branchRestrictionReq, _, err := brApi.RepositoriesWorkspaceRepoSlugBranchRestrictionsPost(c.AuthContext, *branchRestriction, repo, workspace) if err != nil { return diag.FromErr(err) } - branchRestrictionReq, err := client.Post(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions", - d.Get("owner").(string), - d.Get("repository").(string), - ), bytes.NewBuffer(bytedata)) - - if err != nil { - return diag.FromErr(err) - } - - body, readerr := ioutil.ReadAll(branchRestrictionReq.Body) - if readerr != nil { - return diag.FromErr(readerr) - } - - decodeerr := json.Unmarshal(body, &branchRestriction) - if decodeerr != nil { - return diag.FromErr(decodeerr) - } - - d.SetId(string(fmt.Sprintf("%v", branchRestriction.ID))) + d.SetId(string(fmt.Sprintf("%v", branchRestrictionReq.Id))) return resourceBranchRestrictionsRead(ctx, d, m) } func resourceBranchRestrictionsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(Clients).httpClient - - branchRestrictionsReq, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions/%s", - d.Get("owner").(string), - d.Get("repository").(string), - url.PathEscape(d.Id()), - )) - - if branchRestrictionsReq.StatusCode == 200 { - var branchRestriction BranchRestriction - body, readerr := ioutil.ReadAll(branchRestrictionsReq.Body) - if readerr != nil { - return diag.FromErr(readerr) - } + c := m.(Clients).genClient + brApi := c.ApiClient.BranchRestrictionsApi - decodeerr := json.Unmarshal(body, &branchRestriction) - if decodeerr != nil { - return diag.FromErr(decodeerr) - } + brRes, res, err := brApi.RepositoriesWorkspaceRepoSlugBranchRestrictionsIdGet(c.AuthContext, url.PathEscape(d.Id()), + d.Get("repository").(string), d.Get("owner").(string)) + + if err != nil { + return diag.FromErr(err) + } - tflog.Trace(ctx, "branch restriction read", - "id", url.PathEscape(d.Id()), - "body", string(body), - "status", branchRestrictionsReq.StatusCode, - ) - - d.SetId(string(fmt.Sprintf("%v", branchRestriction.ID))) - d.Set("kind", branchRestriction.Kind) - d.Set("pattern", branchRestriction.Pattern) - d.Set("value", branchRestriction.Value) - d.Set("users", branchRestriction.Users) - d.Set("groups", branchRestriction.Groups) - d.Set("branch_type", branchRestriction.BranchType) - d.Set("branch_match_kind", branchRestriction.BranchMatchkind) + if res.StatusCode == 404 { + log.Printf("[WARN] Branch Restrictions (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } + d.SetId(string(fmt.Sprintf("%v", brRes.Id))) + d.Set("kind", brRes.Kind) + d.Set("pattern", brRes.Pattern) + d.Set("value", brRes.Value) + d.Set("users", brRes.Users) + d.Set("groups", brRes.Groups) + d.Set("branch_type", brRes.BranchType) + d.Set("branch_match_kind", brRes.BranchMatchKind) + return nil } func resourceBranchRestrictionsUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(Clients).httpClient + c := m.(Clients).genClient + brApi := c.ApiClient.BranchRestrictionsApi branchRestriction := createBranchRestriction(d) - payload, err := json.Marshal(branchRestriction) - if err != nil { - return diag.FromErr(err) - } - _, err = client.Put(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions/%s", - d.Get("owner").(string), - d.Get("repository").(string), - url.PathEscape(d.Id()), - ), bytes.NewBuffer(payload)) + _, _, err := brApi.RepositoriesWorkspaceRepoSlugBranchRestrictionsIdPut(c.AuthContext, + *branchRestriction, url.PathEscape(d.Id()), + d.Get("repository").(string), d.Get("owner").(string)) if err != nil { return diag.FromErr(err) @@ -271,12 +251,15 @@ func resourceBranchRestrictionsUpdate(ctx context.Context, d *schema.ResourceDat } func resourceBranchRestrictionsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - client := m.(Clients).httpClient - _, err := client.Delete(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions/%s", - d.Get("owner").(string), - d.Get("repository").(string), - url.PathEscape(d.Id()), - )) - - return diag.FromErr(err) + c := m.(Clients).genClient + brApi := c.ApiClient.BranchRestrictionsApi + + _, err := brApi.RepositoriesWorkspaceRepoSlugBranchRestrictionsIdDelete(c.AuthContext, url.PathEscape(d.Id()), + d.Get("repository").(string), d.Get("owner").(string)) + + if err != nil { + return diag.FromErr(err) + } + + return nil } diff --git a/bitbucket/resource_branch_restriction_test.go b/bitbucket/resource_branch_restriction_test.go index 9e9a186f..7d4a9423 100644 --- a/bitbucket/resource_branch_restriction_test.go +++ b/bitbucket/resource_branch_restriction_test.go @@ -12,7 +12,6 @@ import ( ) func TestAccBitbucketBranchRestriction_basic(t *testing.T) { - var branchRestriction BranchRestriction rName := acctest.RandomWithPrefix("tf-test") testUser := os.Getenv("BITBUCKET_TEAM") resourceName := "bitbucket_branch_restriction.test" @@ -25,7 +24,7 @@ func TestAccBitbucketBranchRestriction_basic(t *testing.T) { { Config: testAccBitbucketBranchRestrictionConfig(testUser, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketBranchRestrictionExists(resourceName, &branchRestriction), + testAccCheckBitbucketBranchRestrictionExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "repository", "bitbucket_repository.test", "name"), resource.TestCheckResourceAttr(resourceName, "kind", "force"), resource.TestCheckResourceAttr(resourceName, "pattern", "master"), @@ -43,7 +42,6 @@ func TestAccBitbucketBranchRestriction_basic(t *testing.T) { } func TestAccBitbucketBranchRestriction_model(t *testing.T) { - var branchRestriction BranchRestriction rName := acctest.RandomWithPrefix("tf-test") testUser := os.Getenv("BITBUCKET_TEAM") resourceName := "bitbucket_branch_restriction.test" @@ -56,7 +54,7 @@ func TestAccBitbucketBranchRestriction_model(t *testing.T) { { Config: testAccBitbucketBranchRestrictionModelConfig(testUser, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckBitbucketBranchRestrictionExists(resourceName, &branchRestriction), + testAccCheckBitbucketBranchRestrictionExists(resourceName), resource.TestCheckResourceAttrPair(resourceName, "repository", "bitbucket_repository.test", "name"), resource.TestCheckResourceAttr(resourceName, "kind", "force"), resource.TestCheckResourceAttr(resourceName, "pattern", ""), @@ -106,18 +104,23 @@ resource "bitbucket_branch_restriction" "test" { } func testAccCheckBitbucketBranchRestrictionDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(Clients).httpClient + client := testAccProvider.Meta().(Clients).genClient + brApi := client.ApiClient.BranchRestrictionsApi + for _, rs := range s.RootModule().Resources { if rs.Type != "bitbucket_branch_restriction" { continue } - response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["repository"], url.PathEscape(rs.Primary.Attributes["id"]))) + + _, res, err := brApi.RepositoriesWorkspaceRepoSlugBranchRestrictionsIdGet(client.AuthContext, + url.PathEscape(rs.Primary.ID), + rs.Primary.Attributes["repository"], rs.Primary.Attributes["owner"]) if err == nil { return fmt.Errorf("The resource was found should have errored") } - if response.StatusCode != 404 { + if res.StatusCode != 404 { return fmt.Errorf("BranchRestriction still exists") } } @@ -125,7 +128,7 @@ func testAccCheckBitbucketBranchRestrictionDestroy(s *terraform.State) error { return nil } -func testAccCheckBitbucketBranchRestrictionExists(n string, branchRestriction *BranchRestriction) resource.TestCheckFunc { +func testAccCheckBitbucketBranchRestrictionExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { From 7c239d3e8c8445321fc3612b4ec211899aa513e1 Mon Sep 17 00:00:00 2001 From: drfaust92 Date: Tue, 15 Mar 2022 17:38:58 +0200 Subject: [PATCH 11/11] branch restrict use code gen --- bitbucket/resource_branch_restriction.go | 1 - 1 file changed, 1 deletion(-) diff --git a/bitbucket/resource_branch_restriction.go b/bitbucket/resource_branch_restriction.go index dae3931f..40d2905f 100644 --- a/bitbucket/resource_branch_restriction.go +++ b/bitbucket/resource_branch_restriction.go @@ -184,7 +184,6 @@ func createBranchRestriction(d *schema.ResourceData) *bitbucket.Branchrestrictio } return restict - } func resourceBranchRestrictionsCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {