Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support single or double asterisks in VCS commit file path template (#2417)
h3n4l8ebf408bb7e2
diff --git a/api/environment.go b/api/environment.goindex c2600e8962..8ec31a3b5f 100644--- a/api/environment.go+++ b/api/environment.go@@ -2,6 +2,9 @@ package apiimport ("encoding/json"+ "regexp"++ "github.com/pkg/errors")// Environment is the API message for an environment.@@ -52,6 +55,18 @@ func (find *EnvironmentFind) String() string {return string(str)}+// placeholderRegexp is the regexp for placeholder.+// Refer to https://stackoverflow.com/a/6222235/19075342, but we support '.' for now.+var placeholderRegexp = regexp.MustCompile(`[^\\/?%*:|"<>]+`)++// IsValidEnvironmentName checks if the environment name is valid.+func IsValidEnvironmentName(environmentName string) error {+ if !placeholderRegexp.MatchString(environmentName) {+ return errors.Errorf("environment name %q cannot contain placeholder characters (\\, /, ?, %%, *, :, |, \", <, >)", environmentName)+ }+ return nil+}+// EnvironmentPatch is the API message for patching an environment.type EnvironmentPatch struct {ID int `jsonapi:"primary,environmentPatch"`diff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vueindex 5636152336..9e9ff7b969 100644--- a/frontend/src/components/RepositoryForm.vue+++ b/frontend/src/components/RepositoryForm.vue@@ -100,8 +100,10 @@{{ FILE_REQUIRED_PLACEHOLDER }};<template v-if="fileOptionalPlaceholder.length > 0">{{ $t("common.optional-placeholder") }}:- {{ fileOptionalPlaceholder.join(", ") }}+ {{ fileOptionalPlaceholder.join(", ") }};</template>+ {{ $t("common.optional-directory-wildcard") }}:+ {{ FILE_OPTIONAL_DIRECTORY_WILDCARD }}</div><div class="mt-2 textinfolabel">• {{ $t("repository.file-path-example-schema-migration") }}:@@ -207,6 +209,9 @@ import {const FILE_REQUIRED_PLACEHOLDER = "{{DB_NAME}}, {{VERSION}}, {{TYPE}}";const SCHEMA_REQUIRED_PLACEHOLDER = "{{DB_NAME}}";+const FILE_OPTIONAL_DIRECTORY_WILDCARD = "*, **";+const SINGLE_ASTERISK_REGEX = /\/\*\//g;+const DOUBLE_ASTERISKS_REGEX = /\/\*\*\//g;// eslint-disable-next-line @typescript-eslint/no-empty-interfaceinterface LocalState {}@@ -285,6 +290,11 @@ export default defineComponent({];let result = `${baseDirectory}/${filePathTemplate}`;++ // To replace the wildcard.+ result = result.replace(SINGLE_ASTERISK_REGEX, "/foo/");+ result = result.replace(DOUBLE_ASTERISKS_REGEX, "/foo/bar/");+for (const item of placeholderList) {const re = new RegExp(item.placeholder, "g");result = result.replace(re, item.sampleText);@@ -334,6 +344,7 @@ export default defineComponent({return {FILE_REQUIRED_PLACEHOLDER,fileOptionalPlaceholder,+ FILE_OPTIONAL_DIRECTORY_WILDCARD,SCHEMA_REQUIRED_PLACEHOLDER,schemaOptionalTagPlaceholder,state,diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 3897de3cd9..18bcbc8a9d 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -124,6 +124,7 @@"config-guide": "config guide","required-placeholder": "required placeholder","optional-placeholder": "optional placeholder",+ "optional-directory-wildcard": "optional directory wildcard","sensitive-placeholder": "sensitive - write only","enabled": "enabled","default": "default",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 5ac5940c75..84c6ee4e91 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -124,6 +124,7 @@"config-guide": "配置指南","required-placeholder": "必需的占位符","optional-placeholder": "可选的占位符",+ "optional-directory-wildcard": "可选的目录通配符","sensitive-placeholder": "敏感数据 - 仅写入","enabled": "开启","default": "默认",diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex 1fd890a19d..e17100711a 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -16,7 +16,7 @@ import ()// Type is the type of a database.-//nolint+// nolinttype Type stringconst (@@ -243,6 +243,10 @@ type MigrationInfo struct {Force bool}+// placeholderRegexp is the regexp for placeholder.+// Refer to https://stackoverflow.com/a/6222235/19075342, but we support '.' for now.+const placeholderRegexp = `[^\\/?%*:|"<>]+`+// ParseMigrationInfo matches filePath against filePathTemplate// If filePath matches, then it will derive MigrationInfo from the filePath.// Both filePath and filePathTemplate are the full file path (including the base directory) of the repository.@@ -256,9 +260,13 @@ func ParseMigrationInfo(filePath string, filePathTemplate string) (*MigrationInf}// Escape "." characters to match literals instead of using it as a wildcard.- filePathRegex := strings.ReplaceAll(filePathTemplate, ".", `\.`)+ filePathRegex := strings.ReplaceAll(filePathTemplate, `.`, `\.`)++ filePathRegex = strings.ReplaceAll(filePathRegex, `/*/`, `/[^/]*/`)+ filePathRegex = strings.ReplaceAll(filePathRegex, `**`, `.*`)+for _, placeholder := range placeholderList {- filePathRegex = strings.ReplaceAll(filePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))+ filePathRegex = strings.ReplaceAll(filePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf(`(?P<%s>%s)`, placeholder, placeholderRegexp))}myRegex, err := regexp.Compile(filePathRegex)if err != nil {diff --git a/plugin/db/driver_test.go b/plugin/db/driver_test.goindex 990453121e..662a82b841 100644--- a/plugin/db/driver_test.go+++ b/plugin/db/driver_test.go@@ -32,16 +32,16 @@ func TestParseMigrationInfo(t *testing.T) {wantErr: "",},{- filePath: "db foo_+-=/_#?!$.__1.2.3",+ filePath: "db foo_+-=_#!$.__1.2.3",filePathTemplate: "{{DB_NAME}}__{{VERSION}}",want: MigrationInfo{Version: "1.2.3",- Namespace: "db foo_+-=/_#?!$.",- Database: "db foo_+-=/_#?!$.",+ Namespace: "db foo_+-=_#!$.",+ Database: "db foo_+-=_#!$.",Environment: "",Source: VCS,Type: Migrate,- Description: "Create db foo_+-=/_#?!$. schema migration",+ Description: "Create db foo_+-=_#!$. schema migration",Creator: "",},wantErr: "",diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.goindex 11b95aadbf..aabe2b65ff 100644--- a/plugin/vcs/vcs.go+++ b/plugin/vcs/vcs.go@@ -2,9 +2,14 @@ package vcsimport ("context"+ "fmt""net/http"+ "regexp"+ "strings""sync"+ "github.com/pkg/errors"+"github.com/bytebase/bytebase/common")@@ -255,3 +260,77 @@ func Get(vcsType Type, providerConfig ProviderConfig) Provider {return f(providerConfig)}++// IsAsterisksInTemplateValid checks if the pathTemplate is valid about asterisk.+// Fow now, our rules are:+// 1. Support two asterisks at most.+// 2. Both ends of consecutive asterisks just can be '/'.+// 3. Consecutive asterisks cannot be placed at the beginning or end.+func IsAsterisksInTemplateValid(pathTemplate string) error {+ const maxAsteriskNum = 2+ if err := isMaxConsecutiveAsteriskValid(pathTemplate, maxAsteriskNum); err != nil {+ return err+ }+ if err := isSingleAsteriskInTemplateValid(pathTemplate); err != nil {+ return err+ }+ return isDoubleAsteriskInTemplateValid(pathTemplate)+}++// isSingleAsteriskInTemplateValid checks whether the single in file path template is valid.+func isSingleAsteriskInTemplateValid(pathTemplate string) error {+ return isMultipleTimesAsteriskInTemplateValid(pathTemplate, 1)+}++// isDoubleAsteriskInTemplateValid checks whether the consecutive double asterisks in file path template is valid.+func isDoubleAsteriskInTemplateValid(pathTemplate string) error {+ return isMultipleTimesAsteriskInTemplateValid(pathTemplate, 2)+}++// isMaxConsecutiveAsteriskValid returns true if the pathTemplate contains `n` consecutive asterisk at most.+func isMaxConsecutiveAsteriskValid(pathTemplate string, n int) error {+ re := regexp.MustCompile(strings.Repeat(`\*`, n+1))+ if re.MatchString(pathTemplate) {+ return errors.Errorf("path template %s contains more than %d asterisk", pathTemplate, n)+ }+ return nil+}++// isMultipleTimesAsteriskInTemplateValid checks whether the consecutive asterisks in file path template is valid.+// The rules are():+// 1. Consecutive asterisks cannot be placed at the beginning or end.+// 2. Both ends of consecutive asterisks just can be * or /.+// Take asteriskTimes = 2 as an example:+// "**/test" and "test/**" will break the rule1.+// "abc**" and "?**/" will break the rule2.+func isMultipleTimesAsteriskInTemplateValid(pathTemplate string, asteriskTimes int) error {+ base := strings.Repeat(`\*`, asteriskTimes)+ rs := []struct {+ regex string+ errmsg string+ }{+ {+ regex: fmt.Sprintf(`([^\/\*]+%s)`, base),+ errmsg: `In path template, * can only be preceded by another / or *`,+ },+ {+ regex: fmt.Sprintf(`(%s[^\/\*]+)`, base),+ errmsg: `In path template, only / or * can be followed by *`,+ },+ {+ regex: fmt.Sprintf(`(^(%s))`, base),+ errmsg: fmt.Sprintf(`path template %s contains consecutive asterisks at the beginning`, pathTemplate),+ },+ {+ regex: fmt.Sprintf(`((%s)$)`, base),+ errmsg: fmt.Sprintf(`path template %s contains consecutive asterisks at the end`, pathTemplate),+ },+ }+ for _, rs := range rs {+ re := regexp.MustCompile(rs.regex)+ if re.MatchString(pathTemplate) {+ return errors.New(rs.errmsg)+ }+ }+ return nil+}diff --git a/plugin/vcs/vcs_test.go b/plugin/vcs/vcs_test.gonew file mode 100644index 0000000000..007003fe97--- /dev/null+++ b/plugin/vcs/vcs_test.go@@ -0,0 +1,48 @@+package vcs++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestIsDoubleTimesAsteriskInTemplateValid(t *testing.T) {+ tests := []struct {+ template string+ err bool+ }{+ {+ template: "**",+ err: true,+ },+ {+ template: "bytebase/{{ENV_NAME}}/**",+ err: true,+ },+ {+ template: "**/{{ENV_NAME}}/{{DB_NAME}}.sql",+ err: true,+ },+ {+ template: "bytebase/**/{{ENV_NAME}}/**/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ err: false,+ },+ {+ template: "/**/{{ENV_NAME}}/**/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ err: false,+ },+ // Credit to Linear Issue BYT-1267+ {+ template: "/configure/configure/{{ENV_NAME}}/**/**/{{DESCRIPTION}}.sql",+ err: false,+ },+ }+ for _, test := range tests {+ outputErr := isDoubleAsteriskInTemplateValid(test.template)+ if test.err {+ assert.Error(t, outputErr)+ } else {+ assert.NoError(t, outputErr)+ }+ }+}diff --git a/server/environment.go b/server/environment.goindex 33d2fc9799..ff622a15bf 100644--- a/server/environment.go+++ b/server/environment.go@@ -24,6 +24,10 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {envCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)+ if err := api.IsValidEnvironmentName(envCreate.Name); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)+ }+env, err := s.store.CreateEnvironment(ctx, envCreate)if err != nil {if common.ErrorCode(err) == common.Conflict {@@ -73,6 +77,12 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch environment request").SetInternal(err)}+ if v := envPatch.Name; v != nil {+ if err := api.IsValidEnvironmentName(*v); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)+ }+ }+// Ensure the environment has no instance before it's archived.if v := envPatch.RowStatus; v != nil && *v == string(api.Archived) {normalStatus := api.Normaldiff --git a/server/project.go b/server/project.goindex ad81629a88..99e071b522 100644--- a/server/project.go+++ b/server/project.go@@ -5,6 +5,7 @@ import ("encoding/json""fmt""net/http"+ "path""strconv""strings"@@ -213,6 +214,12 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Wildcard isn't supported for branch setting")}+ // 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()))+ }+project, err := s.store.GetProjectByID(ctx, projectID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project ID: %v", projectID)).SetInternal(err)@@ -404,6 +411,21 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {repo := repoList[0]repoPatch.ID = repo.ID++ // 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())+ }+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)diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex 0e657ea902..6a06dffa9f 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -111,14 +111,11 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {}pd.webhooks = append(pd.webhooks, webhookCreate)- if err := json.NewEncoder(c.Response().Writer).Encode(&gitlab.WebhookInfo{- ID: gl.nextWebhookID,- }); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal WebhookInfo response").SetInternal(err)- }gl.nextWebhookID++- return nil+ return c.JSON(http.StatusCreated, &gitlab.WebhookInfo{+ ID: gl.nextWebhookID,+ })}// readProjectTree reads a project file nodes.diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 52409227e7..b7e97905f2 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -6,6 +6,7 @@ import ("fmt""os""path"+ "strconv""testing""time"@@ -16,6 +17,7 @@ import ("github.com/bytebase/bytebase/plugin/vcs""github.com/bytebase/bytebase/plugin/vcs/github""github.com/bytebase/bytebase/plugin/vcs/gitlab"+ resourcemysql "github.com/bytebase/bytebase/resources/mysql""github.com/bytebase/bytebase/tests/fake")@@ -543,3 +545,318 @@ func TestVCS(t *testing.T) {})}}++func TestWildcardInVCSFilePathTemplate(t *testing.T) {+ branchFilter := "feature/foo"+ dbName := "db"+ externalID := "121"+ repoFullPath := "test/wildcard"++ tests := []struct {+ name string+ vcsProviderCreator fake.VCSProviderCreator+ vcsType vcs.Type+ baseDirectory string+ envName string+ filePathTemplate string+ commitFileNames []string+ commitContents []string+ expect []bool+ newWebhookPushEvent func(gitFile string) interface{}+ }{+ {+ name: "singleAsterisk",+ vcsProviderCreator: fake.NewGitLab,+ vcsType: vcs.GitLabSelfHost,+ baseDirectory: "bbtest",+ envName: "wildcard",+ filePathTemplate: "{{ENV_NAME}}/*/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ commitFileNames: []string{+ // Normal+ fmt.Sprintf("%s/%s/foo/%s__ver1__migrate__create_table_t1.sql", baseDirectory, "wildcard", dbName),+ // One singleAsterisk cannot match two directories.+ fmt.Sprintf("%s/%s/foo/bar/%s__ver2__data__insert_data.sql", baseDirectory, "wildcard", dbName),+ // One singleAsterisk cannot match zero directory.+ fmt.Sprintf("%s/%s/%s__ver3__migrate__create_table_t3.sql", baseDirectory, "wildcard", dbName),+ },+ commitContents: []string{+ "CREATE TABLE t1 (id INT);",+ "INSERT INTO t1 VALUES (1);",+ "CREATE TABLE t3 (id INT);",+ },+ expect: []bool{+ true,+ false,+ false,+ },+ newWebhookPushEvent: func(gitFile string) interface{} {+ return gitlab.WebhookPushEvent{+ ObjectKind: gitlab.WebhookPush,+ Ref: fmt.Sprintf("refs/heads/%s", branchFilter),+ Project: gitlab.WebhookProject{+ ID: 121,+ },+ CommitList: []gitlab.WebhookCommit{+ {+ Timestamp: "2021-01-13T13:14:00Z",+ AddedList: []string{gitFile},+ },+ },+ }+ },+ },+ {+ name: "doubleAsterisks",+ vcsProviderCreator: fake.NewGitLab,+ vcsType: vcs.GitLabSelfHost,+ baseDirectory: "bbtest",+ envName: "wildcard",+ filePathTemplate: "{{ENV_NAME}}/**/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ commitFileNames: []string{+ // Two singleAsterisk can match one directory.+ fmt.Sprintf("%s/%s/foo/%s__ver1__migrate__create_table_t1.sql", baseDirectory, "wildcard", dbName),+ // Two singleAsterisk can match two directories.+ fmt.Sprintf("%s/%s/foo/bar/%s__ver2__migrate__create_table_t2.sql", baseDirectory, "wildcard", dbName),+ // Two singleAsterisk can match three directories or more.+ fmt.Sprintf("%s/%s/foo/bar/foo/%s__ver3__migrate__create_table_t3.sql", baseDirectory, "wildcard", dbName),+ // Two singleAsterisk cannot match zero directory.+ fmt.Sprintf("%s/%s/%s__ver4__migrate__create_table_t4.sql", baseDirectory, "wildcard", dbName),+ },+ commitContents: []string{+ "CREATE TABLE t1 (id INT);",+ "CREATE TABLE t2 (id INT);",+ "CREATE TABLE t3 (id INT);",+ "CREATE TABLE t4 (id INT);",+ },+ expect: []bool{+ true,+ true,+ true,+ false,+ },+ newWebhookPushEvent: func(gitFile string) interface{} {+ return gitlab.WebhookPushEvent{+ ObjectKind: gitlab.WebhookPush,+ Ref: fmt.Sprintf("refs/heads/%s", branchFilter),+ Project: gitlab.WebhookProject{+ ID: 121,+ },+ CommitList: []gitlab.WebhookCommit{+ {+ Timestamp: "2021-01-13T13:14:00Z",+ AddedList: []string{gitFile},+ },+ },+ }+ },+ },+ {+ name: "emptyBaseAndMixAsterisks",+ vcsProviderCreator: fake.NewGitLab,+ envName: "wildcard",+ baseDirectory: "",+ vcsType: vcs.GitLabSelfHost,+ filePathTemplate: "{{ENV_NAME}}/**/foo/*/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ commitFileNames: []string{+ // ** matches foo, foo matches foo, * matches bar+ fmt.Sprintf("%s/foo/foo/bar/%s__ver1__migrate__create_table_t1.sql", "wildcard", dbName),+ // ** matches foo/bar/foo, foo matches foo, * matches bar+ fmt.Sprintf("%s/foo/bar/foo/foo/bar/%s__ver2__migrate__create_table_t2.sql", "wildcard", dbName),+ // cannot match+ fmt.Sprintf("%s/%s__ver3__migrate__create_table_t3.sql", "wildcard", dbName),+ },+ commitContents: []string{+ "CREATE TABLE t1 (id INT);",+ "CREATE TABLE t2 (id INT);",+ "CREATE TABLE t3 (id INT);",+ },+ expect: []bool{+ true,+ true,+ false,+ },+ newWebhookPushEvent: func(gitFile string) interface{} {+ return gitlab.WebhookPushEvent{+ ObjectKind: gitlab.WebhookPush,+ Ref: fmt.Sprintf("refs/heads/%s", branchFilter),+ Project: gitlab.WebhookProject{+ ID: 121,+ },+ CommitList: []gitlab.WebhookCommit{+ {+ Timestamp: "2021-01-13T13:14:00Z",+ AddedList: []string{gitFile},+ },+ },+ }+ },+ },+ // We test the combination of ** and *, and the place holder is not fully represented by the ascii character set.+ {+ name: "mixAsterisks",+ vcsProviderCreator: fake.NewGitLab,+ envName: "生产",+ baseDirectory: "bbtest",+ vcsType: vcs.GitLabSelfHost,+ filePathTemplate: "{{ENV_NAME}}/**/foo/*/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",+ commitFileNames: []string{+ // ** matches foo, foo matches foo, * matches bar+ fmt.Sprintf("%s/%s/foo/foo/bar/%s__ver1__migrate__create_table_t1.sql", baseDirectory, "生产", dbName),+ // ** matches foo/bar/foo, foo matches foo, * matches bar+ fmt.Sprintf("%s/%s/foo/bar/foo/foo/bar/%s__ver2__migrate__create_table_t2.sql", baseDirectory, "生产", dbName),+ // cannot match+ fmt.Sprintf("%s/%s/%s__ver3__migrate__create_table_t3.sql", baseDirectory, "生产", dbName),+ },+ commitContents: []string{+ "CREATE TABLE t1 (id INT);",+ "CREATE TABLE t2 (id INT);",+ "CREATE TABLE t3 (id INT);",+ },+ expect: []bool{+ true,+ true,+ false,+ },+ newWebhookPushEvent: func(gitFile string) interface{} {+ return gitlab.WebhookPushEvent{+ ObjectKind: gitlab.WebhookPush,+ Ref: fmt.Sprintf("refs/heads/%s", branchFilter),+ Project: gitlab.WebhookProject{+ ID: 121,+ },+ CommitList: []gitlab.WebhookCommit{+ {+ Timestamp: "2021-01-13T13:14:00Z",+ AddedList: []string{gitFile},+ },+ },+ }+ },+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ t.Parallel()++ port := getTestPort(t.Name())+ mysqlPort := port + 3+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ err := ctl.StartServer(ctx, t.TempDir(), test.vcsProviderCreator, port)+ a.NoError(err)+ defer func() {+ _ = ctl.Close(ctx)+ }()++ err = ctl.Login()+ a.NoError(err)+ err = ctl.setLicense()+ a.NoError(err)++ // Create a VCS.+ vcs, err := ctl.createVCS(+ api.VCSCreate{+ Name: t.Name(),+ Type: test.vcsType,+ InstanceURL: ctl.vcsURL,+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationID: "testApplicationID",+ Secret: "testApplicationSecret",+ },+ )+ a.NoError(err)++ // Create a project.+ project, err := ctl.createProject(+ api.ProjectCreate{+ Name: "Test VCS Project",+ Key: "TVP",+ },+ )+ a.NoError(err)++ // Create a repository.+ ctl.vcsProvider.CreateRepository(externalID)+ _, err = ctl.createRepository(+ api.RepositoryCreate{+ VCSID: vcs.ID,+ ProjectID: project.ID,+ Name: "Test Repository",+ FullPath: repoFullPath,+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, repoFullPath),+ BranchFilter: branchFilter,+ BaseDirectory: baseDirectory,+ FilePathTemplate: test.filePathTemplate,+ SchemaPathTemplate: "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",+ ExternalID: externalID,+ AccessToken: "accessToken1",+ RefreshToken: "refreshToken1",+ },+ )+ a.NoError(err)++ environment, err := ctl.createEnvrionment(api.EnvironmentCreate{+ Name: test.envName,+ })+ a.NoError(err)+ // Provision an instance.+ instanceName := "testInstance"+ _, stopInstance := resourcemysql.SetupTestInstance(t, mysqlPort)+ defer stopInstance()+ connCfg := getMySQLConnectionConfig(strconv.Itoa(mysqlPort), "")+ instance, err := ctl.addInstance(api.InstanceCreate{+ EnvironmentID: environment.ID,+ Name: instanceName,+ Engine: db.MySQL,+ Host: connCfg.Host,+ Port: connCfg.Port,+ Username: connCfg.Username,+ })+ a.NoError(err)++ // Create an issue that creates a database.+ err = ctl.createDatabase(project, instance, dbName, "", nil /* labelMap */)+ a.NoError(err)++ a.Equal(len(test.expect), len(test.commitFileNames))+ a.Equal(len(test.expect), len(test.commitContents))+ for idx, commitFileName := range test.commitFileNames {+ // Simulate Git commits for schema update.+ err = ctl.vcsProvider.AddFiles(externalID, map[string]string{commitFileName: test.commitContents[idx]})+ a.NoError(err)++ payload, err := json.Marshal(test.newWebhookPushEvent(commitFileName))+ a.NoError(err)+ err = ctl.vcsProvider.SendWebhookPush(externalID, payload)+ a.NoError(err)++ // Check for newly generated issues.+ openStatus := []api.IssueStatus{api.IssueOpen}+ issues, err := ctl.getIssues(+ api.IssueFind{+ ProjectID: &project.ID,+ StatusList: openStatus,+ },+ )+ a.NoError(err)+ if test.expect[idx] {+ a.Len(issues, 1)+ issue := issues[0]+ status, err := ctl.waitIssuePipeline(issue.ID)+ a.NoError(err)+ a.Equal(api.TaskDone, status)+ _, err = ctl.patchIssueStatus(+ api.IssueStatusPatch{+ ID: issue.ID,+ Status: api.IssueDone,+ },+ )+ a.NoError(err)+ } else {+ a.Len(issues, 0)+ }+ }+ })+ }+}diff --git a/tests/tests.go b/tests/tests.goindex 4e56ebbf9a..137912fa68 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -120,6 +120,10 @@ func getTestPort(testName string) int {"TestSchemaAndDataUpdate","TestVCS/GitLab","TestVCS/GitHub",+ "TestWildcardInVCSFilePathTemplate/emptyBaseAndMixAsterisks",+ "TestWildcardInVCSFilePathTemplate/singleAsterisk",+ "TestWildcardInVCSFilePathTemplate/doubleAsterisks",+ "TestWildcardInVCSFilePathTemplate/mixAsterisks","TestTenant","TestTenantVCS/GitLab","TestTenantVCS/GitHub",@@ -515,6 +519,24 @@ func (ctl *controller) patchProject(projectPatch api.ProjectPatch) error {return nil}+func (ctl *controller) createEnvrionment(environmentCreate api.EnvironmentCreate) (*api.Environment, error) {+ buf := new(bytes.Buffer)+ if err := jsonapi.MarshalPayload(buf, &environmentCreate); err != nil {+ return nil, errors.Wrap(err, "failed to marshal environment create")+ }++ body, err := ctl.post("/environment", buf)+ if err != nil {+ return nil, err+ }++ environment := new(api.Environment)+ if err = jsonapi.UnmarshalPayload(body, environment); err != nil {+ return nil, errors.Wrap(err, "failed to unmarshal post project response")+ }+ return environment, nil+}+// getProjects gets the environments.func (ctl *controller) getEnvironments() ([]*api.Environment, error) {body, err := ctl.get("/environment", nil)