Skip to content

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

chore: setup the SQL review CI for Azure DevOps (#7355)

ecmadaode775d7f911f
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index e01bc41714..b108d97026 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -1054,6 +1054,10 @@ func (s *ProjectService) setupVCSSQLReviewCI(ctx context.Context, repository *st
if err := s.setupVCSSQLReviewCIForGitLab(ctx, repository, vcs, branch, sqlReviewEndpoint); err != nil {
return nil, err
}
+ case vcsPlugin.AzureDevOps:
+ if err := s.setupVCSSQLReviewCIForAzureDevOps(ctx, repository, vcs, branch, sqlReviewEndpoint); err != nil {
+ return nil, err
+ }
}
return vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).CreatePullRequest(
@@ -1266,6 +1270,80 @@ func (s *ProjectService) setupVCSSQLReviewCIForGitLab(
})
}
+// setupVCSSQLReviewCIForAzureDevOps will create or update SQL review related files in Azure DevOps to setup SQL review CI.
+func (s *ProjectService) setupVCSSQLReviewCIForAzureDevOps(
+ ctx context.Context,
+ repository *store.RepositoryMessage,
+ vcs *store.ExternalVersionControlMessage,
+ branch *vcsPlugin.BranchInfo,
+ sqlReviewEndpoint string,
+) error {
+ sqlReviewConfig := azure.SetupSQLReviewCI(sqlReviewEndpoint, repository.BranchFilter)
+ fileLastCommitID := ""
+ fileSHA := ""
+
+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return status.Errorf(codes.Internal, "failed to find workspace setting with error: %v", err.Error())
+ }
+ if setting.ExternalUrl == "" {
+ return status.Errorf(codes.FailedPrecondition, "external url is required")
+ }
+
+ fileMeta, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(
+ ctx,
+ common.OauthContext{
+ ClientID: vcs.ApplicationID,
+ ClientSecret: vcs.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: utils.RefreshToken(ctx, s.store, repository.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
+ },
+ vcs.InstanceURL,
+ repository.ExternalID,
+ azure.SQLReviewPipelineFilePath,
+ vcsPlugin.RefInfo{
+ RefType: vcsPlugin.RefTypeBranch,
+ RefName: branch.Name,
+ },
+ )
+ if err != nil {
+ log.Debug(
+ "Failed to get file meta",
+ zap.String("file", azure.SQLReviewPipelineFilePath),
+ zap.String("last_commit", branch.LastCommitID),
+ zap.Int("code", common.ErrorCode(err).Int()),
+ zap.Error(err),
+ )
+ } else if fileMeta != nil {
+ fileLastCommitID = fileMeta.LastCommitID
+ fileSHA = fileMeta.SHA
+ }
+
+ return vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).OverwriteFile(
+ ctx,
+ common.OauthContext{
+ ClientID: vcs.ApplicationID,
+ ClientSecret: vcs.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: utils.RefreshToken(ctx, s.store, repository.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
+ },
+ vcs.InstanceURL,
+ repository.ExternalID,
+ azure.SQLReviewPipelineFilePath,
+ vcsPlugin.FileCommitCreate{
+ Branch: branch.Name,
+ CommitMessage: sqlReviewInVCSPRTitle,
+ Content: sqlReviewConfig,
+ LastCommitID: fileLastCommitID,
+ SHA: fileSHA,
+ },
+ )
+}
+
// createOrUpdateVCSSQLReviewFileForGitLab will create or update SQL review file for GitLab CI.
func (s *ProjectService) createOrUpdateVCSSQLReviewFileForGitLab(
ctx context.Context,
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index 4dad102c13..ae3fd6061b 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -136,6 +136,18 @@ type ServiceHookCodePushEventResource struct {
PushID uint64 `json:"pushId"`
}
+type project struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ State string `json:"state"`
+}
+type repository struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ WebURL string `json:"webUrl"`
+ Project project `json:"project"`
+}
+
// ServiceHookCodePushEvent represents a Azure DevOps service hook code push event.
//
// Docs: https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#git.push
@@ -225,15 +237,14 @@ type ChangesResponse struct {
// 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) {
client := &http.Client{}
- // By design, we encode the repository ID as <organization>/<projectID>/<repositoryID> for Azure DevOps.
- parts := strings.Split(externalRepositoryID, "/")
- if len(parts) != 3 {
- return nil, errors.Errorf("invalid repository ID %q", externalRepositoryID)
+ apiURL, err := getRepositoryAPIURL(externalRepositoryID)
+ if err != nil {
+ return nil, err
}
- organizationName, repositoryID := parts[0], parts[2]
+
values := &url.Values{}
values.Set("api-version", "7.0")
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/commits/%s/changes?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), url.PathEscape(commitID), values.Encode())
+ url := fmt.Sprintf("%s/commits/%s/changes?%s", apiURL, url.PathEscape(commitID), values.Encode())
code, _, body, err := oauth.Get(ctx, client, url, &oauthCtx.AccessToken, tokenRefresher(
oauthContext{
RefreshToken: oauthCtx.RefreshToken,
@@ -246,7 +257,7 @@ func GetChangesByCommit(ctx context.Context, oauthCtx common.OauthContext, exter
return nil, errors.Wrapf(err, "GET %s", url)
}
if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, fmt.Sprintf("commit %q does not exist in the repository %s under the organization %s", commitID, repositoryID, organizationName))
+ return nil, common.Errorf(common.NotFound, fmt.Sprintf("commit %q does not exist in the repository %s", commitID, externalRepositoryID))
}
if code != http.StatusOK {
return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
@@ -271,15 +282,14 @@ func GetChangesByCommit(ctx context.Context, oauthCtx common.OauthContext, exter
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get?view=azure-devops-rest-7.0&tabs=HTTP
func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, _, externalRepositoryID, commitID string) (*vcs.Commit, error) {
- // By design, we encode the repository ID as <organization>/<projectID>/<repositoryID> for Azure DevOps.
- parts := strings.Split(externalRepositoryID, "/")
- if len(parts) != 3 {
- return nil, errors.Errorf("invalid repository ID %q", externalRepositoryID)
+ apiURL, err := getRepositoryAPIURL(externalRepositoryID)
+ if err != nil {
+ return nil, err
}
- organizationName, projectID, repositoryID := parts[0], parts[1], parts[2]
+
values := &url.Values{}
values.Set("api-version", "7.0")
- url := fmt.Sprintf("https://dev.azure.com/%s/%s/_apis/git/repositories/%s/commits/%s?%s", url.PathEscape(organizationName), url.PathEscape(projectID), url.PathEscape(repositoryID), url.PathEscape(commitID), values.Encode())
+ url := fmt.Sprintf("%s/commits/%s?%s", apiURL, url.PathEscape(commitID), values.Encode())
code, _, body, err := oauth.Get(ctx, p.client, url, &oauthCtx.AccessToken, tokenRefresher(
oauthContext{
RefreshToken: oauthCtx.RefreshToken,
@@ -292,7 +302,7 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon
return nil, errors.Wrapf(err, "GET %s", url)
}
if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, fmt.Sprintf("commit %q does not exist in the repository %s under the organization %s", commitID, repositoryID, organizationName))
+ return nil, common.Errorf(common.NotFound, fmt.Sprintf("commit %q does not exist in the repository %s", commitID, externalRepositoryID))
}
if code != http.StatusOK {
return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
@@ -339,11 +349,11 @@ func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx common.OauthCon
// getPaginatedDiffFileList gets the diff file list between two commits with pagination.
func (p *Provider) getPaginatedDiffFileList(ctx context.Context, oauthCtx common.OauthContext, _ string, repositoryID string, beforeCommit string, afterCommit string, page int) ([]vcs.FileDiff, bool, error) {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return nil, false, errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, false, err
}
- organizationName, repositoryID := parts[0], parts[2]
+
values := &url.Values{}
values.Set("api-version", "7.0")
values.Set("$top", fmt.Sprintf("%d", apiPageSize))
@@ -356,7 +366,7 @@ func (p *Provider) getPaginatedDiffFileList(ctx context.Context, oauthCtx common
values.Set("targetVersionType", "commit")
values.Set("diffCommonCommit", "false")
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/diffs/commits?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), values.Encode())
+ url := fmt.Sprintf("%s/diffs/commits?%s", apiURL, values.Encode())
code, _, body, err := oauth.Get(ctx, p.client, url, &oauthCtx.AccessToken, tokenRefresher(
oauthContext{
RefreshToken: oauthCtx.RefreshToken,
@@ -433,20 +443,9 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.O
var result []*vcs.Repository
- type listRepositoriesResponseValueProject struct {
- ID string `json:"id"`
- Name string `json:"name"`
- State string `json:"state"`
- }
- type listRepositoriesResponseValue struct {
- ID string `json:"id"`
- Name string `json:"name"`
- RemoteURL string `json:"remoteUrl"`
- Project listRepositoriesResponseValueProject `json:"project"`
- }
type listRepositoriesResponse struct {
- Count int `json:"count"`
- Value []listRepositoriesResponseValue `json:"value"`
+ Count int `json:"count"`
+ Value []repository `json:"value"`
}
urlParams := &url.Values{}
@@ -490,7 +489,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.O
ID: fmt.Sprintf("%s/%s/%s", organization, r.Project.ID, r.ID),
Name: r.Name,
FullPath: fmt.Sprintf("%s/%s/%s", organization, r.Project.Name, r.Name),
- WebURL: r.RemoteURL,
+ WebURL: r.WebURL,
})
}
return nil
@@ -592,15 +591,15 @@ func (p *Provider) listOrganizationsForMember(ctx context.Context, oauthCtx comm
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/trees/get?view=azure-devops-rest-7.0&tabs=HTTP
func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, _ string, repositoryID string, ref string, filePath string) ([]*vcs.RepositoryTreeNode, error) {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return nil, errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
}
- organizationName, repositoryID := parts[0], parts[2]
+
values := &url.Values{}
values.Set("api-version", "7.0")
values.Set("recursive", "true")
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/trees/%s?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), url.PathEscape(ref), values.Encode())
+ url := fmt.Sprintf("%s/trees/%s?%s", apiURL, url.PathEscape(ref), values.Encode())
code, _, body, err := oauth.Get(ctx, p.client, url, &oauthCtx.AccessToken, tokenRefresher(
oauthContext{
@@ -651,21 +650,24 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,
// OverwriteFile overwrites an existing file at given path in the repository.
func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- return p.createOrUpdateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate, false)
+ create := true
+ if fileCommitCreate.LastCommitID != "" {
+ create = false
+ }
+ return p.createOrUpdateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate, create)
}
func (p *Provider) getLatestCommitIDOnBranch(ctx context.Context, oauthCtx common.OauthContext, repositoryID, branchName string) (string, error) {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return "", errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return "", err
}
- organizationName, repositoryID := parts[0], parts[2]
values := &url.Values{}
values.Set("api-version", "7.0")
values.Set("searchCriteria.itemVersion.version", branchName)
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/commits?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), values.Encode())
+ url := fmt.Sprintf("%s/commits?%s", apiURL, values.Encode())
code, _, body, err := oauth.Get(ctx, p.client, url, &oauthCtx.AccessToken, tokenRefresher(
oauthContext{
RefreshToken: oauthCtx.RefreshToken,
@@ -696,12 +698,14 @@ func (p *Provider) getLatestCommitIDOnBranch(ctx context.Context, oauthCtx commo
return g.Value[0].CommitID, nil
}
+// createOrUpdateFile update or create the file.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-5.1&tabs=HTTP
func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate, create bool) error {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return err
}
- organizationName, externalRepositoryID := parts[0], parts[2]
changeType := "edit"
if create {
@@ -710,7 +714,7 @@ func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.Oauth
values := &url.Values{}
values.Set("api-version", "7.0")
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/pushes?%s", url.PathEscape(organizationName), url.PathEscape(externalRepositoryID), values.Encode())
+ url := fmt.Sprintf("%s/pushes?%s", apiURL, values.Encode())
type createFileReqeustCommitChangesItem struct {
Path string `json:"path"`
@@ -732,8 +736,8 @@ func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.Oauth
type createFileReqeustCommit struct {
Comment string `json:"comment"`
Changes []createFileReqeustCommitChanges `json:"changes"`
- Author createFileReqeustCommitAuthor `json:"author"`
- Committer createFileReqeustCommitAuthor `json:"committer"`
+ Author *createFileReqeustCommitAuthor `json:"author,omitempty"`
+ Committer *createFileReqeustCommitAuthor `json:"committer,omitempty"`
}
type createFileRequestRefUpdates struct {
Name string `json:"name"`
@@ -776,12 +780,12 @@ func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.Oauth
},
}
if fileCommitCreate.AuthorName != "" && fileCommitCreate.AuthorEmail != "" {
- requestBody.Commits[0].Author = createFileReqeustCommitAuthor{
+ requestBody.Commits[0].Author = &createFileReqeustCommitAuthor{
Date: time.Now().Format(time.RFC3339),
Name: fileCommitCreate.AuthorName,
Email: fileCommitCreate.AuthorEmail,
}
- requestBody.Commits[0].Committer = createFileReqeustCommitAuthor{
+ requestBody.Commits[0].Committer = &createFileReqeustCommitAuthor{
Date: time.Now().Format(time.RFC3339),
Name: fileCommitCreate.AuthorName,
Email: fileCommitCreate.AuthorEmail,
@@ -804,7 +808,7 @@ func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.Oauth
return errors.Wrapf(err, "POST %s", url)
}
if code == http.StatusBadRequest {
- log.Info("Failed to create file due to commit conflict, retrying", zap.String("url", url), zap.String("body", string(body)))
+ log.Info("Failed to create file, retrying", zap.String("url", url), zap.String("body", string(body)))
continue
}
if code != http.StatusCreated {
@@ -823,11 +827,11 @@ func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx common.Oauth
// - https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-7.0&tabs=HTTP
// - https://learn.microsoft.com/en-us/rest/api/azure/devops/git/blobs/get-blob?view=azure-devops-rest-7.0&tabs=HTTP
func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, filePath string, refInfo vcs.RefInfo) (*vcs.FileMeta, error) {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return nil, errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
}
- organizationName, repositoryID := parts[0], parts[2]
+
values := &url.Values{}
values.Set("api-version", "7.0")
values.Set("scopePath", filePath)
@@ -846,7 +850,7 @@ func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContex
values.Set("versionDescriptor.versionType", refType)
values.Set("versionDescriptor.version", refInfo.RefName)
- itemsURL := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/items?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), values.Encode())
+ itemsURL := fmt.Sprintf("%s/items?%s", apiURL, values.Encode())
type fileMetaResponseValue struct {
ObjectID string `json:"objectId"`
@@ -889,7 +893,7 @@ func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContex
values = &url.Values{}
values.Set("api-version", "7.0")
values.Set("$format", "json")
- blobURL := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/blobs/%s?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), url.PathEscape(r.Value[0].ObjectID), values.Encode())
+ blobURL := fmt.Sprintf("%s/blobs/%s?%s", apiURL, url.PathEscape(r.Value[0].ObjectID), values.Encode())
type blobsResponse struct {
Size int64 `json:"size"`
@@ -932,11 +936,11 @@ func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContex
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-7.0&tabs=HTTP
func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, _ string, repositoryID string, filePath string, refInfo vcs.RefInfo) (string, error) {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return "", errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return "", err
}
- organizationName, repositoryID := parts[0], parts[2]
+
values := &url.Values{}
values.Set("api-version", "7.0")
values.Set("download", "false")
@@ -956,7 +960,7 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthCon
}
values.Set("versionDescriptor.versionType", refType)
values.Set("versionDescriptor.version", refInfo.RefName)
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/items?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), values.Encode())
+ url := fmt.Sprintf("%s/items?%s", apiURL, values.Encode())
code, _, body, err := oauth.Get(ctx, p.client, url, &oauthCtx.AccessToken, tokenRefresher(
oauthContext{
@@ -987,16 +991,15 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
return nil, errors.New("branch name is required")
}
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return nil, errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
}
- organizationName, repositoryID := parts[0], parts[2]
urlParams := &url.Values{}
urlParams.Set("name", branchName)
urlParams.Set("api-version", "7.0")
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/stats/branches?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), urlParams.Encode())
+ url := fmt.Sprintf("%s/stats/branches?%s", apiURL, urlParams.Encode())
code, _, body, err := oauth.Get(ctx, p.client, url, &oauthCtx.AccessToken, tokenRefresher(
oauthContext{
@@ -1010,7 +1013,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
return nil, errors.Wrapf(err, "GET %s", url)
}
if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, fmt.Sprintf("branch %q does not exist in the repository %s under the organization %s", branchName, repositoryID, organizationName))
+ return nil, common.Errorf(common.NotFound, fmt.Sprintf("branch %q does not exist in the repository %s", branchName, repositoryID))
}
if code != http.StatusOK {
return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
@@ -1026,7 +1029,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
r := new(branchStatResponse)
if err := json.Unmarshal([]byte(body), r); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal get the static of the branch %s of the repository %s under the organization %s response body, body: %s", branchName, repositoryID, organizationName, string(body))
+ return nil, errors.Wrapf(err, "failed to unmarshal get the static of the branch %s of the repository %s with response body, body: %s", branchName, repositoryID, string(body))
}
return &vcs.BranchInfo{
Name: r.Name,
@@ -1035,23 +1038,274 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
}
// CreateBranch creates the branch in the repository.
-func (*Provider) CreateBranch(_ context.Context, _ common.OauthContext, _, _ string, _ *vcs.BranchInfo) error {
- return errors.New("not implemented")
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-7.1
+func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID string, branch *vcs.BranchInfo) error {
+ type refUpdate struct {
+ Name string `json:"name"`
+ OldObjectID string `json:"oldObjectId"`
+ NewObjectID string `json:"newObjectId"`
+ }
+ body, err := json.Marshal(
+ []*refUpdate{
+ {
+ Name: fmt.Sprintf("refs/heads/%s", branch.Name),
+ OldObjectID: "0000000000000000000000000000000000000000",
+ NewObjectID: branch.LastCommitID,
+ },
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal branch create")
+ }
+
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return err
+ }
+
+ urlParams := &url.Values{}
+ urlParams.Set("api-version", "7.0")
+ url := fmt.Sprintf("%s/refs?%s", apiURL, urlParams.Encode())
+
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "GET %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.
-func (*Provider) ListPullRequestFile(_ context.Context, _ common.OauthContext, _, _, _ string) ([]*vcs.PullRequestFile, error) {
- return nil, errors.New("not implemented")
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/get-pull-request?view=azure-devops-rest-7.1
+func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
+ type mergeCommit struct {
+ CommitID string `json:"commitId"`
+ }
+ type azurePullRequest struct {
+ LastMergeCommit *mergeCommit `json:"lastMergeCommit"`
+ }
+
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
+ }
+
+ urlParams := &url.Values{}
+ urlParams.Set("api-version", "7.0")
+ url := fmt.Sprintf("%s/pullrequests/%s?%s", apiURL, pullRequestID, urlParams.Encode())
+
+ code, _, resp, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ 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 create merge request from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to create merge request from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+
+ var res azurePullRequest
+ if err := json.Unmarshal([]byte(resp), &res); err != nil {
+ return nil, err
+ }
+
+ return p.listChangedFilesInCommit(ctx, oauthCtx, repositoryID, res.LastMergeCommit.CommitID)
+}
+
+// listChangedFilesInCommit lists the changed files in the commit.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get-changes?view=azure-devops-rest-7.1&tabs=HTTP
+func (p *Provider) listChangedFilesInCommit(ctx context.Context, oauthCtx common.OauthContext, repositoryID, commitID string) ([]*vcs.PullRequestFile, error) {
+ type changeItem struct {
+ GitObjectType string `json:"gitObjectType"`
+ Path string `json:"path"`
+ CommitID string `json:"commitId"`
+ }
+ type commitChange struct {
+ Item *changeItem `json:"item"`
+ ChangeType string `json:"changeType"`
+ }
+ type commitChangeResponse struct {
+ Changes []*commitChange `json:"changes"`
+ }
+
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
+ }
+
+ urlParams := &url.Values{}
+ urlParams.Set("api-version", "7.0")
+ url := fmt.Sprintf("%s/commits/%s?%s", apiURL, commitID, urlParams.Encode())
+
+ code, _, resp, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ 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 create merge request from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to create merge request from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+
+ var res commitChangeResponse
+ if err := json.Unmarshal([]byte(resp), &res); err != nil {
+ return nil, err
+ }
+
+ files := []*vcs.PullRequestFile{}
+ for _, change := range res.Changes {
+ if change.Item.GitObjectType != "blob" {
+ continue
+ }
+ files = append(files, &vcs.PullRequestFile{
+ Path: change.Item.Path,
+ LastCommitID: change.Item.CommitID,
+ IsDeleted: change.ChangeType == "delete",
+ })
+ }
+
+ return files, nil
}
// CreatePullRequest creates the pull request in the repository.
-func (*Provider) CreatePullRequest(_ context.Context, _ common.OauthContext, _, _ string, _ *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
- return nil, errors.New("not implemented")
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/create?view=azure-devops-rest-7.1&tabs=HTTP
+func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID string, pullRequestCreate *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
+ type azurePullRequest struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ URL string `json:"url"`
+ SourceRefName string `json:"sourceRefName"`
+ TargetRefName string `json:"targetRefName"`
+ Repository *repository `json:"repository,omitempty"`
+ }
+
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
+ }
+
+ urlParams := &url.Values{}
+ urlParams.Set("api-version", "7.0")
+ url := fmt.Sprintf("%s/pullrequests?%s", apiURL, urlParams.Encode())
+
+ body, err := json.Marshal(
+ azurePullRequest{
+ Title: pullRequestCreate.Title,
+ Description: pullRequestCreate.Body,
+ SourceRefName: fmt.Sprintf("refs/heads/%s", pullRequestCreate.Head),
+ TargetRefName: fmt.Sprintf("refs/heads/%s", pullRequestCreate.Base),
+ },
+ )
+ if err != nil {
+ return nil, errors.Wrap(err, "marshal branch create")
+ }
+
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ 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,
+ resp,
+ )
+ }
+
+ var res azurePullRequest
+ if err := json.Unmarshal([]byte(resp), &res); err != nil {
+ return nil, err
+ }
+
+ urlSections := strings.Split(res.URL, "/")
+ prID := urlSections[len(urlSections)-1]
+
+ return &vcs.PullRequest{
+ URL: fmt.Sprintf("%s/pullrequest/%s", res.Repository.WebURL, prID),
+ }, nil
}
// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
func (*Provider) UpsertEnvironmentVariable(context.Context, common.OauthContext, string, string, string, string) error {
- return errors.New("not supported")
+ return nil
}
// CreateWebhook creates a webhook in the organization, and returns the webhook ID which can be used in PatchWebhook.
@@ -1163,16 +1417,15 @@ type CommitsInPush struct {
//
// 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) {
- parts := strings.Split(repositoryID, "/")
- if len(parts) != 3 {
- return nil, errors.Errorf("invalid repository ID %q", repositoryID)
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return nil, err
}
- organizationName, repositoryID := parts[0], parts[2]
values := &url.Values{}
values.Set("api-version", "7.0")
values.Set("pushId", fmt.Sprintf("%d", pushID))
- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/commits?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), values.Encode())
+ url := fmt.Sprintf("%s/commits?%s", apiURL, values.Encode())
client := &http.Client{}
@@ -1267,3 +1520,14 @@ func tokenRefresher(oauthCtx oauthContext, refresher common.TokenRefresher) oaut
return refresher(r.AccessToken, r.RefreshToken, expiresIn)
}
}
+
+func getRepositoryAPIURL(repositoryID string) (string, error) {
+ // By design, we encode the repository ID as <organization>/<projectID>/<repositoryID> for Azure DevOps.
+ 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]
+
+ return fmt.Sprintf("https://dev.azure.com/%s/%s/_apis/git/repositories/%s", url.PathEscape(organizationName), url.PathEscape(projectName), url.PathEscape(repositoryID)), nil
+}
diff --git a/backend/plugin/vcs/azure/bytebase-sql-review.yml b/backend/plugin/vcs/azure/bytebase-sql-review.yml
new file mode 100644
index 0000000000..02be4098e9
--- /dev/null
+++ b/backend/plugin/vcs/azure/bytebase-sql-review.yml
@@ -0,0 +1,58 @@
+variables:
+ - name: api
+ value: "%s"
+
+trigger:
+ - "%s"
+
+pr:
+ paths:
+ include:
+ - "**/*.sql"
+
+pool:
+ vmImage: ubuntu-latest
+
+jobs:
+ - job: SQL_Review
+ steps:
+ - bash: |
+ echo "Start request ${{ variables.api }}"
+
+ if [[ $SYSTEM_PULLREQUEST_PULLREQUESTID == "" ]]; then exit 0; fi
+
+ request_body=$(jq -n \
+ --arg 'repositoryId' "$BUILD_REPOSITORY_ID" \
+ --arg 'pullRequestId' "$SYSTEM_PULLREQUEST_PULLREQUESTID" \
+ --arg 'webURL' "$BUILD_REPOSITORY_URI" \
+ '$ARGS.named')
+
+ response=$(curl --silent --write-out "HTTPSTATUS:%{http_code}" -X POST ${{ variables.api }} \
+ -H "Content-Type: application/json" \
+ -d "$request_body")
+
+ echo "response: $response"
+
+ http_code=$(echo $response | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
+ body=$(echo $response | sed -e 's/HTTPSTATUS\:.*//g')
+
+ if [[ $http_code != 200 ]]; then
+ echo "Failed to check SQL with response code $http_code and body $body"
+ exit 1
+ fi
+
+ content=$(echo $body | jq -r '.content')
+ len=$(echo $content | jq '. | length')
+ if [[ $len == 0 ]]; then exit 0; fi
+
+ msg=$(echo $content | jq -r '.[0]')
+ echo $msg >> bytebase-sql-review.xml
+
+ status=$(echo $body | jq -r '.status')
+ if [[ "$status" == "ERROR" ]]; then exit 1; fi
+ displayName: SQL Review
+ - task: PublishTestResults@2
+ inputs:
+ testResultsFormat: "JUnit"
+ testResultsFiles: "**/bytebase-sql-review.xml"
+ displayName: Upload artifacts
diff --git a/backend/plugin/vcs/azure/sql_review.go b/backend/plugin/vcs/azure/sql_review.go
new file mode 100644
index 0000000000..927050c9fa
--- /dev/null
+++ b/backend/plugin/vcs/azure/sql_review.go
@@ -0,0 +1,23 @@
+package azure
+
+import (
+ _ "embed"
+ "fmt"
+)
+
+// 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"
+)
+
+// SetupSQLReviewCI will setup the SQL review CI content with SQL review endpoint.
+// Users need to enable the branch policy to trigger pipeline in the pull request.
+// https://learn.microsoft.com/en-us/azure/devops/pipelines/repos/azure-repos-git?view=azure-devops&tabs=yaml#pr-triggers
+func SetupSQLReviewCI(endpoint, branch string) string {
+ return fmt.Sprintf(sqlReviewPipeline, endpoint, branch)
+}
diff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vue
index e7eb75d2e0..2bc1fb51ee 100644
--- a/frontend/src/components/RepositoryForm.vue
+++ b/frontend/src/components/RepositoryForm.vue
@@ -460,13 +460,21 @@ const isProjectSchemaChangeTypeSDL = computed(() => {
const canEnableSQLReview = computed(() => {
return (
props.vcsType == ExternalVersionControl_Type.GITHUB ||
- props.vcsType === ExternalVersionControl_Type.GITLAB
+ props.vcsType === ExternalVersionControl_Type.GITLAB ||
+ props.vcsType === ExternalVersionControl_Type.AZURE_DEVOPS
);
});
const enableSQLReviewTitle = computed(() => {
- return props.vcsType === ExternalVersionControl_Type.GITLAB
- ? t("repository.sql-review-ci-enable-gitlab")
- : t("repository.sql-review-ci-enable-github");
+ switch (props.vcsType) {
+ case ExternalVersionControl_Type.GITLAB:
+ return t("repository.sql-review-ci-enable-gitlab");
+ case ExternalVersionControl_Type.GITHUB:
+ return t("repository.sql-review-ci-enable-github");
+ case ExternalVersionControl_Type.AZURE_DEVOPS:
+ return t("repository.sql-review-ci-enable-azure");
+ default:
+ return "";
+ }
});
const sampleFilePath = (
diff --git a/frontend/src/components/RepositoryPanel.vue b/frontend/src/components/RepositoryPanel.vue
index 91a289dfed..71bc5bab63 100644
--- a/frontend/src/components/RepositoryPanel.vue
+++ b/frontend/src/components/RepositoryPanel.vue
@@ -378,7 +378,8 @@ const supportSQLReviewCI = computed(() => {
const { type } = props.vcs;
return (
type == ExternalVersionControl_Type.GITHUB ||
- type === ExternalVersionControl_Type.GITLAB
+ type === ExternalVersionControl_Type.GITLAB ||
+ type === ExternalVersionControl_Type.AZURE_DEVOPS
);
});
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 26e478b65e..aad6c12e4d 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1346,6 +1346,7 @@
"sql-review-ci-enable": "Enable SQL Review CI",
"sql-review-ci-enable-gitlab": "Enable SQL Review CI via GitLab CI",
"sql-review-ci-enable-github": "Enable SQL Review CI via GitHub Action",
+ "sql-review-ci-enable-azure": "Enable SQL Review CI via Azure DevOps Pipeline",
"sql-review-ci-description": "Bytebase will create a {pr} to set up the SQL review CI in your repository. In every {pr}, environment-based SQL review policy will check against changed files matching the \"{pathTemplate}\".",
"sql-review-ci-setup": "Setup SQL Review CI",
"sql-review-ci-setup-failed": "Failed to setup SQL Review CI",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index d3690bbab6..1f925ca56a 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1344,6 +1344,7 @@
"sql-review-ci-enable": "Habilitar la revisión de SQL CI",
"sql-review-ci-enable-gitlab": "Habilitar la revisión de SQL CI a través de GitLab CI",
"sql-review-ci-enable-github": "Habilitar la revisión de SQL CI a través de la acción de GitHub",
+ "sql-review-ci-enable-azure": "Habilite SQL Review CI a través de Azure DevOps Pipeline",
"sql-review-ci-description": "Bytebase creará un {pr} para configurar la revisión de SQL CI en su repositorio. En cada {pr}, la política de revisión de SQL basada en el entorno verificará los archivos modificados que coincidan con el \"{pathTemplate}\".",
"sql-review-ci-setup": "Configurar revisión de SQL CI",
"sql-review-ci-setup-failed": "Error al configurar la revisión de SQL CI",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 926e88ad43..e27fe386e9 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1339,6 +1339,7 @@
"sql-review-ci-enable": "开启 SQL 审核 CI",
"sql-review-ci-enable-gitlab": "基于 GitLab CI 开启 SQL 审核",
"sql-review-ci-enable-github": "基于 GitHub Action 开启 SQL 审核",
+ "sql-review-ci-enable-azure": "基于 Azure DevOps Pipeline 开启 SQL 审核",
"sql-review-ci-description": "Bytebase 会发起 {pr} 为您的代码仓库配置 SQL 审核 CI。在每一个 {pr} 中,任何匹配上「{pathTemplate}」的文件修改将被赋予对应环境的 SQL 审核策略。",
"sql-review-ci-setup": "配置 SQL 审核 CI",
"sql-review-ci-setup-failed": "SQL 审核 CI 创建失败",