Skip to content

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

chore: bitbucket push event (#11427)

Danny Xu47a22b419d31
diff --git a/backend/api/gitops/bitbucket.go b/backend/api/gitops/bitbucket.go
new file mode 100644
index 0000000000..1201854fc2
--- /dev/null
+++ b/backend/api/gitops/bitbucket.go
@@ -0,0 +1,63 @@
+package gitops
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "path/filepath"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func getBitBucketPullRequestInfo(ctx context.Context, vcsProvider *store.VCSProviderMessage, vcsConnector *store.VCSConnectorMessage, body []byte) (*pullRequestInfo, error) {
+ var pushEvent bitbucket.PullRequestPushEvent
+ if err := json.Unmarshal(body, &pushEvent); err != nil {
+ return nil, errors.Errorf("failed to unmarshal push event, error %v", err)
+ }
+
+ if pushEvent.PullRequest.Destination.Branch.Name != vcsConnector.Payload.Branch {
+ return nil, errors.Errorf("committed to branch %q, want branch %q", pushEvent.PullRequest.Destination.Branch.Name, vcsConnector.Payload.Branch)
+ }
+
+ mrFiles, err := vcs.Get(vcs.Bitbucket, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).ListPullRequestFile(ctx, vcsConnector.Payload.ExternalId, fmt.Sprintf("%d", pushEvent.PullRequest.ID))
+ if err != nil {
+ return nil, errors.Errorf("failed to list merge %q request files, error %v", pushEvent.PullRequest.Links.HTML.Href, err)
+ }
+
+ prInfo := &pullRequestInfo{
+ // email. How do we determine the user for BitBucket user?
+ url: pushEvent.PullRequest.Links.HTML.Href,
+ title: pushEvent.PullRequest.Title,
+ description: pushEvent.PullRequest.Description,
+ }
+ for _, v := range mrFiles {
+ if v.IsDeleted {
+ continue
+ }
+ if filepath.Dir(v.Path) != vcsConnector.Payload.BaseDirectory {
+ continue
+ }
+ change, err := getFileChange(v.Path)
+ if err != nil {
+ slog.Error("failed to get file change info", slog.String("path", v.Path), log.BBError(err))
+ }
+ if change != nil {
+ change.path = v.Path
+ prInfo.changes = append(prInfo.changes, change)
+ }
+ }
+ for _, file := range prInfo.changes {
+ content, err := vcs.Get(vcs.Bitbucket, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).ReadFileContent(ctx, vcsConnector.Payload.ExternalId, file.path, vcs.RefInfo{RefType: vcs.RefTypeCommit, RefName: pushEvent.PullRequest.Source.Commit.Hash})
+ if err != nil {
+ return nil, errors.Errorf("failed read file content, merge request %q, file %q, error %v", pushEvent.PullRequest.Links.HTML.Href, file.path, err)
+ }
+ file.content = content
+ }
+ return prInfo, nil
+}
diff --git a/backend/api/gitops/common.go b/backend/api/gitops/common.go
index b6047b54bc..96050f5910 100644
--- a/backend/api/gitops/common.go
+++ b/backend/api/gitops/common.go
@@ -45,14 +45,13 @@ func getFileChange(path string) (*fileChange, error) {
switch {
case strings.HasPrefix(description, "ddl"):
description = strings.TrimPrefix(description, "ddl")
- case strings.HasPrefix(description, "migrate"):
- description = strings.TrimPrefix(description, "migrate")
+ changeType = v1pb.Plan_ChangeDatabaseConfig_MIGRATE
case strings.HasPrefix(description, "dml"):
description = strings.TrimPrefix(description, "dml")
changeType = v1pb.Plan_ChangeDatabaseConfig_DATA
- case strings.HasPrefix(description, "data"):
- description = strings.TrimPrefix(description, "data")
- changeType = v1pb.Plan_ChangeDatabaseConfig_DATA
+ case strings.HasPrefix(description, "ghost"):
+ description = strings.TrimPrefix(description, "ghost")
+ changeType = v1pb.Plan_ChangeDatabaseConfig_MIGRATE_GHOST
}
description = strings.TrimLeft(description, "_-#")
return &fileChange{
diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.go
index e0488fd679..c8454c083a 100644
--- a/backend/api/gitops/webhook.go
+++ b/backend/api/gitops/webhook.go
@@ -109,6 +109,20 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {
if err != nil {
return c.String(http.StatusOK, fmt.Sprintf("failed to get pr info from pull request, error %v", err))
}
+ case vcs.Bitbucket:
+ eventType := c.Request().Header.Get("X-Event-Key")
+ switch eventType {
+ case "pullrequest:created", "pullrequest:updated":
+ return c.String(http.StatusOK, "OK")
+ case "pullrequest:fulfilled":
+ default:
+ return c.String(http.StatusOK, "OK")
+ }
+
+ prInfo, err = getBitBucketPullRequestInfo(ctx, vcsProvider, vcsConnector, body)
+ if err != nil {
+ return c.String(http.StatusOK, fmt.Sprintf("failed to get pr info from pull request, error %v", err))
+ }
default:
return nil
}
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index 00c4c244b6..5ba4bad88b 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -89,6 +89,11 @@ type CommitDiffStat struct {
New CommitFile `json:"new"`
}
+type PullRequestResponse struct {
+ Values []*CommitDiffStat `json:"values"`
+ Next string `json:"next"`
+}
+
func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, url string) (diffs []*CommitDiffStat, next string, err error) {
code, body, err := internal.Get(ctx, url, p.getAuthorization())
if err != nil {
@@ -105,10 +110,7 @@ func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, url string) (
)
}
- var resp struct {
- Values []*CommitDiffStat `json:"values"`
- Next string `json:"next"`
- }
+ var resp PullRequestResponse
if err := json.Unmarshal([]byte(body), &resp); err != nil {
return nil, "", errors.Wrapf(err, "failed to unmarshal file diff data from Bitbucket Cloud instance %s", url)
}
@@ -273,7 +275,7 @@ func (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName strin
// 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, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
var bbcDiffs []*CommitDiffStat
- next := fmt.Sprintf("%s/repositories/%s/pullrequests/%s/diffstat?pagelen=%d", p.APIURL(p.instanceURL), url.PathEscape(repositoryID), pullRequestID, apiPageSize)
+ next := fmt.Sprintf("%s/repositories/%s/pullrequests/%s/diffstat?pagelen=%d", p.APIURL(p.instanceURL), repositoryID, pullRequestID, apiPageSize)
for next != "" {
var err error
var diffs []*CommitDiffStat
diff --git a/backend/plugin/vcs/bitbucket/webhook_events.go b/backend/plugin/vcs/bitbucket/webhook_events.go
new file mode 100644
index 0000000000..92eb90c14d
--- /dev/null
+++ b/backend/plugin/vcs/bitbucket/webhook_events.go
@@ -0,0 +1,39 @@
+package bitbucket
+
+// Header X-Event-Key: pullrequest:created, pullrequest:updated, pullrequest:fulfilled.
+
+// PullRequestPushEvent is the json message for pull request push event.
+type PullRequestPushEvent struct {
+ // Actor: does not include email.
+ PullRequest EventPullRequest `json:"pullrequest"`
+}
+
+type EventPullRequest struct {
+ ID int `json:"id"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Destination EventBranch `json:"destination"`
+ Source EventBranch `json:"source"`
+ Links EventLinks `json:"links"`
+}
+
+type EventBranch struct {
+ Branch EventBranchName `json:"branch"`
+ Commit EventCommit `json:"commit"`
+}
+
+type EventBranchName struct {
+ Name string `json:"name"`
+}
+
+type EventCommit struct {
+ Hash string `json:"hash"`
+}
+
+type EventLinks struct {
+ HTML EventHTML `json:"html"`
+}
+
+type EventHTML struct {
+ Href string `json:"href"`
+}
diff --git a/backend/tests/fake/bitbucket.go b/backend/tests/fake/bitbucket.go
index 440db735ae..125bd9da80 100644
--- a/backend/tests/fake/bitbucket.go
+++ b/backend/tests/fake/bitbucket.go
@@ -40,6 +40,11 @@ type bitbucketRepositoryData struct {
// diffStats is the map for commits compare. The map key has the format
// "to..from" which is SHA or branch name.
diffStats map[string][]*bitbucket.CommitDiffStat
+ // pullRequests is the map for repository pull request.
+ // the map key is the pull request id.
+ pullRequests map[int]struct {
+ Files []*bitbucket.CommitDiffStat
+ }
}
// NewBitbucket creates a new fake implementation of Bitbucket VCS provider.
@@ -60,6 +65,7 @@ func NewBitbucket(port int) VCSProvider {
g.POST("/repositories/:owner/:repo/src", bb.createRepositoryFile)
g.GET("/repositories/:owner/:repo/refs/branches/:branchName", bb.getRepositoryBranch)
g.GET("/repositories/:owner/:repo/diffstat/:baseHead", bb.compareCommits)
+ g.GET("/repositories/:owner/:repo/pullrequests/:prID/diffstat", bb.listPullRequestFile)
return bb
}
@@ -221,6 +227,9 @@ func (bb *Bitbucket) CreateRepository(id string) {
files: make(map[string]string),
refs: map[string]*bitbucket.Branch{},
diffStats: map[string][]*bitbucket.CommitDiffStat{},
+ pullRequests: map[int]struct {
+ Files []*bitbucket.CommitDiffStat
+ }{},
}
}
@@ -341,6 +350,56 @@ func (bb *Bitbucket) GetFiles(repositoryID string, filePaths ...string) (map[str
}
// AddPullRequest creates a new pull request and add changed files to it.
-func (*Bitbucket) AddPullRequest(string, int, []*vcs.PullRequestFile) error {
- return errors.New("not implemented yet")
+func (bb *Bitbucket) AddPullRequest(repositoryID string, prID int, files []*vcs.PullRequestFile) error {
+ r, ok := bb.repositories[repositoryID]
+ if !ok {
+ return errors.Errorf("Bitbucket repository %q does not exist", repositoryID)
+ }
+ var pullRequestFiles []*bitbucket.CommitDiffStat
+ for _, file := range files {
+ status := "added"
+ if file.IsDeleted {
+ status = "removed"
+ }
+ pullRequestFiles = append(pullRequestFiles, &bitbucket.CommitDiffStat{
+ Status: status,
+ New: bitbucket.CommitFile{
+ Path: file.Path,
+ },
+ })
+ }
+
+ r.pullRequests[prID] = struct {
+ Files []*bitbucket.CommitDiffStat
+ }{
+ Files: pullRequestFiles,
+ }
+ return nil
+}
+
+func (bb *Bitbucket) listPullRequestFile(c echo.Context) error {
+ r, err := bb.validRepository(c)
+ if err != nil {
+ return err
+ }
+
+ prNumber, err := strconv.Atoi(c.Param("prID"))
+ if err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("The pull request id is invalid: %v", c.Param("prID")))
+ }
+
+ pullRequest, ok := r.pullRequests[prNumber]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("Cannot found the pull request: %v", c.Param("prID")))
+ }
+
+ rep := bitbucket.PullRequestResponse{
+ Values: pullRequest.Files,
+ }
+
+ buf, err := json.Marshal(rep)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
}
diff --git a/backend/tests/vcs_test.go b/backend/tests/vcs_test.go
index 9485335c5e..3bb2a842df 100644
--- a/backend/tests/vcs_test.go
+++ b/backend/tests/vcs_test.go
@@ -11,6 +11,7 @@ import (
"google.golang.org/protobuf/types/known/fieldmaskpb"
"github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket"
"github.com/bytebase/bytebase/backend/plugin/vcs/github"
"github.com/bytebase/bytebase/backend/plugin/vcs/gitlab"
"github.com/bytebase/bytebase/backend/tests/fake"
@@ -84,6 +85,27 @@ func TestVCS(t *testing.T) {
},
},
},
+ {
+ name: "Bitbucket",
+ vcsProviderCreator: fake.NewBitbucket,
+ vcsType: v1pb.VCSProvider_BITBUCKET,
+ externalID: "octocat/Hello-World",
+ repositoryFullPath: "octocat/Hello-World",
+ webhookPushEvent: bitbucket.PullRequestPushEvent{
+ PullRequest: bitbucket.EventPullRequest{
+ ID: pullRequestID,
+ Title: pullRequestTitle,
+ Description: pullRequestDescription,
+ Destination: bitbucket.EventBranch{
+ Branch: bitbucket.EventBranchName{Name: branchName},
+ },
+ Source: bitbucket.EventBranch{
+ Commit: bitbucket.EventCommit{Hash: "cc63b0592388a7ab1b05b005ad8c8dc14ce432b1"},
+ },
+ Links: bitbucket.EventLinks{HTML: bitbucket.EventHTML{Href: fmt.Sprintf("https://bitbucket.org/test/vcs/pull-requests/%d", pullRequestID)}},
+ },
+ },
+ },
}
for _, test := range tests {
// Fix the problem that closure in a for loop will always use the last element.