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(vcs): filter commits in push event webhook by commits diff (#3411)
Yilong Libbf0c0bd534f
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 1baff0cb28..62975a75ac 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -203,6 +203,8 @@ type WebhookCommit struct {// WebhookPushEvent is the API message for webhook push event.type WebhookPushEvent struct {Ref string `json:"ref"`+ Before string `json:"before"`+ After string `json:"after"`Repository WebhookRepository `json:"repository"`Sender WebhookSender `json:"sender"`Commits []WebhookCommit `json:"commits"`@@ -315,6 +317,11 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon}, nil}+// GetDiffFileList gets the diff files list between two commits.+func (*Provider) GetDiffFileList(_ context.Context, _ common.OauthContext, _, _, _, _ string) ([]vcs.FileDiff, error) {+ return nil, nil+}+// FetchUserInfo fetches user info of given user ID.func (p *Provider) FetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceURL, username string) (*vcs.UserInfo, error) {return p.fetchUserInfoImpl(ctx, oauthCtx, instanceURL, fmt.Sprintf("users/%s", username))@@ -1429,7 +1436,10 @@ func (p WebhookPushEvent) ToVCS() vcs.PushEvent {})}return vcs.PushEvent{+ VCSType: vcs.GitHubCom,Ref: p.Ref,+ Before: p.Before,+ After: p.After,RepositoryID: p.Repository.FullName,RepositoryURL: p.Repository.HTMLURL,RepositoryFullPath: p.Repository.FullName,diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex b48d76943c..a154c55bd4 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -89,6 +89,8 @@ type WebhookCommit struct {type WebhookPushEvent struct {ObjectKind WebhookType `json:"object_kind"`Ref string `json:"ref"`+ Before string `json:"before"`+ After string `json:"after"`AuthorName string `json:"user_name"`Project WebhookProject `json:"project"`CommitList []WebhookCommit `json:"commits"`@@ -124,6 +126,11 @@ type File struct {LastCommitID string}+// CommitsDiff represents a GitLab API response for comparing two commits.+type CommitsDiff struct {+ FileDiffList []MergeRequestFile `json:"diffs"`+}+// ProjectRole is the role of the project member.type ProjectRole string@@ -416,6 +423,61 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon}, nil}+// GetDiffFileList gets the diff files list between two commits.+func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]vcs.FileDiff, error) {+ url := fmt.Sprintf("%s/projects/%s/repository/compare?from=%s&to=%s", p.APIURL(instanceURL), repositoryID, beforeCommit, afterCommit)+ code, _, body, err := oauth.Get(+ ctx,+ p.client,+ url,+ &oauthCtx.AccessToken,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),+ )+ if err != nil {+ return nil, errors.Wrapf(err, "GET %s", url)+ }++ if code == http.StatusNotFound {+ return nil, common.Errorf(common.NotFound, "failed to get diff file list from URL %s", url)+ } else if code >= 300 {+ return nil,+ errors.Errorf("failed to get diff file list from URL %s, status code: %d, body: %s",+ url,+ code,+ body,+ )+ }++ diffs := &CommitsDiff{}+ if err := json.Unmarshal([]byte(body), diffs); err != nil {+ return nil, errors.Wrapf(err, "failed to unmarshal file diff data from GitLab instance %s", instanceURL)+ }++ var ret []vcs.FileDiff+ for _, diff := range diffs.FileDiffList {+ item := vcs.FileDiff{+ Path: diff.NewPath,+ }+ if diff.NewFile {+ item.Type = vcs.FileDiffTypeAdded+ } else if diff.DeletedFile {+ item.Type = vcs.FileDiffTypeRemoved+ } else {+ item.Type = vcs.FileDiffTypeModified+ }+ ret = append(ret, item)+ }+ return ret, nil+}+// FetchUserInfo fetches user info of given user ID.func (p *Provider) FetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, instanceURL, userID string) (*vcs.UserInfo, error) {return p.fetchUserInfoImpl(ctx, oauthCtx, instanceURL, fmt.Sprintf("users/%s", userID))@@ -1406,7 +1468,10 @@ func (p WebhookPushEvent) ToVCS() (vcs.PushEvent, error) {})}return vcs.PushEvent{+ VCSType: vcs.GitLabSelfHost,Ref: p.Ref,+ Before: p.Before,+ After: p.After,RepositoryID: fmt.Sprintf("%v", p.Project.ID),RepositoryURL: p.Project.WebURL,RepositoryFullPath: p.Project.FullPath,diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.goindex cb71de8b67..3c37247da4 100644--- a/plugin/vcs/vcs.go+++ b/plugin/vcs/vcs.go@@ -83,6 +83,25 @@ type FileMeta struct {LastCommitID string}+// FileDiffType is the type of file diff.+type FileDiffType int++const (+ // FileDiffTypeAdded means the file is newly added.+ FileDiffTypeAdded FileDiffType = iota+ // FileDiffTypeModified means the file is modified.+ FileDiffTypeModified+ // FileDiffTypeRemoved means the file is removed.+ FileDiffTypeRemoved+)++// FileDiff contains file diffs between two commits.+// It's obtained by comparing the base and head commits of a PR/MR so that we know the real changes.+type FileDiff struct {+ Path string+ Type FileDiffType+}+// RepositoryTreeNode records the node(file/folder) of a repository tree from `git ls-tree`.type RepositoryTreeNode struct {Path string@@ -94,6 +113,8 @@ type PushEvent struct {VCSType Type `json:"vcsType"`BaseDirectory string `json:"baseDir"`Ref string `json:"ref"`+ Before string `json:"before"`+ After string `json:"after"`RepositoryID string `json:"repositoryId"`RepositoryURL string `json:"repositoryUrl"`RepositoryFullPath string `json:"repositoryFullPath"`@@ -191,6 +212,14 @@ type Provider interface {// repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)// commitID: the commit IDFetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, commitID string) (*Commit, error)+ // Get the diff files list between two commits+ //+ // oauthCtx: OAuth context to fetch commit+ // instanceURL: VCS instance URL+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)+ // beforeCommit: the previous commit+ // afterCommit: the current commit+ GetDiffFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]FileDiff, error)// Fetch the user info of the given userID//// oauthCtx: OAuth context to write the file contentdiff --git a/server/webhook.go b/server/webhook.goindex f68c0bcbee..90449a325c 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -492,8 +492,14 @@ func (s *Server) processPushEvent(ctx context.Context, repositoryList []*api.Repreturn nil, nil}+ repo := repositoryList[0]+ filteredDistinctFileList, err := s.filterFilesByCommitsDiff(ctx, repo, distinctFileList, baseVCSPushEvent.Before, baseVCSPushEvent.After)+ if err != nil {+ return nil, err+ }+var createdMessageList []string- repoID2FileItemList := groupFileInfoByRepo(distinctFileList, repositoryList)+ repoID2FileItemList := groupFileInfoByRepo(filteredDistinctFileList, repositoryList)for _, fileInfoListInRepo := range repoID2FileItemList {// There are possibly multiple files in the push event.// Each file corresponds to a (database name, schema version) pair.@@ -537,6 +543,44 @@ func (s *Server) processPushEvent(ctx context.Context, repositoryList []*api.Repreturn createdMessageList, nil}+// Users may merge commits from other branches, and some of the commits merged in may already be merged into the main branch.+// In that case, the commits in the push event contains files which are not added in this PR/MR.+// We use the compare API to get the file diffs and filter files by the diffs.+func (s *Server) filterFilesByCommitsDiff(ctx context.Context, repo *api.Repository, distinctFileList []vcs.DistinctFileItem, beforeCommit, afterCommit string) ([]vcs.DistinctFileItem, error) {+ fileDiffList, err := vcs.Get(repo.VCS.Type, vcs.ProviderConfig{}).GetDiffFileList(+ ctx,+ common.OauthContext{+ ClientID: repo.VCS.ApplicationID,+ ClientSecret: repo.VCS.Secret,+ AccessToken: repo.AccessToken,+ RefreshToken: repo.RefreshToken,+ Refresher: s.refreshToken(ctx, repo.WebURL),+ },+ repo.VCS.InstanceURL,+ repo.ExternalID,+ beforeCommit,+ afterCommit,+ )+ if err != nil {+ return nil, errors.WithMessagef(err, "failed to get file diff list for repository %s", repo.ExternalID)+ }+ var filteredDistinctFileList []vcs.DistinctFileItem+ for _, file := range distinctFileList {+ for _, diff := range fileDiffList {+ if file.FileName == diff.Path {+ filteredDistinctFileList = append(filteredDistinctFileList, file)+ break+ }+ }+ }+ // Skip filtering for GitHub.+ // TODO(dragonly): remove this when GetDiffFileList is also implemented for GitHub.+ if fileDiffList == nil {+ filteredDistinctFileList = distinctFileList+ }+ return filteredDistinctFileList, nil+}+type fileInfo struct {item vcs.DistinctFileItemmigrationInfo *db.MigrationInfodiff --git a/tests/fake/github.go b/tests/fake/github.goindex b9d983039c..cf4088c43a 100644--- a/tests/fake/github.go+++ b/tests/fake/github.go@@ -440,6 +440,11 @@ func (gh *GitHub) CreateRepository(id string) {}}+// AddCommitsDiff adds a commits diff.+func (*GitHub) AddCommitsDiff(_, _, _ string, _ []vcs.FileDiff) error {+ return nil+}+// SendWebhookPush sends out a webhook for a push event for the GitHub// repository using given payload.func (gh *GitHub) SendWebhookPush(repositoryID string, payload []byte) error {diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex 09a344e156..f59a54641f 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -49,6 +49,9 @@ type projectData struct {*gitlab.MergeRequestChange*gitlab.MergeRequest}+ // commitsDiff is the map for commits compare.+ // The map key has the format "from...to" which is SHA or branch name.+ commitsDiff map[string]*gitlab.CommitsDiff}// NewGitLab creates a new fake implementation of GitLab VCS provider.@@ -81,6 +84,7 @@ func NewGitLab(port int) VCSProvider {projectGroup.POST("/projects/:id/variables", gl.createProjectEnvironmentVariable)projectGroup.PUT("/projects/:id/variables/:variableKey", gl.updateProjectEnvironmentVariable)projectGroup.GET("/projects/:id/merge_requests/:mrID/changes", gl.getMergeRequestChanges)+ projectGroup.GET("/projects/:id/repository/compare", gl.compareCommits)return gl}@@ -115,6 +119,7 @@ func (gl *GitLab) CreateRepository(id string) {*gitlab.MergeRequestChange*gitlab.MergeRequest}{},+ commitsDiff: map[string]*gitlab.CommitsDiff{},}}@@ -437,7 +442,7 @@ func (gl *GitLab) getMergeRequestChanges(c echo.Context) error {mergeRequest, ok := pd.mergeRequests[mrNumber]if !ok {- return c.String(http.StatusNotFound, fmt.Sprintf("Cannot found the merge request: %v", c.Param("mrID")))+ return c.String(http.StatusNotFound, fmt.Sprintf("Cannot find the merge request: %v", c.Param("mrID")))}buf, err := json.Marshal(mergeRequest.MergeRequestChange)@@ -447,6 +452,49 @@ func (gl *GitLab) getMergeRequestChanges(c echo.Context) error {return c.String(http.StatusOK, string(buf))}+func (gl *GitLab) compareCommits(c echo.Context) error {+ pd, err := gl.validProject(c)+ if err != nil {+ return err+ }+ key := fmt.Sprintf("%s...%s", c.QueryParam("from"), c.QueryParam("to"))+ diff, ok := pd.commitsDiff[key]+ if !ok {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Cannot find the diff key %s", key))+ }+ buf, err := json.Marshal(diff)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal response body").SetInternal(err)+ }+ return c.String(http.StatusOK, string(buf))+}++// AddCommitsDiff adds a commits diff.+func (gl *GitLab) AddCommitsDiff(projectID, fromCommit, toCommit string, fileDiffList []vcs.FileDiff) error {+ pd, ok := gl.projects[projectID]+ if !ok {+ return errors.Errorf("gitlab project %q doesn't exist", projectID)+ }+ key := fmt.Sprintf("%s...%s", fromCommit, toCommit)+ commitsDiff := &gitlab.CommitsDiff{+ FileDiffList: []gitlab.MergeRequestFile{},+ }+ for _, fileDiff := range fileDiffList {+ mrFile := gitlab.MergeRequestFile{+ NewPath: fileDiff.Path,+ }+ switch fileDiff.Type {+ case vcs.FileDiffTypeAdded:+ mrFile.NewFile = true+ case vcs.FileDiffTypeRemoved:+ mrFile.DeletedFile = true+ }+ commitsDiff.FileDiffList = append(commitsDiff.FileDiffList, mrFile)+ }+ pd.commitsDiff[key] = commitsDiff+ return nil+}+// SendWebhookPush sends out a webhook for a push event for the GitLab project// using given payload.func (gl *GitLab) SendWebhookPush(projectID string, payload []byte) error {diff --git a/tests/fake/provider.go b/tests/fake/provider.goindex 7df9106a76..6b63993b90 100644--- a/tests/fake/provider.go+++ b/tests/fake/provider.go@@ -28,6 +28,8 @@ type VCSProvider interface {GetFiles(repositoryID string, filePaths ...string) (map[string]string, error)// AddPullRequest creates a new pull request and add changed files to it.AddPullRequest(repositoryID string, prID int, files []*vcs.PullRequestFile) error+ // AddCommitsDiff adds a commits diff.+ AddCommitsDiff(repositoryID, fromCommit, toCommit string, fileDiffList []vcs.FileDiff) error}// VCSProviderCreator a function to create a new VCSProvider.diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex a813da9c60..59351f6414 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -277,7 +277,7 @@ func TestVCS(t *testing.T) {vcsType vcs.TypeexternalID stringrepositoryFullPath string- newWebhookPushEvent func(added [][]string, modified [][]string) interface{}+ newWebhookPushEvent func(added, modified [][]string, beforeSHA, afterSHA string) interface{}}{{name: "GitLab",@@ -285,7 +285,7 @@ func TestVCS(t *testing.T) {vcsType: vcs.GitLabSelfHost,externalID: "121",repositoryFullPath: "test/schemaUpdate",- newWebhookPushEvent: func(added [][]string, modified [][]string) interface{} {+ newWebhookPushEvent: func(added, modified [][]string, beforeSHA, afterSHA string) interface{} {var commitList []gitlab.WebhookCommitfor i := range added {commitList = append(commitList, gitlab.WebhookCommit{@@ -297,6 +297,8 @@ func TestVCS(t *testing.T) {return gitlab.WebhookPushEvent{ObjectKind: gitlab.WebhookPush,Ref: "refs/heads/feature/foo",+ Before: beforeSHA,+ After: afterSHA,Project: gitlab.WebhookProject{ID: 121,},@@ -310,7 +312,7 @@ func TestVCS(t *testing.T) {vcsType: vcs.GitHubCom,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",- newWebhookPushEvent: func(added [][]string, modified [][]string) interface{} {+ newWebhookPushEvent: func(added, modified [][]string, beforeSHA, afterSHA string) interface{} {var commits []github.WebhookCommitfor i := range added {commits = append(commits, github.WebhookCommit{@@ -328,7 +330,9 @@ func TestVCS(t *testing.T) {})}return github.WebhookPushEvent{- Ref: "refs/heads/feature/foo",+ Ref: "refs/heads/feature/foo",+ Before: beforeSHA,+ After: afterSHA,Repository: github.WebhookRepository{ID: 211,FullName: "octocat/Hello-World",@@ -361,7 +365,7 @@ func TestVCS(t *testing.T) {a.NoError(err)// Create a VCS.- vcs, err := ctl.createVCS(+ apiVCS, err := ctl.createVCS(api.VCSCreate{Name: t.Name(),Type: test.vcsType,@@ -386,7 +390,7 @@ func TestVCS(t *testing.T) {ctl.vcsProvider.CreateRepository(test.externalID)_, err = ctl.createRepository(api.RepositoryCreate{- VCSID: vcs.ID,+ VCSID: apiVCS.ID,ProjectID: project.ID,Name: "Test Repository",FullPath: test.repositoryFullPath,@@ -437,8 +441,20 @@ func TestVCS(t *testing.T) {gitFile1 := "bbtest/Prod/testVCSSchemaUpdate##ver1##migrate##create_table_book.sql"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile1: migrationStatement})a.NoError(err)+ // This file is merged from other branch and included in this push event's commits.+ // But it is already merged into the main branch and the commits diff does not contain it.+ // So this file should be excluded when generating the issue.+ gitFileMergeFromOtherBranch := "bbtest/Prod/testVCSSchemaUpdate##ver0##migrate##merge_from_other_branch.sql"+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFileMergeFromOtherBranch: "SELECT 1;"})+ a.NoError(err)+ err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "1", "2", []vcs.FileDiff{+ {Path: gitFile1, Type: vcs.FileDiffTypeAdded},+ {Path: gitFile2, Type: vcs.FileDiffTypeAdded},+ {Path: gitFile3, Type: vcs.FileDiffTypeAdded},+ })+ a.NoError(err)- payload, err := json.Marshal(test.newWebhookPushEvent([][]string{{gitFile3}, {gitFile2}, {gitFile1}}, [][]string{nil, nil, nil}))+ payload, err := json.Marshal(test.newWebhookPushEvent([][]string{{gitFile1}, {gitFile2}, {gitFile3}, {gitFileMergeFromOtherBranch}}, [][]string{nil, nil, nil, nil}, "1", "2"))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -462,7 +478,12 @@ func TestVCS(t *testing.T) {// TODO(p0ny): expose task DAG list and check the dependency.a.Equal(api.TaskDatabaseSchemaUpdate, issue.Pipeline.StageList[0].TaskList[0].Type)a.Equal("[testVCSSchemaUpdate] Alter schema", issue.Name)- a.Equal("By VCS files Prod/testVCSSchemaUpdate##ver1##migrate##create_table_book.sql, Prod/testVCSSchemaUpdate##ver2##migrate##create_table_book2.sql, Prod/testVCSSchemaUpdate##ver3##migrate##create_table_book3.sql", issue.Description)+ if test.name == "GitLab" {+ a.Equal("By VCS files Prod/testVCSSchemaUpdate##ver1##migrate##create_table_book.sql, Prod/testVCSSchemaUpdate##ver2##migrate##create_table_book2.sql, Prod/testVCSSchemaUpdate##ver3##migrate##create_table_book3.sql", issue.Description)+ } else {+ // TODO(dragonly): remove this when GetDiffFileList is also implemented for GitHub.+ a.Equal("By VCS files Prod/testVCSSchemaUpdate##ver0##migrate##merge_from_other_branch.sql, Prod/testVCSSchemaUpdate##ver1##migrate##create_table_book.sql, Prod/testVCSSchemaUpdate##ver2##migrate##create_table_book2.sql, Prod/testVCSSchemaUpdate##ver3##migrate##create_table_book3.sql", issue.Description)+ }_, err = ctl.patchIssueStatus(api.IssueStatusPatch{ID: issue.ID,@@ -477,11 +498,14 @@ func TestVCS(t *testing.T) {a.Equal(bookSchemaSQLResult, result)// Simulate Git commits for failed data update.- gitFile3 = "bbtest/Prod/testVCSSchemaUpdate##ver4##data##insert_data.sql"- err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile3: dataUpdateStatementWrong})+ gitFile4 := "bbtest/Prod/testVCSSchemaUpdate##ver4##data##insert_data.sql"+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile4: dataUpdateStatementWrong})a.NoError(err)-- payload, err = json.Marshal(test.newWebhookPushEvent([][]string{{gitFile3}}, [][]string{nil}))+ err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "2", "3", []vcs.FileDiff{+ {Path: gitFile4, Type: vcs.FileDiffTypeAdded},+ })+ a.NoError(err)+ payload, err = json.Marshal(test.newWebhookPushEvent([][]string{{gitFile4}}, [][]string{nil}, "2", "3"))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -502,9 +526,13 @@ func TestVCS(t *testing.T) {a.Equal(api.TaskFailed, status)// Simulate Git commits for a correct modified date update.- err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile3: dataUpdateStatement})+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile4: dataUpdateStatement})a.NoError(err)- payload, err = json.Marshal(test.newWebhookPushEvent([][]string{nil}, [][]string{{gitFile3}}))+ err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "3", "4", []vcs.FileDiff{+ {Path: gitFile4, Type: vcs.FileDiffTypeModified},+ })+ a.NoError(err)+ payload, err = json.Marshal(test.newWebhookPushEvent([][]string{nil}, [][]string{{gitFile4}}, "3", "4"))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -600,6 +628,59 @@ func TestVCS(t *testing.T) {SchemaPrev: "",},}+ // TODO(dragonly): remove this when GetDiffFileList is also implemented for GitHub.+ if test.name == "GitHub" {+ wantHistories = []api.MigrationHistory{+ {+ Database: databaseName,+ Source: db.VCS,+ Type: db.Data,+ Status: db.Done,+ Schema: dumpedSchema3,+ SchemaPrev: dumpedSchema3,+ },+ {+ Database: databaseName,+ Source: db.VCS,+ Type: db.Migrate,+ Status: db.Done,+ Schema: dumpedSchema3,+ SchemaPrev: dumpedSchema2,+ },+ {+ Database: databaseName,+ Source: db.VCS,+ Type: db.Migrate,+ Status: db.Done,+ Schema: dumpedSchema2,+ SchemaPrev: dumpedSchema,+ },+ {+ Database: databaseName,+ Source: db.VCS,+ Type: db.Migrate,+ Status: db.Done,+ Schema: dumpedSchema,+ SchemaPrev: "",+ },+ {+ Database: databaseName,+ Source: db.VCS,+ Type: db.Migrate,+ Status: db.Done,+ Schema: "",+ SchemaPrev: "",+ },+ {+ Database: databaseName,+ Source: db.UI,+ Type: db.Migrate,+ Status: db.Done,+ Schema: "",+ SchemaPrev: "",+ },+ }+ }a.Equal(len(wantHistories), len(histories))for i, history := range histories {@@ -629,7 +710,7 @@ func TestVCS_SDL(t *testing.T) {vcsType vcs.TypeexternalID stringrepositoryFullPath string- newWebhookPushEvent func(added []string, modified []string) interface{}+ newWebhookPushEvent func(added, modified []string, beforeSHA, afterSHA string) interface{}}{{name: "GitLab",@@ -637,10 +718,12 @@ func TestVCS_SDL(t *testing.T) {vcsType: vcs.GitLabSelfHost,externalID: "121",repositoryFullPath: "test/schemaUpdate",- newWebhookPushEvent: func(added []string, modified []string) interface{} {+ newWebhookPushEvent: func(added, modified []string, beforeSHA, afterSHA string) interface{} {return gitlab.WebhookPushEvent{ObjectKind: gitlab.WebhookPush,Ref: "refs/heads/feature/foo",+ Before: beforeSHA,+ After: afterSHA,Project: gitlab.WebhookProject{ID: 121,},@@ -660,9 +743,11 @@ func TestVCS_SDL(t *testing.T) {vcsType: vcs.GitHubCom,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",- newWebhookPushEvent: func(added []string, modified []string) interface{} {+ newWebhookPushEvent: func(added, modified []string, beforeSHA, afterSHA string) interface{} {return github.WebhookPushEvent{- Ref: "refs/heads/feature/foo",+ Ref: "refs/heads/feature/foo",+ Before: beforeSHA,+ After: afterSHA,Repository: github.WebhookRepository{ID: 211,FullName: "octocat/Hello-World",@@ -809,7 +894,7 @@ func TestVCS_SDL(t *testing.T) {})a.NoError(err)- payload, err := json.Marshal(test.newWebhookPushEvent(nil /* added */, []string{schemaFile}))+ payload, err := json.Marshal(test.newWebhookPushEvent(nil /* added */, []string{schemaFile}, "1", "2"))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -847,7 +932,7 @@ func TestVCS_SDL(t *testing.T) {})a.NoError(err)- payload, err = json.Marshal(test.newWebhookPushEvent([]string{dataFile}, nil /* modified */))+ payload, err = json.Marshal(test.newWebhookPushEvent([]string{dataFile}, nil /* modified */, "2", "3"))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -1009,17 +1094,34 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {externalID := "121"repoFullPath := "test/wildcard"+ defaultNewWebhookPushEvent := func(added []string, beforeSHA, afterSHA string) interface{} {+ return gitlab.WebhookPushEvent{+ ObjectKind: gitlab.WebhookPush,+ Ref: fmt.Sprintf("refs/heads/%s", branchFilter),+ Before: beforeSHA,+ After: afterSHA,+ Project: gitlab.WebhookProject{+ ID: 121,+ },+ CommitList: []gitlab.WebhookCommit{+ {+ Timestamp: "2021-01-13T13:14:00Z",+ AddedList: added,+ },+ },+ }+ }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 string+ vcsProviderCreator fake.VCSProviderCreator+ vcsType vcs.Type+ baseDirectory string+ envName string+ filePathTemplate string+ commitNewFileNames []string+ commitNewFileContents []string+ expect []bool+ newWebhookPushEvent func(added []string, beforeSHA, afterSHA string) interface{}}{{name: "singleAsterisk",@@ -1028,7 +1130,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {baseDirectory: "bbtest",envName: "wildcard",filePathTemplate: "{{ENV_NAME}}/*/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",- commitFileNames: []string{+ commitNewFileNames: []string{// Normalfmt.Sprintf("%s/%s/foo/%s##ver1##migrate##create_table_t1.sql", baseDirectory, "wildcard", dbName),// One singleAsterisk cannot match two directories.@@ -1036,7 +1138,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {// One singleAsterisk cannot match zero directory.fmt.Sprintf("%s/%s/%s##ver3##migrate##create_table_t3.sql", baseDirectory, "wildcard", dbName),},- commitContents: []string{+ commitNewFileContents: []string{"CREATE TABLE t1 (id INT);","INSERT INTO t1 VALUES (1);","CREATE TABLE t3 (id INT);",@@ -1046,22 +1148,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {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{- {- ID: "68211f18905c46e8bda58a8fee98051f2ffe40bb",- Timestamp: "2021-01-13T13:14:00Z",- AddedList: []string{gitFile},- },- },- }- },+ newWebhookPushEvent: defaultNewWebhookPushEvent,},{name: "doubleAsterisks",@@ -1070,7 +1157,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {baseDirectory: "bbtest",envName: "wildcard",filePathTemplate: "{{ENV_NAME}}/**/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",- commitFileNames: []string{+ commitNewFileNames: []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.@@ -1080,7 +1167,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {// Two singleAsterisk cannot match zero directory.fmt.Sprintf("%s/%s/%s##ver4##migrate##create_table_t4.sql", baseDirectory, "wildcard", dbName),},- commitContents: []string{+ commitNewFileContents: []string{"CREATE TABLE t1 (id INT);","CREATE TABLE t2 (id INT);","CREATE TABLE t3 (id INT);",@@ -1092,22 +1179,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {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{- {- ID: "68211f18905c46e8bda58a8fee98051f2ffe40bb",- Timestamp: "2021-01-13T13:14:00Z",- AddedList: []string{gitFile},- },- },- }- },+ newWebhookPushEvent: defaultNewWebhookPushEvent,},{name: "emptyBaseAndMixAsterisks",@@ -1116,7 +1188,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {baseDirectory: "",vcsType: vcs.GitLabSelfHost,filePathTemplate: "{{ENV_NAME}}/**/foo/*/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",- commitFileNames: []string{+ commitNewFileNames: []string{// ** matches foo, foo matches foo, * matches barfmt.Sprintf("%s/foo/foo/bar/%s##ver1##migrate##create_table_t1.sql", "wildcard", dbName),// ** matches foo/bar/foo, foo matches foo, * matches bar@@ -1124,7 +1196,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {// cannot matchfmt.Sprintf("%s/%s##ver3##migrate##create_table_t3.sql", "wildcard", dbName),},- commitContents: []string{+ commitNewFileContents: []string{"CREATE TABLE t1 (id INT);","CREATE TABLE t2 (id INT);","CREATE TABLE t3 (id INT);",@@ -1134,22 +1206,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {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{- {- ID: "68211f18905c46e8bda58a8fee98051f2ffe40bb",- Timestamp: "2021-01-13T13:14:00Z",- AddedList: []string{gitFile},- },- },- }- },+ newWebhookPushEvent: defaultNewWebhookPushEvent,},// We test the combination of ** and *, and the place holder is not fully represented by the ascii character set.{@@ -1159,7 +1216,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {baseDirectory: "bbtest",vcsType: vcs.GitLabSelfHost,filePathTemplate: "{{ENV_NAME}}/**/foo/*/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",- commitFileNames: []string{+ commitNewFileNames: []string{// ** matches foo, foo matches foo, * matches barfmt.Sprintf("%s/%s/foo/foo/bar/%s##ver1##migrate##create_table_t1.sql", baseDirectory, "生产", dbName),// ** matches foo/bar/foo, foo matches foo, * matches bar@@ -1167,7 +1224,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {// cannot matchfmt.Sprintf("%s/%s/%s##ver3##migrate##create_table_t3.sql", baseDirectory, "生产", dbName),},- commitContents: []string{+ commitNewFileContents: []string{"CREATE TABLE t1 (id INT);","CREATE TABLE t2 (id INT);","CREATE TABLE t3 (id INT);",@@ -1177,22 +1234,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {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{- {- ID: "68211f18905c46e8bda58a8fee98051f2ffe40bb",- Timestamp: "2021-01-13T13:14:00Z",- AddedList: []string{gitFile},- },- },- }- },+ newWebhookPushEvent: defaultNewWebhookPushEvent,},// No asterisk{@@ -1202,12 +1244,12 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {baseDirectory: "bbtest",vcsType: vcs.GitLabSelfHost,filePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}/sql/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",- commitFileNames: []string{+ commitNewFileNames: []string{fmt.Sprintf("%s/%s/%s/sql/%s##ver1##migrate##create_table_t1.sql", baseDirectory, "ZO", dbName, dbName),fmt.Sprintf("%s/%s/%s/%s##ver2##migrate##create_table_t2.sql", baseDirectory, "ZO", dbName, dbName),fmt.Sprintf("%s/%s/%s/sql/%s##ver3##migrate##create_table_t3.sql", baseDirectory, "ZO", dbName, dbName),},- commitContents: []string{+ commitNewFileContents: []string{"CREATE TABLE t1 (id INT);","CREATE TABLE t2 (id INT);","CREATE TABLE t3 (id INT);",@@ -1217,22 +1259,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {false,true,},- 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{- {- ID: "68211f18905c46e8bda58a8fee98051f2ffe40bb",- Timestamp: "2021-01-13T13:14:00Z",- AddedList: []string{gitFile},- },- },- }- },+ newWebhookPushEvent: defaultNewWebhookPushEvent,},}for _, test := range tests {@@ -1255,7 +1282,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {a.NoError(err)// Create a VCS.- vcs, err := ctl.createVCS(+ apiVCS, err := ctl.createVCS(api.VCSCreate{Name: t.Name(),Type: test.vcsType,@@ -1280,7 +1307,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {ctl.vcsProvider.CreateRepository(externalID)_, err = ctl.createRepository(api.RepositoryCreate{- VCSID: vcs.ID,+ VCSID: apiVCS.ID,ProjectID: project.ID,Name: "Test Repository",FullPath: repoFullPath,@@ -1317,14 +1344,21 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {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 {+ a.Equal(len(test.expect), len(test.commitNewFileNames))+ a.Equal(len(test.expect), len(test.commitNewFileContents))++ for idx, commitFileName := range test.commitNewFileNames {// Simulate Git commits for schema update.- err = ctl.vcsProvider.AddFiles(externalID, map[string]string{commitFileName: test.commitContents[idx]})+ err = ctl.vcsProvider.AddFiles(externalID, map[string]string{commitFileName: test.commitNewFileContents[idx]})a.NoError(err)-- payload, err := json.Marshal(test.newWebhookPushEvent(commitFileName))+ // We always commit one file at a time in this test.+ beforeCommit := strconv.Itoa(idx)+ afterCommit := strconv.Itoa(idx + 1)+ err = ctl.vcsProvider.AddCommitsDiff(externalID, beforeCommit, afterCommit, []vcs.FileDiff{+ {Path: commitFileName, Type: vcs.FileDiffTypeAdded},+ })+ a.NoError(err)+ payload, err := json.Marshal(test.newWebhookPushEvent([]string{commitFileName}, beforeCommit, afterCommit))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(externalID, payload)a.NoError(err)