Skip to content

Commit

Permalink
Merge pull request #47 from DrFaust92/bb-client-2
Browse files Browse the repository at this point in the history
Using BB generated client Pt 2
  • Loading branch information
DrFaust92 authored Mar 15, 2022
2 parents f304a8f + 7c239d3 commit 6ac6f88
Show file tree
Hide file tree
Showing 15 changed files with 426 additions and 647 deletions.
50 changes: 10 additions & 40 deletions bitbucket/data_hook_types.go
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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{}{
Expand Down
152 changes: 67 additions & 85 deletions bitbucket/resource_branch_restriction.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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,
}
Expand All @@ -168,100 +180,67 @@ 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

}

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))

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 err != nil {
return diag.FromErr(err)
}

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)
Expand All @@ -271,12 +250,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
}
19 changes: 11 additions & 8 deletions bitbucket/resource_branch_restriction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"),
Expand All @@ -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"
Expand All @@ -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", ""),
Expand Down Expand Up @@ -106,26 +104,31 @@ 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")
}
}

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 {
Expand Down
Loading

0 comments on commit 6ac6f88

Please sign in to comment.