Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring of bitbucket provider with better error support and general improvments #13390

Merged
merged 1 commit into from
Apr 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 79 additions & 36 deletions builtin/providers/bitbucket/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,64 +2,107 @@ package bitbucket

import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)

// Error represents a error from the bitbucket api.
type Error struct {
APIError struct {
Message string `json:"message,omitempty"`
} `json:"error,omitempty"`
Type string `json:"type,omitempty"`
StatusCode int
Endpoint string
}

func (e Error) Error() string {
return fmt.Sprintf("API Error: %d %s %s", e.StatusCode, e.Endpoint, e.APIError.Message)
}

const (
// BitbucketEndpoint is the fqdn used to talk to bitbucket
BitbucketEndpoint string = "https://api.bitbucket.org/"
)

type BitbucketClient struct {
Username string
Password string
Username string
Password string
HTTPClient *http.Client
}

func (c *BitbucketClient) Get(endpoint string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://api.bitbucket.org/"+endpoint, nil)
func (c *BitbucketClient) Do(method, endpoint string, payload *bytes.Buffer) (*http.Response, error) {

absoluteendpoint := BitbucketEndpoint + endpoint
log.Printf("[DEBUG] Sending request to %s %s", method, absoluteendpoint)

var bodyreader io.Reader

if payload != nil {
log.Printf("[DEBUG] With payload %s", payload.String())
bodyreader = payload
}

req, err := http.NewRequest(method, absoluteendpoint, bodyreader)
if err != nil {
return nil, err
}

req.SetBasicAuth(c.Username, c.Password)
return client.Do(req)

if payload != nil {
// Can cause bad request when putting default reviews if set.
req.Header.Add("Content-Type", "application/json")
}

req.Close = true

resp, err := c.HTTPClient.Do(req)
log.Printf("[DEBUG] Resp: %v Err: %v", resp, err)
if resp.StatusCode >= 400 || resp.StatusCode < 200 {
apiError := Error{
StatusCode: resp.StatusCode,
Endpoint: endpoint,
}

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}

log.Printf("[DEBUG] Resp Body: %s", string(body))

err = json.Unmarshal(body, &apiError)
if err != nil {
apiError.APIError.Message = string(body)
}

return resp, error(apiError)

}
return resp, err
}

func (c *BitbucketClient) Get(endpoint string) (*http.Response, error) {
return c.Do("GET", endpoint, nil)
}

func (c *BitbucketClient) Post(endpoint string, jsonpayload *bytes.Buffer) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("POST", "https://api.bitbucket.org/"+endpoint, jsonpayload)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
req.Header.Add("content-type", "application/json")
return client.Do(req)
return c.Do("POST", endpoint, jsonpayload)
}

func (c *BitbucketClient) Put(endpoint string, jsonpayload *bytes.Buffer) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("PUT", "https://api.bitbucket.org/"+endpoint, jsonpayload)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
req.Header.Add("content-type", "application/json")
return client.Do(req)
return c.Do("PUT", endpoint, jsonpayload)
}

func (c *BitbucketClient) PutOnly(endpoint string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("PUT", "https://api.bitbucket.org/"+endpoint, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
return client.Do(req)
return c.Do("PUT", endpoint, nil)
}

func (c *BitbucketClient) Delete(endpoint string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("DELETE", "https://api.bitbucket.org/"+endpoint, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
return client.Do(req)
return c.Do("DELETE", endpoint, nil)
}
7 changes: 5 additions & 2 deletions builtin/providers/bitbucket/provider.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package bitbucket

import (
"net/http"

"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
Expand Down Expand Up @@ -30,8 +32,9 @@ func Provider() terraform.ResourceProvider {

func providerConfigure(d *schema.ResourceData) (interface{}, error) {
client := &BitbucketClient{
Username: d.Get("username").(string),
Password: d.Get("password").(string),
Username: d.Get("username").(string),
Password: d.Get("password").(string),
HTTPClient: &http.Client{},
}

return client, nil
Expand Down
19 changes: 10 additions & 9 deletions builtin/providers/bitbucket/resource_default_reviewers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bitbucket
import (
"encoding/json"
"fmt"

"github.com/hashicorp/terraform/helper/schema"
)

Expand Down Expand Up @@ -49,7 +50,7 @@ func resourceDefaultReviewersCreate(d *schema.ResourceData, m interface{}) error
client := m.(*BitbucketClient)

for _, user := range d.Get("reviewers").(*schema.Set).List() {
reviewer_resp, err := client.PutOnly(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers/%s",
reviewerResp, err := client.PutOnly(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers/%s",
d.Get("owner").(string),
d.Get("repository").(string),
user,
Expand All @@ -59,11 +60,11 @@ func resourceDefaultReviewersCreate(d *schema.ResourceData, m interface{}) error
return err
}

if reviewer_resp.StatusCode != 200 {
return fmt.Errorf("Failed to create reviewer %s got code %d", user.(string), reviewer_resp.StatusCode)
if reviewerResp.StatusCode != 200 {
return fmt.Errorf("Failed to create reviewer %s got code %d", user.(string), reviewerResp.StatusCode)
}

defer reviewer_resp.Body.Close()
defer reviewerResp.Body.Close()
}

d.SetId(fmt.Sprintf("%s/%s/reviewers", d.Get("owner").(string), d.Get("repository").(string)))
Expand All @@ -72,26 +73,26 @@ func resourceDefaultReviewersCreate(d *schema.ResourceData, m interface{}) error
func resourceDefaultReviewersRead(d *schema.ResourceData, m interface{}) error {
client := m.(*BitbucketClient)

reviewers_response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers",
reviewersResponse, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/default-reviewers",
d.Get("owner").(string),
d.Get("repository").(string),
))

var reviewers PaginatedReviewers

decoder := json.NewDecoder(reviewers_response.Body)
decoder := json.NewDecoder(reviewersResponse.Body)
err = decoder.Decode(&reviewers)
if err != nil {
return err
}

terraform_reviewers := make([]string, 0, len(reviewers.Values))
terraformReviewers := make([]string, 0, len(reviewers.Values))

for _, reviewer := range reviewers.Values {
terraform_reviewers = append(terraform_reviewers, reviewer.Username)
terraformReviewers = append(terraformReviewers, reviewer.Username)
}

d.Set("reviewers", terraform_reviewers)
d.Set("reviewers", terraformReviewers)

return nil
}
Expand Down
Loading