From dd207502d8275183cfd0d771d074c771af9ae1ce Mon Sep 17 00:00:00 2001 From: Anthony Erbe Date: Wed, 30 Jun 2021 08:15:26 -0500 Subject: [PATCH] adding branch creation (#143) --- bitbucket.go | 11 +++++++++++ repository.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/bitbucket.go b/bitbucket.go index d9a8889..474f306 100644 --- a/bitbucket.go +++ b/bitbucket.go @@ -210,6 +210,17 @@ type RepositoryBranchOptions struct { BranchName string `json:"branch_name"` } +type RepositoryBranchCreationOptions struct { + Owner string `json:"owner"` + RepoSlug string `json:"repo_slug"` + Name string `json:"name"` + Target RepositoryBranchTarget `json:"target"` +} + +type RepositoryBranchTarget struct { + Hash string `json:"hash"` +} + type RepositoryTagOptions struct { Owner string `json:"owner"` RepoSlug string `json:"repo_slug"` diff --git a/repository.go b/repository.go index f5c2405..613cd74 100644 --- a/repository.go +++ b/repository.go @@ -331,6 +331,24 @@ func (r *Repository) GetBranch(rbo *RepositoryBranchOptions) (*RepositoryBranch, return decodeRepositoryBranch(bodyString) } +func (r *Repository) CreateBranch(rbo *RepositoryBranchCreationOptions) (*RepositoryBranch, error) { + urlStr := r.c.requestUrl("/repositories/%s/%s/refs/branches", rbo.Owner, rbo.RepoSlug) + data := r.buildBranchBody(rbo) + + response, err := r.c.executeRaw("POST", urlStr, data) + if err != nil { + return nil, err + } + + bodyBytes, err := ioutil.ReadAll(response) + if err != nil { + return nil, err + } + + bodyString := string(bodyBytes) + return decodeRepositoryBranchCreated(bodyString) +} + func (r *Repository) ListTags(rbo *RepositoryTagOptions) (*RepositoryTags, error) { params := url.Values{} @@ -798,6 +816,17 @@ func (r *Repository) buildPipelineBuildNumberBody(rpbno *RepositoryPipelineBuild return r.buildJsonBody(body) } +func (r *Repository) buildBranchBody(rbo *RepositoryBranchCreationOptions) string { + body := map[string]interface{}{ + "name": rbo.Name, + "target": map[string]string{ + "hash": rbo.Target.Hash, + }, + } + + return r.buildJsonBody(body) +} + func (r *Repository) buildTagBody(rbo *RepositoryTagCreationOptions) string { body := map[string]interface{}{ "name": rbo.Name, @@ -949,6 +978,15 @@ func decodeRepositoryBranch(branchResponseStr string) (*RepositoryBranch, error) return &repositoryBranch, nil } +func decodeRepositoryBranchCreated(branchResponseStr string) (*RepositoryBranch, error) { + var responseBranchCreated RepositoryBranch + err := json.Unmarshal([]byte(branchResponseStr), &responseBranchCreated) + if err != nil { + return nil, err + } + return &responseBranchCreated, nil +} + func decodeRepositoryTagCreated(tagResponseStr string) (*RepositoryTag, error) { var responseTagCreated RepositoryTag err := json.Unmarshal([]byte(tagResponseStr), &responseTagCreated)