Skip to content

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

feat(azure-devops, gitops): backend support azure devops in gitops (#7205)

h3n4lb70977f504d7
diff --git a/backend/api/v1/externalvs_service.go b/backend/api/v1/externalvs_service.go
index 78f85727ff..9befee37e2 100644
--- a/backend/api/v1/externalvs_service.go
+++ b/backend/api/v1/externalvs_service.go
@@ -143,6 +143,14 @@ func (s *ExternalVersionControlService) SearchExternalVersionControlProjects(ctx
return nil, status.Errorf(codes.NotFound, "External version control not found: %v", err)
}
+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find workspace setting with error: %v", err.Error())
+ }
+ if setting.ExternalUrl == "" {
+ return nil, status.Errorf(codes.FailedPrecondition, "external url is required")
+ }
+
apiExternalProjectList, err := vcs.Get(externalVersionControl.Type, vcs.ProviderConfig{}).FetchAllRepositoryList(
ctx,
common.OauthContext{
@@ -150,6 +158,7 @@ func (s *ExternalVersionControlService) SearchExternalVersionControlProjects(ctx
ClientSecret: externalVersionControl.Secret,
AccessToken: request.AccessToken,
RefreshToken: request.RefreshToken,
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
Refresher: nil,
},
externalVersionControl.InstanceURL,
@@ -251,7 +260,7 @@ func (s *ExternalVersionControlService) ExchangeToken(ctx context.Context, reque
return nil, status.Errorf(codes.Internal, "failed to find workspace setting with error: %v", err.Error())
}
if setting.ExternalUrl == "" {
- return nil, status.Errorf(codes.InvalidArgument, "external url is required")
+ return nil, status.Errorf(codes.FailedPrecondition, "external url is required")
}
oauthExchange.RedirectURL = fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl)
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index df57e99849..a147025864 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -25,6 +25,7 @@ import (
enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
vcsPlugin "github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/azure"
"github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket"
"github.com/bytebase/bytebase/backend/plugin/vcs/github"
"github.com/bytebase/bytebase/backend/plugin/vcs/gitlab"
@@ -383,6 +384,14 @@ func (s *ProjectService) UpdateProjectGitOpsInfo(ctx context.Context, request *v
return nil, status.Errorf(codes.NotFound, "project %q has been deleted", projectName)
}
+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find workspace setting with error: %v", err.Error())
+ }
+ if setting.ExternalUrl == "" {
+ return nil, status.Errorf(codes.FailedPrecondition, "external url is required")
+ }
+
repo, err := s.store.GetRepositoryV2(ctx, &store.FindRepositoryMessage{
ProjectResourceID: &project.ResourceID,
})
@@ -413,7 +422,26 @@ func (s *ProjectService) UpdateProjectGitOpsInfo(ctx context.Context, request *v
case "branch_filter":
patch.BranchFilter = &request.ProjectGitopsInfo.BranchFilter
case "base_directory":
- baseDir := strings.Trim(request.ProjectGitopsInfo.BaseDirectory, "/")
+ intVCSUID, err := strconv.Atoi(request.ProjectGitopsInfo.VcsUid)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "invalid vcs uid: %s", request.ProjectGitopsInfo.VcsUid)
+ }
+ storeVCS, err := s.store.GetExternalVersionControlV2(ctx, intVCSUID)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find vcs: %s", err.Error())
+ }
+ if storeVCS == nil {
+ return nil, status.Errorf(codes.NotFound, "vcs %d not found", intVCSUID)
+ }
+ baseDir := request.ProjectGitopsInfo.BaseDirectory
+ // Azure DevOps base directory should start with /.
+ if storeVCS.Type == vcsPlugin.AzureDevOps {
+ if !strings.HasPrefix(baseDir, "/") {
+ baseDir = "/" + request.ProjectGitopsInfo.BaseDirectory
+ }
+ } else {
+ baseDir = strings.Trim(request.ProjectGitopsInfo.BaseDirectory, "/")
+ }
patch.BaseDirectory = &baseDir
case "file_path_template":
if err := api.ValidateRepositoryFilePathTemplate(request.ProjectGitopsInfo.FilePathTemplate, project.TenantMode); err != nil {
@@ -456,6 +484,7 @@ func (s *ProjectService) UpdateProjectGitOpsInfo(ctx context.Context, request *v
repo.RefreshToken,
repo.ExternalID,
*v,
+ setting.ExternalUrl,
)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check branch: %v", err.Error())
@@ -559,6 +588,13 @@ func (s *ProjectService) UnsetProjectGitOpsInfo(ctx context.Context, request *v1
if err != nil {
return nil, status.Errorf(codes.Internal, `failed to list repository for web url "%s" with error: %v`, repo.WebURL, err.Error())
}
+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find workspace setting with error: %v", err.Error())
+ }
+ if setting.ExternalUrl == "" {
+ return nil, status.Errorf(codes.FailedPrecondition, "external url is required")
+ }
if len(repos) == 0 {
// Delete the webhook after we successfully delete the repository.
// This is because in case the webhook deletion fails, we can still have a cleanup process to cleanup the orphaned webhook.
@@ -572,6 +608,7 @@ func (s *ProjectService) UnsetProjectGitOpsInfo(ctx context.Context, request *v1
AccessToken: repo.AccessToken,
RefreshToken: repo.RefreshToken,
Refresher: refreshTokenNoop(),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
},
vcs.InstanceURL,
repo.ExternalID,
@@ -826,6 +863,28 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *v
return nil, status.Errorf(codes.FailedPrecondition, setupExternalURLError)
}
+ intVCSUID, err := strconv.Atoi(request.ProjectGitopsInfo.VcsUid)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "invalid vcs uid: %s", request.ProjectGitopsInfo.VcsUid)
+ }
+ storeVCS, err := s.store.GetExternalVersionControlV2(ctx, intVCSUID)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find vcs: %s", err.Error())
+ }
+ if storeVCS == nil {
+ return nil, status.Errorf(codes.NotFound, "vcs %d not found", intVCSUID)
+ }
+
+ baseDir := request.ProjectGitopsInfo.BaseDirectory
+ // Azure DevOps base directory should start with /.
+ if storeVCS.Type == vcsPlugin.AzureDevOps {
+ if !strings.HasPrefix(baseDir, "/") {
+ baseDir = "/" + request.ProjectGitopsInfo.BaseDirectory
+ }
+ } else {
+ baseDir = strings.Trim(request.ProjectGitopsInfo.BaseDirectory, "/")
+ }
+
vcsID, err := strconv.Atoi(request.ProjectGitopsInfo.VcsUid)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid vcs id: %s", request.ProjectGitopsInfo.VcsUid)
@@ -839,7 +898,7 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *v
FullPath: request.ProjectGitopsInfo.FullPath,
WebURL: request.ProjectGitopsInfo.WebUrl,
BranchFilter: request.ProjectGitopsInfo.BranchFilter,
- BaseDirectory: request.ProjectGitopsInfo.BaseDirectory,
+ BaseDirectory: baseDir,
FilePathTemplate: request.ProjectGitopsInfo.FilePathTemplate,
SchemaPathTemplate: request.ProjectGitopsInfo.SchemaPathTemplate,
SheetPathTemplate: request.ProjectGitopsInfo.SheetPathTemplate,
@@ -888,6 +947,7 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *v
repositoryCreate.RefreshToken,
repositoryCreate.ExternalID,
repositoryCreate.BranchFilter,
+ setting.ExternalUrl,
)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check branch %s with error: %v", repositoryCreate.BranchFilter, err.Error())
@@ -935,8 +995,6 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *v
repositoryCreate.ExternalWebhookID = webhookID
}
- // Remove enclosing /
- repositoryCreate.BaseDirectory = strings.Trim(repositoryCreate.BaseDirectory, "/")
repository, err := s.store.CreateRepositoryV2(ctx, repositoryCreate, ctx.Value(common.PrincipalIDContextKey).(int))
if err != nil {
if common.ErrorCode(err) == common.Conflict {
@@ -954,6 +1012,10 @@ func (s *ProjectService) setupVCSSQLReviewCI(ctx context.Context, repository *st
return nil, err
}
+ if setting.ExternalUrl == "" {
+ return nil, status.Errorf(codes.FailedPrecondition, "external url is required")
+ }
+
branch, err := s.setupVCSSQLReviewBranch(ctx, repository, vcs)
if err != nil {
return nil, err
@@ -967,6 +1029,7 @@ func (s *ProjectService) setupVCSSQLReviewCI(ctx context.Context, repository *st
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,
@@ -1001,6 +1064,7 @@ func (s *ProjectService) setupVCSSQLReviewCI(ctx context.Context, repository *st
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,
@@ -1016,6 +1080,13 @@ func (s *ProjectService) setupVCSSQLReviewCI(ctx context.Context, repository *st
// setupVCSSQLReviewBranch will create a new branch to setup SQL review CI.
func (s *ProjectService) setupVCSSQLReviewBranch(ctx context.Context, repository *store.RepositoryMessage, vcs *store.ExternalVersionControlMessage) (*vcsPlugin.BranchInfo, error) {
+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find workspace setting with error: %v", err.Error())
+ }
+ if setting.ExternalUrl == "" {
+ return nil, status.Errorf(codes.FailedPrecondition, "external url is required")
+ }
branch, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).GetBranch(
ctx,
common.OauthContext{
@@ -1024,6 +1095,7 @@ func (s *ProjectService) setupVCSSQLReviewBranch(ctx context.Context, repository
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,
@@ -1046,6 +1118,7 @@ func (s *ProjectService) setupVCSSQLReviewBranch(ctx context.Context, repository
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,
@@ -1069,6 +1142,14 @@ func (s *ProjectService) setupVCSSQLReviewCIForGitHub(
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{
@@ -1077,6 +1158,7 @@ func (s *ProjectService) setupVCSSQLReviewCIForGitHub(
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,
@@ -1104,6 +1186,7 @@ func (s *ProjectService) setupVCSSQLReviewCIForGitHub(
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,
@@ -1126,6 +1209,13 @@ func (s *ProjectService) setupVCSSQLReviewCIForGitLab(
branch *vcsPlugin.BranchInfo,
sqlReviewEndpoint string,
) error {
+ 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")
+ }
// create or update the .gitlab-ci.yml
if err := s.createOrUpdateVCSSQLReviewFileForGitLab(ctx, repository, vcs, branch, gitlab.CIFilePath, func(fileMeta *vcsPlugin.FileMeta) (string, error) {
content := make(map[string]any)
@@ -1139,6 +1229,7 @@ func (s *ProjectService) setupVCSSQLReviewCIForGitLab(
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,
@@ -1178,6 +1269,13 @@ func (s *ProjectService) createOrUpdateVCSSQLReviewFileForGitLab(
fileName string,
getNewContent func(meta *vcsPlugin.FileMeta) (string, error),
) error {
+ 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")
+ }
fileExisted := true
fileMeta, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(
ctx,
@@ -1187,6 +1285,7 @@ func (s *ProjectService) createOrUpdateVCSSQLReviewFileForGitLab(
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,
@@ -1221,6 +1320,7 @@ func (s *ProjectService) createOrUpdateVCSSQLReviewFileForGitLab(
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,
@@ -1243,6 +1343,7 @@ func (s *ProjectService) createOrUpdateVCSSQLReviewFileForGitLab(
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,
@@ -2713,7 +2814,7 @@ func isBranchNotFound(
ctx context.Context,
vcs *store.ExternalVersionControlMessage,
store *store.Store,
- webURL, accessToken, refreshToken, externalID, branch string,
+ webURL, accessToken, refreshToken, externalID, branch, externalURL string,
) (bool, error) {
_, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).GetBranch(ctx,
common.OauthContext{
@@ -2722,6 +2823,7 @@ func isBranchNotFound(
AccessToken: accessToken,
RefreshToken: refreshToken,
Refresher: utils.RefreshToken(ctx, store, webURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", externalURL),
},
vcs.InstanceURL, externalID, branch)
@@ -2772,6 +2874,33 @@ func createVCSWebhook(ctx context.Context, vcsType vcsPlugin.Type, webhookEndpoi
if err != nil {
return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
}
+ case vcsPlugin.AzureDevOps:
+ part := strings.Split(externalRepoID, "/")
+ if len(part) != 3 {
+ return "", errors.Errorf("invalid external repo id %q", externalRepoID)
+ }
+ projectID, repositoryID := part[1], part[2]
+
+ webhookPost := azure.WebhookCreateOrUpdate{
+ ConsumerActionID: "httpRequest",
+ ConsumerID: "webHooks",
+ ConsumerInputs: azure.WebhookCreateConsumerInputs{
+ URL: fmt.Sprintf("%s/hook/azure/%s", gitopsWebhookURL, webhookEndpointID),
+ AcceptUntrustedCerts: true,
+ },
+ EventType: "git.push",
+ PublisherID: "tfs",
+ PublisherInputs: azure.WebhookCreatePublisherInputs{
+ Repository: repositoryID,
+ Branch: "", /* Any branches */
+ PushedBy: "", /* Any users */
+ ProjectID: projectID,
+ },
+ }
+ webhookCreatePayload, err = json.Marshal(webhookPost)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
+ }
}
webhookID, err := vcsPlugin.Get(vcsType, vcsPlugin.ProviderConfig{}).CreateWebhook(
ctx,
diff --git a/backend/api/v1/sheet_service.go b/backend/api/v1/sheet_service.go
index 1b75aacca8..a8df16e9be 100644
--- a/backend/api/v1/sheet_service.go
+++ b/backend/api/v1/sheet_service.go
@@ -476,8 +476,17 @@ func (s *SheetService) SyncSheets(ctx context.Context, request *v1pb.SyncSheetsR
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("VCS not found for sync sheet: %d", repo.VCSUID))
}
+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to find workspace setting with error: %v", err.Error())
+ }
+ if setting.ExternalUrl == "" {
+ return nil, status.Errorf(codes.FailedPrecondition, "external url is required")
+ }
+
basePath := filepath.Dir(repo.SheetPathTemplate)
// TODO(Steven): The repo.branchFilter could be `test/*` which cannot be the ref value.
+ // TODO(zp): We may need a need VCS interface to get fetch repository file list for a branch instead of a SHA1.
fileList, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).FetchRepositoryFileList(ctx,
common.OauthContext{
ClientID: vcs.ApplicationID,
@@ -485,6 +494,7 @@ func (s *SheetService) SyncSheets(ctx context.Context, request *v1pb.SyncSheetsR
AccessToken: repo.AccessToken,
RefreshToken: repo.RefreshToken,
Refresher: utils.RefreshToken(ctx, s.store, repo.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
},
vcs.InstanceURL,
repo.ExternalID,
@@ -511,6 +521,7 @@ func (s *SheetService) SyncSheets(ctx context.Context, request *v1pb.SyncSheetsR
AccessToken: repo.AccessToken,
RefreshToken: repo.RefreshToken,
Refresher: utils.RefreshToken(ctx, s.store, repo.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
},
vcs.InstanceURL,
repo.ExternalID,
@@ -528,6 +539,7 @@ func (s *SheetService) SyncSheets(ctx context.Context, request *v1pb.SyncSheetsR
AccessToken: repo.AccessToken,
RefreshToken: repo.RefreshToken,
Refresher: utils.RefreshToken(ctx, s.store, repo.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
},
vcs.InstanceURL,
repo.ExternalID,
@@ -545,6 +557,7 @@ func (s *SheetService) SyncSheets(ctx context.Context, request *v1pb.SyncSheetsR
AccessToken: repo.AccessToken,
RefreshToken: repo.RefreshToken,
Refresher: utils.RefreshToken(ctx, s.store, repo.WebURL),
+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),
},
vcs.InstanceURL,
repo.ExternalID,
diff --git a/backend/common/oauth.go b/backend/common/oauth.go
index bbacbe85f7..2c07320721 100644
--- a/backend/common/oauth.go
+++ b/backend/common/oauth.go
@@ -9,6 +9,7 @@ type OauthContext struct {
ClientSecret string
AccessToken string
RefreshToken string
+ RedirectURL string
Refresher TokenRefresher
}
diff --git a/backend/migrator/migration/dev/LATEST.sql b/backend/migrator/migration/dev/LATEST.sql
index 6a06396bdb..63e58119e8 100644
--- a/backend/migrator/migration/dev/LATEST.sql
+++ b/backend/migrator/migration/dev/LATEST.sql
@@ -1137,7 +1137,7 @@ CREATE TABLE sheet (
name TEXT NOT NULL,
statement TEXT NOT NULL,
visibility TEXT NOT NULL CHECK (visibility IN ('PRIVATE', 'PROJECT', 'PUBLIC')) DEFAULT 'PRIVATE',
- source TEXT NOT NULL CONSTRAINT sheet_source_check CHECK (source IN ('BYTEBASE', 'GITLAB', 'GITHUB', 'BITBUCKET', 'BYTEBASE_ARTIFACT')) DEFAULT 'BYTEBASE',
+ source TEXT NOT NULL CONSTRAINT sheet_source_check CHECK (source IN ('BYTEBASE', 'GITLAB', 'GITHUB', 'BITBUCKET', 'AZURE_DEVOPS', 'BYTEBASE_ARTIFACT')) DEFAULT 'BYTEBASE',
type TEXT NOT NULL CHECK (type IN ('SQL')) DEFAULT 'SQL',
payload JSONB NOT NULL DEFAULT '{}'
);
diff --git a/backend/migrator/migration/prod/2.5/0002##update_vcs_type_check.sql b/backend/migrator/migration/prod/2.5/0002##update_vcs_type_check.sql
index 687fbe00ca..7bc63bf0a4 100644
--- a/backend/migrator/migration/prod/2.5/0002##update_vcs_type_check.sql
+++ b/backend/migrator/migration/prod/2.5/0002##update_vcs_type_check.sql
@@ -1,2 +1,5 @@
ALTER TABLE vcs DROP CONSTRAINT vcs_type_check;
ALTER TABLE vcs ADD CONSTRAINT vcs_type_check CHECK (type IN ('GITLAB', 'GITHUB', 'BITBUCKET', 'AZURE_DEVOPS'));
+
+ALTER TABLE sheet DROP CONSTRAINT sheet_source_check;
+ALTER TABLE sheet ADD CONSTRAINT sheet_source_check CHECK (source IN ('BYTEBASE', 'GITLAB', 'GITHUB', 'BITBUCKET', 'AZURE_DEVOPS', 'BYTEBASE_ARTIFACT'));
\ No newline at end of file
diff --git a/backend/migrator/migration/prod/LATEST.sql b/backend/migrator/migration/prod/LATEST.sql
index 50a1ba0d0c..94a39862f6 100644
--- a/backend/migrator/migration/prod/LATEST.sql
+++ b/backend/migrator/migration/prod/LATEST.sql
@@ -923,7 +923,7 @@ CREATE TABLE vcs (
updater_id INTEGER NOT NULL REFERENCES principal (id),
updated_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),
name TEXT NOT NULL,
- type TEXT NOT NULL CHECK (type IN ('GITLAB', 'GITHUB', 'BITBUCKET')),
+ type TEXT NOT NULL CHECK (type IN ('GITLAB', 'GITHUB', 'BITBUCKET', 'AZURE_DEVOPS')),
instance_url TEXT NOT NULL CHECK ((instance_url LIKE 'http://%' OR instance_url LIKE 'https://%') AND instance_url = rtrim(instance_url, '/')),
api_url TEXT NOT NULL CHECK ((api_url LIKE 'http://%' OR api_url LIKE 'https://%') AND api_url = rtrim(api_url, '/')),
application_id TEXT NOT NULL,
@@ -1136,7 +1136,7 @@ CREATE TABLE sheet (
name TEXT NOT NULL,
statement TEXT NOT NULL,
visibility TEXT NOT NULL CHECK (visibility IN ('PRIVATE', 'PROJECT', 'PUBLIC')) DEFAULT 'PRIVATE',
- source TEXT NOT NULL CONSTRAINT sheet_source_check CHECK (source IN ('BYTEBASE', 'GITLAB', 'GITHUB', 'BITBUCKET', 'BYTEBASE_ARTIFACT')) DEFAULT 'BYTEBASE',
+ source TEXT NOT NULL CONSTRAINT sheet_source_check CHECK (source IN ('BYTEBASE', 'GITLAB', 'GITHUB', 'BITBUCKET', 'AZURE_DEVOPS', 'BYTEBASE_ARTIFACT')) DEFAULT 'BYTEBASE',
type TEXT NOT NULL CHECK (type IN ('SQL')) DEFAULT 'SQL',
payload JSONB NOT NULL DEFAULT '{}'
);
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index bc2522542f..1dcd23455b 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -2,25 +2,36 @@
package azure
import (
+ "bytes"
"context"
"encoding/json"
+ "fmt"
"io"
"net/http"
"net/url"
+ "path/filepath"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
+ "go.uber.org/zap"
+ "golang.org/x/exp/slices"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/internal/oauth"
)
func init() {
vcs.Register(vcs.AzureDevOps, newProvider)
}
+const (
+ apiPageSize = 100
+)
+
var _ vcs.Provider = (*Provider)(nil)
// Provider is a Azure DevOps VCS provider.
@@ -42,7 +53,7 @@ func (*Provider) APIURL(instanceURL string) string {
return instanceURL
}
-// oauthResponse is a Bitbucket Cloud OAuth response.
+// oauthResponse is a Azure DevOps OAuth response.
type oauthResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
@@ -52,6 +63,88 @@ type oauthResponse struct {
ErrorDescription string `json:"error_description,omitempty"`
}
+// WebhookCreateConsumerInputs represents the consumer inputs for creating a webhook.
+type WebhookCreateConsumerInputs struct {
+ URL string `json:"url"`
+ AcceptUntrustedCerts bool `json:"acceptUntrustedCerts"`
+}
+
+// WebhookCreatePublisherInputs represents the publisher inputs for creating a webhook.
+type WebhookCreatePublisherInputs struct {
+ Repository string `json:"repository"`
+ Branch string `json:"branch"`
+ PushedBy string `json:"pushedBy"`
+ ProjectID string `json:"projectId"`
+}
+
+// WebhookCreateOrUpdate represents a Bitbucket API request for creating or
+// updating a webhook.
+type WebhookCreateOrUpdate struct {
+ ConsumerActionID string `json:"consumerActionId"`
+ ConsumerID string `json:"consumerId"`
+ ConsumerInputs WebhookCreateConsumerInputs `json:"consumerInputs"`
+ EventType string `json:"eventType"`
+ PublisherID string `json:"publisherId"`
+ PublisherInputs WebhookCreatePublisherInputs `json:"publisherInputs"`
+}
+
+// CommitAuthor represents a Azure DevOps commit author.
+type CommitAuthor struct {
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Date time.Time `json:"date"`
+}
+
+// ServiceHookCodePushEventMessage represents a Azure DevOps service hook code push event message.
+type ServiceHookCodePushEventMessage struct {
+ Text string `json:"text"`
+}
+
+// ServiceHookCodePushEventResourceCommit represents a Azure DevOps service hook code push event resource commit.
+type ServiceHookCodePushEventResourceCommit struct {
+ CommitID string `json:"commitId"`
+ Author CommitAuthor `json:"author"`
+ Comment string `json:"comment"`
+ URL string `json:"url"`
+}
+
+// ServiceHookCodePushEventRefUpdates represents a Azure DevOps service hook code push event ref updates.
+type ServiceHookCodePushEventRefUpdates struct {
+ Name string `json:"name"`
+ OldObjectID string `json:"oldObjectId"`
+ NewObjectID string `json:"newObjectId"`
+}
+
+// ServiceHookCodePushEventResourcePushedBy represents a Azure DevOps service hook code push event resource pushed by.
+type ServiceHookCodePushEventResourcePushedBy struct {
+ DisplayName string `json:"displayName"`
+ UniqueName string `json:"uniqueName"`
+}
+
+// ServiceHookCodePushEventResourceRepository represents a Azure DevOps service hook code push event resource repository.
+type ServiceHookCodePushEventResourceRepository struct {
+ Name string `json:"name"`
+ URL string `json:"url"`
+}
+
+// ServiceHookCodePushEventResource represents a Azure DevOps service hook code push event resource.
+type ServiceHookCodePushEventResource struct {
+ Commits []ServiceHookCodePushEventResourceCommit `json:"commits"`
+ Repository ServiceHookCodePushEventResourceRepository `json:"repository"`
+ RefUpdates []ServiceHookCodePushEventRefUpdates `json:"refUpdates"`
+ PushedBy ServiceHookCodePushEventResourcePushedBy `json:"pushedBy"`
+ PushID uint64 `json:"pushId"`
+}
+
+// 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
+type ServiceHookCodePushEvent struct {
+ EventType string `json:"eventType"`
+ Message ServiceHookCodePushEventMessage `json:"message"`
+ Resource ServiceHookCodePushEventResource `json:"resource"`
+}
+
// toVCSOAuthToken converts the response to *vcs.OAuthToken.
func (o oauthResponse) toVCSOAuthToken() (*vcs.OAuthToken, error) {
expiresIn, err := strconv.ParseInt(o.ExpiresIn, 10, 64)
@@ -108,54 +201,804 @@ func (p *Provider) ExchangeOAuthToken(ctx context.Context, _ string, oauthExchan
return oauthResp.toVCSOAuthToken()
}
-// TryLogin tries to fetch the user info from the current OAuth context.
-func (*Provider) TryLogin(context.Context, common.OauthContext, string) (*vcs.UserInfo, error) {
- return nil, errors.New("not implemented")
+// ChangesResponseChangeItem represents a Azure DevOps changes response change item.
+type ChangesResponseChangeItem struct {
+ GitObjectType string `json:"gitObjectType"`
+ Path string `json:"path"`
+}
+
+// ChangesResponseChange represents a Azure DevOps changes response change.
+type ChangesResponseChange struct {
+ Item ChangesResponseChangeItem `json:"item"`
+ ChangeType string `json:"changeType"`
+}
+
+// ChangesResponse represents a Azure DevOps changes response.
+type ChangesResponse struct {
+ Changes []ChangesResponseChange `json:"changes"`
+}
+
+// GetChangesByCommit gets the changes by commit ID.
+//
+// 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) {
+ 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)
+ }
+ 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())
+ code, _, body, err := oauth.Get(ctx, 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, fmt.Sprintf("commit %q does not exist in the repository %s under the organization %s", commitID, repositoryID, organizationName))
+ }
+ if code != http.StatusOK {
+ return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ changes := new(ChangesResponse)
+ if err := json.Unmarshal([]byte(body), changes); err != nil {
+ return nil, errors.Wrapf(err, "unmarshal body")
+ }
+
+ var result ChangesResponse
+ for _, change := range changes.Changes {
+ if change.Item.GitObjectType == "blob" {
+ result.Changes = append(result.Changes, change)
+ }
+ }
+
+ return &result, nil
}
// FetchCommitByID fetches the commit data by its ID from the repository.
-func (*Provider) FetchCommitByID(_ context.Context, _ common.OauthContext, _, _, _ string) (*vcs.Commit, error) {
- return nil, errors.New("not implemented")
+//
+// 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)
+ }
+ 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())
+ code, _, body, 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, fmt.Sprintf("commit %q does not exist in the repository %s under the organization %s", commitID, repositoryID, organizationName))
+ }
+ if code != http.StatusOK {
+ return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ type fetchCommitByIDResponse struct {
+ CommitID string `json:"commitId"`
+ Author CommitAuthor `json:"author"`
+ RemoteURL string `json:"remoteUrl"`
+ }
+
+ commit := new(fetchCommitByIDResponse)
+ if err := json.Unmarshal([]byte(body), commit); err != nil {
+ return nil, errors.Wrapf(err, "unmarshal body")
+ }
+
+ return &vcs.Commit{
+ ID: commit.CommitID,
+ AuthorName: commit.Author.Name,
+ CreatedTs: commit.Author.Date.Unix(),
+ URL: commit.RemoteURL,
+ }, nil
}
// GetDiffFileList gets the diff files list between two commits.
-func (*Provider) GetDiffFileList(_ context.Context, _ common.OauthContext, _, _, _, _ string) ([]vcs.FileDiff, error) {
- return nil, errors.New("not implemented")
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/diffs/get?view=azure-devops-rest-7.0&tabs=HTTP#between-commit-ids
+func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, beforeCommit string, afterCommit string) ([]vcs.FileDiff, error) {
+ var result []vcs.FileDiff
+ page := 0
+ for {
+ files, hasMore, err := p.getPaginatedDiffFileList(ctx, oauthCtx, instanceURL, repositoryID, beforeCommit, afterCommit, page)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get paginated diff file list")
+ }
+ result = append(result, files...)
+ if !hasMore {
+ break
+ }
+ page++
+ }
+ return result, nil
}
-// FetchAllRepositoryList fetches all repositories.
-func (*Provider) FetchAllRepositoryList(_ context.Context, _ common.OauthContext, _ string) ([]*vcs.Repository, error) {
- return nil, errors.New("not implemented")
+// 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)
+ }
+ organizationName, repositoryID := parts[0], parts[2]
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+ values.Set("$top", fmt.Sprintf("%d", apiPageSize))
+ values.Set("$skip", fmt.Sprintf("%d", page*apiPageSize))
+ if beforeCommit != "" {
+ values.Set("baseVersion", beforeCommit)
+ values.Set("baseVersionType", "commit")
+ }
+ values.Set("targetVersion", afterCommit)
+ 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())
+ code, _, body, 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, false, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code != http.StatusOK {
+ return nil, false, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ type diffFileResponseChangeItem struct {
+ Path string `json:"path"`
+ }
+ type diffFileResponseChange struct {
+ Item diffFileResponseChangeItem `json:"item"`
+ ChangeType string `json:"changeType"`
+ }
+ type diffFileResponse struct {
+ Changes []diffFileResponseChange `json:"changes"`
+ }
+
+ r := new(diffFileResponse)
+ if err := json.Unmarshal([]byte(body), r); err != nil {
+ return nil, false, errors.Wrapf(err, "failed to unmarshal get diff file list response body, code %v", code)
+ }
+
+ result := make([]vcs.FileDiff, 0, len(r.Changes))
+ for _, c := range r.Changes {
+ var changeType vcs.FileDiffType
+ switch c.ChangeType {
+ case "add":
+ changeType = vcs.FileDiffTypeAdded
+ case "delete":
+ changeType = vcs.FileDiffTypeRemoved
+ case "edit":
+ changeType = vcs.FileDiffTypeModified
+ default:
+ changeType = vcs.FileDiffTypeUnknown
+ }
+ result = append(result, vcs.FileDiff{
+ Path: c.Item.Path,
+ Type: changeType,
+ })
+ }
+
+ return result, len(r.Changes) == apiPageSize, nil
+}
+
+// FetchAllRepositoryList fetches all projects where the authenticated use has permissions, which is required
+// to create webhook in the repository.
+//
+// NOTE: Azure DevOps does not support listing all projects cross all organizations API yet, thus we need
+// to follow the https://stackoverflow.com/questions/53608013/get-all-organizations-via-rest-api-for-azure-devops
+// to get all projects.
+// The request included in this function requires the following scopes:
+// vso.profile, vso.project.
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories/list?view=azure-devops-rest-7.0&tabs=HTTP
+func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.OauthContext, _ string) ([]*vcs.Repository, error) {
+ publicAlias, err := p.getAuthenticatedProfilePublicAlias(ctx, oauthCtx)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get authenticated profile public alias")
+ }
+ log.Info("Authenticated user public alias", zap.String("publicAlias", publicAlias))
+ organizations, err := p.listOrganizationsForMember(ctx, oauthCtx, publicAlias)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to list organizations for member")
+ }
+
+ 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"`
+ }
+
+ urlParams := &url.Values{}
+ urlParams.Set("api-version", "7.0")
+ for _, organization := range organizations {
+ if err := func() error {
+ url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories?%s", url.PathEscape(organization), urlParams.Encode())
+ code, _, body, 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 errors.Wrapf(err, "GET %s", url)
+ }
+ if code != http.StatusOK {
+ return errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ l := new(listRepositoriesResponse)
+ if err := json.Unmarshal([]byte(body), l); err != nil {
+ return errors.Wrapf(err, "failed to unmarshal list organizations for member response body %v, code %v", body, code)
+ }
+
+ for _, r := range l.Value {
+ if r.Project.State != "wellFormed" {
+ log.Debug("Skip the repository whose project is not wellFormed", zap.String("organization", organization), zap.String("project", r.Project.Name), zap.String("repository", r.Name))
+ }
+
+ result = append(result, &vcs.Repository{
+ 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,
+ })
+ }
+ return nil
+ }(); err != nil {
+ return nil, errors.Wrapf(err, "failed to list repositories under the organization %s", organization)
+ }
+ }
+
+ // Sort result by FullPath.
+ slices.SortFunc[*vcs.Repository](result, func(i, j *vcs.Repository) bool {
+ return i.FullPath < j.FullPath
+ })
+
+ return result, nil
+}
+
+// getAuthenticatedProfilePublicAlias gets the authenticated user's profile, and returns the public alias in the
+// profile response.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/profile/profiles/get?view=azure-devops-rest-7.0&tabs=HTTP
+func (p *Provider) getAuthenticatedProfilePublicAlias(ctx context.Context, oauthCtx common.OauthContext) (string, error) {
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+ url := fmt.Sprintf("https://app.vssps.visualstudio.com/_apis/profile/profiles/me?%s", values.Encode())
+
+ code, _, body, 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 "", errors.Wrapf(err, "GET %s", url)
+ }
+ if code != http.StatusOK {
+ return "", errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ type profileAlias struct {
+ PublicAlias string `json:"publicAlias"`
+ }
+
+ r := new(profileAlias)
+ if err := json.Unmarshal([]byte(body), r); err != nil {
+ return "", errors.Wrapf(err, "failed to unmarshal profile response body, code %v", code)
+ }
+
+ return r.PublicAlias, nil
+}
+
+// listOrganizationsForMember lists all organization for a given member.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/account/accounts/list?view=azure-devops-rest-7.0&tabs=HTTP
+func (p *Provider) listOrganizationsForMember(ctx context.Context, oauthCtx common.OauthContext, memberID string) ([]string, error) {
+ urlParams := &url.Values{}
+ urlParams.Set("memberId", memberID)
+ urlParams.Set("api-version", "7.0")
+ url := fmt.Sprintf("https://app.vssps.visualstudio.com/_apis/accounts?%s", urlParams.Encode())
+
+ code, _, body, 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.StatusOK {
+ return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ type accountsValue struct {
+ AccountName string `json:"accountName"`
+ }
+ type accountsResponse struct {
+ Count int `json:"count"`
+ Value []accountsValue `json:"value"`
+ }
+
+ r := new(accountsResponse)
+ if err := json.Unmarshal([]byte(body), r); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal list organizations for member response body, code %v", code)
+ }
+
+ result := make([]string, 0, len(r.Value))
+ for _, v := range r.Value {
+ result = append(result, v.AccountName)
+ }
+
+ return result, nil
}
// FetchRepositoryFileList fetches the all files from the given repository tree recursively.
-func (*Provider) FetchRepositoryFileList(_ context.Context, _ common.OauthContext, _, _, _, _ string) ([]*vcs.RepositoryTreeNode, error) {
- return nil, errors.New("not implemented")
+//
+// 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)
+ }
+ 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())
+
+ code, _, body, 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.StatusOK {
+ return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ type getTreesResponseTreeEntries struct {
+ RelativePath string `json:"relativePath"`
+ GitObjectType string `json:"gitObjectType"`
+ }
+ type getTreesResponse struct {
+ TreeEntries []getTreesResponseTreeEntries `json:"treeEntries"`
+ }
+
+ r := new(getTreesResponse)
+ if err := json.Unmarshal([]byte(body), r); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal get trees response body, code %v", code)
+ }
+
+ result := make([]*vcs.RepositoryTreeNode, 0, len(r.TreeEntries))
+ for _, e := range r.TreeEntries {
+ if e.GitObjectType != "blob" || !strings.HasPrefix(e.RelativePath, filePath) {
+ continue
+ }
+ result = append(result, &vcs.RepositoryTreeNode{
+ Path: e.RelativePath,
+ Type: e.GitObjectType,
+ })
+ }
+ return result, nil
}
// CreateFile creates a file at given path in the repository.
-func (*Provider) CreateFile(_ context.Context, _ common.OauthContext, _, _, _ string, _ vcs.FileCommitCreate) error {
- return errors.New("not implemented")
+func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
+ return p.createOrUpdateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate, true)
}
// 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.CreateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate)
+ return p.createOrUpdateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate, false)
+}
+
+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)
+ }
+ 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())
+ code, _, body, 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 "", errors.Wrapf(err, "GET %s", url)
+ }
+ if code != http.StatusOK {
+ return "", errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ type getCommitsOnBranchResponseValue struct {
+ CommitID string `json:"commitId"`
+ }
+ type getCommitsOnBranchResponse struct {
+ Value []getCommitsOnBranchResponseValue `json:"value"`
+ }
+
+ g := new(getCommitsOnBranchResponse)
+ if err := json.Unmarshal([]byte(body), g); err != nil {
+ return "", errors.Wrapf(err, "failed to unmarshal get commits on branch response body, code %v", code)
+ }
+
+ return g.Value[0].CommitID, nil
+}
+
+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)
+ }
+ organizationName, exteralRepositoryID := parts[0], parts[2]
+
+ changeType := "edit"
+ if create {
+ changeType = "add"
+ }
+
+ 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(exteralRepositoryID), values.Encode())
+
+ type createFileReqeustCommitChangesItem struct {
+ Path string `json:"path"`
+ }
+ type createFileReqeustCommitChangesNewContent struct {
+ Content string `json:"content"`
+ ContentType string `json:"contentType"`
+ }
+ type createFileReqeustCommitChanges struct {
+ ChangeType string `json:"changeType"`
+ Item createFileReqeustCommitChangesItem `json:"item"`
+ NewContent createFileReqeustCommitChangesNewContent `json:"newContent"`
+ }
+ type createFileReqeustCommitAuthor struct {
+ Date string `json:"date"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ }
+ type createFileReqeustCommit struct {
+ Comment string `json:"comment"`
+ Changes []createFileReqeustCommitChanges `json:"changes"`
+ Author createFileReqeustCommitAuthor `json:"author"`
+ Committer createFileReqeustCommitAuthor `json:"committer"`
+ }
+ type createFileRequestRefUpdates struct {
+ Name string `json:"name"`
+ OldObjectID string `json:"oldObjectId"`
+ }
+ type createFileRequest struct {
+ RefUpdates []createFileRequestRefUpdates `json:"refUpdates"`
+ Commits []createFileReqeustCommit `json:"commits"`
+ }
+
+ for i := 0; i < 3; i++ {
+ branchCommit, err := p.getLatestCommitIDOnBranch(ctx, oauthCtx, repositoryID, fileCommitCreate.Branch)
+ if err != nil {
+ return errors.Wrapf(err, "failed to get latest commit ID on branch %q", fileCommitCreate.Branch)
+ }
+
+ requestBody := &createFileRequest{
+ RefUpdates: []createFileRequestRefUpdates{
+ {
+ Name: fmt.Sprintf("refs/heads/%s", fileCommitCreate.Branch),
+ OldObjectID: branchCommit,
+ },
+ },
+ Commits: []createFileReqeustCommit{
+ {
+ Comment: fileCommitCreate.CommitMessage,
+ Changes: []createFileReqeustCommitChanges{
+ {
+ ChangeType: changeType,
+ Item: createFileReqeustCommitChangesItem{
+ Path: filePath,
+ },
+ NewContent: createFileReqeustCommitChangesNewContent{
+ Content: fileCommitCreate.Content,
+ ContentType: "rawtext",
+ },
+ },
+ },
+ },
+ },
+ }
+ if fileCommitCreate.AuthorName != "" && fileCommitCreate.AuthorEmail != "" {
+ requestBody.Commits[0].Author = createFileReqeustCommitAuthor{
+ Date: time.Now().Format(time.RFC3339),
+ Name: fileCommitCreate.AuthorName,
+ Email: fileCommitCreate.AuthorEmail,
+ }
+ requestBody.Commits[0].Committer = createFileReqeustCommitAuthor{
+ Date: time.Now().Format(time.RFC3339),
+ Name: fileCommitCreate.AuthorName,
+ Email: fileCommitCreate.AuthorEmail,
+ }
+ }
+
+ marshalBody, err := json.Marshal(requestBody)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal create file request body, request body: %+v", requestBody)
+ }
+ code, _, body, err := oauth.Post(ctx, p.client, url, &oauthCtx.AccessToken, bytes.NewReader(marshalBody), tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ oauthCtx.Refresher,
+ ))
+ if err != nil {
+ 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)))
+ continue
+ }
+ if code != http.StatusCreated {
+ return errors.Errorf("non-201 POST %s status code %d with body %q", url, code, string(body))
+ }
+
+ return nil
+ }
+
+ return errors.Errorf("failed to create file after 3 retries")
}
// ReadFileMeta reads the metadata of the given file in the repository.
-func (*Provider) ReadFileMeta(_ context.Context, _ common.OauthContext, _, _, _, _ string) (*vcs.FileMeta, error) {
- return nil, errors.New("not implemented")
+//
+// Docs:
+// - 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, ref string) (*vcs.FileMeta, error) {
+ parts := strings.Split(repositoryID, "/")
+ if len(parts) != 3 {
+ return nil, errors.Errorf("invalid repository ID %q", repositoryID)
+ }
+ organizationName, repositoryID := parts[0], parts[2]
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+ values.Set("scopePath", filePath)
+ values.Set("$format", "json")
+ values.Set("versionDescriptor.version", ref)
+ itemsURL := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/items?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), values.Encode())
+
+ type fileMetaResponseValue struct {
+ ObjectID string `json:"objectId"`
+ CommitID string `json:"commitId"`
+ Path string `json:"path"`
+ URL string `json:"url"`
+ }
+ type fileMetaResponse struct {
+ Value []fileMetaResponseValue `json:"value"`
+ }
+
+ code, _, body, err := oauth.Get(ctx, p.client, itemsURL, &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", itemsURL)
+ }
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to read file meta from URL %s", itemsURL)
+ }
+ if code != http.StatusOK {
+ return nil, errors.Errorf("non-200 GET %s status code %d with body %q", itemsURL, code, string(body))
+ }
+
+ r := new(fileMetaResponse)
+ if err := json.Unmarshal([]byte(body), r); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal get file meta response body, code %v", code)
+ }
+
+ // Validate Presumption: The response should only contain one file meta.
+ if len(r.Value) != 1 {
+ return nil, errors.Wrapf(err, fmt.Sprintf("expect to get one file meta, but got %d, response: %+v", len(r.Value), r))
+ }
+
+ 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())
+
+ type blobsResponse struct {
+ Size int64 `json:"size"`
+ }
+
+ code, _, body, err = oauth.Get(ctx, p.client, blobURL, &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", blobURL)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to read file size from URL %s", blobURL)
+ }
+ if code != http.StatusOK {
+ return nil, errors.Errorf("non-200 GET %s status code %d with body %q", blobURL, code, string(body))
+ }
+
+ b := new(blobsResponse)
+ if err := json.Unmarshal([]byte(body), b); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal get file meta response body, code %v", code)
+ }
+
+ return &vcs.FileMeta{
+ Name: filepath.Base(r.Value[0].Path),
+ Path: r.Value[0].Path,
+ Size: b.Size,
+ LastCommitID: r.Value[0].CommitID,
+ SHA: r.Value[0].ObjectID,
+ }, nil
}
// ReadFileContent reads the content of the given file in the repository.
-func (*Provider) ReadFileContent(_ context.Context, _ common.OauthContext, _, _, _, _ string) (string, error) {
- return "", errors.New("not implemented")
+//
+// 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, ref string) (string, error) {
+ parts := strings.Split(repositoryID, "/")
+ if len(parts) != 3 {
+ return "", errors.Errorf("invalid repository ID %q", repositoryID)
+ }
+ organizationName, repositoryID := parts[0], parts[2]
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+ values.Set("download", "false")
+ values.Set("resolveLfs", "true")
+ values.Set("includeContent", "true")
+ values.Set("path", filePath)
+ values.Set("versionDescriptor.version", ref)
+ url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories/%s/items?%s", url.PathEscape(organizationName), url.PathEscape(repositoryID), values.Encode())
+
+ code, _, body, 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 "", errors.Wrapf(err, "GET %s", url)
+ }
+ if code != http.StatusOK {
+ return "", errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+ return string(body), nil
}
-// GetBranch gets the given branch in the repository.
-func (*Provider) GetBranch(_ context.Context, _ common.OauthContext, _, _, _ string) (*vcs.BranchInfo, error) {
- return nil, errors.New("not implemented")
+// GetBranch try to retrieve the branch from the repository, and returns the last commit ID of the branch, if the branch
+// does not exist, it returns common.NotFound.
+// Args:
+// - repositoryID: The repository ID in the format of <organization>/<repository>.
+// - branchName: The branch name.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/stats/get?view=azure-devops-rest-7.0&tabs=HTTP
+func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+ if branchName == "" {
+ 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)
+ }
+ 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())
+
+ code, _, body, 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, fmt.Sprintf("branch %q does not exist in the repository %s under the organization %s", branchName, repositoryID, organizationName))
+ }
+ if code != http.StatusOK {
+ return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
+ }
+
+ type branchStatResponseCommit struct {
+ CommitID string `json:"commitId"`
+ }
+ type branchStatResponse struct {
+ Name string `json:"name"`
+ Commit branchStatResponseCommit `json:"commit"`
+ }
+
+ 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 &vcs.BranchInfo{
+ Name: r.Name,
+ LastCommitID: r.Commit.CommitID,
+ }, nil
}
// CreateBranch creates the branch in the repository.
@@ -178,17 +1021,216 @@ func (*Provider) UpsertEnvironmentVariable(context.Context, common.OauthContext,
return errors.New("not supported")
}
-// CreateWebhook creates a webhook in the repository with given payload.
-func (*Provider) CreateWebhook(_ context.Context, _ common.OauthContext, _, _ string, _ []byte) (string, error) {
- return "", errors.New("not implemented")
+// CreateWebhook creates a webhook in the organization, and returns the webhook ID which can be used in PatchWebhook.
+// API Version 7.0 do not specify the OAuth scope for creating webhook explicitly, but it works.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/hooks/subscriptions/create?view=azure-devops-rest-7.0&tabs=HTTP
+func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, _, externalRepositoryID string, payload []byte) (string, error) {
+ parts := strings.Split(externalRepositoryID, "/")
+ if len(parts) != 3 {
+ return "", errors.Errorf("invalid repository ID %q", externalRepositoryID)
+ }
+ organizationName, _, _ := parts[0], parts[1], parts[2]
+ urlParams := &url.Values{}
+ urlParams.Set("api-version", "7.0")
+ url := fmt.Sprintf("https://dev.azure.com/%s/_apis/hooks/subscriptions?%s", url.PathEscape(organizationName), urlParams.Encode())
+ code, _, body, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(payload),
+ tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to create webhook")
+ }
+ if code != http.StatusOK {
+ return "", errors.Errorf("failed to create webhook, code: %v, body: %s", code, string(body))
+ }
+
+ type createServiceResponse struct {
+ ID string `json:"id"`
+ }
+ c := new(createServiceResponse)
+ if err := json.Unmarshal([]byte(body), c); err != nil {
+ return "", errors.Wrapf(err, "failed to unmarshal create webhook response body, code %v", code)
+ }
+ return fmt.Sprintf("%s/%s", organizationName, c.ID), nil
}
-// PatchWebhook patches the webhook in the repository with given payload.
+// PatchWebhook patches the webhook in the repository.
+// Due to the Azure DevOps API do not provide an endpoint the update the webhook,
+// so we should set the webhook full configuration in the payload.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/hooks/subscriptions/replace-subscription?view=azure-devops-rest-7.0&tabs=HTTP
+// (2023/07/07, zp): It seems that the PatchWebhook API of each provider is not used by Bytebase, should we remove it?
func (*Provider) PatchWebhook(_ context.Context, _ common.OauthContext, _, _, _ string, _ []byte) error {
return errors.New("not implemented")
}
-// DeleteWebhook deletes the webhook from the repository.
-func (*Provider) DeleteWebhook(_ context.Context, _ common.OauthContext, _, _, _ string) error {
- return errors.New("not implemented")
+// DeleteWebhook deletes the webhook in the repository.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/hooks/subscriptions/delete?view=azure-devops-rest-7.0&tabs=HTTP
+func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, _, _, webhookID string) error {
+ // By design, we encode the webhook ID as <organization>/<webhookID> for Azure DevOps.
+ parts := strings.Split(webhookID, "/")
+ if len(parts) != 2 {
+ return errors.Errorf("invalid webhook ID %q", webhookID)
+ }
+ organizationName, webhookID := parts[0], parts[1]
+
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+ url := fmt.Sprintf("https://dev.azure.com/%s/_apis/hooks/subscriptions/%s?%s", url.PathEscape(organizationName), url.PathEscape(webhookID), values.Encode())
+
+ code, _, body, err := oauth.Delete(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ oauthContext{
+ RefreshToken: oauthCtx.RefreshToken,
+ ClientSecret: oauthCtx.ClientSecret,
+ RedirectURL: oauthCtx.RedirectURL,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "failed to send delete webhook request")
+ }
+ if code != http.StatusNoContent {
+ return errors.Errorf("failed to delete webhook, code: %v, body: %s", code, string(body))
+ }
+
+ 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) {
+ parts := strings.Split(repositoryID, "/")
+ if len(parts) != 3 {
+ return nil, errors.Errorf("invalid repository ID %q", repositoryID)
+ }
+ 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())
+
+ client := &http.Client{}
+
+ code, _, body, err := oauth.Get(
+ ctx,
+ 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, "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
+}
+
+// oauthContext is the request context for OAuth.
+type oauthContext struct {
+ ClientSecret string
+ RefreshToken string
+ RedirectURL string
+}
+
+type refreshOAuthTokenResponse struct {
+ AccessToken string `json:"access_token"`
+ ExpiresIn string `json:"expires_in"`
+ RefreshToken string `json:"refresh_token"`
+}
+
+// https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops#refresh-an-expired-access-token
+func tokenRefresher(oauthCtx oauthContext, refresher common.TokenRefresher) oauth.TokenRefresher {
+ return func(ctx context.Context, client *http.Client, oldToken *string) error {
+ values := url.Values{}
+ values.Set("client_assertion_type", `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)
+ values.Set("client_assertion", oauthCtx.ClientSecret)
+ values.Set("grant_type", "refresh_token")
+ values.Set("assertion", oauthCtx.RefreshToken)
+ values.Set("redirect_uri", oauthCtx.RedirectURL)
+ encodedValues := values.Encode()
+
+ url := "https://app.vssps.visualstudio.com/oauth2/token"
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(encodedValues))
+ if err != nil {
+ return errors.Wrapf(err, "construct POST %s", url)
+ }
+
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Content-Length", strconv.Itoa(len(encodedValues)))
+ resp, err := client.Do(req)
+ if err != nil {
+ return errors.Wrapf(err, "failed to refresh OAuth token")
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return errors.Wrapf(err, "read body of POST %s", url)
+ }
+ defer 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)
+ }
+
+ r := new(refreshOAuthTokenResponse)
+ if err := json.Unmarshal(body, r); err != nil {
+ return errors.Wrapf(err, "failed to unmarshal refresh OAuth token response body, code %v", resp.StatusCode)
+ }
+
+ *oldToken = r.AccessToken
+
+ var expiresIn int64
+ if r.ExpiresIn != "" {
+ expiresAt, _ := strconv.ParseInt(r.ExpiresIn, 10, 64)
+ expiresIn = time.Now().Unix() + expiresAt
+ }
+ return refresher(r.AccessToken, r.RefreshToken, expiresIn)
+ }
}
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index 178663e8be..c3648893f7 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -119,13 +119,6 @@ func (p *Provider) ExchangeOAuthToken(ctx context.Context, instanceURL string, o
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"`
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index 290017ed55..88e4473de1 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -203,51 +203,6 @@ type WebhookPushEvent struct {
Commits []WebhookCommit `json:"commits"`
}
-// fetchUserInfoImpl fetches user information from the given resourceURI, which
-// should be either "user" or "users/{username}".
-func (p *Provider) fetchUserInfoImpl(ctx context.Context, oauthCtx common.OauthContext, instanceURL, resourceURI string) (*vcs.UserInfo, error) {
- url := fmt.Sprintf("%s/%s", p.APIURL(instanceURL), resourceURI)
- 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 read user info from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to read user info from URL %s, status code: %d, body: %s", url, code, body)
- }
-
- var user User
- if err = json.Unmarshal([]byte(body), &user); err != nil {
- return nil, errors.Wrap(err, "unmarshal")
- }
- return &vcs.UserInfo{
- PublicEmail: user.Email,
- Name: user.Name,
- State: vcs.StateActive,
- }, err
-}
-
-// TryLogin tries to fetch the user info from the current OAuth context.
-func (p *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*vcs.UserInfo, error) {
- return p.fetchUserInfoImpl(ctx, oauthCtx, instanceURL, "user")
-}
-
// CommitAuthor represents a GitHub API response for a commit author.
type CommitAuthor struct {
// Date expects corresponding JSON value is a string in RFC 3339 format,
@@ -674,6 +629,7 @@ func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContex
return nil, errors.Wrapf(err, "GET %s", url)
}
+ // TODO(zp): should check non-200 return value?
if code == http.StatusNotFound {
return nil, common.Errorf(common.NotFound, "failed to read file meta from URL %s", url)
} else if code >= 300 {
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index 7aef220e27..81863cd2f2 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -314,51 +314,6 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx co
return repos, len(repos) >= apiPageSize, nil
}
-// fetchUserInfoImpl fetches user information from the given resourceURI, which
-// should be either "user" or "users/{userID}".
-func (p *Provider) fetchUserInfoImpl(ctx context.Context, oauthCtx common.OauthContext, instanceURL, resourceURI string) (*vcs.UserInfo, error) {
- url := fmt.Sprintf("%s/%s", p.APIURL(instanceURL), resourceURI)
- 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 read user info from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to read user info from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- var userInfo vcs.UserInfo
- if err := json.Unmarshal([]byte(body), &userInfo); err != nil {
- return nil, errors.Wrap(err, "unmarshal")
- }
- return &userInfo, err
-}
-
-// TryLogin tries to fetch the user info from the current OAuth context.
-func (p *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*vcs.UserInfo, error) {
- return p.fetchUserInfoImpl(ctx, oauthCtx, instanceURL, "user")
-}
-
// FetchCommitByID fetches the commit data by its ID from the repository.
func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, commitID string) (*vcs.Commit, error) {
url := fmt.Sprintf("%s/projects/%s/repository/commits/%s", p.APIURL(instanceURL), repositoryID, commitID)
diff --git a/backend/plugin/vcs/internal/oauth/oauth.go b/backend/plugin/vcs/internal/oauth/oauth.go
index 1f6a2bba78..108021b6c0 100644
--- a/backend/plugin/vcs/internal/oauth/oauth.go
+++ b/backend/plugin/vcs/internal/oauth/oauth.go
@@ -157,6 +157,11 @@ func (e oauthError) Error() string {
// When it's error like 404, GitLab API doesn't return it as error so we keep
// the similar behavior and let caller check the response status code.
func getOAuthErrorDetails(code int, body []byte) error {
+ // Special case for Azure DevOps OAuth error.
+ if code == http.StatusNonAuthoritativeInfo && bytes.Contains(body, []byte("Azure DevOps Services | Sign In")) {
+ return &oauthError{}
+ }
+
if 200 <= code && code < 300 {
return nil
}
diff --git a/backend/plugin/vcs/vcs.go b/backend/plugin/vcs/vcs.go
index 435e0ab72d..146442a35f 100644
--- a/backend/plugin/vcs/vcs.go
+++ b/backend/plugin/vcs/vcs.go
@@ -205,18 +205,13 @@ type Provider interface {
// oauthExchange: api message for exchanging oauth token
ExchangeOAuthToken(ctx context.Context, instanceURL string, oauthExchange *common.OAuthExchange) (*OAuthToken, error)
- // Try to use this provider as an auth provider and fetch the user info from the OAuth context
- //
- // oauthCtx: OAuth context to write the file content
- // instanceURL: VCS instance URL
- TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*UserInfo, error)
// Fetch the commit data by id
//
// oauthCtx: OAuth context to fetch commit
// instanceURL: VCS instance URL
- // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
+ // externalRepositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
// commitID: the commit ID
- FetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, commitID string) (*Commit, error)
+ FetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, instanceURL, externalRepositoryID, commitID string) (*Commit, error)
// Get the diff files list between two commits
//
// oauthCtx: OAuth context to fetch commit
diff --git a/backend/server/webhook.go b/backend/server/webhook.go
index e32016a6c5..d13b12cd12 100644
--- a/backend/server/webhook.go
+++ b/backend/server/webhook.go
@@ -38,7 +38,7 @@ import (
"github.com/bytebase/bytebase/backend/plugin/vcs"
// Register azure plugin.
- _ "github.com/bytebase/bytebase/backend/plugin/vcs/azure"
+ "github.com/bytebase/bytebase/backend/plugin/vcs/azure"
"github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket"
"github.com/bytebase/bytebase/backend/plugin/vcs/github"
"github.com/bytebase/bytebase/backend/plugin/vcs/gitlab"
@@ -324,6 +324,176 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return c.String(http.StatusOK, strings.Join(allCreatedMessages, "\n"))
})
+ g.POST("/azure/:id", func(c echo.Context) error {
+ ctx := c.Request().Context()
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read webhook request").SetInternal(err)
+ }
+ pushEvent := new(azure.ServiceHookCodePushEvent)
+ if err := json.Unmarshal(body, pushEvent); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)
+ }
+
+ // Valite presumptions.
+ // This shouldn't happen as we only setup webhook to receive push event, just in case.
+ if pushEvent.EventType != "git.push" {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %s, want git.push", pushEvent.EventType))
+ }
+ // All the examples on https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#code-pushed
+ // have only one ref update.
+ if len(pushEvent.Resource.RefUpdates) != 1 {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Presumption failed: the number of ref updates is not 1, got %d", len(pushEvent.Resource.RefUpdates)))
+ }
+ // For Azure DevOps, if users create a new branch and push it to the remote. It will trigger a code push event,
+ // but do not contain any commits in the event. So we do not need to consider the case that the commit id is
+ // all zero.
+ for _, commit := range pushEvent.Resource.Commits {
+ if commit.CommitID == strings.Repeat("0", 40) {
+ return echo.NewHTTPError(http.StatusBadRequest, "Presumption failed: the commit id is all zero")
+ }
+ }
+
+ webhookEndpointID := c.Param("id")
+ // TODO(zp): find a better way to recognize the refine repository id, we use the format:
+ // organization_name/project_name/repository_name
+ repositories, err := s.store.ListRepositoryV2(ctx, &store.FindRepositoryMessage{
+ WebhookEndpointID: &webhookEndpointID,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to list repositories").SetInternal(err)
+ }
+ // Check the consistence of the repositories, it should not throw any error by right.
+ for i := 1; i < len(repositories); i++ {
+ if repositories[i].ExternalID != repositories[0].ExternalID {
+ return echo.NewHTTPError(http.StatusPreconditionFailed, "The repositories external id are not consistent: %v", fmt.Sprintf("%v", repositories))
+ }
+ }
+ repositoryID := repositories[0].ExternalID
+
+ // Filter out all the commits created by Bytebase(e.g. write-back the latest schema) to avoid infinite loop.
+ nonBytebaseCommitList := filterAzureBytebaseCommit(pushEvent.Resource.Commits)
+ if len(nonBytebaseCommitList) == 0 {
+ var commitIDs []string
+ for _, commit := range pushEvent.Resource.Commits {
+ commitIDs = append(commitIDs, commit.CommitID)
+ }
+ log.Debug("all commits are created by Bytebase",
+ zap.String("repoURL", pushEvent.Resource.Repository.URL),
+ zap.String("repoID", repositoryID),
+ zap.String("repoName", pushEvent.Resource.Repository.Name),
+ zap.String("commits", strings.Join(commitIDs, ", ")),
+ )
+ return c.String(http.StatusOK, "OK")
+ }
+ pushEvent.Resource.Commits = nonBytebaseCommitList
+
+ // Filter out the repository which does not match the branch filter.
+ filter := func(repo *store.RepositoryMessage) (bool, error) {
+ refUpdates := pushEvent.Resource.RefUpdates
+ for _, refUpdate := range refUpdates {
+ trimmed := strings.TrimPrefix(refUpdate.Name, "refs/heads/")
+ if trimmed == repo.BranchFilter {
+ return true, nil
+ }
+ }
+ return false, nil
+ }
+ repositoryList, err := s.filterRepository(ctx, c.Param("id"), repositoryID, filter)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to filter repository").SetInternal(err)
+ }
+ if len(repositoryList) == 0 {
+ log.Debug("Empty handle repo list. Ignore this push event.")
+ return c.String(http.StatusOK, "No repository matched")
+ }
+
+ // commitList := make([]vcs.Commit, len(nonBytebaseCommitList))
+ // // Azure DevOps' service hook does not contain the file diff information for each commit, so we need to backfill
+ // // the file diff information by ourselves.
+ // // We will use the previous commit id as the base commit id and the current commit id as the target commit id to
+ // // get the file diff information commit by commit. We use the oldObjectId in resources.refUpdates as the base commit id
+ // // for the first commit.
+ // // NOTE: We presume that the sequence of the commits in the code push event is the reverse order of the commit sequence(aka. stack sequence, commit first, appear last) in the repository.
+ backfillCommits := make([]vcs.Commit, 0, len(nonBytebaseCommitList))
+ for _, commit := range nonBytebaseCommitList {
+ changes, err := azure.GetChangesByCommit(ctx, common.OauthContext{
+ ClientID: repositoryList[0].vcs.ApplicationID,
+ ClientSecret: repositoryList[0].vcs.Secret,
+ AccessToken: repositoryList[0].repository.AccessToken,
+ RefreshToken: repositoryList[0].repository.RefreshToken,
+ Refresher: utils.RefreshToken(ctx, s.store, repositoryList[0].repository.WebURL),
+ }, repositoryList[0].repository.ExternalID, commit.CommitID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get changes by commit %q", commit.CommitID)).SetInternal(err)
+ }
+
+ var addedList, modifiedList []string
+ for _, change := range changes.Changes {
+ switch change.ChangeType {
+ case "add":
+ addedList = append(addedList, change.Item.Path)
+ case "edit":
+ modifiedList = append(modifiedList, change.Item.Path)
+ }
+ }
+
+ backfillCommits = append(backfillCommits, vcs.Commit{
+ ID: commit.CommitID,
+ Title: commit.Comment,
+ Message: commit.Comment,
+ CreatedTs: commit.Author.Date.Unix(),
+ URL: commit.URL,
+ AuthorName: commit.Author.Name,
+ AuthorEmail: commit.Author.Email,
+ AddedList: addedList,
+ ModifiedList: modifiedList,
+ })
+ }
+
+ // Backfill web url for commits.
+ if pushEvent.Resource.PushID != 0 {
+ commitsInPush, err := azure.GetPushCommitsByPushID(ctx, common.OauthContext{
+ ClientID: repositoryList[0].vcs.ApplicationID,
+ ClientSecret: repositoryList[0].vcs.Secret,
+ AccessToken: repositoryList[0].repository.AccessToken,
+ RefreshToken: repositoryList[0].repository.RefreshToken,
+ Refresher: utils.RefreshToken(ctx, s.store, repositoryList[0].repository.WebURL),
+ }, repositoryList[0].repository.ExternalID, pushEvent.Resource.PushID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get push commits by push id %d", pushEvent.Resource.PushID)).SetInternal(err)
+ }
+ // Convert values to map from commitID to remote url.
+ commitID2Value := make(map[string]string)
+ for _, value := range commitsInPush.Value {
+ commitID2Value[value.CommitID] = value.RemoteURL
+ }
+ for i := range backfillCommits {
+ if remoteURL, ok := commitID2Value[backfillCommits[i].ID]; ok {
+ backfillCommits[i].URL = remoteURL
+ }
+ }
+ }
+
+ baseVCSPushEvent := vcs.PushEvent{
+ VCSType: vcs.AzureDevOps,
+ Ref: pushEvent.Resource.RefUpdates[0].Name,
+ Before: pushEvent.Resource.RefUpdates[0].OldObjectID,
+ After: pushEvent.Resource.RefUpdates[0].NewObjectID,
+ RepositoryID: repositoryList[0].repository.ExternalID,
+ RepositoryURL: repositoryList[0].repository.WebURL,
+ RepositoryFullPath: repositoryList[0].repository.ExternalID,
+ AuthorName: pushEvent.Resource.PushedBy.DisplayName,
+ CommitList: backfillCommits,
+ }
+
+ createdMessages, err := s.processPushEvent(ctx, repositoryList, baseVCSPushEvent)
+ if err != nil {
+ return err
+ }
+ return c.String(http.StatusOK, strings.Join(createdMessages, "\n"))
+ })
// id is the webhookEndpointID in repository
// This endpoint is generated and injected into GitHub action & GitLab CI during the VCS setup.
g.POST("/sql-review/:id", func(c echo.Context) error {
@@ -968,14 +1138,15 @@ func (s *Server) processPushEvent(ctx context.Context, repoInfoList []*repoInfo,
}
}
- var createdMessageList []string
repoID2FileItemList := groupFileInfoByRepo(filteredDistinctFileList, repoInfoList)
+
+ var createdMessageList []string
for _, fileInfoListInRepo := range repoID2FileItemList {
// There are possibly multiple files in the push event.
// Each file corresponds to a (database name, schema version) pair.
// We want the migration statements are sorted by the file's schema version, and grouped by the database name.
- dbID2FileInfoList := groupFileInfoByDatabase(fileInfoListInRepo)
- for _, fileInfoListInDB := range dbID2FileInfoList {
+ dbName2FileInfoList := groupFileInfoByDatabase(fileInfoListInRepo)
+ for _, fileInfoListInDB := range dbName2FileInfoList {
fileInfoListSorted := sortFilesBySchemaVersion(fileInfoListInDB)
repoInfo := fileInfoListSorted[0].repoInfo
pushEvent := baseVCSPushEvent
@@ -1013,7 +1184,8 @@ func (s *Server) processPushEvent(ctx context.Context, repoInfoList []*repoInfo,
return createdMessageList, nil
}
-// Users may merge commits from other branches, and some of the commits merged in may already be merged into the main branch.
+// Users may merge commits from other branches,
+// and some of the commits merged in may already be merged into the main branch.
// In that case, the commits in the push event contains files which are not added in this PR/MR.
// We use the compare API to get the file diffs and filter files by the diffs.
// TODO(dragonly): generate distinct file change list from the commits diff instead of filter.
@@ -1950,6 +2122,17 @@ func getSQLAdviceFileList(adviceMap map[string][]advisor.Advice) []string {
return fileList
}
+func filterAzureBytebaseCommit(list []azure.ServiceHookCodePushEventResourceCommit) []azure.ServiceHookCodePushEventResourceCommit {
+ var result []azure.ServiceHookCodePushEventResourceCommit
+ for _, commit := range list {
+ if commit.Author.Name == vcs.BytebaseAuthorName && commit.Author.Email == vcs.BytebaseAuthorEmail {
+ continue
+ }
+ result = append(result, commit)
+ }
+ return result
+}
+
func filterGitHubBytebaseCommit(list []github.WebhookCommit) []github.WebhookCommit {
var result []github.WebhookCommit
for _, commit := range list {
diff --git a/frontend/src/components/RepositoryPanel.vue b/frontend/src/components/RepositoryPanel.vue
index d7e4caf60c..91a289dfed 100644
--- a/frontend/src/components/RepositoryPanel.vue
+++ b/frontend/src/components/RepositoryPanel.vue
@@ -281,6 +281,7 @@ import {
ExternalVersionControl,
ExternalVersionControl_Type,
} from "@/types/proto/v1/externalvs_service";
+import { getVCSUid } from "@/store/modules/v1/common";
interface LocalState {
repositoryConfig: RepositoryConfig;
@@ -475,6 +476,9 @@ const doUpdate = async () => {
state.repositoryConfig.enableSQLReviewCI;
const repositoryPatch: Partial<ProjectGitOpsInfo> = {};
+
+ repositoryPatch.vcsUid = `${getVCSUid(props.vcs.name)}`;
+
if (props.repository.branchFilter != state.repositoryConfig.branchFilter) {
repositoryPatch.branchFilter = state.repositoryConfig.branchFilter;
}
diff --git a/frontend/src/components/RepositoryVCSProviderPanel.vue b/frontend/src/components/RepositoryVCSProviderPanel.vue
index 40ac82abd4..1ec3e5e93a 100644
--- a/frontend/src/components/RepositoryVCSProviderPanel.vue
+++ b/frontend/src/components/RepositoryVCSProviderPanel.vue
@@ -18,6 +18,9 @@
<template v-if="vcs.type === ExternalVersionControl_Type.BITBUCKET">
<img class="h-6 w-auto" src="../assets/bitbucket-logo.svg" />
</template>
+ <template v-if="vcs.type === ExternalVersionControl_Type.AZURE_DEVOPS">
+ <img class="h-6 w-auto" src="../assets/azure-devops-logo.svg" />
+ </template>
<span>{{ vcs.title }}</span>
</button>
</template>
@@ -116,6 +119,8 @@ const selectVCS = (vcs: ExternalVersionControl) => {
authorizeUrl = `${vcs.url}/login/oauth/authorize`;
} else if (vcs.type === ExternalVersionControl_Type.BITBUCKET) {
authorizeUrl = `https://bitbucket.org/site/oauth2/authorize`;
+ } else if (vcs.type === ExternalVersionControl_Type.AZURE_DEVOPS) {
+ authorizeUrl = "https://app.vssps.visualstudio.com/oauth2/authorize";
}
openWindowForOAuth(
authorizeUrl,
diff --git a/frontend/src/components/VCSProviderOAuthPanel.vue b/frontend/src/components/VCSProviderOAuthPanel.vue
index 6a474543fa..80f14b0d32 100644
--- a/frontend/src/components/VCSProviderOAuthPanel.vue
+++ b/frontend/src/components/VCSProviderOAuthPanel.vue
@@ -489,7 +489,9 @@
Scopes
</dt>
<!-- TODO: decide necessary scopes -->
- <dd class="text-sm text-main">Code (full)</dd>
+ <dd class="text-sm text-main">
+ Code (full), Identity (read), Project and team (read)
+ </dd>
</div>
</dl>
</div>
diff --git a/frontend/src/store/modules/v1/repository.ts b/frontend/src/store/modules/v1/repository.ts
index ff1cae1861..246f5c0e2b 100644
--- a/frontend/src/store/modules/v1/repository.ts
+++ b/frontend/src/store/modules/v1/repository.ts
@@ -60,6 +60,7 @@ export const useRepositoryV1Store = defineStore("repository_v1", () => {
allowMissing: true,
});
} else {
+ gitopsInfo.vcsUid = repo.vcsUid;
const updateMask = getUpdateMaskForRepository(repo, gitopsInfo);
if (updateMask.length === 0) {
return repo;
diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.ts
index 57c520757f..b9ad49c5c7 100644
--- a/frontend/src/types/oauth.ts
+++ b/frontend/src/types/oauth.ts
@@ -76,7 +76,7 @@ export function openWindowForOAuth(
// Scopes for Azure: https://learn.microsoft.com/zh-cn/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops#scopes
// We need full scopes in the application: https://stackoverflow.com/questions/56143321/azure-devops-oauth-enpoint-always-returns-error-invalidscope
// TODO: decide necessary scopes
- endpointQueryParams["scope"] = "vso.code_full vso.identity";
+ endpointQueryParams["scope"] = "vso.code_full vso.identity vso.project";
endpointQueryParams["response_type"] = "Assertion";
windowOpenOptions =
"location=yes,left=200,top=200,height=640,width=720,scrollbars=yes,status=yes";
diff --git a/frontend/src/views/SettingWorkspaceVCSDetail.vue b/frontend/src/views/SettingWorkspaceVCSDetail.vue
index ffb68f5cc1..9db9ecc397 100644
--- a/frontend/src/views/SettingWorkspaceVCSDetail.vue
+++ b/frontend/src/views/SettingWorkspaceVCSDetail.vue
@@ -303,6 +303,8 @@ const doUpdate = () => {
authorizeUrl = `https://github.com/login/oauth/authorize`;
} else if (vcs.value.type === ExternalVersionControl_Type.BITBUCKET) {
authorizeUrl = `https://bitbucket.org/site/oauth2/authorize`;
+ } else if (vcs.value.type === ExternalVersionControl_Type.AZURE_DEVOPS) {
+ authorizeUrl = "https://app.vssps.visualstudio.com/oauth2/authorize";
}
const newWindow = openWindowForOAuth(
authorizeUrl,