Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: move getCommitList to gitlab/github package (#2904)
Danny Xu2b7c90305c20
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 9a6fba2ea2..7f411a8d1a 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -961,3 +961,37 @@ func tokenRefresher(instanceURL string, oauthCtx oauthContext, refresher common.return refresher(r.AccessToken, r.RefreshToken, expireAt)}}++// ToVCS returns the push event in VCS format.+func (p WebhookPushEvent) ToVCS() vcs.PushEvent {+ var commitList []vcs.Commit+ for _, commit := range p.Commits {+ // The Distinct is false if the commit has not been pushed before.+ if !commit.Distinct {+ continue+ }+ // Per Git convention, the message title and body are separated by two new line characters.+ messages := strings.SplitN(commit.Message, "\n\n", 2)+ messageTitle := messages[0]++ commitList = append(commitList, vcs.Commit{+ ID: commit.ID,+ Title: messageTitle,+ Message: commit.Message,+ CreatedTs: commit.Timestamp.Unix(),+ URL: commit.URL,+ AuthorName: commit.Author.Name,+ AuthorEmail: commit.Author.Email,+ AddedList: commit.Added,+ ModifiedList: commit.Modified,+ })+ }+ return vcs.PushEvent{+ Ref: p.Ref,+ RepositoryID: p.Repository.FullName,+ RepositoryURL: p.Repository.HTMLURL,+ RepositoryFullPath: p.Repository.FullName,+ AuthorName: p.Sender.Login,+ CommitList: commitList,+ }+}diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 3dce9fb43d..ce997d642b 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -989,3 +989,33 @@ func tokenRefresher(instanceURL string, oauthCtx oauthContext, refresher common.return refresher(r.AccessToken, r.RefreshToken, expireAt)}}++// ToVCS returns the push event in VCS format.+func (p WebhookPushEvent) ToVCS() (vcs.PushEvent, error) {+ var commitList []vcs.Commit+ for _, commit := range p.CommitList {+ createdTime, err := time.Parse(time.RFC3339, commit.Timestamp)+ if err != nil {+ return vcs.PushEvent{}, errors.Wrapf(err, "failed to parse commit %s's timestamp %s", commit.ID, common.EscapeForLogging(commit.Timestamp))+ }+ commitList = append(commitList, vcs.Commit{+ ID: commit.ID,+ Title: commit.Title,+ Message: commit.Message,+ CreatedTs: createdTime.Unix(),+ URL: commit.URL,+ AuthorName: commit.Author.Name,+ AuthorEmail: commit.Author.Email,+ AddedList: commit.AddedList,+ ModifiedList: commit.ModifiedList,+ })+ }+ return vcs.PushEvent{+ Ref: p.Ref,+ RepositoryID: fmt.Sprintf("%v", p.Project.ID),+ RepositoryURL: p.Project.WebURL,+ RepositoryFullPath: p.Project.FullPath,+ AuthorName: p.AuthorName,+ CommitList: commitList,+ }, nil+}diff --git a/plugin/vcs/util.go b/plugin/vcs/util.goindex eb8175fd49..2c7210ce49 100644--- a/plugin/vcs/util.go+++ b/plugin/vcs/util.go@@ -5,6 +5,10 @@ import ("strings""github.com/pkg/errors"+ "go.uber.org/zap"++ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/common/log")// Branch is the helper function returns the branch name from reference name.@@ -17,3 +21,85 @@ func Branch(ref string) (string, error) {return "", errors.Errorf("invalid Git ref: %s", ref)}++// FileItemType is the type of a file item.+type FileItemType string++// The list of file item types.+const (+ FileItemTypeAdded FileItemType = "added"+ FileItemTypeModified FileItemType = "modified"+)++// DistinctFileItem is an item for distinct file in push event commits.+// We are observing the push webhook event so that we will receive the event either when:+// 1. A commit is directly pushed to a branch.+// 2. One or more commits are merged to a branch.+//+// There is a complication to deal with the 2nd type. A typical workflow is a developer first+// commits the migration file to the feature branch, and at a later point, she creates a merge+// request to merge the commit to the main branch. Even the developer only creates a single commit+// on the feature branch, that merge request may contain multiple commits (unless both squash and fast-forward merge are used):+// 1. The original commit on the feature branch.+// 2. The merge request commit.+//+// And both commits would include that added migration file. Since we create an issue per migration file,+// we need to filter the commit list to prevent creating a duplicated issue. GitLab has a limitation to distinguish+// whether the commit is a merge commit (https://gitlab.com/gitlab-org/gitlab/-/issues/30914), so we need to dedup+// ourselves. Below is the filtering algorithm:+// 1. If we observe the same migration file multiple times, then we should use the latest migration file. This does not matter+// for change-based migration since a developer would always create different migration file with incremental names, while it+// will be important for the state-based migration, since the file name is always the same and we need to use the latest snapshot.+// 2. Maintain the relative commit order between different migration files. If migration file A happens before migration file B,+// then we should create an issue for migration file A first.+type DistinctFileItem struct {+ CreatedTs int64+ Commit Commit+ FileName string+ ItemType FileItemType+}++// GetDistinctFileList gets the distinct files from push event commits.+func (p PushEvent) GetDistinctFileList() []DistinctFileItem {+ // Use list instead of map because we need to maintain the relative commit order in the source branch.+ var distinctFileList []DistinctFileItem+ for _, commit := range p.CommitList {+ log.Debug("Pre-processing commit to dedup migration files...",+ zap.String("id", common.EscapeForLogging(commit.ID)),+ zap.String("title", common.EscapeForLogging(commit.Title)),+ )++ addDistinctFile := func(fileName string, itemType FileItemType) {+ item := DistinctFileItem{+ CreatedTs: commit.CreatedTs,+ Commit: commit,+ FileName: fileName,+ ItemType: itemType,+ }+ for i, file := range distinctFileList {+ // For the migration file with the same name, keep the one from the latest commit+ if item.FileName != file.FileName {+ continue+ }+ if file.CreatedTs < commit.CreatedTs {+ // A file can be added and then modified in a later commit. We should consider the item as added.+ if file.ItemType == FileItemTypeAdded {+ item.ItemType = FileItemTypeAdded+ }+ distinctFileList[i] = item+ }+ // The fileName should be unique within the distinctFileList.+ return+ }+ distinctFileList = append(distinctFileList, item)+ }++ for _, added := range commit.AddedList {+ addDistinctFile(added, FileItemTypeAdded)+ }+ for _, modified := range commit.ModifiedList {+ addDistinctFile(modified, FileItemTypeModified)+ }+ }+ return distinctFileList+}diff --git a/plugin/vcs/util_test.go b/plugin/vcs/util_test.goindex 1597169f61..7e11899dff 100644--- a/plugin/vcs/util_test.go+++ b/plugin/vcs/util_test.go@@ -2,6 +2,7 @@ package vcsimport ("testing"+ "time""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -38,3 +39,442 @@ func TestBranch(t *testing.T) {assert.Equal(t, result, test.want)}}++func TestGetDistinctFileList(t *testing.T) {+ timestamp1 := "2021-01-13T00:00:00+00:00"+ timestamp2 := "2021-01-14T00:00:00+00:00"+ timestamp3 := "2021-01-15T00:00:00+00:00"+ time1, _ := time.Parse(time.RFC3339, timestamp1)+ time2, _ := time.Parse(time.RFC3339, timestamp2)+ time3, _ := time.Parse(time.RFC3339, timestamp3)+ ts1 := time1.Unix()+ ts2 := time2.Unix()+ ts3 := time3.Unix()++ tests := []struct {+ name string+ commitList []Commit+ want []DistinctFileItem+ }{+ {+ name: "Empty",+ commitList: []Commit{},+ want: nil,+ },+ {+ name: "Single commit, single file",+ commitList: []Commit{+ {+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ },+ },+ },+ want: []DistinctFileItem{+ {+ CreatedTs: ts1,+ Commit: Commit{+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ },+ },+ FileName: "v1.sql",+ ItemType: FileItemTypeAdded,+ },+ },+ },+ {+ name: "Single commit, multiple files",+ commitList: []Commit{+ {+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ },+ },+ },+ want: []DistinctFileItem{+ {+ CreatedTs: ts1,+ Commit: Commit{+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ },+ },+ FileName: "v1.sql",+ ItemType: FileItemTypeAdded,+ },+ {+ CreatedTs: ts1,+ Commit: Commit{+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ },+ },+ FileName: "v2.sql",+ ItemType: FileItemTypeAdded,+ },+ },+ },+ {+ name: "Multi commits, single file",+ commitList: []Commit{+ {+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ },+ },+ {+ ID: "2",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts2,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ },+ },+ },+ want: []DistinctFileItem{+ {+ CreatedTs: ts2,+ Commit: Commit{+ ID: "2",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts2,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ },+ },+ FileName: "v1.sql",+ ItemType: FileItemTypeAdded,+ },+ },+ },+ {+ name: "Multi commits, single file, direct push",+ commitList: []Commit{+ {+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ },+ },+ {+ ID: "2",+ Title: "Commit 2",+ Message: "Update 2",+ CreatedTs: ts2,+ URL: "example.com",+ AuthorName: "bob",+ ModifiedList: []string{+ "v1.sql",+ },+ },+ },+ want: []DistinctFileItem{+ {+ CreatedTs: ts2,+ Commit: Commit{+ ID: "2",+ Title: "Commit 2",+ Message: "Update 2",+ CreatedTs: ts2,+ URL: "example.com",+ AuthorName: "bob",+ ModifiedList: []string{+ "v1.sql",+ },+ },+ FileName: "v1.sql",+ ItemType: FileItemTypeAdded,+ },+ },+ },+ {+ name: "Multi commits, multi files",+ commitList: []Commit{+ {+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ },+ },+ {+ ID: "2",+ Title: "Commit 2",+ Message: "Update 2",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v3.sql",+ },+ },+ {+ ID: "3",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ },+ },+ want: []DistinctFileItem{+ {+ CreatedTs: ts3,+ Commit: Commit{+ ID: "3",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ },+ FileName: "v1.sql",+ ItemType: FileItemTypeAdded,+ },+ {+ CreatedTs: ts3,+ Commit: Commit{+ ID: "3",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ },+ FileName: "v2.sql",+ ItemType: FileItemTypeAdded,+ },+ {+ CreatedTs: ts3,+ Commit: Commit{+ ID: "3",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ },+ FileName: "v3.sql",+ ItemType: FileItemTypeAdded,+ },+ },+ },+ {+ name: "Multi commits, multi files, include modified",+ commitList: []Commit{+ {+ ID: "1",+ Title: "Commit 1",+ Message: "Update 1",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ },+ },+ {+ ID: "2",+ Title: "Commit 2",+ Message: "Update 2",+ CreatedTs: ts1,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v3.sql",+ },+ },+ {+ ID: "3",+ Title: "Commit 3",+ Message: "Update 3",+ CreatedTs: ts2,+ URL: "example.com",+ AuthorName: "bob",+ ModifiedList: []string{+ "v3.sql",+ "v4.sql",+ },+ },+ {+ ID: "4",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ // This file is both added and modified in the commits above.+ // GitLab will treat this as added in the merge commit.+ "v3.sql",+ },+ ModifiedList: []string{"v4.sql"},+ },+ },+ want: []DistinctFileItem{+ {+ CreatedTs: ts3,+ Commit: Commit{+ ID: "4",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ ModifiedList: []string{"v4.sql"},+ },+ FileName: "v1.sql",+ ItemType: FileItemTypeAdded,+ },+ {+ CreatedTs: ts3,+ Commit: Commit{+ ID: "4",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ ModifiedList: []string{"v4.sql"},+ },+ FileName: "v2.sql",+ ItemType: FileItemTypeAdded,+ },+ {+ CreatedTs: ts3,+ Commit: Commit{+ ID: "4",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ ModifiedList: []string{"v4.sql"},+ },+ FileName: "v3.sql",+ ItemType: FileItemTypeAdded,+ },+ {+ CreatedTs: ts3,+ Commit: Commit{+ ID: "4",+ Title: "Merge branch",+ Message: "Merge update",+ CreatedTs: ts3,+ URL: "example.com",+ AuthorName: "bob",+ AddedList: []string{+ "v1.sql",+ "v2.sql",+ "v3.sql",+ },+ ModifiedList: []string{"v4.sql"},+ },+ FileName: "v4.sql",+ ItemType: FileItemTypeModified,+ },+ },+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ p := PushEvent{CommitList: tt.commitList}+ got := p.GetDistinctFileList()+ assert.Equal(t, tt.want, got)+ })+ }+}diff --git a/server/webhook.go b/server/webhook.goindex 2a34a1133e..cebf095d50 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -14,7 +14,6 @@ import ("path""regexp""strings"- "time""github.com/labstack/echo/v4""github.com/pkg/errors"@@ -62,18 +61,10 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}log.Debug("Process push event in repos", zap.Any("repos", repositoryList))- commitList, err := convertGitLabCommitList(pushEvent.CommitList)+ baseVCSPushEvent, err := pushEvent.ToVCS()if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to convert GitLab commits").SetInternal(err)}- baseVCSPushEvent := vcs.PushEvent{- Ref: pushEvent.Ref,- RepositoryID: repositoryID,- RepositoryURL: pushEvent.Project.WebURL,- RepositoryFullPath: pushEvent.Project.FullPath,- AuthorName: pushEvent.AuthorName,- CommitList: commitList,- }createdMessages, err := s.createIssuesFromCommits(ctx, repositoryList, baseVCSPushEvent)if err != nil {@@ -124,15 +115,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}log.Debug("Process push event in repos", zap.Any("repos", repositoryList))- commitList := convertGitHubCommitList(pushEvent.Commits)- baseVCSPushEvent := vcs.PushEvent{- Ref: pushEvent.Ref,- RepositoryID: repositoryID,- RepositoryURL: pushEvent.Repository.HTMLURL,- RepositoryFullPath: repositoryID,- AuthorName: pushEvent.Sender.Login,- CommitList: commitList,- }+ baseVCSPushEvent := pushEvent.ToVCS()createdMessages, err := s.createIssuesFromCommits(ctx, repositoryList, baseVCSPushEvent)if err != nil {@@ -142,80 +125,6 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {})}-func (s *Server) createIssuesFromCommits(ctx context.Context, repositoryList []*api.Repository, baseVCSPushEvent vcs.PushEvent) ([]string, error) {- distinctFileList := getDistinctFileList(baseVCSPushEvent.CommitList)- if len(distinctFileList) == 0 {- var commitIDs []string- for _, c := range baseVCSPushEvent.CommitList {- commitIDs = append(commitIDs, c.ID)- }- log.Warn("No files found from the push event",- zap.String("repoURL", common.EscapeForLogging(baseVCSPushEvent.RepositoryURL)),- zap.String("repoName", baseVCSPushEvent.RepositoryFullPath),- zap.String("commits", strings.Join(commitIDs, ",")))- return nil, nil- }-- var createdMessages []string- for _, item := range distinctFileList {- var createdMessageList []string- repoID2ActivityCreateList := make(map[int][]*api.ActivityCreate)- for _, repo := range repositoryList {- pushEvent := baseVCSPushEvent- pushEvent.VCSType = repo.VCS.Type- pushEvent.BaseDirectory = repo.BaseDirectory- pushEvent.FileCommit = vcs.FileCommit{- ID: item.commit.ID,- Title: item.commit.Title,- Message: item.commit.Message,- CreatedTs: item.commit.CreatedTs,- URL: item.commit.URL,- AuthorName: item.commit.AuthorName,- AuthorEmail: item.commit.AuthorEmail,- Added: common.EscapeForLogging(item.fileName),- }-- createdMessage, created, activityCreateList, err := s.createIssueFromPushEvent(- ctx,- &pushEvent,- repo,- item.fileName,- item.itemType,- )- if err != nil {- return nil, err- }- if created {- createdMessageList = append(createdMessageList, createdMessage)- }- repoID2ActivityCreateList[repo.ID] = append(repoID2ActivityCreateList[repo.ID], activityCreateList...)- }- if len(createdMessageList) == 0 {- for _, repo := range repositoryList {- if activityCreateList, ok := repoID2ActivityCreateList[repo.ID]; ok {- for _, activityCreate := range activityCreateList {- if _, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {- log.Warn("Failed to create project activity for the ignored repository file",- zap.Error(err),- )- }- }- }- }- }- createdMessages = append(createdMessages, createdMessageList...)- }-- if len(createdMessages) == 0 {- var repoURLs []string- for _, repo := range repositoryList {- repoURLs = append(repoURLs, repo.WebURL)- }- log.Warn("Ignored push event because no applicable file found in the commit list", zap.Any("repos", repoURLs))- }- return createdMessages, nil-}-type repositoryFilter func(string) (bool, error)func (s *Server) filterRepository(ctx context.Context, webhookEndpointID string, pushEventRef, pushEventRepositoryID string, filter repositoryFilter) ([]*api.Repository, error) {@@ -289,132 +198,236 @@ func parseBranchNameFromRefs(ref string) (string, error) {return ref[len(expectedPrefix):], nil}-func convertGitLabCommitList(commitList []gitlab.WebhookCommit) ([]vcs.Commit, error) {- var ret []vcs.Commit- for _, commit := range commitList {- createdTime, err := time.Parse(time.RFC3339, commit.Timestamp)- if err != nil {- return nil, errors.Wrapf(err, "failed to parse commit %s's timestamp %s", commit.ID, common.EscapeForLogging(commit.Timestamp))- }- ret = append(ret, vcs.Commit{- ID: commit.ID,- Title: commit.Title,- Message: commit.Message,- CreatedTs: createdTime.Unix(),- URL: commit.URL,- AuthorName: commit.Author.Name,- AuthorEmail: commit.Author.Email,- AddedList: commit.AddedList,- ModifiedList: commit.ModifiedList,- })- }- return ret, nil-}+func (s *Server) createIssuesFromCommits(ctx context.Context, repositoryList []*api.Repository, baseVCSPushEvent vcs.PushEvent) ([]string, error) {+ distinctFileList := baseVCSPushEvent.GetDistinctFileList()+ if len(distinctFileList) == 0 {+ var commitIDs []string+ for _, c := range baseVCSPushEvent.CommitList {+ commitIDs = append(commitIDs, c.ID)+ }+ log.Warn("No files found from the push event",+ zap.String("repoURL", common.EscapeForLogging(baseVCSPushEvent.RepositoryURL)),+ zap.String("repoName", baseVCSPushEvent.RepositoryFullPath),+ zap.String("commits", strings.Join(commitIDs, ",")))+ return nil, nil+ }-func convertGitHubCommitList(commitList []github.WebhookCommit) []vcs.Commit {- var ret []vcs.Commit- for _, commit := range commitList {- // The Distinct is false if the commit has not been pushed before.- if !commit.Distinct {- continue+ var createdMessages []string+ for _, item := range distinctFileList {+ var createdMessageList []string+ repoID2ActivityCreateList := make(map[int][]*api.ActivityCreate)+ for _, repo := range repositoryList {+ pushEvent := baseVCSPushEvent+ pushEvent.VCSType = repo.VCS.Type+ pushEvent.BaseDirectory = repo.BaseDirectory+ pushEvent.FileCommit = vcs.FileCommit{+ ID: item.Commit.ID,+ Title: item.Commit.Title,+ Message: item.Commit.Message,+ CreatedTs: item.Commit.CreatedTs,+ URL: item.Commit.URL,+ AuthorName: item.Commit.AuthorName,+ AuthorEmail: item.Commit.AuthorEmail,+ Added: common.EscapeForLogging(item.FileName),+ }++ createdMessage, created, activityCreateList, err := s.createIssueFromPushEvent(+ ctx,+ &pushEvent,+ repo,+ item.FileName,+ item.ItemType,+ )+ if err != nil {+ return nil, err+ }+ if created {+ createdMessageList = append(createdMessageList, createdMessage)+ }+ repoID2ActivityCreateList[repo.ID] = append(repoID2ActivityCreateList[repo.ID], activityCreateList...)}- // Per Git convention, the message title and body are separated by two new line characters.- messages := strings.SplitN(commit.Message, "\n\n", 2)- messageTitle := messages[0]-- ret = append(ret, vcs.Commit{- ID: commit.ID,- Title: messageTitle,- Message: commit.Message,- CreatedTs: commit.Timestamp.Unix(),- URL: commit.URL,- AuthorName: commit.Author.Name,- AuthorEmail: commit.Author.Email,- AddedList: commit.Added,- ModifiedList: commit.Modified,- })- }- return ret+ if len(createdMessageList) == 0 {+ for _, repo := range repositoryList {+ if activityCreateList, ok := repoID2ActivityCreateList[repo.ID]; ok {+ for _, activityCreate := range activityCreateList {+ if _, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {+ log.Warn("Failed to create project activity for the ignored repository file",+ zap.Error(err),+ )+ }+ }+ }+ }+ }+ createdMessages = append(createdMessages, createdMessageList...)+ }++ if len(createdMessages) == 0 {+ var repoURLs []string+ for _, repo := range repositoryList {+ repoURLs = append(repoURLs, repo.WebURL)+ }+ log.Warn("Ignored push event because no applicable file found in the commit list", zap.Any("repos", repoURLs))+ }+ return createdMessages, nil}-// fileItemType is the type of a file item.-type fileItemType string+// createIssueFromPushEvent attempts to create a new issue for the given file of+// the push event. It returns "created=true" when a new issue has been created,+// along with the creation message to be presented in the UI. An *echo.HTTPError+// is returned in case of the error during the process.+func (s *Server) createIssueFromPushEvent(ctx context.Context, pushEvent *vcs.PushEvent, repo *api.Repository, file string, fileType vcs.FileItemType) (string, bool, []*api.ActivityCreate, error) {+ if repo.Project.TenantMode == api.TenantModeTenant {+ if !s.feature(api.FeatureMultiTenancy) {+ return "", false, nil, echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())+ }+ }-// The list of file item types.-const (- fileItemTypeAdded fileItemType = "added"- fileItemTypeModified fileItemType = "modified"-)+ fileEscaped := common.EscapeForLogging(file)+ log.Debug("Processing file",+ zap.String("file", fileEscaped),+ zap.String("commit", common.EscapeForLogging(pushEvent.FileCommit.ID)),+ )-// We are observing the push webhook event so that we will receive the event either when:-// 1. A commit is directly pushed to a branch.-// 2. One or more commits are merged to a branch.-//-// There is a complication to deal with the 2nd type. A typical workflow is a developer first-// commits the migration file to the feature branch, and at a later point, she creates a merge-// request to merge the commit to the main branch. Even the developer only creates a single commit-// on the feature branch, that merge request may contain multiple commits (unless both squash and fast-forward merge are used):-// 1. The original commit on the feature branch.-// 2. The merge request commit.-//-// And both commits would include that added migration file. Since we create an issue per migration file,-// we need to filter the commit list to prevent creating a duplicated issue. GitLab has a limitation to distinguish-// whether the commit is a merge commit (https://gitlab.com/gitlab-org/gitlab/-/issues/30914), so we need to dedup-// ourselves. Below is the filtering algorithm:-// 1. If we observe the same migration file multiple times, then we should use the latest migration file. This does not matter-// for change-based migration since a developer would always create different migration file with incremental names, while it-// will be important for the state-based migration, since the file name is always the same and we need to use the latest snapshot.-// 2. Maintain the relative commit order between different migration files. If migration file A happens before migration file B,-// then we should create an issue for migration file A first.-type distinctFileItem struct {- createdTs int64- commit vcs.Commit- fileName string- itemType fileItemType-}+ if !strings.HasPrefix(fileEscaped, repo.BaseDirectory) {+ log.Debug("Ignored file outside the base directory",+ zap.String("file", fileEscaped),+ zap.String("base_directory", repo.BaseDirectory),+ )+ return "", false, nil, nil+ }-func getDistinctFileList(commitList []vcs.Commit) []distinctFileItem {- // Use list instead of map because we need to maintain the relative commit order in the source branch.- var distinctFileList []distinctFileItem- for _, commit := range commitList {- log.Debug("Pre-processing commit to dedup migration files...",- zap.String("id", common.EscapeForLogging(commit.ID)),- zap.String("title", common.EscapeForLogging(commit.Title)),+ schemaInfo, err := parseSchemaFileInfo(repo.BaseDirectory, repo.SchemaPathTemplate, fileEscaped)+ if err != nil {+ log.Debug("Failed to parse schema file info",+ zap.String("file", fileEscaped),+ zap.Error(err),)+ return "", false, nil, nil+ }- addDistinctFile := func(fileName string, itemType fileItemType) {- item := distinctFileItem{- createdTs: commit.CreatedTs,- commit: commit,- fileName: fileName,- itemType: itemType,- }- for i, file := range distinctFileList {- // For the migration file with the same name, keep the one from the latest commit- if item.fileName != file.fileName {- continue- }- if file.createdTs < commit.CreatedTs {- // A file can be added and then modified in a later commit. We should consider the item as added.- if file.itemType == fileItemTypeAdded {- item.itemType = fileItemTypeAdded- }- distinctFileList[i] = item- }- // The fileName should be unique within the distinctFileList.- return- }- distinctFileList = append(distinctFileList, item)+ var migrationDetailList []*api.MigrationDetail+ var activityCreateList []*api.ActivityCreate+ var migrationDescription string+ var migrationType db.MigrationType++ if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeDDL && schemaInfo != nil {+ log.Debug("Ignored schema file for non-SDL", zap.String("file", file), zap.String("type", string(fileType)))+ return "", false, nil, nil+ }++ if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeSDL && schemaInfo != nil {+ // Having no schema info indicates that the file is not a schema file (e.g.+ // "*__LATEST.sql"), try to parse the migration info see if it is a data update.+ migrationDetailList, activityCreateList = s.prepareIssueFromPushEventSDL(ctx, repo, pushEvent, schemaInfo, file)+ migrationDescription = "Apply_schema_diff"+ migrationType = db.Migrate+ } else {+ // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.+ migrationInfo, err := db.ParseMigrationInfo(file, path.Join(repo.BaseDirectory, repo.FilePathTemplate))+ if err != nil {+ log.Error("Failed to parse migration info",+ zap.Int("project", repo.ProjectID),+ zap.Any("pushEvent", pushEvent),+ zap.String("file", file),+ zap.Error(err),+ )+ return "", false, nil, nil+ }+ migrationDescription = migrationInfo.Description+ migrationType = migrationInfo.Type++ if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeSDL && migrationInfo.Type != db.Data {+ activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, file, errors.Errorf("Only DATA type migration scripts are allowed but got %q", migrationInfo.Type))+ return "", false, []*api.ActivityCreate{activityCreate}, nil}- for _, added := range commit.AddedList {- addDistinctFile(added, fileItemTypeAdded)+ // We are here dealing with:+ // 1. data update in SDL/DDL+ // 2. schema update in DDL+ migrationDetailList, activityCreateList = s.prepareIssueFromPushEventDDL(ctx, repo, pushEvent, file, fileType, migrationInfo)+ }++ if len(migrationDetailList) == 0 {+ return "", false, activityCreateList, nil+ }++ // Create schema update issue+ creatorID := api.SystemBotID+ if pushEvent.FileCommit.AuthorEmail != "" {+ committerPrincipal, err := s.store.GetPrincipalByEmail(ctx, pushEvent.FileCommit.AuthorEmail)+ if err != nil {+ log.Error("Failed to find the principal with committer email",+ zap.String("email", common.EscapeForLogging(pushEvent.FileCommit.AuthorEmail)),+ zap.Error(err),+ )+ }+ if committerPrincipal == nil {+ log.Debug("Failed to find the principal with committer email, use system bot instead",+ zap.String("email", common.EscapeForLogging(pushEvent.FileCommit.AuthorEmail)),+ )+ } else {+ creatorID = committerPrincipal.ID}- for _, modified := range commit.ModifiedList {- addDistinctFile(modified, fileItemTypeModified)+ }++ createContext, err := json.Marshal(+ &api.MigrationContext{+ MigrationType: migrationType,+ VCSPushEvent: pushEvent,+ DetailList: migrationDetailList,+ },+ )+ if err != nil {+ return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal update schema context").SetInternal(err)+ }++ issueType := api.IssueDatabaseSchemaUpdate+ if migrationType == db.Data {+ issueType = api.IssueDatabaseDataUpdate+ }+ issueCreate := &api.IssueCreate{+ ProjectID: repo.ProjectID,+ Name: fmt.Sprintf("%s by %s", migrationDescription, strings.TrimPrefix(fileEscaped, repo.BaseDirectory+"/")),+ Type: issueType,+ Description: pushEvent.FileCommit.Message,+ AssigneeID: api.SystemBotID,+ CreateContext: string(createContext),+ }+ issue, err := s.createIssue(ctx, issueCreate, creatorID)+ if err != nil {+ errMsg := "Failed to create schema update issue"+ if issueType == api.IssueDatabaseDataUpdate {+ errMsg = "Failed to create data update issue"}+ return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, errMsg).SetInternal(err)+ }++ // Create a project activity after successfully creating the issue from the push event.+ activityPayload, err := json.Marshal(+ api.ActivityProjectRepositoryPushPayload{+ VCSPushEvent: *pushEvent,+ IssueID: issue.ID,+ IssueName: issue.Name,+ },+ )+ if err != nil {+ return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)+ }++ activityCreate := &api.ActivityCreate{+ CreatorID: creatorID,+ ContainerID: repo.ProjectID,+ Type: api.ActivityProjectRepositoryPush,+ Level: api.ActivityInfo,+ Comment: fmt.Sprintf("Created issue %q.", issue.Name),+ Payload: string(activityPayload),}- return distinctFileList+ if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {+ return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)+ }++ return fmt.Sprintf("Created issue %q on adding %s", issue.Name, file), true, activityCreateList, nil}// findProjectDatabases finds the list of databases with given name in the@@ -594,7 +607,7 @@ func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Rep// prepareIssueFromPushEventDDL returns a list of update schema details derived// from the given push event for DDL.-func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, fileName string, fileType fileItemType, migrationInfo *db.MigrationInfo) ([]*api.MigrationDetail, []*api.ActivityCreate) {+func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, fileName string, fileType vcs.FileItemType, migrationInfo *db.MigrationInfo) ([]*api.MigrationDetail, []*api.ActivityCreate) {statement, err := s.readFileContent(ctx, pushEvent, repo, fileName)if err != nil {activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, fileName, errors.Wrap(err, "Failed to read file content"))@@ -621,7 +634,7 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repreturn nil, []*api.ActivityCreate{activityCreate}}- if fileType == fileItemTypeAdded {+ if fileType == vcs.FileItemTypeAdded {for _, database := range databases {migrationDetailList = append(migrationDetailList,&api.MigrationDetail{@@ -683,164 +696,6 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [return nil}-// createIssueFromPushEvent attempts to create a new issue for the given file of-// the push event. It returns "created=true" when a new issue has been created,-// along with the creation message to be presented in the UI. An *echo.HTTPError-// is returned in case of the error during the process.-func (s *Server) createIssueFromPushEvent(ctx context.Context, pushEvent *vcs.PushEvent, repo *api.Repository, file string, fileType fileItemType) (string, bool, []*api.ActivityCreate, error) {- if repo.Project.TenantMode == api.TenantModeTenant {- if !s.feature(api.FeatureMultiTenancy) {- return "", false, nil, echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())- }- }-- fileEscaped := common.EscapeForLogging(file)- log.Debug("Processing file",- zap.String("file", fileEscaped),- zap.String("commit", common.EscapeForLogging(pushEvent.FileCommit.ID)),- )-- if !strings.HasPrefix(fileEscaped, repo.BaseDirectory) {- log.Debug("Ignored file outside the base directory",- zap.String("file", fileEscaped),- zap.String("base_directory", repo.BaseDirectory),- )- return "", false, nil, nil- }-- schemaInfo, err := parseSchemaFileInfo(repo.BaseDirectory, repo.SchemaPathTemplate, fileEscaped)- if err != nil {- log.Debug("Failed to parse schema file info",- zap.String("file", fileEscaped),- zap.Error(err),- )- return "", false, nil, nil- }-- var migrationDetailList []*api.MigrationDetail- var activityCreateList []*api.ActivityCreate- var migrationDescription string- var migrationType db.MigrationType-- if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeDDL && schemaInfo != nil {- log.Debug("Ignored schema file for non-SDL", zap.String("file", file), zap.String("type", string(fileType)))- return "", false, nil, nil- }-- if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeSDL && schemaInfo != nil {- // Having no schema info indicates that the file is not a schema file (e.g.- // "*__LATEST.sql"), try to parse the migration info see if it is a data update.- migrationDetailList, activityCreateList = s.prepareIssueFromPushEventSDL(ctx, repo, pushEvent, schemaInfo, file)- migrationDescription = "Apply_schema_diff"- migrationType = db.Migrate- } else {- // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.- migrationInfo, err := db.ParseMigrationInfo(file, path.Join(repo.BaseDirectory, repo.FilePathTemplate))- if err != nil {- log.Error("Failed to parse migration info",- zap.Int("project", repo.ProjectID),- zap.Any("pushEvent", pushEvent),- zap.String("file", file),- zap.Error(err),- )- return "", false, nil, nil- }- migrationDescription = migrationInfo.Description- migrationType = migrationInfo.Type-- if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeSDL && migrationInfo.Type != db.Data {- activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, file, errors.Errorf("Only DATA type migration scripts are allowed but got %q", migrationInfo.Type))- return "", false, []*api.ActivityCreate{activityCreate}, nil- }-- // We are here dealing with:- // 1. data update in SDL/DDL- // 2. schema update in DDL- migrationDetailList, activityCreateList = s.prepareIssueFromPushEventDDL(ctx, repo, pushEvent, file, fileType, migrationInfo)- }-- if len(migrationDetailList) == 0 {- return "", false, activityCreateList, nil- }-- // Create schema update issue- creatorID := api.SystemBotID- if pushEvent.FileCommit.AuthorEmail != "" {- committerPrincipal, err := s.store.GetPrincipalByEmail(ctx, pushEvent.FileCommit.AuthorEmail)- if err != nil {- log.Error("Failed to find the principal with committer email",- zap.String("email", common.EscapeForLogging(pushEvent.FileCommit.AuthorEmail)),- zap.Error(err),- )- }- if committerPrincipal == nil {- log.Debug("Failed to find the principal with committer email, use system bot instead",- zap.String("email", common.EscapeForLogging(pushEvent.FileCommit.AuthorEmail)),- )- } else {- creatorID = committerPrincipal.ID- }- }-- createContext, err := json.Marshal(- &api.MigrationContext{- MigrationType: migrationType,- VCSPushEvent: pushEvent,- DetailList: migrationDetailList,- },- )- if err != nil {- return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal update schema context").SetInternal(err)- }-- issueType := api.IssueDatabaseSchemaUpdate- if migrationType == db.Data {- issueType = api.IssueDatabaseDataUpdate- }- issueCreate := &api.IssueCreate{- ProjectID: repo.ProjectID,- Name: fmt.Sprintf("%s by %s", migrationDescription, strings.TrimPrefix(fileEscaped, repo.BaseDirectory+"/")),- Type: issueType,- Description: pushEvent.FileCommit.Message,- AssigneeID: api.SystemBotID,- CreateContext: string(createContext),- }- issue, err := s.createIssue(ctx, issueCreate, creatorID)- if err != nil {- errMsg := "Failed to create schema update issue"- if issueType == api.IssueDatabaseDataUpdate {- errMsg = "Failed to create data update issue"- }- return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, errMsg).SetInternal(err)- }-- // Create a project activity after successfully creating the issue from the push event.- activityPayload, err := json.Marshal(- api.ActivityProjectRepositoryPushPayload{- VCSPushEvent: *pushEvent,- IssueID: issue.ID,- IssueName: issue.Name,- },- )- if err != nil {- return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)- }-- activityCreate := &api.ActivityCreate{- CreatorID: creatorID,- ContainerID: repo.ProjectID,- Type: api.ActivityProjectRepositoryPush,- Level: api.ActivityInfo,- Comment: fmt.Sprintf("Created issue %q.", issue.Name),- Payload: string(activityPayload),- }- if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {- return "", false, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)- }-- return fmt.Sprintf("Created issue %q on adding %s", issue.Name, file), true, activityCreateList, nil-}-// parseSchemaFileInfo attempts to parse the given schema file path to extract// the schema file info. It returns (nil, nil) if it doesn't looks like a schema// file path.diff --git a/server/webhook_test.go b/server/webhook_test.goindex 783e95dd85..c5cd3ae41c 100644--- a/server/webhook_test.go+++ b/server/webhook_test.go@@ -2,452 +2,11 @@ package serverimport ("testing"- "time""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"-- "github.com/bytebase/bytebase/plugin/vcs")-func TestGetDistinctFileList(t *testing.T) {- timestamp1 := "2021-01-13T00:00:00+00:00"- timestamp2 := "2021-01-14T00:00:00+00:00"- timestamp3 := "2021-01-15T00:00:00+00:00"- time1, _ := time.Parse(time.RFC3339, timestamp1)- time2, _ := time.Parse(time.RFC3339, timestamp2)- time3, _ := time.Parse(time.RFC3339, timestamp3)- ts1 := time1.Unix()- ts2 := time2.Unix()- ts3 := time3.Unix()-- tests := []struct {- name string- commitList []vcs.Commit- want []distinctFileItem- }{- {- name: "Empty",- commitList: []vcs.Commit{},- want: nil,- },- {- name: "Single commit, single file",- commitList: []vcs.Commit{- {- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- },- },- },- want: []distinctFileItem{- {- createdTs: ts1,- commit: vcs.Commit{- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- },- },- fileName: "v1.sql",- itemType: fileItemTypeAdded,- },- },- },- {- name: "Single commit, multiple files",- commitList: []vcs.Commit{- {- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- },- },- },- want: []distinctFileItem{- {- createdTs: ts1,- commit: vcs.Commit{- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- },- },- fileName: "v1.sql",- itemType: fileItemTypeAdded,- },- {- createdTs: ts1,- commit: vcs.Commit{- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- },- },- fileName: "v2.sql",- itemType: fileItemTypeAdded,- },- },- },- {- name: "Multi commits, single file",- commitList: []vcs.Commit{- {- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- },- },- {- ID: "2",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts2,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- },- },- },- want: []distinctFileItem{- {- createdTs: ts2,- commit: vcs.Commit{- ID: "2",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts2,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- },- },- fileName: "v1.sql",- itemType: fileItemTypeAdded,- },- },- },- {- name: "Multi commits, single file, direct push",- commitList: []vcs.Commit{- {- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- },- },- {- ID: "2",- Title: "Commit 2",- Message: "Update 2",- CreatedTs: ts2,- URL: "example.com",- AuthorName: "bob",- ModifiedList: []string{- "v1.sql",- },- },- },- want: []distinctFileItem{- {- createdTs: ts2,- commit: vcs.Commit{- ID: "2",- Title: "Commit 2",- Message: "Update 2",- CreatedTs: ts2,- URL: "example.com",- AuthorName: "bob",- ModifiedList: []string{- "v1.sql",- },- },- fileName: "v1.sql",- itemType: fileItemTypeAdded,- },- },- },- {- name: "Multi commits, multi files",- commitList: []vcs.Commit{- {- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- },- },- {- ID: "2",- Title: "Commit 2",- Message: "Update 2",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v3.sql",- },- },- {- ID: "3",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- },- },- want: []distinctFileItem{- {- createdTs: ts3,- commit: vcs.Commit{- ID: "3",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- },- fileName: "v1.sql",- itemType: fileItemTypeAdded,- },- {- createdTs: ts3,- commit: vcs.Commit{- ID: "3",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- },- fileName: "v2.sql",- itemType: fileItemTypeAdded,- },- {- createdTs: ts3,- commit: vcs.Commit{- ID: "3",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- },- fileName: "v3.sql",- itemType: fileItemTypeAdded,- },- },- },- {- name: "Multi commits, multi files, include modified",- commitList: []vcs.Commit{- {- ID: "1",- Title: "Commit 1",- Message: "Update 1",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- },- },- {- ID: "2",- Title: "Commit 2",- Message: "Update 2",- CreatedTs: ts1,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v3.sql",- },- },- {- ID: "3",- Title: "Commit 3",- Message: "Update 3",- CreatedTs: ts2,- URL: "example.com",- AuthorName: "bob",- ModifiedList: []string{- "v3.sql",- "v4.sql",- },- },- {- ID: "4",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- // This file is both added and modified in the commits above.- // GitLab will treat this as added in the merge commit.- "v3.sql",- },- ModifiedList: []string{"v4.sql"},- },- },- want: []distinctFileItem{- {- createdTs: ts3,- commit: vcs.Commit{- ID: "4",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- ModifiedList: []string{"v4.sql"},- },- fileName: "v1.sql",- itemType: fileItemTypeAdded,- },- {- createdTs: ts3,- commit: vcs.Commit{- ID: "4",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- ModifiedList: []string{"v4.sql"},- },- fileName: "v2.sql",- itemType: fileItemTypeAdded,- },- {- createdTs: ts3,- commit: vcs.Commit{- ID: "4",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- ModifiedList: []string{"v4.sql"},- },- fileName: "v3.sql",- itemType: fileItemTypeAdded,- },- {- createdTs: ts3,- commit: vcs.Commit{- ID: "4",- Title: "Merge branch",- Message: "Merge update",- CreatedTs: ts3,- URL: "example.com",- AuthorName: "bob",- AddedList: []string{- "v1.sql",- "v2.sql",- "v3.sql",- },- ModifiedList: []string{"v4.sql"},- },- fileName: "v4.sql",- itemType: fileItemTypeModified,- },- },- },- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := getDistinctFileList(tt.commitList)- assert.Equal(t, tt.want, got)- })- }-}-func TestValidateGitHubWebhookSignature256(t *testing.T) {//nolint:misspellconst payload = `{"ref":"refs/heads/main","before":"07da1e122bdbb81da8499b6d82c6b6302581a5a7","after":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","repository":{"id":470746482,"node_id":"R_kgDOHA8Fcg","name":"bytebase-test","full_name":"unknwon/bytebase-test","private":true,"owner":{"name":"unknwon","email":"[email protected]","login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"html_url":"https://github.com/unknwon/bytebase-test","description":null,"fork":false,"url":"https://github.com/unknwon/bytebase-test","forks_url":"https://api.github.com/repos/unknwon/bytebase-test/forks","keys_url":"https://api.github.com/repos/unknwon/bytebase-test/keys{/key_id}","collaborators_url":"https://api.github.com/repos/unknwon/bytebase-test/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/unknwon/bytebase-test/teams","hooks_url":"https://api.github.com/repos/unknwon/bytebase-test/hooks","issue_events_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/events{/number}","events_url":"https://api.github.com/repos/unknwon/bytebase-test/events","assignees_url":"https://api.github.com/repos/unknwon/bytebase-test/assignees{/user}","branches_url":"https://api.github.com/repos/unknwon/bytebase-test/branches{/branch}","tags_url":"https://api.github.com/repos/unknwon/bytebase-test/tags","blobs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/unknwon/bytebase-test/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/refs{/sha}","trees_url":"https://api.github.com/repos/unknwon/bytebase-test/git/trees{/sha}","statuses_url":"https://api.github.com/repos/unknwon/bytebase-test/statuses/{sha}","languages_url":"https://api.github.com/repos/unknwon/bytebase-test/languages","stargazers_url":"https://api.github.com/repos/unknwon/bytebase-test/stargazers","contributors_url":"https://api.github.com/repos/unknwon/bytebase-test/contributors","subscribers_url":"https://api.github.com/repos/unknwon/bytebase-test/subscribers","subscription_url":"https://api.github.com/repos/unknwon/bytebase-test/subscription","commits_url":"https://api.github.com/repos/unknwon/bytebase-test/commits{/sha}","git_commits_url":"https://api.github.com/repos/unknwon/bytebase-test/git/commits{/sha}","comments_url":"https://api.github.com/repos/unknwon/bytebase-test/comments{/number}","issue_comment_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/comments{/number}","contents_url":"https://api.github.com/repos/unknwon/bytebase-test/contents/{+path}","compare_url":"https://api.github.com/repos/unknwon/bytebase-test/compare/{base}...{head}","merges_url":"https://api.github.com/repos/unknwon/bytebase-test/merges","archive_url":"https://api.github.com/repos/unknwon/bytebase-test/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/unknwon/bytebase-test/downloads","issues_url":"https://api.github.com/repos/unknwon/bytebase-test/issues{/number}","pulls_url":"https://api.github.com/repos/unknwon/bytebase-test/pulls{/number}","milestones_url":"https://api.github.com/repos/unknwon/bytebase-test/milestones{/number}","notifications_url":"https://api.github.com/repos/unknwon/bytebase-test/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/unknwon/bytebase-test/labels{/name}","releases_url":"https://api.github.com/repos/unknwon/bytebase-test/releases{/id}","deployments_url":"https://api.github.com/repos/unknwon/bytebase-test/deployments","created_at":1647463607,"updated_at":"2022-03-16T20:46:47Z","pushed_at":1658671596,"git_url":"git://github.com/unknwon/bytebase-test.git","ssh_url":"[email protected]:unknwon/bytebase-test.git","clone_url":"https://github.com/unknwon/bytebase-test.git","svn_url":"https://github.com/unknwon/bytebase-test","homepage":null,"size":20,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":0,"license":{"key":"apache-2.0","name":"Apache License 2.0","spdx_id":"Apache-2.0","url":"https://api.github.com/licenses/apache-2.0","node_id":"MDc6TGljZW5zZTI="},"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"private","forks":0,"open_issues":0,"watchers":0,"default_branch":"main","stargazers":0,"master_branch":"main"},"pusher":{"name":"unknwon","email":"[email protected]"},"sender":{"login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"created":false,"deleted":false,"forced":false,"base_ref":null,"compare":"https://github.com/unknwon/bytebase-test/compare/07da1e122bdb...5a96148ac5ef","commits":[{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}],"head_commit":{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}}`