Skip to content

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

chore: cleanup code (#11419)

Danny Xu36a34751af9f
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index 1ef71542af..005c4032eb 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -123,6 +123,7 @@ type project struct {
Name string `json:"name"`
State string `json:"state"`
}
+
type repository struct {
ID string `json:"id"`
Name string `json:"name"`
@@ -161,11 +162,11 @@ type ChangesResponse struct {
Changes []ChangesResponseChange `json:"changes"`
}
-// GetChangesByCommit gets the changes by commit ID, and returns the list of blob files changed in the specify commit.
+// getChangesByCommit gets the changes by commit ID, and returns the list of blob files changed in the specify commit.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get-changes?view=azure-devops-rest-7.0&tabs=HTTP
// TODO(zp): We should GET the changes pagenated, otherwise it may hit the Azure DevOps API limit.
-func GetChangesByCommit(ctx context.Context, oauthCtx *common.OauthContext, externalRepositoryID, commitID string) (*ChangesResponse, error) {
+func getChangesByCommit(ctx context.Context, oauthCtx *common.OauthContext, externalRepositoryID, commitID string) (*ChangesResponse, error) {
client := &http.Client{}
apiURL, err := getRepositoryAPIURL(externalRepositoryID)
if err != nil {
@@ -476,7 +477,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
return nil, err
}
- changeResponse, err := GetChangesByCommit(ctx, oauthCtx, repositoryID, res.LastMergeCommit.CommitID)
+ changeResponse, err := getChangesByCommit(ctx, oauthCtx, repositoryID, res.LastMergeCommit.CommitID)
if err != nil {
return nil, err
}
@@ -559,190 +560,6 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthCont
return nil
}
-// CommitsInPushValue is the commit in the push.
-type CommitsInPushValue struct {
- CommitID string `json:"commitId"`
- RemoteURL string `json:"remoteUrl"`
-}
-
-// CommitsInPush is the commits in the push.
-type CommitsInPush struct {
- Value []CommitsInPushValue `json:"value"`
-}
-
-// GetPushCommitsByPushID gets the commits in the push by batch, it is useful when the push contains a lot of commits.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get-push-commits?view=azure-devops-rest-7.0&tabs=HTTP
-func GetPushCommitsByPushID(ctx context.Context, oauthCtx *common.OauthContext, repositoryID string, pushID uint64) (*CommitsInPush, error) {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return nil, err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- values.Set("pushId", fmt.Sprintf("%d", pushID))
- url := fmt.Sprintf("%s/commits?%s", apiURL, values.Encode())
-
- client := &http.Client{}
-
- code, _, body, err := oauth.Get(
- ctx,
- client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "failed to get push commits")
- }
- if code != http.StatusOK {
- return nil, errors.Errorf("failed to get push commits, code: %v, body: %s", code, string(body))
- }
-
- r := new(CommitsInPush)
- if err := json.Unmarshal([]byte(body), r); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal get push commits response body, code %v", code)
- }
-
- return r, nil
-}
-
-// PullRequest is the pull request.
-type PullRequest struct {
- ID uint64 `json:"pullRequestId"`
- Status string `json:"status"`
- TargetRefName string `json:"targetRefName"`
-}
-
-// QueryPullRequest queries the pull request by the last merge commit.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-query/get?view=azure-devops-rest-7.0#gitpullrequestqueryinput
-func QueryPullRequest(ctx context.Context, oauthCtx *common.OauthContext, repositoryID string, lastMergeCommit string) ([]*PullRequest, error) {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return nil, err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
-
- url := fmt.Sprintf("%s/pullrequestquery?%s", apiURL, values.Encode())
-
- client := &http.Client{}
- type pullRequestQueryInputQuery struct {
- Item []string `json:"items"`
- Type string `json:"type"`
- }
-
- type pullRequestQueryInput struct {
- Queries []pullRequestQueryInputQuery `json:"queries"`
- }
-
- b := pullRequestQueryInput{
- Queries: []pullRequestQueryInputQuery{
- {
- Item: []string{
- lastMergeCommit,
- },
- Type: "lastMergeCommit",
- },
- },
- }
-
- marshalBody, err := json.Marshal(b)
- if err != nil {
- return nil, errors.Wrap(err, "marshal pull request query input")
- }
-
- code, _, body, err := oauth.Post(ctx, client, url, oauthCtx.AccessToken, bytes.NewReader(marshalBody))
- if err != nil {
- return nil, errors.Wrapf(err, "failed to query pull request")
- }
-
- if code != http.StatusCreated {
- return nil, errors.Errorf("failed to query pull request, code: %v, body: %s", code, string(body))
- }
-
- type pullRequestQueryResponseMapElem struct {
- ID uint64 `json:"pullRequestId"`
- Status string `json:"status"`
- TargetRefName string `json:"targetRefName"`
- }
- type pullRequestQueryResponseResult map[string][]pullRequestQueryResponseMapElem
-
- type pullRequestQueryResponse struct {
- Results []pullRequestQueryResponseResult `json:"results"`
- }
-
- r := new(pullRequestQueryResponse)
- if err := json.Unmarshal([]byte(body), r); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal query pull request response body, code %v", code)
- }
-
- if len(r.Results) == 0 {
- return nil, nil
- }
- if len(r.Results) != 1 {
- return nil, errors.Errorf("expected one result, but got %d, body: %v", len(r.Results), string(body))
- }
- if len(r.Results[0]) != 1 {
- return nil, errors.Errorf("expected one element in result, but got %d, body: %v", len(r.Results[0]), string(body))
- }
-
- var result []*PullRequest
- for _, item := range r.Results[0] {
- for _, elem := range item {
- result = append(result, &PullRequest{
- ID: elem.ID,
- Status: elem.Status,
- TargetRefName: elem.TargetRefName,
- })
- }
- }
-
- return result, nil
-}
-
-// GetPullRequestCommits gets the commits in the pull request.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-commits/get-pull-request-commits?view=azure-devops-rest-7.0
-func GetPullRequestCommits(ctx context.Context, oauthCtx *common.OauthContext, repositoryID string, pullRequestID uint64) ([]ServiceHookCodePushEventResourceCommit, error) {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return nil, err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- url := fmt.Sprintf("%s/pullRequests/%d/commits?%s", apiURL, pullRequestID, values.Encode())
-
- client := &http.Client{}
-
- code, _, resp, err := oauth.Get(
- ctx,
- client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
- if code != http.StatusOK {
- return nil, errors.Errorf("failed to get pull request commits, code: %v, body: %s", code, string(resp))
- }
-
- type pullRequestCommitsResponse struct {
- Value []ServiceHookCodePushEventResourceCommit `json:"value"`
- }
-
- r := new(pullRequestCommitsResponse)
- if err := json.Unmarshal([]byte(resp), r); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal get pull request commits response body, code %v", code)
- }
-
- return r.Value, nil
-}
-
func getRepositoryAPIURL(repositoryID string) (string, error) {
// By design, we encode the repository ID as <organization>/<projectID>/<repositoryID> for Azure DevOps.
parts := strings.Split(repositoryID, "/")
diff --git a/backend/plugin/vcs/azure/sql_review.go b/backend/plugin/vcs/azure/sql_review.go
deleted file mode 100644
index b2e78b87b7..0000000000
--- a/backend/plugin/vcs/azure/sql_review.go
+++ /dev/null
@@ -1,228 +0,0 @@
-package azure
-
-import (
- "bytes"
- "context"
- _ "embed"
- "encoding/json"
- "fmt"
- "net/http"
- "net/url"
- "strings"
-
- "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"
-)
-
-// sqlReviewPipeline is the Azure pipeline for SQL review in VCS workflow.
-//
-//go:embed bytebase-sql-review.yml
-var sqlReviewPipeline string
-
-const (
- // SQLReviewPipelineFilePath is the SQL review pipeline file path.
- SQLReviewPipelineFilePath = ".pipelines/pipeline.bytebase-sql-review.yml"
- // sqlReviewPipelineName is the pipeline name for SQL review.
- sqlReviewPipelineName = "Bytebase SQL Review Pipeline"
-)
-
-// SetupSQLReviewCI will setup the SQL review CI content with SQL review endpoint.
-func SetupSQLReviewCI(endpoint, branch string) string {
- return fmt.Sprintf(sqlReviewPipeline, endpoint, branch, vcs.SQLReviewAPISecretName)
-}
-
-type pipeline struct {
- ID int `jsno:"id"`
- Name string `jsno:"name"`
-}
-
-type pipelineCreate struct {
- Name string `json:"name"`
- Configuration *pipelineConfig `json:"configuration"`
-}
-
-type pipelineRepository struct {
- ID string `json:"id"`
- Type string `json:"type"`
-}
-
-type pipelineConfig struct {
- Type string `json:"type"`
- Path string `json:"path"`
- Repository *pipelineRepository `json:"repository"`
- Variables map[string]*pipelineVariable `json:"variables"`
-}
-
-type pipelineVariable struct {
- Value string `json:"value"`
- IsSecret bool `json:"isSecret"`
- AllowOverride bool `json:"allowOverride"`
-}
-
-type branchPolicyCreate struct {
- IsBlocking bool `json:"isBlocking"`
- IsDeleted bool `json:"isDeleted"`
- IsEnabled bool `json:"isEnabled"`
- Settings *branchPolicySetting `json:"settings"`
- Type *policy `json:"type"`
-}
-
-type branchPolicySetting struct {
- // BuildDefinitionID is the pipeline ID.
- BuildDefinitionID int `json:"buildDefinitionId"`
- DisplayName string `json:"displayName"`
- ManualQueueOnly bool `json:"manualQueueOnly"`
- QueueOnSourceUpdateOnly bool `json:"queueOnSourceUpdateOnly"`
- Scope []*branchPolicyScope `json:"scope"`
- // ValidDuration is the expiration in minutes for build artifacts.
- ValidDuration int `json:"validDuration"`
-}
-
-type branchPolicyScope struct {
- // MatchKind should always be "Exact"
- MatchKind string `json:"matchKind"`
- // RefName is the target branch name.
- RefName string `json:"refName"`
- RepositoryID string `json:"repositoryId"`
-}
-
-// policy is the API message for azure policy.
-// It is hard code with specific id.
-// We can check all the policies in docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/policy/types/list?view=azure-devops-rest-7.1
-// For branch validation policy, we will hardcode the id as "0609b952-1397-4640-95ec-e00a01b2c241".
-type policy struct {
- ID string `json:"id"`
-}
-
-// EnableSQLReviewCI enables the SQL review pipeline and policy.
-func EnableSQLReviewCI(ctx context.Context, oauthCtx *common.OauthContext, repositoryTitle, repositoryID, branch, token string) error {
- pipeline, err := createSQLReviewPipeline(ctx, oauthCtx, repositoryTitle, repositoryID, token)
- if err != nil {
- return err
- }
- return createSQLReviewBranchPolicy(ctx, oauthCtx, repositoryID, branch, pipeline.ID)
-}
-
-// createSQLReviewPipeline creates the SQL Review pipeline.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/pipelines/create?view=azure-devops-rest-7.1
-func createSQLReviewPipeline(ctx context.Context, oauthCtx *common.OauthContext, repositoryTitle, repositoryID, token string) (*pipeline, error) {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return nil, errors.Errorf("invalid repository ID %q", repositoryID)
- }
- organizationName, projectName, repositoryID := parts[0], parts[1], parts[2]
-
- values := &url.Values{}
- values.Set("api-version", "7.1-preview.1")
-
- client := &http.Client{}
- apiURL := fmt.Sprintf("https://dev.azure.com/%s/%s/_apis/pipelines?%s", url.PathEscape(organizationName), url.PathEscape(projectName), values.Encode())
- payload := &pipelineCreate{
- Name: fmt.Sprintf("%s for %s", sqlReviewPipelineName, repositoryTitle),
- Configuration: &pipelineConfig{
- Type: "yaml",
- Path: SQLReviewPipelineFilePath,
- Repository: &pipelineRepository{
- ID: repositoryID,
- Type: "azureReposGit",
- },
- Variables: map[string]*pipelineVariable{
- vcs.SQLReviewAPISecretName: {
- Value: token,
- AllowOverride: false,
- IsSecret: true,
- },
- },
- },
- }
-
- body, err := json.Marshal(payload)
- if err != nil {
- return nil, errors.Wrap(err, "marshal branch create")
- }
-
- code, _, resp, err := oauth.Post(
- ctx,
- client,
- apiURL,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return nil, errors.Wrapf(err, "POST %s", apiURL)
- }
- if code >= 300 {
- return nil, errors.Errorf("non-200 POST %s status code %d with body %q", apiURL, code, string(resp))
- }
-
- result := new(pipeline)
- if err := json.Unmarshal([]byte(resp), result); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal response body")
- }
-
- return result, nil
-}
-
-// createSQLReviewPolicy creates the SQL Review policy.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/create?view=azure-devops-rest-7.0
-func createSQLReviewBranchPolicy(ctx context.Context, oauthCtx *common.OauthContext, repositoryID, branch string, pipelineID int) error {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return errors.Errorf("invalid repository ID %q", repositoryID)
- }
- organizationName, projectName, repositoryID := parts[0], parts[1], parts[2]
-
- values := &url.Values{}
- values.Set("api-version", "7.1-preview.1")
-
- client := &http.Client{}
- apiURL := fmt.Sprintf("https://dev.azure.com/%s/%s/_apis/policy/configurations?%s", url.PathEscape(organizationName), url.PathEscape(projectName), values.Encode())
- payload := &branchPolicyCreate{
- IsBlocking: true,
- IsDeleted: false,
- IsEnabled: true,
- Settings: &branchPolicySetting{
- BuildDefinitionID: pipelineID,
- DisplayName: sqlReviewPipelineName,
- ManualQueueOnly: false,
- QueueOnSourceUpdateOnly: true,
- ValidDuration: 720,
- Scope: []*branchPolicyScope{
- {
- MatchKind: "Exact",
- RefName: fmt.Sprintf("refs/heads/%s", branch),
- RepositoryID: repositoryID,
- },
- },
- },
- Type: &policy{
- ID: "0609b952-1397-4640-95ec-e00a01b2c241",
- },
- }
-
- body, err := json.Marshal(payload)
- if err != nil {
- return errors.Wrap(err, "marshal policy create")
- }
-
- code, _, resp, err := oauth.Post(
- ctx,
- client,
- apiURL,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "POST %s", apiURL)
- }
- if code >= 300 {
- return errors.Errorf("non-200 POST %s status code %d with body %q", apiURL, code, string(resp))
- }
-
- return nil
-}
diff --git a/backend/plugin/vcs/bitbucket/sql_review.go b/backend/plugin/vcs/bitbucket/sql_review.go
deleted file mode 100644
index eb69a7aef8..0000000000
--- a/backend/plugin/vcs/bitbucket/sql_review.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package bitbucket
-
-import (
- "bytes"
- "context"
- _ "embed"
- "encoding/json"
- "fmt"
- "net/http"
-
- "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"
-
- "gopkg.in/yaml.v3"
-)
-
-type pipelineStep struct {
- Name string `yaml:"name"`
- Image string `yaml:"image"`
- Script []string `yaml:"script"`
-}
-
-type pipeline struct {
- Step *pipelineStep `yaml:"step"`
-}
-
-type pipelineConfig struct {
- Enabled bool `json:"enabled"`
-}
-
-const (
- // CIFilePath is the local path for BitBucket ci file.
- CIFilePath = "bitbucket-pipelines.yml"
- // SQLReviewScriptFilePath is the local path for SQL review CI script.
- SQLReviewScriptFilePath = ".pipeline/bytebase-sql-review.sh"
- pipelineStepName = "Bytebase SQL Review"
-)
-
-// sqlReviewPipelineStep is the pipeline step for SQL review in VCS workflow.
-//
-//go:embed pipeline-step.yml
-var sqlReviewPipelineStep string
-
-// SQLReviewScript is the script file for SQL review in VCS workflow.
-//
-//go:embed bytebase-sql-review.sh
-var SQLReviewScript string
-
-func getSQLReviewStep(endpoint string) string {
- return fmt.Sprintf(
- sqlReviewPipelineStep,
- pipelineStepName,
- SQLReviewScriptFilePath,
- endpoint,
- vcs.SQLReviewAPISecretName,
- )
-}
-
-// EnableSQLReviewCI enables the pipeline.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-put.
-func EnableSQLReviewCI(ctx context.Context, oauthCtx *common.OauthContext, apiURL, repositoryID string) error {
- body, err := json.Marshal(
- pipelineConfig{
- Enabled: true,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal pipeline config")
- }
-
- client := &http.Client{}
- url := fmt.Sprintf("%s/repositories/%s/pipelines_config", apiURL, repositoryID)
- code, _, resp, err := oauth.Put(
- ctx,
- client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
- if code >= 300 {
- return errors.Errorf("failed to update pipeline config from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
-func SetupBitBucketCI(bitBucketCI map[string]any, endpoint string) (string, error) {
- if _, ok := bitBucketCI["image"]; !ok {
- bitBucketCI["image"] = "atlassian/default-image:4"
- }
- if _, ok := bitBucketCI["pipelines"]; !ok {
- bitBucketCI["pipelines"] = make(map[string]any)
- }
- // enable pipeline for pull request
- // https://support.atlassian.com/bitbucket-cloud/docs/pipeline-start-conditions/#Pull-Requests
- // https://stackoverflow.com/questions/55019205/how-to-run-pipeline-only-on-pull-request-to-master-branch
- if _, ok := bitBucketCI["pipelines"].(map[string]any)["pull-requests"]; !ok {
- bitBucketCI["pipelines"].(map[string]any)["pull-requests"] = make(map[string]any)
- }
- if _, ok := bitBucketCI["pipelines"].(map[string]any)["pull-requests"].(map[string]any)["**"]; !ok {
- bitBucketCI["pipelines"].(map[string]any)["pull-requests"].(map[string]any)["**"] = []any{}
- }
-
- var prSteps []any
- switch steps := bitBucketCI["pipelines"].(map[string]any)["pull-requests"].(map[string]any)["**"].(type) {
- case []any:
- prSteps = append(prSteps, steps...)
- default:
- prSteps = append(prSteps, steps)
- }
-
- stepStr := getSQLReviewStep(endpoint)
- pipelineStep := &pipelineStep{}
- if err := yaml.Unmarshal([]byte(stepStr), pipelineStep); err != nil {
- return "", errors.Wrapf(err, "failed to parse pipeline step")
- }
-
- index := findSQLReviewStepIndex(prSteps)
- if index >= 0 {
- prSteps = append(prSteps[:index], prSteps[index+1:]...)
- }
- prSteps = append(prSteps, &pipeline{
- Step: pipelineStep,
- })
-
- bitBucketCI["pipelines"].(map[string]any)["pull-requests"].(map[string]any)["**"] = prSteps
-
- newContent, err := yaml.Marshal(bitBucketCI)
- if err != nil {
- return "", err
- }
-
- return string(newContent), nil
-}
-
-func findSQLReviewStepIndex(steps []any) int {
- for i, data := range steps {
- if val, ok := data.(map[string]any); ok {
- if step, ok := val["step"].(map[string]any); ok {
- if step["name"] == pipelineStepName {
- return i
- }
- }
- }
- }
-
- return -1
-}