Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(vcs): implement core VCS logic for Bitbucket Cloud (#4855)

Joe Chen6de65d9ee3a5
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
new file mode 100644
index 0000000000..c6b5a7ed41
--- /dev/null
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -0,0 +1,1043 @@
+// Package bitbucket is the plugin for Bitbucket Cloud.
+package bitbucket
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "path"
+ "strings"
+ "time"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
+)
+
+const (
+ // bitbucketCloudURL is URL for the Bitbucket Cloud.
+ bitbucketCloudURL = "https://bitbucket.org"
+
+ // apiPageSize is the default page size when making API requests.
+ apiPageSize = 100
+)
+
+func init() {
+ vcs.Register(vcs.Bitbucket, newProvider)
+}
+
+var _ vcs.Provider = (*Provider)(nil)
+
+// Provider is a Bitbucket Cloud VCS provider.
+type Provider struct {
+ client *http.Client
+}
+
+func newProvider(config vcs.ProviderConfig) vcs.Provider {
+ if config.Client == nil {
+ config.Client = &http.Client{}
+ }
+ return &Provider{
+ client: config.Client,
+ }
+}
+
+// APIURL returns the API URL path of Bitbucket Cloud.
+func (*Provider) APIURL(string) string {
+ return "https://api.bitbucket.org/2.0"
+}
+
+// oauthResponse is a Bitbucket Cloud OAuth response.
+type oauthResponse struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ ExpiresIn int64 `json:"expires_in"`
+ Error string `json:"error,omitempty"`
+ ErrorDescription string `json:"error_description,omitempty"`
+}
+
+// toVCSOAuthToken converts the response to *vcs.OAuthToken.
+func (o oauthResponse) toVCSOAuthToken() *vcs.OAuthToken {
+ oauthToken := &vcs.OAuthToken{
+ AccessToken: o.AccessToken,
+ RefreshToken: o.RefreshToken,
+ ExpiresIn: o.ExpiresIn,
+ CreatedAt: time.Now().Unix(),
+ ExpiresTs: time.Now().Add(time.Duration(o.ExpiresIn) * time.Second).Unix(),
+ }
+ return oauthToken
+}
+
+// ExchangeOAuthToken exchanges OAuth content with the provided authorization code.
+func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*vcs.OAuthToken, error) {
+ form := &url.Values{}
+ form.Set("grant_type", "authorization_code")
+ form.Set("code", oauthExchange.Code)
+ url := fmt.Sprintf("%s/site/oauth2/access_token", instanceURL)
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(form.Encode()))
+ if err != nil {
+ return nil, errors.Wrapf(err, "construct POST %s", url)
+ }
+
+ digested := base64.StdEncoding.EncodeToString([]byte(oauthExchange.ClientID + ":" + oauthExchange.ClientSecret))
+ req.Header.Set("Authorization", digested)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := p.client.Do(req)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to exchange OAuth token")
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to read OAuth response body, code %v", resp.StatusCode)
+ }
+ defer func() {
+ _ = resp.Body.Close()
+ }()
+
+ oauthResp := new(oauthResponse)
+ if err := json.Unmarshal(body, oauthResp); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal OAuth response body, code %v", resp.StatusCode)
+ }
+ if oauthResp.Error != "" {
+ return nil, errors.Errorf("failed to exchange OAuth token, error: %v, error_description: %v", oauthResp.Error, oauthResp.ErrorDescription)
+ }
+ return oauthResp.toVCSOAuthToken(), nil
+}
+
+// TryLogin tries to fetch the user info from the current OAuth context.
+func (*Provider) TryLogin(context.Context, common.OauthContext, string) (*vcs.UserInfo, error) {
+ // TODO: We will remove VCS login as part of https://linear.app/bytebase/issue/BYT-2615,
+ // so leaving it as unimplemented here.
+ return nil, errors.New("not implemented")
+}
+
+// User represents a Bitbucket Cloud API response for a user.
+type User struct {
+ DisplayName string `json:"display_name"`
+}
+
+// CommitAuthor represents a Bitbucket Cloud API response for a commit author.
+type CommitAuthor struct {
+ User User `json:"user"`
+}
+
+// Commit represents a Bitbucket Cloud API response for a commit.
+type Commit struct {
+ Hash string `json:"hash"`
+ Author CommitAuthor `json:"author"`
+ // Date expects corresponding JSON value is a string in RFC 3339 format,
+ // see https://pkg.go.dev/time#Time.MarshalJSON.
+ Date time.Time `json:"date"`
+}
+
+// FetchCommitByID fetches the commit data by its ID from the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-commit-commit-get
+func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, commitID string) (*vcs.Commit, error) {
+ url := fmt.Sprintf("%s/repositories/%s/commit/%s", p.APIURL(instanceURL), url.PathEscape(repositoryID), commitID)
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrap(err, "GET")
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to fetch commit data from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s", url, code, body)
+ }
+
+ commit := &Commit{}
+ if err := json.Unmarshal([]byte(body), commit); err != nil {
+ return nil, errors.Wrap(err, "unmarshal body")
+ }
+
+ return &vcs.Commit{
+ ID: commit.Hash,
+ AuthorName: commit.Author.User.DisplayName,
+ CreatedTs: commit.Date.Unix(),
+ }, nil
+}
+
+// CommitFile represents a Bitbucket Cloud API response for a file at a commit.
+type CommitFile struct {
+ Path string `json:"path"`
+ Links struct {
+ Self struct {
+ Href string `json:"href"`
+ } `json:"self"`
+ } `json:"links"`
+}
+
+// CommitDiffStat represents a Bitbucket Cloud API response for commit diff stat.
+type CommitDiffStat struct {
+ // The status of the diff stat object, possible values are "added", "removed",
+ // "modified", "renamed".
+ Status string `json:"status"`
+ New CommitFile `json:"new"`
+}
+
+// GetDiffFileList gets the diff files list between two commits.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-diffstat-spec-get
+func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]vcs.FileDiff, error) {
+ var bbcDiffs []*CommitDiffStat
+ page := 1
+ for {
+ url := fmt.Sprintf("%s/repositories/%s/diffstat/%s..%s?page=%d&pagelen=%d", p.APIURL(instanceURL), url.PathEscape(repositoryID), afterCommit, beforeCommit, page, apiPageSize)
+ diffs, hasNextPage, err := p.fetchPaginatedDiffFileList(ctx, oauthCtx, instanceURL, url)
+ if err != nil {
+ return nil, errors.Wrap(err, "fetch paginated list")
+ }
+ bbcDiffs = append(bbcDiffs, diffs...)
+
+ if !hasNextPage {
+ break
+ }
+ page++
+ }
+
+ var diffs []vcs.FileDiff
+ for _, d := range bbcDiffs {
+ diff := vcs.FileDiff{
+ Path: d.New.Path,
+ }
+ switch d.Status {
+ case "added":
+ diff.Type = vcs.FileDiffTypeAdded
+ case "modified":
+ diff.Type = vcs.FileDiffTypeModified
+ case "removed":
+ diff.Type = vcs.FileDiffTypeRemoved
+ default:
+ // Skip because we don't care about file diff in other status
+ continue
+ }
+ diffs = append(diffs, diff)
+ }
+ return diffs, nil
+}
+
+func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, url string) (diffs []*CommitDiffStat, hasNextPage bool, err error) {
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, false, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, false, common.Errorf(common.NotFound, "failed to get file diff list from URL %s", url)
+ } else if code >= 300 {
+ return nil, false, errors.Errorf("failed to get file diff list from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var resp struct {
+ Values []*CommitDiffStat `json:"values"`
+ Next bool `json:"next"`
+ }
+ if err := json.Unmarshal([]byte(body), &resp); err != nil {
+ return nil, false, errors.Wrapf(err, "failed to unmarshal file diff data from Bitbucket Cloud instance %s", instanceURL)
+ }
+ return resp.Values, resp.Next, nil
+}
+
+// Repository represents a Bitbucket Cloud API response for a repository.
+type Repository struct {
+ UUID string `json:"uuid"`
+ Name string `json:"name"`
+ FullName string `json:"full_name"`
+}
+
+// RepositoryPermission represents a Bitbucket Cloud API response for a
+// repository permission.
+type RepositoryPermission struct {
+ Repository Repository `json:"repository"`
+}
+
+// FetchAllRepositoryList fetches all repositories where the authenticated user
+// has admin permissions, which is required to create webhook in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-user-permissions-repositories-get
+func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {
+ var bbcRepos []*Repository
+ page := 1
+ for {
+ repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, oauthCtx, instanceURL, page)
+ if err != nil {
+ return nil, errors.Wrap(err, "fetch paginated list")
+ }
+ bbcRepos = append(bbcRepos, repos...)
+
+ if !hasNextPage {
+ break
+ }
+ page++
+ }
+
+ var repos []*vcs.Repository
+ for _, r := range bbcRepos {
+ repos = append(repos,
+ &vcs.Repository{
+ ID: r.UUID,
+ Name: r.Name,
+ FullPath: r.FullName,
+ WebURL: fmt.Sprintf("%s/%s", instanceURL, r.FullName),
+ },
+ )
+ }
+ return repos, nil
+}
+
+// fetchPaginatedRepositoryList fetches repositories where the authenticated
+// user has admin access to in given page. It returns the paginated results
+// along with a boolean indicating whether the next page exists.
+func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, page int) (repos []*Repository, hasNextPage bool, err error) {
+ url := fmt.Sprintf(`%s/user/permissions/repositories?q=%s&page=%d&pagelen=%d`, p.APIURL(instanceURL), url.PathEscape(`permission="admin"`), page, apiPageSize)
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, false, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, false, common.Errorf(common.NotFound, "failed to fetch repository list from URL %s", url)
+ } else if code >= 300 {
+ return nil, false,
+ errors.Errorf("failed to fetch repository list from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var resp struct {
+ Values []*RepositoryPermission `json:"values"`
+ Next bool `json:"next"`
+ }
+ if err := json.Unmarshal([]byte(body), &resp); err != nil {
+ return nil, false, errors.Wrap(err, "unmarshal")
+ }
+
+ for _, v := range resp.Values {
+ repos = append(repos,
+ &Repository{
+ UUID: v.Repository.UUID,
+ Name: v.Repository.Name,
+ FullName: v.Repository.FullName,
+ },
+ )
+ }
+ return repos, resp.Next, nil
+}
+
+// TreeEntry represents a Bitbucket Cloud API response for a repository tree
+// entry.
+type TreeEntry struct {
+ Type string `json:"type"`
+ Path string `json:"path"`
+ Size int64 `json:"size"`
+ Commit Commit `json:"commit"`
+}
+
+// FetchRepositoryFileList fetches the all files from the given repository tree
+// recursively.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#directory-listings
+func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {
+ var bbcTreeEntries []*TreeEntry
+ page := 1
+ for {
+ treeEntries, hasNextPage, err := p.fetchPaginatedRepositoryFileList(ctx, oauthCtx, instanceURL, repositoryID, ref, filePath, page)
+ if err != nil {
+ return nil, errors.Wrap(err, "fetch paginated list")
+ }
+ bbcTreeEntries = append(bbcTreeEntries, treeEntries...)
+
+ if !hasNextPage {
+ break
+ }
+ page++
+ }
+
+ var treeNodes []*vcs.RepositoryTreeNode
+ for _, n := range bbcTreeEntries {
+ treeNodes = append(treeNodes,
+ &vcs.RepositoryTreeNode{
+ Path: n.Path,
+ Type: n.Type,
+ },
+ )
+ }
+ return treeNodes, nil
+}
+
+// fetchPaginatedRepositoryFileList fetches files under a repository tree
+// recursively in given page. It returns the paginated results along with a
+// boolean indicating whether the next page exists.
+func (p *Provider) fetchPaginatedRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, ref, filePath string, page int) (_ []*TreeEntry, hasNextPage bool, err error) {
+ // NOTE: There is no way to ask the Bitbucket Cloud API to return all
+ // subdirectories recursively, 10 levels down is just a good guess.
+ url := fmt.Sprintf("%s/repositories/%s/src/%s/%s?max_depth=10&q=%s&page=%d&pagelen=%d", p.APIURL(instanceURL), repositoryID, ref, url.PathEscape(filePath), url.QueryEscape(`type="commit_file"`), page, apiPageSize)
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, false, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, false, common.Errorf(common.NotFound, "failed to fetch repository file list from URL %s", url)
+ } else if code >= 300 {
+ return nil, false,
+ errors.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var resp struct {
+ Values []*TreeEntry `json:"values"`
+ Next bool `json:"next"`
+ }
+ if err := json.Unmarshal([]byte(body), &resp); err != nil {
+ return nil, false, errors.Wrap(err, "unmarshal body")
+ }
+ return resp.Values, resp.Next, nil
+}
+
+// CreateFile creates a file at given path in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#api-repositories-workspace-repo-slug-src-post
+func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
+ var body bytes.Buffer
+ w := multipart.NewWriter(&body)
+ part, err := w.CreateFormFile("filename", filePath)
+ if err != nil {
+ return errors.Wrap(err, "failed to create form file")
+ }
+ _, err = part.Write([]byte(fileCommitCreate.Content))
+ if err != nil {
+ return errors.Wrap(err, "failed to write file to form")
+ }
+ _ = w.Close()
+
+ urlParams := &url.Values{}
+ urlParams.Set("message", url.QueryEscape(fileCommitCreate.CommitMessage))
+ urlParams.Set("parents", fileCommitCreate.LastCommitID)
+ urlParams.Set("branch", fileCommitCreate.Branch)
+
+ url := fmt.Sprintf("%s/repositories/%s/src?%s", p.APIURL(instanceURL), repositoryID, urlParams.Encode())
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ &body,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "POST %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to create/update file through URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+ return nil
+}
+
+// OverwriteFile overwrites an existing file at given path in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#api-repositories-workspace-repo-slug-src-post
+func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
+ return p.CreateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate)
+}
+
+// ReadFileMeta reads the metadata of the given file in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#file-meta-data
+func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (*vcs.FileMeta, error) {
+ url := fmt.Sprintf("%s/repositories/%s/src/%s/%s?format=meta", p.APIURL(instanceURL), repositoryID, ref, url.PathEscape(filePath))
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to read file from URL %s", url)
+ } else if code >= 300 {
+ return nil,
+ errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var treeEntry TreeEntry
+ if err = json.Unmarshal([]byte(body), &treeEntry); err != nil {
+ return nil, errors.Wrap(err, "unmarshal body")
+ }
+
+ if treeEntry.Type != "commit_file" {
+ return nil, errors.Errorf("%q is not a file", filePath)
+ }
+
+ return &vcs.FileMeta{
+ Name: path.Base(treeEntry.Path),
+ Path: treeEntry.Path,
+ Size: treeEntry.Size,
+ LastCommitID: treeEntry.Commit.Hash,
+ }, nil
+}
+
+// ReadFileContent reads the content of the given file in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#raw-file-contents
+func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (string, error) {
+ url := fmt.Sprintf("%s/repositories/%s/src/%s/%s", p.APIURL(instanceURL), repositoryID, ref, url.PathEscape(filePath))
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return "", errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return "", common.Errorf(common.NotFound, "failed to read file from URL %s", url)
+ } else if code >= 300 {
+ return "",
+ errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+ return body, nil
+}
+
+// Branch is the API message for Bitbucket Cloud branch.
+type Branch struct {
+ Name string `json:"name"`
+ Target struct {
+ Hash string `json:"hash"`
+ } `json:"target"`
+}
+
+// GetBranch gets the given branch in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-name-get
+func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+ url := fmt.Sprintf("%s/repositories/%s/refs/branches/%s", p.APIURL(instanceURL), repositoryID, branchName)
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to get branch from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to get branch from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var branch Branch
+ if err := json.Unmarshal([]byte(body), &branch); err != nil {
+ return nil, errors.Wrap(err, "unmarshal body")
+ }
+
+ return &vcs.BranchInfo{
+ Name: branch.Name,
+ LastCommitID: branch.Target.Hash,
+ }, nil
+}
+
+type branchCreateTarget struct {
+ Hash string `json:"hash"`
+}
+
+type branchCreate struct {
+ Name string `json:"name"`
+ Target branchCreateTarget `json:"target"`
+}
+
+// CreateBranch creates the branch in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-post
+func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
+ body, err := json.Marshal(
+ branchCreate{
+ Name: branch.Name,
+ Target: branchCreateTarget{Hash: branch.LastCommitID},
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal branch create")
+ }
+
+ url := fmt.Sprintf("%s/repositories/%s/refs/branches", p.APIURL(instanceURL), repositoryID)
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "POST %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to create branch from URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+ return nil
+}
+
+// ListPullRequestFile lists the changed files in the pull request.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pullrequests/#api-repositories-workspace-repo-slug-pullrequests-pull-request-id-diffstat-get
+func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
+ var bbcDiffs []*CommitDiffStat
+ page := 1
+ for {
+ url := fmt.Sprintf("%s/repositories/%s/pullrequests/%s/diffstat?page=%d&pagelen=%d", p.APIURL(instanceURL), url.PathEscape(repositoryID), pullRequestID, page, apiPageSize)
+ diffs, hasNextPage, err := p.fetchPaginatedDiffFileList(ctx, oauthCtx, instanceURL, url)
+ if err != nil {
+ return nil, errors.Wrap(err, "fetch paginated list")
+ }
+ bbcDiffs = append(bbcDiffs, diffs...)
+
+ if !hasNextPage {
+ break
+ }
+ page++
+ }
+
+ // NOTE: The API response does not guarantee to return the value of the commit
+ // ID, so we need to extract it from the link instead.
+ extractCommitIDFromLinkSelf := func(href string) string {
+ const anchor = "/src/"
+ i := strings.Index(href, anchor)
+ if i < 0 {
+ return "<no commit ID found>"
+ }
+ fields := strings.SplitN(href[i+len(anchor):], "/", 2)
+ return fields[0]
+ }
+
+ var files []*vcs.PullRequestFile
+ for _, d := range bbcDiffs {
+ file := &vcs.PullRequestFile{
+ Path: d.New.Path,
+ LastCommitID: extractCommitIDFromLinkSelf(d.New.Links.Self.Href),
+ IsDeleted: d.Status == "removed",
+ }
+ files = append(files, file)
+ }
+ return files, nil
+}
+
+type pullRequestCreateBranch struct {
+ Name string `json:"name"`
+}
+type pullRequestCreateTarget struct {
+ Branch pullRequestCreateBranch `json:"branch"`
+}
+
+type pullRequestCreate struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ CloseSourceBranch bool `json:"close_source_branch"`
+ Source pullRequestCreateTarget `json:"source"`
+ Destination pullRequestCreateTarget `json:"destination"`
+}
+
+// CreatePullRequest creates the pull request in the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pullrequests/#api-repositories-workspace-repo-slug-pullrequests-post
+func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, create *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
+ payload, err := json.Marshal(
+ pullRequestCreate{
+ Title: create.Title,
+ Description: create.Body,
+ CloseSourceBranch: create.RemoveHeadAfterMerged,
+ Source: pullRequestCreateTarget{
+ Branch: pullRequestCreateBranch{Name: create.Head},
+ },
+ Destination: pullRequestCreateTarget{
+ Branch: pullRequestCreateBranch{Name: create.Base},
+ },
+ },
+ )
+ if err != nil {
+ return nil, errors.Wrap(err, "marshal pull request create")
+ }
+
+ url := fmt.Sprintf("%s/repositories/%s/pullrequests", p.APIURL(instanceURL), repositoryID)
+ code, _, body, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(payload),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "POST %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to create pull request from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to create pull request from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var resp struct {
+ Links struct {
+ HTML struct {
+ Href string `json:"href"`
+ } `json:"html"`
+ } `json:"links"`
+ }
+ if err := json.Unmarshal([]byte(body), &resp); err != nil {
+ return nil, err
+ }
+
+ return &vcs.PullRequest{
+ URL: resp.Links.HTML.Href,
+ }, nil
+}
+
+// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
+//
+// WARNING: This is not supported in Bitbucket Cloud.
+func (*Provider) UpsertEnvironmentVariable(context.Context, common.OauthContext, string, string, string, string) error {
+ return errors.New("not supported")
+}
+
+// CreateWebhook creates a webhook in the repository with given payload.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-post
+func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
+ url := fmt.Sprintf("%s/repositories/%s/hooks", p.APIURL(instanceURL), repositoryID)
+ code, _, body, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(payload),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return "", errors.Wrapf(err, "POST %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return "", common.Errorf(common.NotFound, "failed to create webhook through URL %s", url)
+ }
+
+ // Bitbucket Cloud returns 201 HTTP status codes upon successful webhook creation,
+ // see https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-post-responses for details.
+ if code != http.StatusCreated {
+ return "", errors.Errorf("failed to create webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ var resp struct {
+ UUID string `json:"uuid"`
+ }
+ if err = json.Unmarshal([]byte(body), &resp); err != nil {
+ return "", errors.Wrap(err, "unmarshal body")
+ }
+ return resp.UUID, nil
+}
+
+// PatchWebhook patches the webhook in the repository with given payload.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-uid-put
+func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error {
+ url := fmt.Sprintf("%s/repositories/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
+ code, _, body, err := oauth.Put(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(payload),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "PUT %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to patch webhook through URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+ return nil
+}
+
+// DeleteWebhook deletes the webhook from the repository.
+//
+// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-uid-delete
+func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string) error {
+ url := fmt.Sprintf("%s/repositories/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
+ code, _, body, err := oauth.Delete(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "DELETE %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil // It is OK if the webhook has already gone
+ } else if code >= 300 {
+ return errors.Errorf("failed to delete webhook through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+ return nil
+}
+
+// oauthContext is the request context for refreshing OAuth token.
+type oauthContext struct {
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ RefreshToken string `json:"refresh_token"`
+ GrantType string `json:"grant_type"`
+}
+
+type refreshOAuthResponse struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ ExpiresIn int64 `json:"expires_in"`
+ // token_type, scope are not used.
+}
+
+func tokenRefresher(instanceURL string, oauthCtx oauthContext, refresher common.TokenRefresher) oauth.TokenRefresher {
+ return func(ctx context.Context, client *http.Client, oldToken *string) error {
+ form := &url.Values{}
+ form.Set("grant_type", "refresh_token")
+ form.Set("refresh_token", oauthCtx.RefreshToken)
+ url := fmt.Sprintf("%s/site/oauth2/access_token", instanceURL)
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(form.Encode()))
+ if err != nil {
+ return errors.Wrapf(err, "construct POST %s", url)
+ }
+ digested := base64.StdEncoding.EncodeToString([]byte(oauthCtx.ClientID + ":" + oauthCtx.ClientSecret))
+ req.Header.Set("Authorization", digested)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return errors.Wrapf(err, "POST %s", url)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return errors.Wrapf(err, "read body of POST %s", url)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ return errors.Errorf("non-200 POST %s status code %d with body %q", url, resp.StatusCode, body)
+ }
+
+ var r refreshOAuthResponse
+ if err = json.Unmarshal(body, &r); err != nil {
+ return errors.Wrapf(err, "unmarshal body from POST %s", url)
+ }
+
+ // Update the old token to new value for retries.
+ *oldToken = r.AccessToken
+
+ expireAt := time.Now().Add(time.Duration(r.ExpiresIn) * time.Second).Unix()
+ return refresher(r.AccessToken, r.RefreshToken, expireAt)
+ }
+}
diff --git a/backend/plugin/vcs/bitbucket/bitbucket_test.go b/backend/plugin/vcs/bitbucket/bitbucket_test.go
new file mode 100644
index 0000000000..2e97e3f4fb
--- /dev/null
+++ b/backend/plugin/vcs/bitbucket/bitbucket_test.go
@@ -0,0 +1,932 @@
+package bitbucket
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
+)
+
+func TestProvider_ExchangeOAuthToken(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/site/oauth2/access_token", r.URL.Path)
+ assert.Equal(t, "dGVzdF9jbGllbnRfaWQ6dGVzdF9jbGllbnRfc2VjcmV0", r.Header.Get("Authorization"))
+
+ require.NoError(t, r.ParseForm())
+ assert.Equal(t, "authorization_code", r.PostForm.Get("grant_type"))
+ assert.Equal(t, "test_code", r.PostForm.Get("code"))
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "access_token": "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54",
+ "token_type": "bearer",
+ "expires_in": 3600,
+ "refresh_token": "8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1"
+}
+`)),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.ExchangeOAuthToken(ctx, "",
+ &common.OAuthExchange{
+ ClientID: "test_client_id",
+ ClientSecret: "test_client_secret",
+ Code: "test_code",
+ RedirectURL: "http://localhost:3000",
+ },
+ )
+ require.NoError(t, err)
+
+ // We use time.Now() to compute the values of CreatedAt and ExpiresTs so there
+ // is no point to assert.
+ got.CreatedAt = 0
+ got.ExpiresTs = 0
+
+ want := &vcs.OAuthToken{
+ AccessToken: "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54",
+ RefreshToken: "8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1",
+ ExpiresIn: 3600,
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_FetchCommitByID(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/bitbucket/geordi/commit/f7591a1", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-commit-commit-get
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "rendered": {
+ "message": {
+ "raw": "Add a GEORDI_OUTPUT_DIR setting",
+ "markup": "markdown",
+ "html": "<p>Add a GEORDI_OUTPUT_DIR setting</p>",
+ "type": "rendered"
+ }
+ },
+ "hash": "f7591a13eda445d9a9167f98eb870319f4b6c2d8",
+ "repository": {
+ "name": "geordi",
+ "type": "repository",
+ "full_name": "bitbucket/geordi",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi"
+ },
+ "html": {
+ "href": "https://bitbucket.org/bitbucket/geordi"
+ },
+ "avatar": {
+ "href": "https://bytebucket.org/ravatar/%7B85d08b4e-571d-44e9-a507-fa476535aa98%7D?ts=1730260"
+ }
+ },
+ "uuid": "{85d08b4e-571d-44e9-a507-fa476535aa98}"
+ },
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
+ },
+ "comments": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8/comments"
+ },
+ "patch": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/patch/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
+ },
+ "html": {
+ "href": "https://bitbucket.org/bitbucket/geordi/commits/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
+ },
+ "diff": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/diff/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
+ },
+ "approve": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8/approve"
+ },
+ "statuses": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8/statuses"
+ }
+ },
+ "author": {
+ "raw": "Brodie Rao <[email protected]>",
+ "type": "author",
+ "user": {
+ "display_name": "Brodie Rao",
+ "uuid": "{9484702e-c663-4afd-aefb-c93a8cd31c28}",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/users/%7B9484702e-c663-4afd-aefb-c93a8cd31c28%7D"
+ },
+ "html": {
+ "href": "https://bitbucket.org/%7B9484702e-c663-4afd-aefb-c93a8cd31c28%7D/"
+ },
+ "avatar": {
+ "href": "https://avatar-management--avatars.us-west-2.prod.public.atl-paas.net/557058:3aae1e05-702a-41e5-81c8-f36f29afb6ca/613070db-28b0-421f-8dba-ae8a87e2a5c7/128"
+ }
+ },
+ "type": "user",
+ "nickname": "brodie",
+ "account_id": "557058:3aae1e05-702a-41e5-81c8-f36f29afb6ca"
+ }
+ },
+ "summary": {
+ "raw": "Add a GEORDI_OUTPUT_DIR setting",
+ "markup": "markdown",
+ "html": "<p>Add a GEORDI_OUTPUT_DIR setting</p>",
+ "type": "rendered"
+ },
+ "participants": [],
+ "parents": [
+ {
+ "type": "commit",
+ "hash": "f06941fec4ef6bcb0c2456927a0cf258fa4f899b",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f06941fec4ef6bcb0c2456927a0cf258fa4f899b"
+ },
+ "html": {
+ "href": "https://bitbucket.org/bitbucket/geordi/commits/f06941fec4ef6bcb0c2456927a0cf258fa4f899b"
+ }
+ }
+ }
+ ],
+ "date": "2012-07-16T19:37:54+00:00",
+ "message": "Add a GEORDI_OUTPUT_DIR setting",
+ "type": "commit"
+}
+`)),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.FetchCommitByID(ctx, common.OauthContext{}, bitbucketCloudURL, "bitbucket/geordi", "f7591a1")
+ require.NoError(t, err)
+
+ want := &vcs.Commit{
+ ID: "f7591a13eda445d9a9167f98eb870319f4b6c2d8",
+ AuthorName: "Brodie Rao",
+ CreatedTs: 1342467474,
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_GetDiffFileList(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/1/diffstat/after_sha..before_sha", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#sample-output
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "pagelen": 500,
+ "values": [
+ {
+ "type": "diffstat",
+ "status": "modified",
+ "lines_removed": 1,
+ "lines_added": 2,
+ "old": {
+ "path": "setup.py",
+ "escaped_path": "setup.py",
+ "type": "commit_file",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/src/e1749643d655d7c7014001a6c0f58abaf42ad850/setup.py"
+ }
+ }
+ },
+ "new": {
+ "path": "setup.py",
+ "escaped_path": "setup.py",
+ "type": "commit_file",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/src/d222fa235229c55dad20b190b0b571adf737d5a6/setup.py"
+ }
+ }
+ }
+ }
+ ],
+ "page": 1,
+ "size": 1
+}
+`)),
+ }, nil
+ },
+ )
+ ctx := context.Background()
+ got, err := p.GetDiffFileList(ctx, common.OauthContext{}, bitbucketCloudURL, "1", "before_sha", "after_sha")
+ require.NoError(t, err)
+
+ want := []vcs.FileDiff{
+ {
+ Path: "setup.py",
+ Type: vcs.FileDiffTypeModified,
+ },
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_FetchAllRepositoryList(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/user/permissions/repositories", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-user-permissions-repositories-get
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "pagelen": 10,
+ "values": [
+ {
+ "type": "repository_permission",
+ "user": {
+ "type": "user",
+ "nickname": "evzijst",
+ "display_name": "Erik van Zijst",
+ "uuid": "{d301aafa-d676-4ee0-88be-962be7417567}"
+ },
+ "repository": {
+ "type": "repository",
+ "name": "geordi",
+ "full_name": "bitbucket/geordi",
+ "uuid": "{85d08b4e-571d-44e9-a507-fa476535aa98}"
+ },
+ "permission": "admin"
+ }
+ ],
+ "page": 1,
+ "size": 1
+}
+`)),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.FetchAllRepositoryList(ctx, common.OauthContext{}, bitbucketCloudURL)
+ require.NoError(t, err)
+
+ want := []*vcs.Repository{
+ {
+ ID: "{85d08b4e-571d-44e9-a507-fa476535aa98}",
+ Name: "geordi",
+ FullPath: "bitbucket/geordi",
+ WebURL: "https://bitbucket.org/bitbucket/geordi",
+ },
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_FetchRepositoryFileList(t *testing.T) {
+ // Example response derived from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#directory-listings
+ const response = `
+{
+ "pagelen": 10,
+ "values": [
+ {
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py"
+ },
+ "meta": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py?format=meta"
+ }
+ },
+ "path": "tests/__init__.py",
+ "commit": {
+ "type": "commit",
+ "hash": "eefd5ef5d3df01aed629f650959d6706d54cd335",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/commit/eefd5ef5d3df01aed629f650959d6706d54cd335"
+ },
+ "html": {
+ "href": "https://bitbucket.org/atlassian/bbql/commits/eefd5ef5d3df01aed629f650959d6706d54cd335"
+ }
+ }
+ },
+ "attributes": [],
+ "type": "commit_file",
+ "size": 0
+ }
+ ],
+ "page": 1,
+ "size": 1
+}
+`
+ t.Run("no path prefix", func(t *testing.T) {
+ ctx := context.Background()
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(response)),
+ }, nil
+ })
+
+ got, err := p.FetchRepositoryFileList(ctx, common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "eefd5ef", "")
+ require.NoError(t, err)
+
+ want := []*vcs.RepositoryTreeNode{
+ {
+ Path: "tests/__init__.py",
+ Type: "commit_file",
+ },
+ }
+ assert.Equal(t, want, got)
+ })
+
+ t.Run("has path prefix", func(t *testing.T) {
+ ctx := context.Background()
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/tests", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(response)),
+ }, nil
+ })
+
+ got, err := p.FetchRepositoryFileList(ctx, common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "eefd5ef", "tests")
+ require.NoError(t, err)
+
+ // Non-blob type should be excluded
+ want := []*vcs.RepositoryTreeNode{
+ {
+ Path: "tests/__init__.py",
+ Type: "commit_file",
+ },
+ }
+ assert.Equal(t, want, got)
+ })
+}
+
+func TestProvider_CreateFile(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/username/slug/src", r.URL.Path)
+ assert.Equal(t, "Initial+commit", r.URL.Query().Get("message"))
+ assert.Empty(t, r.URL.Query().Get("parents"))
+ assert.Equal(t, "main", r.URL.Query().Get("branch"))
+
+ body, err := io.ReadAll(r.Body)
+ require.NoError(t, err)
+ wantBodyContains := "Content-Disposition: form-data; name=\"filename\"; filename=\"repo/path/to/image.png\"\r\nContent-Type: application/octet-stream\r\n\r\n#!/bin/sh\nhalt"
+ assert.Contains(t, string(body), wantBodyContains)
+ return &http.Response{
+ StatusCode: http.StatusCreated,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ err := p.CreateFile(
+ ctx,
+ common.OauthContext{},
+ bitbucketCloudURL,
+ "username/slug",
+ "repo/path/to/image.png",
+ vcs.FileCommitCreate{
+ Branch: "main",
+ Content: "#!/bin/sh\nhalt",
+ CommitMessage: "Initial commit",
+ },
+ )
+ require.NoError(t, err)
+}
+
+func TestProvider_OverwriteFile(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/username/slug/src", r.URL.Path)
+ assert.Equal(t, "Initial+commit", r.URL.Query().Get("message"))
+ assert.Equal(t, "7638417db6d59f3c431d3e1f261cc637155684cd", r.URL.Query().Get("parents"))
+ assert.Equal(t, "main", r.URL.Query().Get("branch"))
+
+ body, err := io.ReadAll(r.Body)
+ require.NoError(t, err)
+ wantBodyContains := "Content-Disposition: form-data; name=\"filename\"; filename=\"repo/path/to/image.png\"\r\nContent-Type: application/octet-stream\r\n\r\n#!/bin/sh\nhalt"
+ assert.Contains(t, string(body), wantBodyContains)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ err := p.OverwriteFile(
+ ctx,
+ common.OauthContext{},
+ bitbucketCloudURL,
+ "username/slug",
+ "repo/path/to/image.png",
+ vcs.FileCommitCreate{
+ Branch: "main",
+ Content: "#!/bin/sh\nhalt",
+ CommitMessage: "Initial commit",
+ LastCommitID: "7638417db6d59f3c431d3e1f261cc637155684cd",
+ },
+ )
+ require.NoError(t, err)
+}
+
+func TestProvider_ReadFileMeta(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/tests/__init__.py", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response derived from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#file-meta-data
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py"
+ },
+ "meta": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py?format=meta"
+ }
+ },
+ "path": "tests/__init__.py",
+ "commit": {
+ "type": "commit",
+ "hash": "eefd5ef5d3df01aed629f650959d6706d54cd335",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/commit/eefd5ef5d3df01aed629f650959d6706d54cd335"
+ },
+ "html": {
+ "href": "https://bitbucket.org/atlassian/bbql/commits/eefd5ef5d3df01aed629f650959d6706d54cd335"
+ }
+ }
+ },
+ "attributes": [],
+ "type": "commit_file",
+ "size": 100
+}
+`)),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.ReadFileMeta(ctx, common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "tests/__init__.py", "eefd5ef")
+ require.NoError(t, err)
+
+ want := &vcs.FileMeta{
+ Name: "__init__.py",
+ Path: "tests/__init__.py",
+ Size: 100,
+ LastCommitID: "eefd5ef5d3df01aed629f650959d6706d54cd335",
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_ReadFileContent(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/tests/__init__.py", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("#!/bin/sh\nhalt")),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.ReadFileContent(ctx, common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "tests/__init__.py", "eefd5ef")
+ require.NoError(t, err)
+
+ want := "#!/bin/sh\nhalt"
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_GetBranch(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/atlassian/aui/refs/branches/master", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-name-get
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "name": "master",
+ "links": {
+ "commits": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commits/master"
+ },
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/refs/branches/master"
+ },
+ "html": {
+ "href": "https://bitbucket.org/atlassian/aui/branch/master"
+ }
+ },
+ "default_merge_strategy": "squash",
+ "merge_strategies": [
+ "merge_commit",
+ "squash",
+ "fast_forward"
+ ],
+ "type": "branch",
+ "target": {
+ "hash": "e7d158ff7ed5538c28f94cd97a9ad569680fc94e",
+ "repository": {
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui"
+ },
+ "html": {
+ "href": "https://bitbucket.org/atlassian/aui"
+ },
+ "avatar": {
+ "href": "https://bytebucket.org/ravatar/%7B585074de-7b60-4fd1-81ed-e0bc7fafbda5%7D?ts=86317"
+ }
+ },
+ "type": "repository",
+ "name": "aui",
+ "full_name": "atlassian/aui",
+ "uuid": "{585074de-7b60-4fd1-81ed-e0bc7fafbda5}"
+ },
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
+ },
+ "comments": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e/comments"
+ },
+ "patch": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/patch/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
+ },
+ "html": {
+ "href": "https://bitbucket.org/atlassian/aui/commits/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
+ },
+ "diff": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/diff/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
+ },
+ "approve": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e/approve"
+ },
+ "statuses": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e/statuses"
+ }
+ },
+ "author": {
+ "raw": "psre-renovate-bot <[email protected]>",
+ "type": "author",
+ "user": {
+ "display_name": "psre-renovate-bot",
+ "uuid": "{250a442a-3ab3-4fcb-87c3-3c8f3df65ec7}",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/users/%7B250a442a-3ab3-4fcb-87c3-3c8f3df65ec7%7D"
+ },
+ "html": {
+ "href": "https://bitbucket.org/%7B250a442a-3ab3-4fcb-87c3-3c8f3df65ec7%7D/"
+ },
+ "avatar": {
+ "href": "https://secure.gravatar.com/avatar/6972ee037c9f36360170a86f544071a2?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FP-3.png"
+ }
+ },
+ "nickname": "Renovate Bot",
+ "type": "user",
+ "account_id": "5d5355e8c6b9320d9ea5b28d"
+ }
+ },
+ "parents": [
+ {
+ "hash": "eab868a309e75733de80969a7bed1ec6d4651e06",
+ "type": "commit",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/eab868a309e75733de80969a7bed1ec6d4651e06"
+ },
+ "html": {
+ "href": "https://bitbucket.org/atlassian/aui/commits/eab868a309e75733de80969a7bed1ec6d4651e06"
+ }
+ }
+ }
+ ],
+ "date": "2021-04-12T06:44:38+00:00",
+ "message": "Merged in issue/NONE-renovate-master-babel-monorepo (pull request #2883)",
+ "type": "commit"
+ }
+}
+`)),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.GetBranch(ctx, common.OauthContext{}, bitbucketCloudURL, "atlassian/aui", "master")
+ require.NoError(t, err)
+
+ want := &vcs.BranchInfo{
+ Name: "master",
+ LastCommitID: "e7d158ff7ed5538c28f94cd97a9ad569680fc94e",
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_CreateBranch(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/seanfarley/hg/refs/branches", r.URL.Path)
+
+ body, err := io.ReadAll(r.Body)
+ require.NoError(t, err)
+ wantBody := `{"name":"smf/create-feature","target":{"hash":"aa218f56b14c9653891f9e74264a383fa43fefbd"}}`
+ assert.Equal(t, wantBody, string(body))
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ err := p.CreateBranch(
+ ctx,
+ common.OauthContext{},
+ bitbucketCloudURL,
+ "seanfarley/hg",
+ &vcs.BranchInfo{
+ Name: "smf/create-feature",
+ LastCommitID: "aa218f56b14c9653891f9e74264a383fa43fefbd",
+ },
+ )
+ require.NoError(t, err)
+}
+
+func TestProvider_ListPullRequestFile(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/1/pullrequests/10086/diffstat", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#sample-output
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "pagelen": 500,
+ "values": [
+ {
+ "type": "diffstat",
+ "status": "modified",
+ "lines_removed": 1,
+ "lines_added": 2,
+ "old": {
+ "path": "setup.py",
+ "escaped_path": "setup.py",
+ "type": "commit_file",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/src/e1749643d655d7c7014001a6c0f58abaf42ad850/setup.py"
+ }
+ }
+ },
+ "new": {
+ "path": "setup.py",
+ "escaped_path": "setup.py",
+ "type": "commit_file",
+ "links": {
+ "self": {
+ "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/src/d222fa235229c55dad20b190b0b571adf737d5a6/setup.py"
+ }
+ }
+ }
+ }
+ ],
+ "page": 1,
+ "size": 1
+}
+`)),
+ }, nil
+ },
+ )
+ ctx := context.Background()
+ got, err := p.ListPullRequestFile(ctx, common.OauthContext{}, bitbucketCloudURL, "1", "10086")
+ require.NoError(t, err)
+
+ want := []*vcs.PullRequestFile{
+ {
+ Path: "setup.py",
+ LastCommitID: "d222fa235229c55dad20b190b0b571adf737d5a6",
+ IsDeleted: false,
+ },
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_CreatePullRequest(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/octocat/Hello-World/pullrequests", r.URL.Path)
+
+ body, err := io.ReadAll(r.Body)
+ require.NoError(t, err)
+ wantBody := `{"title":"Amazing new feature","description":"Please pull these awesome changes in!","close_source_branch":true,"source":{"branch":{"name":"new-topic"}},"destination":{"branch":{"name":"master"}}}`
+ assert.Equal(t, wantBody, string(body))
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "links": {
+ "self": {
+ "href": "<string>",
+ "name": "<string>"
+ },
+ "html": {
+ "href": "https://bitbucket.org/octocat/Hello-World/pull-requests/108"
+ }
+ },
+ "id": 108,
+ "title": "Amazing new feature",
+ "state": "OPEN",
+ "source": {
+ "branch": {
+ "name": "new-topic",
+ "merge_strategies": [
+ "merge_commit"
+ ]
+ }
+ },
+ "destination": {
+ "branch": {
+ "name": "master",
+ "merge_strategies": [
+ "merge_commit"
+ ]
+ }
+ },
+ "comment_count": 51,
+ "task_count": 53,
+ "close_source_branch": true
+}
+`)),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.CreatePullRequest(
+ ctx,
+ common.OauthContext{},
+ bitbucketCloudURL,
+ "octocat/Hello-World",
+ &vcs.PullRequestCreate{
+ Title: "Amazing new feature",
+ Body: "Please pull these awesome changes in!",
+ Head: "new-topic",
+ Base: "master",
+ RemoveHeadAfterMerged: true,
+ },
+ )
+ require.NoError(t, err)
+ assert.Equal(t, "https://bitbucket.org/octocat/Hello-World/pull-requests/108", got.URL)
+}
+
+func TestProvider_CreateWebhook(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, "/2.0/repositories/1/hooks", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusCreated,
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "uuid": "6611a7e9-6890-4e8e-84c5-b9707397da8b",
+ "description": "Webhook Description",
+ "url": "https://example.com/",
+ "subject_type": "repository",
+ "active": true,
+ "events": [
+ "repo:push",
+ "issue:created",
+ "issue:updated"
+ ]
+}
+`)),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.CreateWebhook(
+ ctx,
+ common.OauthContext{},
+ bitbucketCloudURL,
+ "1",
+ []byte(`
+{
+ "description": "Webhook Description",
+ "url": "https://example.com/",
+ "active": true,
+ "events": [
+ "repo:push",
+ "issue:created",
+ "issue:updated"
+ ]
+}`),
+ )
+ require.NoError(t, err)
+ assert.Equal(t, "6611a7e9-6890-4e8e-84c5-b9707397da8b", got)
+}
+
+func TestProvider_PatchWebhook(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, http.MethodPut, r.Method)
+ assert.Equal(t, "/2.0/repositories/1/hooks/1", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ err := p.PatchWebhook(ctx, common.OauthContext{}, bitbucketCloudURL, "1", "1", []byte(""))
+ require.NoError(t, err)
+}
+
+func TestProvider_DeleteWebhook(t *testing.T) {
+ p := newMockProvider(func(r *http.Request) (*http.Response, error) {
+ assert.Equal(t, http.MethodDelete, r.Method)
+ assert.Equal(t, "/2.0/repositories/1/hooks/1", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("")),
+ }, nil
+ },
+ )
+
+ ctx := context.Background()
+ err := p.DeleteWebhook(ctx, common.OauthContext{}, bitbucketCloudURL, "1", "1")
+ require.NoError(t, err)
+}
+
+func TestOAuth_RefreshToken(t *testing.T) {
+ ctx := context.Background()
+ client := &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {
+ token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ if token == "expired" {
+ return &http.Response{
+ StatusCode: http.StatusUnauthorized,
+ Body: io.NopCloser(strings.NewReader(`
+ {"error":"invalid_token","error_description":"Token is expired. You can either do re-authorization or token refresh."}
+ `)),
+ }, nil
+ }
+
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "access_token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a",
+ "expires_in": 3600,
+ "refresh_token": "ghr_1B4a2e77838347a7E420ce178F2E7c6912E169246c34E1ccbF66C46812d16D5B1A9Dc86A1498"
+}
+`)),
+ }, nil
+ },
+ },
+ }
+ token := "expired"
+
+ calledRefresher := false
+ refresher := func(_, _ string, _ int64) error {
+ calledRefresher = true
+ return nil
+ }
+
+ _, _, _, err := oauth.Get(
+ ctx,
+ client,
+ "https://https://api.bitbucket.org/2.0/user",
+ &token,
+ tokenRefresher(
+ bitbucketCloudURL,
+ oauthContext{},
+ refresher,
+ ),
+ )
+ require.NoError(t, err)
+ assert.Equal(t, "ghu_16C7e42F292c6912E7710c838347Ae178B4a", token)
+ assert.True(t, calledRefresher)
+}
+
+func newMockProvider(mockRoundTrip func(r *http.Request) (*http.Response, error)) vcs.Provider {
+ return newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: mockRoundTrip,
+ },
+ },
+ },
+ )
+}
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index 7c594cb597..6b27e056d5 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -967,7 +967,7 @@ func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthC
),
)
if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
+ return nil, errors.Wrapf(err, "POST %s", url)
}
if code == http.StatusNotFound {
diff --git a/backend/plugin/vcs/vcs.go b/backend/plugin/vcs/vcs.go
index a4de5a5043..c2d37823c5 100644
--- a/backend/plugin/vcs/vcs.go
+++ b/backend/plugin/vcs/vcs.go
@@ -22,6 +22,8 @@ const (
GitLab Type = "GITLAB"
// GitHub is the VCS type for GitHub (both GitHub.com and GitHun Enterprise).
GitHub Type = "GITHUB"
+ // Bitbucket is the VCS type for Bitbucket Cloud (bitbucket.org).
+ Bitbucket Type = "BITBUCKET"
// SQLReviewAPISecretName is the api secret name used in GitHub action or GitLab CI workflow.
SQLReviewAPISecretName = "SQL_REVIEW_API_SECRET"