Skip to content

Commit

Permalink
Check HTTP response status code in DownloadRepository (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
omerzi authored Dec 18, 2022
1 parent 76aa707 commit e75d840
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 7 deletions.
12 changes: 7 additions & 5 deletions vcsclient/azurerepos.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,11 @@ func (client *AzureReposClient) DownloadRepository(ctx context.Context, owner, r
}()
res, err := client.sendDownloadRepoRequest(ctx, repository, branch)
defer func() {
e := res.Body.Close()
if err == nil {
err = e
if res.Body != nil {
e := res.Body.Close()
if err == nil {
err = e
}
}
}()
if err != nil {
Expand Down Expand Up @@ -140,8 +142,8 @@ func (client *AzureReposClient) sendDownloadRepoRequest(ctx context.Context, rep
if res, err = httpClient.Do(req); err != nil {
return
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
err = fmt.Errorf("bad HTTP status: %d", res.StatusCode)
if err = vcsutils.CheckResponseStatusWithBody(res, http.StatusOK); err != nil {
return &http.Response{}, err
}
client.logger.Info(repository, "downloaded successfully, starting with repository extraction")
return
Expand Down
3 changes: 3 additions & 0 deletions vcsclient/bitbucketcloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,9 @@ func (client *BitbucketCloudClient) DownloadRepository(ctx context.Context, owne
if err != nil {
return err
}
if err = vcsutils.CheckResponseStatusWithBody(response, http.StatusOK); err != nil {
return err
}
client.logger.Info(repository, "downloaded successfully, starting with repository extraction")
err = vcsutils.Untar(localPath, response.Body, true)
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions vcsclient/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,9 @@ func (client *GitHubClient) DownloadRepository(ctx context.Context, owner, repos
return err
}
defer func() { _ = resp.Body.Close() }()
if err = vcsutils.CheckResponseStatusWithBody(resp, http.StatusOK); err != nil {
return err
}
client.logger.Info(repository, "downloaded successfully, starting with repository extraction")
err = vcsutils.Untar(localPath, resp.Body, true)
if err != nil {
Expand Down
37 changes: 35 additions & 2 deletions vcsutils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"archive/zip"
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
Expand All @@ -16,8 +17,6 @@ import (
"strings"
)

var ErrStatusCode = "invalid status code. expected %d and received %d"

// CreateToken create a random UUID
func CreateToken() string {
return uuid.New().String()
Expand Down Expand Up @@ -235,6 +234,40 @@ func unzipFile(f *zip.File, destination string) (err error) {
return safeCopy(destinationFile, zippedFile)
}

func CheckResponseStatusWithBody(resp *http.Response, expectedStatusCodes ...int) error {
for _, statusCode := range expectedStatusCodes {
if statusCode == resp.StatusCode {
return nil
}
}

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

return GenerateResponseError(resp.Status, generateErrorString(body))
}

func GenerateResponseError(status, body string) error {
responseErrString := "server response: " + status
if body != "" {
responseErrString = responseErrString + "\n" + body
}
return fmt.Errorf(responseErrString)
}

func generateErrorString(bodyArray []byte) string {
var content bytes.Buffer
if len(bodyArray) > 0 {
if err := json.Indent(&content, bodyArray, "", " "); err != nil {
return string(bodyArray)
}
return content.String()
}
return ""
}

// CreateDotGitFolderWithRemote creates a .git folder inside path with remote details of remoteName and remoteUrl
func CreateDotGitFolderWithRemote(path, remoteName, remoteUrl string) error {
repo, err := git.PlainInit(path, false)
Expand Down
19 changes: 19 additions & 0 deletions vcsutils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,25 @@ func TestGetZeroValue(t *testing.T) {
assert.Equal(t, 0.0, GetZeroValue[float64]())
}

func TestGenerateResponseError(t *testing.T) {
status := "404"
emptyBodyErr := GenerateResponseError(status, "")
assert.Error(t, emptyBodyErr)
assert.Equal(t, "server response: 404", emptyBodyErr.Error())
err := GenerateResponseError(status, "error")
assert.Error(t, err)
assert.Equal(t, "server response: 404\nerror", err.Error())
}

func TestCheckResponseStatusWithBody(t *testing.T) {
expectedStatusCode := 200
resp := &http.Response{
Status: "200",
StatusCode: 200,
}
assert.NoError(t, CheckResponseStatusWithBody(resp, expectedStatusCode))
}

func TestCreateDotGitFolderWithRemote(t *testing.T) {
dir1, err := os.MkdirTemp("", "tmp")
assert.NoError(t, err)
Expand Down

0 comments on commit e75d840

Please sign in to comment.