Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: migrate vcs to v1 (#6428)
Danny Xua67729c0a60f
diff --git a/.golangci.yaml b/.golangci.yamlindex a49f3bc4f7..4118eff5a0 100644--- a/.golangci.yaml+++ b/.golangci.yaml@@ -39,6 +39,7 @@ run:- mysqlskip-dirs:- proto/generated-go+ - frontendlinters-settings:goimports:diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex 5565fed947..d9e167262e 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -542,6 +542,7 @@ func (s *ProjectService) UnsetProjectGitOpsInfo(ctx context.Context, request *v1// TODO: migrate to v1 store.repositoryDelete := &api.RepositoryDelete{+ ProjectID: repo.Project.ID,ProjectResourceID: repo.Project.ResourceID,DeleterID: ctx.Value(common.PrincipalIDContextKey).(int),}@@ -851,7 +852,9 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *vExternalID: request.ProjectGitopsInfo.ExternalId,AccessToken: request.ProjectGitopsInfo.AccessToken,RefreshToken: request.ProjectGitopsInfo.RefreshToken,- ExpiresTs: request.ProjectGitopsInfo.ExpiresTime.Seconds,+ }+ if request.ProjectGitopsInfo.ExpiresTime != nil {+ repositoryCreate.ExpiresTs = request.ProjectGitopsInfo.ExpiresTime.AsTime().Unix()}if repositoryCreate.BranchFilter == "" {diff --git a/backend/server/project.go b/backend/server/project.goindex 508a813bf8..2de2e9d8c9 100644--- a/backend/server/project.go+++ b/backend/server/project.go@@ -1,11 +1,9 @@package serverimport (- "context""encoding/json""fmt""net/http"- "path""path/filepath""regexp""strconv"@@ -15,403 +13,15 @@ import ("github.com/google/jsonapi""github.com/labstack/echo/v4""github.com/pkg/errors"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log"api "github.com/bytebase/bytebase/backend/legacyapi"vcsPlugin "github.com/bytebase/bytebase/backend/plugin/vcs"- "github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket"- "github.com/bytebase/bytebase/backend/plugin/vcs/github"- "github.com/bytebase/bytebase/backend/plugin/vcs/gitlab""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils")func (s *Server) registerProjectRoutes(g *echo.Group) {- // When we link the repository with the project, we will also change the project workflow type to VCS- g.POST("/project/:projectID/repository", func(c echo.Context) error {- ctx := c.Request().Context()-- setting, err := s.store.GetWorkspaceGeneralSetting(ctx)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "failed to get workspace setting").SetInternal(err)- }- if setting.ExternalUrl == "" {- return echo.NewHTTPError(http.StatusBadRequest, "external URL isn't setup yet, see https://www.bytebase.com/docs/get-started/install/external-url")- }-- projectID, err := strconv.Atoi(c.Param("projectID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("projectID"))).SetInternal(err)- }- project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{UID: &projectID})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)- }- if project == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project not found with ID %d", projectID))- }- if project.Deleted {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project %d is deleted", projectID))- }-- repositoryCreate := &api.RepositoryCreate{- ProjectID: projectID,- ProjectResourceID: project.ResourceID,- CreatorID: c.Get(getPrincipalIDContextKey()).(int),- }- if err := jsonapi.UnmarshalPayload(c.Request().Body, repositoryCreate); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed create linked repository request").SetInternal(err)- }- if repositoryCreate.BranchFilter == "" {- return echo.NewHTTPError(http.StatusBadRequest, "Branch must be specified.")- }-- // We need to check the FilePathTemplate in create repository request.- // This avoids to a certain extent that the creation succeeds but does not work.- if err := vcsPlugin.IsAsterisksInTemplateValid(path.Join(repositoryCreate.BaseDirectory, repositoryCreate.FilePathTemplate)); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, errors.Wrap(err, errors.Wrap(err, "Invalid base directory and filepath template combination").Error()))- }-- if err := api.ValidateRepositoryFilePathTemplate(repositoryCreate.FilePathTemplate, project.TenantMode); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformed create linked repository request: %s", err.Error()))- }-- if err := api.ValidateRepositorySchemaPathTemplate(repositoryCreate.SchemaPathTemplate, project.TenantMode); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformed create linked repository request: %s", err.Error()))- }-- vcs, err := s.store.GetVCSByID(ctx, repositoryCreate.VCSID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find VCS for creating repository: %d", repositoryCreate.VCSID)).SetInternal(err)- }- if vcs == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS not found with ID: %d", repositoryCreate.VCSID))- }-- // When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.- if !strings.Contains(repositoryCreate.BranchFilter, "*") {- notFound, err := isBranchNotFound(- ctx,- vcs,- s.store,- repositoryCreate.WebURL,- repositoryCreate.AccessToken,- repositoryCreate.RefreshToken,- repositoryCreate.ExternalID,- repositoryCreate.BranchFilter,- )- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get branch %q", repositoryCreate.BranchFilter)).SetInternal(err)- }- if notFound {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Branch %q not found in repository %s.", repositoryCreate.BranchFilter, repositoryCreate.Name))- }- }-- // For a particular VCS repo, all Bytebase projects share the same webhook.- repositories, err := s.store.FindRepository(ctx, &api.RepositoryFind{- WebURL: &repositoryCreate.WebURL,- })- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find repository with web url: %s", repositoryCreate.WebURL)).SetInternal(err)- }-- repositoryCreate.WebhookURLHost = setting.ExternalUrl- // If we can find at least one repository with the same web url, we will use the same webhook instead of creating a new one.- if len(repositories) > 0 {- repo := repositories[0]- repositoryCreate.WebhookEndpointID = repo.WebhookEndpointID- repositoryCreate.WebhookSecretToken = repo.WebhookSecretToken- repositoryCreate.ExternalWebhookID = repo.ExternalWebhookID- } else {- // Bytebase needs to create a webbook in the connecting repository pointing back to the- // Bytebase address exposed at --external-url.- if setting.ExternalUrl == "" {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Bytebase must start with --external-url to configure GitOps workflow, docs: %s", common.ExternalURLPlaceholder))- }-- workspaceID, err := s.store.GetWorkspaceID(ctx)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, err.Error())- }-- repositoryCreate.WebhookEndpointID = fmt.Sprintf("%s-%d", workspaceID, time.Now().Unix())- secretToken, err := common.RandomString(gitlab.SecretTokenLength)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate random secret token for VCS").SetInternal(err)- }- repositoryCreate.WebhookSecretToken = secretToken-- gitopsWebhookURL := setting.GitopsWebhookUrl- if gitopsWebhookURL == "" {- gitopsWebhookURL = setting.ExternalUrl- }- webhookID, err := createVCSWebhook(ctx, vcs.Type, repositoryCreate.WebhookEndpointID, secretToken, repositoryCreate.AccessToken, vcs.InstanceURL, repositoryCreate.ExternalID, gitopsWebhookURL)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create webhook for project ID: %v", repositoryCreate.ProjectID)).SetInternal(err)- }- repositoryCreate.ExternalWebhookID = webhookID- }- // Remove enclosing /- repositoryCreate.BaseDirectory = strings.Trim(repositoryCreate.BaseDirectory, "/")- repository, err := s.store.CreateRepository(ctx, repositoryCreate)- if err != nil {- if common.ErrorCode(err) == common.Conflict {- return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Project %d has already linked repository", repositoryCreate.ProjectID))- }- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to link project repository").SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, repository); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal link project repository response").SetInternal(err)- }- return nil- })-- // Requires a separate API to return the repository, we do this because- // 1. repository also contains project, which would cause circular dependency when composing it.- // 2. repository info is only needed when fetching a particular project by id, thus it's unnecessary to include it in the project list response.- g.GET("/project/:projectID/repository", func(c echo.Context) error {- ctx := c.Request().Context()- projectID, err := strconv.Atoi(c.Param("projectID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)- }-- repoFind := &api.RepositoryFind{- ProjectID: &projectID,- }- repoList, err := s.store.FindRepository(ctx, repoFind)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectID)).SetInternal(err)- }-- // Just be defensive, this shouldn't happen because we set UNIQUE constraint on project_id- if len(repoList) > 1 {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoList), projectID)).SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, repoList); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", projectID)).SetInternal(err)- }- return nil- })-- // When we unlink the repository with the project, we will also change the project workflow type to UI- g.PATCH("/project/:projectID/repository", func(c echo.Context) error {- ctx := c.Request().Context()- projectID, err := strconv.Atoi(c.Param("projectID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)- }- repoPatch := &api.RepositoryPatch{- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),- }- if err := jsonapi.UnmarshalPayload(c.Request().Body, repoPatch); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch linked repository request").SetInternal(err)- }-- project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{UID: &projectID})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)- }- if project == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project not found with ID %d", projectID))- }- if project.Deleted {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project %d is deleted", projectID))- }-- if repoPatch.FilePathTemplate != nil {- if err := api.ValidateRepositoryFilePathTemplate(*repoPatch.FilePathTemplate, project.TenantMode); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformed patch linked repository request: %s", err.Error()))- }- }-- if repoPatch.SchemaPathTemplate != nil {- if err := api.ValidateRepositorySchemaPathTemplate(*repoPatch.SchemaPathTemplate, project.TenantMode); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformed create linked repository request: %s", err.Error()))- }- }-- // Remove enclosing /- if repoPatch.BaseDirectory != nil {- baseDir := strings.Trim(*repoPatch.BaseDirectory, "/")- repoPatch.BaseDirectory = &baseDir- }-- repoFind := &api.RepositoryFind{- ProjectID: &projectID,- }- repoList, err := s.store.FindRepository(ctx, repoFind)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectID)).SetInternal(err)- }-- // Just be defensive, this shouldn't happen because we set UNIQUE constraint on project_id- if len(repoList) > 1 {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoList), projectID)).SetInternal(err)- } else if len(repoList) == 0 {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", projectID))- }-- repo := repoList[0]- repoPatch.ID = &repo.ID- newBranchFilter := repo.BranchFilter- if repoPatch.BranchFilter != nil {- newBranchFilter = *repoPatch.BranchFilter- }- if newBranchFilter == "" {- return echo.NewHTTPError(http.StatusBadRequest, "Branch must be specified.")- }-- vcs, err := s.store.GetVCSByID(ctx, repo.VCSID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find VCS for creating repository: %d", repo.VCSID)).SetInternal(err)- }- if vcs == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS not found with ID: %d", repo.VCSID))- }-- // When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.- if !strings.Contains(newBranchFilter, "*") {- notFound, err := isBranchNotFound(- ctx,- vcs,- s.store,- repo.WebURL,- repo.AccessToken,- repo.RefreshToken,- repo.ExternalID,- newBranchFilter,- )- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get branch %q", newBranchFilter)).SetInternal(err)- }- if notFound {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Branch %q not found in repository %s.", newBranchFilter, repo.Name))- }- }-- // We need to check the FilePathTemplate in create repository request.- // This avoids to a certain extent that the creation succeeds but does not work.- newBaseDirectory, newFilePathTemplate := repo.BaseDirectory, repo.FilePathTemplate- if repoPatch.BaseDirectory != nil {- newBaseDirectory = *repoPatch.BaseDirectory- }- if repoPatch.FilePathTemplate != nil {- newFilePathTemplate = *repoPatch.FilePathTemplate- }-- if err := vcsPlugin.IsAsterisksInTemplateValid(path.Join(newBaseDirectory, newFilePathTemplate)); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, errors.Wrap(err, "Invalid base directory and filepath template combination").Error())- }-- // DO NOT enable the EnableSQLReviewCI field.- // We will update it through POST /project/:projectID/repository/:repositoryID/sql-review-ci endpoint- if repoPatch.EnableSQLReviewCI != nil && *repoPatch.EnableSQLReviewCI && !repo.EnableSQLReviewCI {- repoPatch.EnableSQLReviewCI = &repo.EnableSQLReviewCI- }-- updatedRepo, err := s.store.PatchRepository(ctx, repoPatch)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectID)).SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, updatedRepo); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", projectID)).SetInternal(err)- }- return nil- })-- // When we unlink the repository with the project, we will also change the project workflow type to UI- g.DELETE("/project/:projectID/repository", func(c echo.Context) error {- ctx := c.Request().Context()- projectID, err := strconv.Atoi(c.Param("projectID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)- }- project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{UID: &projectID})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)- }- if project == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project not found with ID %d", projectID))- }-- repositoryFind := &api.RepositoryFind{- ProjectID: &projectID,- }- repoList, err := s.store.FindRepository(ctx, repositoryFind)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectID)).SetInternal(err)- }-- // Just be defensive, this shouldn't happen because we set UNIQUE constraint on project_id- if len(repoList) > 1 {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(repoList), projectID)).SetInternal(err)- } else if len(repoList) == 0 {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", projectID))- }-- repo := repoList[0]- vcs, err := s.store.GetVCSByID(ctx, repo.VCSID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectID)).SetInternal(err)- }- if vcs == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS not found with ID: %d", repo.VCSID))- }-- repositoryDelete := &api.RepositoryDelete{- ProjectID: projectID,- ProjectResourceID: project.ResourceID,- DeleterID: c.Get(getPrincipalIDContextKey()).(int),- }- if err := s.store.DeleteRepository(ctx, repositoryDelete); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectID)).SetInternal(err)- }-- // We use one webhook in one repo for at least one Bytebase project, so we only delete the webhook if this project is the last one using this webhook.- repos, err := s.store.FindRepository(ctx, &api.RepositoryFind{- WebURL: &repo.WebURL,- })- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find repository for web url: %s", repo.WebURL)).SetInternal(err)- }- 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.- // If we delete it before we delete the repository, then if the repository deletion fails, we will have a broken repository with no webhook.- if err = vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).DeleteWebhook(- ctx,- // Need to get ApplicationID, Secret from vcs instead of repository.vcs since the latter is not composed.- common.OauthContext{- ClientID: vcs.ApplicationID,- ClientSecret: vcs.Secret,- AccessToken: repo.AccessToken,- RefreshToken: repo.RefreshToken,- Refresher: refreshTokenNoop(),- },- vcs.InstanceURL,- repo.ExternalID,- repo.ExternalWebhookID,- ); err != nil {- // Despite the error here, we have deleted the repository in the database, we still return success.- log.Error("Failed to delete webhook for project", zap.Int("project", projectID), zap.Int("repo", repo.ID), zap.Error(err))- }- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- c.Response().WriteHeader(http.StatusOK)- return nil- })-g.PATCH("/project/:id/deployment", func(c echo.Context) error {ctx := c.Request().Context()projectID, err := strconv.Atoi(c.Param("id"))@@ -735,89 +345,6 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {})}-func createVCSWebhook(ctx context.Context, vcsType vcsPlugin.Type, webhookEndpointID, secretToken, accessToken, instanceURL, externalRepoID, gitopsWebhookURL string) (string, error) {- // Create a new webhook and retrieve the created webhook ID- var webhookCreatePayload []byte- var err error- switch vcsType {- case vcsPlugin.GitLab:- webhookCreate := gitlab.WebhookCreate{- URL: fmt.Sprintf("%s/hook/gitlab/%s", gitopsWebhookURL, webhookEndpointID),- SecretToken: secretToken,- PushEvents: true,- EnableSSLVerification: false, // TODO(tianzhou): This is set to false, be lax to not enable_ssl_verification- }- webhookCreatePayload, err = json.Marshal(webhookCreate)- if err != nil {- return "", errors.Wrap(err, "failed to marshal request body for creating webhook")- }- case vcsPlugin.GitHub:- webhookPost := github.WebhookCreateOrUpdate{- Config: github.WebhookConfig{- URL: fmt.Sprintf("%s/hook/github/%s", gitopsWebhookURL, webhookEndpointID),- ContentType: "json",- Secret: secretToken,- InsecureSSL: 1, // TODO: Allow user to specify this value through api.RepositoryCreate- },- Events: []string{"push"},- }- webhookCreatePayload, err = json.Marshal(webhookPost)- if err != nil {- return "", errors.Wrap(err, "failed to marshal request body for creating webhook")- }- case vcsPlugin.Bitbucket:- webhookPost := bitbucket.WebhookCreateOrUpdate{- Description: "Bytebase GitOps",- URL: fmt.Sprintf("%s/hook/bitbucket/%s", gitopsWebhookURL, webhookEndpointID),- Active: true,- Events: []string{"repo:push"},- }- 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,- common.OauthContext{- AccessToken: accessToken,- // We use refreshTokenNoop() because the repository isn't created yet.- Refresher: refreshTokenNoop(),- },- instanceURL,- externalRepoID,- webhookCreatePayload,- )- if err != nil {- return "", errors.Wrap(err, "failed to create webhook")- }- return webhookID, nil-}--// refreshToken is a no-op token refresher. It should be used when the repository isn't created yet.-func refreshTokenNoop() common.TokenRefresher {- return func(newToken, newRefreshToken string, expiresTs int64) error {- return nil- }-}--func isBranchNotFound(ctx context.Context, vcs *api.VCS, store *store.Store, webURL, accessToken, refreshToken, externalID, branch string) (bool, error) {- _, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{}).GetBranch(ctx,- common.OauthContext{- ClientID: vcs.ApplicationID,- ClientSecret: vcs.Secret,- AccessToken: accessToken,- RefreshToken: refreshToken,- Refresher: utils.RefreshToken(ctx, store, webURL),- },- vcs.InstanceURL, externalID, branch)-- if common.ErrorCode(err) == common.NotFound {- return true, nil- }- return false, err-}-// SheetInfo represents the sheet related information from sheetPathTemplate.type SheetInfo struct {EnvironmentID stringdiff --git a/backend/server/server.go b/backend/server/server.goindex 91f25204b3..99c92d4dca 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -515,7 +515,6 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s.registerInboxRoutes(apiGroup)s.registerBookmarkRoutes(apiGroup)s.registerSQLRoutes(apiGroup)- s.registerVCSRoutes(apiGroup)s.registerAnomalyRoutes(apiGroup)// Register healthz endpoint.diff --git a/backend/server/vcs.go b/backend/server/vcs.godeleted file mode 100644index d0300da4ed..0000000000--- a/backend/server/vcs.go+++ /dev/null@@ -1,197 +0,0 @@-package server--import (- "fmt"- "net/http"- "strconv"- "strings"-- "github.com/google/jsonapi"- "github.com/labstack/echo/v4"-- "github.com/bytebase/bytebase/backend/common"- api "github.com/bytebase/bytebase/backend/legacyapi"- "github.com/bytebase/bytebase/backend/plugin/vcs"-)--func (s *Server) registerVCSRoutes(g *echo.Group) {- g.POST("/vcs", func(c echo.Context) error {- ctx := c.Request().Context()- vcsCreate := &api.VCSCreate{- CreatorID: c.Get(getPrincipalIDContextKey()).(int),- }- if err := jsonapi.UnmarshalPayload(c.Request().Body, vcsCreate); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed create VCS request").SetInternal(err)- }- // Trim ending "/"- vcsCreate.InstanceURL = strings.TrimRight(vcsCreate.InstanceURL, "/")- vcsCreate.APIURL = vcs.Get(vcsCreate.Type, vcs.ProviderConfig{}).APIURL(vcsCreate.InstanceURL)-- vcs, err := s.store.CreateVCS(ctx, vcsCreate)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create VCS").SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, vcs); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create VCS response").SetInternal(err)- }- return nil- })-- g.GET("/vcs", func(c echo.Context) error {- ctx := c.Request().Context()- vcsFind := &api.VCSFind{}- vcsList, err := s.store.FindVCS(ctx, vcsFind)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch vcs list").SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, vcsList); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal vcs list response").SetInternal(err)- }- return nil- })-- g.GET("/vcs/:vcsID", func(c echo.Context) error {- ctx := c.Request().Context()- id, err := strconv.Atoi(c.Param("vcsID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("vcsID"))).SetInternal(err)- }-- vcs, err := s.store.GetVCSByID(ctx, id)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch vcs ID: %v", id)).SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, vcs); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal vcs ID response: %v", id)).SetInternal(err)- }- return nil- })-- g.PATCH("/vcs/:vcsID", func(c echo.Context) error {- ctx := c.Request().Context()- id, err := strconv.Atoi(c.Param("vcsID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("VCS ID is not a number: %s", c.Param("vcsID"))).SetInternal(err)- }-- vcsPatch := &api.VCSPatch{- ID: id,- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),- }- if err := jsonapi.UnmarshalPayload(c.Request().Body, vcsPatch); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed change VCS request").SetInternal(err)- }-- vcs, err := s.store.PatchVCS(ctx, vcsPatch)- if err != nil {- if common.ErrorCode(err) == common.NotFound {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", id))- }- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to change VCS ID: %v", id)).SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, vcs); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal VCS change response: %v", id)).SetInternal(err)- }- return nil- })-- g.DELETE("/vcs/:vcsID", func(c echo.Context) error {- ctx := c.Request().Context()- id, err := strconv.Atoi(c.Param("vcsID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("VCS is not a number: %s", c.Param("vcsID"))).SetInternal(err)- }-- vcsDelete := &api.VCSDelete{- ID: id,- DeleterID: c.Get(getPrincipalIDContextKey()).(int),- }- if err := s.store.DeleteVCS(ctx, vcsDelete); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete VCS with ID %d", id)).SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- c.Response().WriteHeader(http.StatusOK)- return nil- })-- g.GET("/vcs/:vcsID/repository", func(c echo.Context) error {- ctx := c.Request().Context()- id, err := strconv.Atoi(c.Param("vcsID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("vcsID"))).SetInternal(err)- }-- repositoryFind := &api.RepositoryFind{- VCSID: &id,- }- repoList, err := s.store.FindRepository(ctx, repositoryFind)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for vcs ID: %v", id)).SetInternal(err)- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, repoList); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal repository list response for vcs ID: %v", id)).SetInternal(err)- }- return nil- })-- g.GET("/vcs/:vcsID/external-repository", func(c echo.Context) error {- ctx := c.Request().Context()- id, err := strconv.Atoi(c.Param("vcsID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("vcsID"))).SetInternal(err)- }- accessToken := c.Request().Header.Get("accessToken")- refreshToken := c.Request().Header.Get("refreshToken")-- vcsFound, err := s.store.GetVCSByID(ctx, id)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch VCS, ID: %v", id)).SetInternal(err)- }- if vcsFound == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to find VCS, ID: %v", id))- }-- repoList, err := vcs.Get(vcsFound.Type, vcs.ProviderConfig{}).FetchAllRepositoryList(- ctx,- common.OauthContext{- ClientID: vcsFound.ApplicationID,- ClientSecret: vcsFound.Secret,- AccessToken: accessToken,- RefreshToken: refreshToken,- Refresher: nil,- },- vcsFound.InstanceURL,- )- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find external repository, instance URL: %s", vcsFound.InstanceURL)).SetInternal(err)- }-- var externalRepoList []*api.ExternalRepository- for _, repo := range repoList {- externalRepoList = append(externalRepoList, &api.ExternalRepository{- ID: repo.ID,- FullPath: repo.FullPath,- Name: repo.Name,- WebURL: repo.WebURL,- })- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, externalRepoList); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal response").SetInternal(err)- }-- return nil- })-}diff --git a/backend/store/repository.go b/backend/store/repository.goindex 4889a83879..4bea90ea50 100644--- a/backend/store/repository.go+++ b/backend/store/repository.go@@ -131,6 +131,12 @@ func (s *Store) PatchRepository(ctx context.Context, patch *api.RepositoryPatch)// DeleteRepository deletes an existing repository by ID.func (s *Store) DeleteRepository(ctx context.Context, delete *api.RepositoryDelete) error {+ if delete.ProjectID == 0 {+ return errors.Errorf("project ID must be set")+ }+ if delete.ProjectResourceID == "" {+ return errors.Errorf("project resource ID must be set")+ }tx, err := s.db.BeginTx(ctx, nil)if err != nil {return errdiff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.goindex 4ade3732d4..904e4ef5ba 100644--- a/backend/tests/schema_update_test.go+++ b/backend/tests/schema_update_test.go@@ -267,7 +267,7 @@ func TestVCS(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath stringnewWebhookPushEvent func(added, modified [][]string, beforeSHA, afterSHA string) any@@ -275,7 +275,7 @@ func TestVCS(t *testing.T) {{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",newWebhookPushEvent: func(added, modified [][]string, beforeSHA, afterSHA string) any {@@ -302,7 +302,7 @@ func TestVCS(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(added, modified [][]string, beforeSHA, afterSHA string) any {@@ -341,7 +341,7 @@ func TestVCS(t *testing.T) {{name: "Bitbucket",vcsProviderCreator: fake.NewBitbucket,- vcsType: vcs.Bitbucket,+ vcsType: v1pb.ExternalVersionControl_BITBUCKET,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(added, _ [][]string, beforeSHA, afterSHA string) any {@@ -423,16 +423,16 @@ func TestVCS(t *testing.T) {a.NoError(err)// Create a VCS.- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project.@@ -448,22 +448,23 @@ func TestVCS(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: "{{ENV_ID}}/.{{DB_NAME}}##LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)// Provision an instance.@@ -739,7 +740,7 @@ func TestVCS_SDL(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath stringnewWebhookPushEvent func(added, modified []string, beforeSHA, afterSHA string) any@@ -747,7 +748,7 @@ func TestVCS_SDL(t *testing.T) {{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",newWebhookPushEvent: func(added, modified []string, beforeSHA, afterSHA string) any {@@ -772,7 +773,7 @@ func TestVCS_SDL(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(added, modified []string, beforeSHA, afterSHA string) any {@@ -853,16 +854,16 @@ func TestVCS_SDL(t *testing.T) {a.NoError(err)// Create a VCS- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project@@ -878,22 +879,23 @@ func TestVCS_SDL(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: "{{ENV_ID}}/.{{DB_NAME}}##LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)prodEnvironment, _, err := ctl.getEnvironment(ctx, "prod")@@ -1141,7 +1143,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypebaseDirectory stringenvName stringfilePathTemplate string@@ -1153,7 +1155,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {{name: "singleAsterisk",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,baseDirectory: "bbtest",envName: "wildcard",filePathTemplate: "{{ENV_ID}}/*/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",@@ -1180,7 +1182,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {{name: "continuousSingleAsterisk",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,baseDirectory: "bbtest",envName: "wildcard",filePathTemplate: "{{ENV_ID}}/*/*/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",@@ -1206,7 +1208,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {{name: "doubleAsterisks",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,baseDirectory: "bbtest",envName: "wildcard",filePathTemplate: "{{ENV_ID}}/**/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",@@ -1239,7 +1241,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {vcsProviderCreator: fake.NewGitLab,envName: "wildcard",baseDirectory: "",- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,filePathTemplate: "{{ENV_ID}}/**/foo/*/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",commitNewFileNames: []string{// ** matches foo, foo matches foo, * matches bar@@ -1267,7 +1269,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {vcsProviderCreator: fake.NewGitLab,envName: "prod1",baseDirectory: "bbtest",- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,filePathTemplate: "{{ENV_ID}}/**/foo/*/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",commitNewFileNames: []string{// ** matches foo, foo matches foo, * matches bar@@ -1295,7 +1297,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {vcsProviderCreator: fake.NewGitLab,envName: "ZO",baseDirectory: "bbtest",- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,filePathTemplate: "{{ENV_ID}}/{{DB_NAME}}/sql/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",commitNewFileNames: []string{fmt.Sprintf("%s/%s/%s/sql/%s##ver1##migrate##create_table_t1.sql", baseDirectory, "zo", dbName, dbName),@@ -1337,16 +1339,16 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {a.NoError(err)// Create a VCS.- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project.@@ -1362,22 +1364,23 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {err = ctl.vcsProvider.CreateBranch(externalID, branchFilter)a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: repoFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, repoFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, repoFullPath),BranchFilter: branchFilter,BaseDirectory: test.baseDirectory,FilePathTemplate: test.filePathTemplate,SchemaPathTemplate: "{{ENV_ID}}/.{{DB_NAME}}##LATEST.sql",- ExternalID: externalID,+ ExternalId: externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)environment, err := ctl.environmentServiceClient.CreateEnvironment(ctx,@@ -1454,19 +1457,19 @@ func TestVCS_SQL_Review(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath string- getEmptySQLReviewResult func(repo *api.Repository, filePath, rootURL string) *api.VCSSQLReviewResult- getSQLReviewResult func(repo *api.Repository, filePath string) *api.VCSSQLReviewResult+ getEmptySQLReviewResult func(gitOpsInfo *v1pb.ProjectGitOpsInfo, filePath, rootURL string) *api.VCSSQLReviewResult+ getSQLReviewResult func(gitOpsInfo *v1pb.ProjectGitOpsInfo, filePath string) *api.VCSSQLReviewResult}{{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",- getEmptySQLReviewResult: func(repo *api.Repository, filePath, rootURL string) *api.VCSSQLReviewResult {+ getEmptySQLReviewResult: func(gitOpsInfo *v1pb.ProjectGitOpsInfo, filePath, rootURL string) *api.VCSSQLReviewResult {pathes := strings.Split(filePath, "/")return &api.VCSSQLReviewResult{Status: advisor.Warn,@@ -1482,7 +1485,7 @@ func TestVCS_SQL_Review(t *testing.T) {},}},- getSQLReviewResult: func(repo *api.Repository, filePath string) *api.VCSSQLReviewResult {+ getSQLReviewResult: func(gitOpsInfo *v1pb.ProjectGitOpsInfo, filePath string) *api.VCSSQLReviewResult {pathes := strings.Split(filePath, "/")filename := pathes[len(pathes)-1]return &api.VCSSQLReviewResult{@@ -1505,10 +1508,10 @@ func TestVCS_SQL_Review(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",- getEmptySQLReviewResult: func(repo *api.Repository, filePath, rootURL string) *api.VCSSQLReviewResult {+ getEmptySQLReviewResult: func(gitOpsInfo *v1pb.ProjectGitOpsInfo, filePath, rootURL string) *api.VCSSQLReviewResult {return &api.VCSSQLReviewResult{Status: advisor.Warn,Content: []string{@@ -1520,7 +1523,7 @@ func TestVCS_SQL_Review(t *testing.T) {},}},- getSQLReviewResult: func(repo *api.Repository, filePath string) *api.VCSSQLReviewResult {+ getSQLReviewResult: func(gitOpsInfo *v1pb.ProjectGitOpsInfo, filePath string) *api.VCSSQLReviewResult {return &api.VCSSQLReviewResult{Status: advisor.Warn,Content: []string{@@ -1585,16 +1588,16 @@ func TestVCS_SQL_Review(t *testing.T) {a.NoError(err)// Create a VCS.- vcsData, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project.@@ -1628,25 +1631,26 @@ func TestVCS_SQL_Review(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- repository, err := ctl.createRepository(- api.RepositoryCreate{- VCSID: vcsData.ID,- ProjectID: projectUID,- Name: "Test Repository",+ gitOpsInfo, err := ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: "{{ENV_ID}}/.{{DB_NAME}}##LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)- a.NotNil(repository)- a.Equal(false, repository.EnableSQLReviewCI)+ a.NotNil(gitOpsInfo)+ a.Equal(false, gitOpsInfo.EnableSqlReviewCi)resp, err := ctl.projectServiceClient.SetupProjectSQLReviewCI(ctx, &v1pb.SetupSQLReviewCIRequest{Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),@@ -1654,11 +1658,11 @@ func TestVCS_SQL_Review(t *testing.T) {a.NoError(err)a.NotEmpty(resp.PullRequestUrl)- repositoryList, err := ctl.listRepository(projectUID)+ gitOpsInfo, err = ctl.projectServiceClient.GetProjectGitOpsInfo(ctx, &v1pb.GetProjectGitOpsInfoRequest{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ })a.NoError(err)- a.NotNil(repositoryList)- a.Equal(1, len(repositoryList))- a.Equal(true, repositoryList[0].EnableSQLReviewCI)+ a.Equal(true, gitOpsInfo.EnableSqlReviewCi)// Simulate Git commits and pull request for SQL review.prID := rand.Int()@@ -1681,14 +1685,14 @@ func TestVCS_SQL_Review(t *testing.T) {a.NoError(err)// trigger SQL review with empty policy.- res, err := postVCSSQLReview(ctl, repository, &api.VCSSQLReviewRequest{- RepositoryID: repository.ExternalID,+ res, err := postVCSSQLReview(ctl, gitOpsInfo, &api.VCSSQLReviewRequest{+ RepositoryID: gitOpsInfo.ExternalId,PullRequestID: fmt.Sprintf("%d", prID),- WebURL: repository.WebURL,+ WebURL: gitOpsInfo.WebUrl,})a.NoError(err)- emptySQLReview := test.getEmptySQLReviewResult(repository, gitFile, ctl.rootURL)+ emptySQLReview := test.getEmptySQLReviewResult(gitOpsInfo, gitFile, ctl.rootURL)a.Equal(emptySQLReview.Status, res.Status)a.Equal(emptySQLReview.Content, res.Content)@@ -1707,14 +1711,14 @@ func TestVCS_SQL_Review(t *testing.T) {})a.NoError(err)- reviewResult, err := postVCSSQLReview(ctl, repository, &api.VCSSQLReviewRequest{- RepositoryID: repository.ExternalID,+ reviewResult, err := postVCSSQLReview(ctl, gitOpsInfo, &api.VCSSQLReviewRequest{+ RepositoryID: gitOpsInfo.ExternalId,PullRequestID: fmt.Sprintf("%d", prID),- WebURL: repository.WebURL,+ WebURL: gitOpsInfo.WebUrl,})a.NoError(err)- expectResult := test.getSQLReviewResult(repository, gitFile)+ expectResult := test.getSQLReviewResult(gitOpsInfo, gitFile)a.Equal(expectResult.Status, reviewResult.Status)a.Equal(expectResult.Content, reviewResult.Content)})@@ -1729,7 +1733,7 @@ func TestBranchNameInVCSSetupAndUpdate(t *testing.T) {want bool}type vcsTestCase struct {- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypevcsProviderCreator fake.VCSProviderCreatorexternalID stringrepoFullPath string@@ -1738,7 +1742,7 @@ func TestBranchNameInVCSSetupAndUpdate(t *testing.T) {tests := []vcsTestCase{{- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,vcsProviderCreator: fake.NewGitLab,externalID: "1234",repoFullPath: "1234",@@ -1778,7 +1782,7 @@ func TestBranchNameInVCSSetupAndUpdate(t *testing.T) {},},{- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,vcsProviderCreator: fake.NewGitHub,externalID: "test/branch",repoFullPath: "test/branch",@@ -1838,23 +1842,21 @@ func TestBranchNameInVCSSetupAndUpdate(t *testing.T) {}()// Create a VCS.- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: "testName",+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: "testName",Type: vcsTest.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testID",Secret: "testSecret",},- )+ })a.NoError(err)// Create a project.project, err := ctl.createProject(ctx)a.NoError(err)- projectUID, err := strconv.Atoi(project.Uid)- a.NoError(err)for _, test := range vcsTest.caseList {test := test@@ -1869,28 +1871,31 @@ func TestBranchNameInVCSSetupAndUpdate(t *testing.T) {}// Create a repository.- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: vcsTest.repoFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, vcsTest.repoFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, vcsTest.repoFullPath),BranchFilter: test.branchFilter,BaseDirectory: "",FilePathTemplate: "{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: "",- ExternalID: vcsTest.externalID,+ ExternalId: vcsTest.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })if test.want {a.Error(err)} else {a.NoError(err)- err = ctl.unlinkRepository(projectUID)+ _, err = ctl.projectServiceClient.UnsetProjectGitOpsInfo(ctx, &v1pb.UnsetProjectGitOpsInfoRequest{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ })a.NoError(err)}})@@ -1916,8 +1921,8 @@ func getWorkspaceID(ctl *controller) (string, error) {}// postVCSSQLReview will create the VCS SQL review and get the response.-func postVCSSQLReview(ctl *controller, repo *api.Repository, request *api.VCSSQLReviewRequest) (*api.VCSSQLReviewResult, error) {- url := fmt.Sprintf("%s/hook/sql-review/%s", ctl.rootURL, repo.WebhookEndpointID)+func postVCSSQLReview(ctl *controller, gitOpsInfo *v1pb.ProjectGitOpsInfo, request *api.VCSSQLReviewRequest) (*api.VCSSQLReviewResult, error) {+ url := fmt.Sprintf("%s/hook/sql-review/%s", ctl.rootURL, gitOpsInfo.WebhookEndpointId)payload, err := json.Marshal(request)if err != nil {@@ -2319,7 +2324,7 @@ func TestVCS_SDL_MySQL(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath stringnewWebhookPushEvent func(added, modified []string, beforeSHA, afterSHA string) any@@ -2327,7 +2332,7 @@ func TestVCS_SDL_MySQL(t *testing.T) {{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",newWebhookPushEvent: func(added, modified []string, beforeSHA, afterSHA string) any {@@ -2352,7 +2357,7 @@ func TestVCS_SDL_MySQL(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(added, modified []string, beforeSHA, afterSHA string) any {@@ -2432,16 +2437,16 @@ func TestVCS_SDL_MySQL(t *testing.T) {a.NoError(err)// Create a VCS- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project@@ -2466,22 +2471,23 @@ func TestVCS_SDL_MySQL(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: "{{ENV_ID}}/.{{DB_NAME}}##LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)prodEnvironment, _, err := ctl.getEnvironment(ctx, "prod")diff --git a/backend/tests/sheet_vcs_test.go b/backend/tests/sheet_vcs_test.goindex 4fa314d264..a4546e2938 100644--- a/backend/tests/sheet_vcs_test.go+++ b/backend/tests/sheet_vcs_test.go@@ -4,12 +4,11 @@ import ("context""fmt""strconv"+ "strings""testing""github.com/stretchr/testify/require"- api "github.com/bytebase/bytebase/backend/legacyapi"- "github.com/bytebase/bytebase/backend/plugin/vcs""github.com/bytebase/bytebase/backend/tests/fake"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -19,21 +18,21 @@ func TestSheetVCS(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath string}{{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",},{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",},@@ -57,16 +56,16 @@ func TestSheetVCS(t *testing.T) {}()// Create a VCS.- vcs, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project.@@ -82,23 +81,24 @@ func TestSheetVCS(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: vcs.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: "{{ENV_ID}}/.{{DB_NAME}}##LATEST.sql",SheetPathTemplate: "sheet/{{NAME}}.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)// Initial git files.diff --git a/backend/tests/tenant_test.go b/backend/tests/tenant_test.goindex 980f8dd233..a6d621be48 100644--- a/backend/tests/tenant_test.go+++ b/backend/tests/tenant_test.go@@ -214,7 +214,7 @@ func TestTenantVCS(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath stringnewWebhookPushEvent func(gitFile, beforeSHA, afterSHA string) any@@ -222,7 +222,7 @@ func TestTenantVCS(t *testing.T) {{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -246,7 +246,7 @@ func TestTenantVCS(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -302,16 +302,16 @@ func TestTenantVCS(t *testing.T) {a.NoError(err)// Create a VCS.- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project.@@ -336,22 +336,23 @@ func TestTenantVCS(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: ".LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)// Provision instances.@@ -669,7 +670,7 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath stringnewWebhookPushEvent func(gitFile, beforeSHA, afterSHA string) any@@ -677,7 +678,7 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -701,7 +702,7 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -757,16 +758,16 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {a.NoError(err)// Create a VCS.- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a project.@@ -792,22 +793,23 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: ".LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)// Provision instances.@@ -969,7 +971,7 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath stringnewWebhookPushEvent func(gitFile, beforeSHA, afterSHA string) any@@ -977,7 +979,7 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/schemaUpdate",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -1001,7 +1003,7 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -1057,16 +1059,16 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {a.NoError(err)// Create a VCS.- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )+ })a.NoError(err)// Create a tenant project with empty database name template.@@ -1091,22 +1093,23 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: ".LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )+ AllowMissing: true,+ })a.NoError(err)// Provision instances.@@ -1229,10 +1232,12 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {// TestTenantVCS_YAML tests the behavior when use a YAML file to do DML in a// tenant project.func TestTenantVCS_YAML(t *testing.T) {+ a := require.New(t)+tests := []struct {name stringvcsProviderCreator fake.VCSProviderCreator- vcsType vcs.Type+ vcsType v1pb.ExternalVersionControl_TypeexternalID stringrepositoryFullPath stringnewWebhookPushEvent func(gitFile, beforeSHA, afterSHA string) any@@ -1240,7 +1245,7 @@ func TestTenantVCS_YAML(t *testing.T) {{name: "GitLab",vcsProviderCreator: fake.NewGitLab,- vcsType: vcs.GitLab,+ vcsType: v1pb.ExternalVersionControl_GITLAB,externalID: "121",repositoryFullPath: "test/dataUpdate",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -1264,7 +1269,7 @@ func TestTenantVCS_YAML(t *testing.T) {{name: "GitHub",vcsProviderCreator: fake.NewGitHub,- vcsType: vcs.GitHub,+ vcsType: v1pb.ExternalVersionControl_GITHUB,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",newWebhookPushEvent: func(gitFile, beforeSHA, afterSHA string) any {@@ -1310,26 +1315,26 @@ func TestTenantVCS_YAML(t *testing.T) {dataDir: t.TempDir(),vcsProviderCreator: test.vcsProviderCreator,})- require.NoError(t, err)+ a.NoError(err)defer func() {_ = ctl.Close(ctx)}()err = ctl.setLicense()- require.NoError(t, err)+ a.NoError(err)// Create a VCS.- apiVCS, err := ctl.createVCS(- api.VCSCreate{- Name: t.Name(),+ evcs, err := ctl.evcsClient.CreateExternalVersionControl(ctx, &v1pb.CreateExternalVersionControlRequest{+ ExternalVersionControl: &v1pb.ExternalVersionControl{+ Title: t.Name(),Type: test.vcsType,- InstanceURL: ctl.vcsURL,- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),- ApplicationID: "testApplicationID",+ Url: ctl.vcsURL,+ ApiUrl: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationId: "testApplicationID",Secret: "testApplicationSecret",},- )- require.NoError(t, err)+ })+ a.NoError(err)// Create a tenant project with empty database name template.projectID := generateRandomString("project", 10)@@ -1343,34 +1348,35 @@ func TestTenantVCS_YAML(t *testing.T) {},ProjectId: projectID,})- require.NoError(t, err)+ a.NoError(err)projectUID, err := strconv.Atoi(project.Uid)- require.NoError(t, err)+ a.NoError(err)// Create a repository.ctl.vcsProvider.CreateRepository(test.externalID)// Create the brancherr = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")- require.NoError(t, err)+ a.NoError(err)- _, err = ctl.createRepository(- api.RepositoryCreate{- VCSID: apiVCS.ID,- ProjectID: projectUID,- Name: "Test Repository",+ _, err = ctl.projectServiceClient.UpdateProjectGitOpsInfo(ctx, &v1pb.UpdateProjectGitOpsInfoRequest{+ ProjectGitopsInfo: &v1pb.ProjectGitOpsInfo{+ Name: fmt.Sprintf("%s/gitOpsInfo", project.Name),+ VcsUid: strings.TrimPrefix(evcs.Name, "externalVersionControls/"),+ Title: "Test Repository",FullPath: test.repositoryFullPath,- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),BranchFilter: "feature/foo",BaseDirectory: baseDirectory,FilePathTemplate: "{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",SchemaPathTemplate: ".LATEST.sql",- ExternalID: test.externalID,+ ExternalId: test.externalID,AccessToken: "accessToken1",RefreshToken: "refreshToken1",},- )- require.NoError(t, err)+ AllowMissing: true,+ })+ a.NoError(err)// Provision instances.instanceRootDir := t.TempDir()@@ -1379,11 +1385,11 @@ func TestTenantVCS_YAML(t *testing.T) {var testInstanceDirs []stringfor i := 0; i < testTenantNumber; i++ {instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", testInstanceName, i))- require.NoError(t, err)+ a.NoError(err)testInstanceDirs = append(testInstanceDirs, instanceDir)}testEnvironment, _, err := ctl.getEnvironment(ctx, "test")- require.NoError(t, err)+ a.NoError(err)// Add the provisioned instances.var testInstances []*v1pb.Instance@@ -1397,7 +1403,7 @@ func TestTenantVCS_YAML(t *testing.T) {DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: testInstanceDir}},},})- require.NoError(t, err)+ a.NoError(err)testInstances = append(testInstances, instance)}@@ -1425,7 +1431,7 @@ func TestTenantVCS_YAML(t *testing.T) {},},)- require.NoError(t, err)+ a.NoError(err)// Create issues that create databases.const baseDatabaseName = "TestTenantVCS_YAML"@@ -1433,7 +1439,7 @@ func TestTenantVCS_YAML(t *testing.T) {tenant := fmt.Sprintf("tenant%d", i)databaseName := baseDatabaseName + "_" + tenanterr := ctl.createDatabase(ctx, projectUID, testInstance, databaseName, "", nil /* labelMap */)- require.NoError(t, err)+ a.NoError(err)}// Getting databases for each environment.@@ -1441,7 +1447,7 @@ func TestTenantVCS_YAML(t *testing.T) {Parent: "instances/-",Filter: fmt.Sprintf(`project == "%s"`, project.Name),})- require.NoError(t, err)+ a.NoError(err)databases := resp.Databasesvar testDatabases []*v1pb.Database@@ -1453,28 +1459,28 @@ func TestTenantVCS_YAML(t *testing.T) {}}}- require.Equal(t, testTenantNumber, len(testDatabases))+ a.Equal(testTenantNumber, len(testDatabases))// Simulate Git commits for schema update.gitFile1 := baseDirectory + "/ver1##migrate##create_a_test_table.sql"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile1: migrationStatement})- require.NoError(t, err)+ a.NoError(err)err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "1", "2", []vcs.FileDiff{{Path: gitFile1, Type: vcs.FileDiffTypeAdded},})- require.NoError(t, err)+ a.NoError(err)payload, err := json.Marshal(test.newWebhookPushEvent(gitFile1, "1", "2"))- require.NoError(t, err)+ a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)- require.NoError(t, err)+ a.NoError(err)// Get schema update issues.issues, err := ctl.getIssues(&projectUID, api.IssueOpen)- require.NoError(t, err)- require.Len(t, issues, 1)+ a.NoError(err)+ a.Len(issues, 1)status, err := ctl.waitIssuePipeline(ctx, issues[0].ID)- require.NoError(t, err)- require.Equal(t, api.TaskDone, status)+ a.NoError(err)+ a.Equal(api.TaskDone, status)// Simulate Git commits for data update.database0Name := "TestTenantVCS_YAML_tenant0"@@ -1492,22 +1498,22 @@ statement: |),},)- require.NoError(t, err)+ a.NoError(err)err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "2", "3", []vcs.FileDiff{{Path: gitFile2, Type: vcs.FileDiffTypeAdded},})- require.NoError(t, err)+ a.NoError(err)payload, err = json.Marshal(test.newWebhookPushEvent(gitFile2, "2", "3"))- require.NoError(t, err)+ a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)- require.NoError(t, err)+ a.NoError(err)// Get data update issues.issues, err = ctl.getIssues(&projectUID, api.IssueOpen)- require.NoError(t, err)+ a.NoError(err)status, err = ctl.waitIssuePipeline(ctx, issues[0].ID)- require.NoError(t, err)- require.Equal(t, api.TaskDone, status)+ a.NoError(err)+ a.Equal(api.TaskDone, status)})}}diff --git a/backend/tests/tests.go b/backend/tests/tests.goindex 255af5ed6f..872263b22e 100644--- a/backend/tests/tests.go+++ b/backend/tests/tests.go@@ -167,6 +167,7 @@ type controller struct {instanceServiceClient v1pb.InstanceServiceClientdatabaseServiceClient v1pb.DatabaseServiceClientsheetServiceClient v1pb.SheetServiceClient+ evcsClient v1pb.ExternalVersionControlServiceClientcookie stringgrpcMDAccessToken string@@ -436,6 +437,7 @@ func (ctl *controller) start(ctx context.Context, port int) (context.Context, erctl.instanceServiceClient = v1pb.NewInstanceServiceClient(ctl.grpcConn)ctl.databaseServiceClient = v1pb.NewDatabaseServiceClient(ctl.grpcConn)ctl.sheetServiceClient = v1pb.NewSheetServiceClient(ctl.grpcConn)+ ctl.evcsClient = v1pb.NewExternalVersionControlServiceClient(ctl.grpcConn)return metadata.NewOutgoingContext(ctx, metadata.Pairs("Authorization",@@ -619,13 +621,6 @@ func (ctl *controller) patchOpenAPI(shortURL string, body io.Reader) (io.ReadClo})}-func (ctl *controller) delete(shortURL string, body io.Reader) (io.ReadCloser, error) {- url := fmt.Sprintf("%s%s", ctl.apiURL, shortURL)- return ctl.request("DELETE", url, body, nil, map[string]string{- "Cookie": ctl.cookie,- })-}-func (ctl *controller) request(method, fullURL string, body io.Reader, params, header map[string]string) (io.ReadCloser, error) {req, err := http.NewRequest(method, fullURL, body)if err != nil {diff --git a/backend/tests/vcs.go b/backend/tests/vcs.godeleted file mode 100644index e39b9d7ab6..0000000000--- a/backend/tests/vcs.go+++ /dev/null@@ -1,81 +0,0 @@-package tests--import (- "bytes"- "fmt"- "reflect"-- "github.com/google/jsonapi"- "github.com/pkg/errors"-- api "github.com/bytebase/bytebase/backend/legacyapi"-)--// createVCS creates a VCS.-func (ctl *controller) createVCS(vcsCreate api.VCSCreate) (*api.VCS, error) {- buf := new(bytes.Buffer)- if err := jsonapi.MarshalPayload(buf, &vcsCreate); err != nil {- return nil, errors.Wrap(err, "failed to marshal vcsCreate")- }-- body, err := ctl.post("/vcs", buf)- if err != nil {- return nil, err- }-- vcs := new(api.VCS)- if err = jsonapi.UnmarshalPayload(body, vcs); err != nil {- return nil, errors.Wrap(err, "fail to unmarshal vcs response")- }- return vcs, nil-}--// createRepository links the repository with the project.-func (ctl *controller) createRepository(repositoryCreate api.RepositoryCreate) (*api.Repository, error) {- buf := new(bytes.Buffer)- if err := jsonapi.MarshalPayload(buf, &repositoryCreate); err != nil {- return nil, errors.Wrap(err, "failed to marshal repositoryCreate")- }-- body, err := ctl.post(fmt.Sprintf("/project/%d/repository", repositoryCreate.ProjectID), buf)- if err != nil {- return nil, err- }-- repository := new(api.Repository)- if err = jsonapi.UnmarshalPayload(body, repository); err != nil {- return nil, errors.Wrap(err, "fail to unmarshal repository response")- }- return repository, nil-}--// unlinkRepository unlinks the repository from the project by projectID.-func (ctl *controller) unlinkRepository(projectID int) error {- _, err := ctl.delete(fmt.Sprintf("/project/%d/repository", projectID), nil)- if err != nil {- return err- }- return nil-}--// listRepository gets the repository list.-func (ctl *controller) listRepository(projectID int) ([]*api.Repository, error) {- body, err := ctl.get(fmt.Sprintf("/project/%d/repository", projectID), nil)- if err != nil {- return nil, err- }-- var repositories []*api.Repository- ps, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(api.Repository)))- if err != nil {- return nil, errors.Wrap(err, "fail to unmarshal get repository response")- }- for _, p := range ps {- repository, ok := p.(*api.Repository)- if !ok {- return nil, errors.Errorf("fail to convert repository")- }- repositories = append(repositories, repository)- }- return repositories, nil-}