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): use diff to get changes in GitHub push event webhook (#3433)
Yilong Li7eb47faf6d07
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 62975a75ac..84fc55682f 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -317,9 +317,65 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon}, nil}+// CommitsDiff represents a GitHub API response for comparing two commits.+type CommitsDiff struct {+ Files []PullRequestFile `json:"files"`+}+// GetDiffFileList gets the diff files list between two commits.-func (*Provider) GetDiffFileList(_ context.Context, _ common.OauthContext, _, _, _, _ string) ([]vcs.FileDiff, error) {- return nil, nil+func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]vcs.FileDiff, error) {+ url := fmt.Sprintf("%s/repos/%s/compare/%s...%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 file diff list from URL %s", url)+ } else if code >= 300 {+ return nil, errors.Errorf("failed to get file diff 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 GitHub instance %s", instanceURL)+ }++ var ret []vcs.FileDiff+ for _, file := range diffs.Files {+ item := vcs.FileDiff{+ Path: file.FileName,+ }+ switch file.Status {+ case "added":+ item.Type = vcs.FileDiffTypeAdded+ case "modified":+ item.Type = vcs.FileDiffTypeModified+ case "removed":+ item.Type = vcs.FileDiffTypeRemoved+ }+ ret = append(ret, item)+ }++ return ret, nil}// FetchUserInfo fetches user info of given user ID.@@ -939,9 +995,9 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,}if code == http.StatusNotFound {- return nil, common.Errorf(common.NotFound, "failed to create branch from URL %s", url)+ return nil, common.Errorf(common.NotFound, "failed to get branch from URL %s", url)} else if code >= 300 {- return nil, errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",+ return nil, errors.Errorf("failed to get branch from URL %s, status code: %d, body: %s",url,code,body,diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.goindex 3c37247da4..6bd2e80213 100644--- a/plugin/vcs/vcs.go+++ b/plugin/vcs/vcs.go@@ -87,8 +87,10 @@ type FileMeta struct {type FileDiffType intconst (+ // FileDiffTypeUnknown means the file is an unknown diff type.+ FileDiffTypeUnknown FileDiffType = iota// FileDiffTypeAdded means the file is newly added.- FileDiffTypeAdded FileDiffType = iota+ FileDiffTypeAdded// FileDiffTypeModified means the file is modified.FileDiffTypeModified// FileDiffTypeRemoved means the file is removed.diff --git a/server/webhook.go b/server/webhook.goindex 336481c5d1..49a153f337 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -546,6 +546,7 @@ func (s *Server) processPushEvent(ctx context.Context, repositoryList []*api.Rep// Users may merge commits from other branches, and some of the commits merged in may already be merged into the main branch.// In that case, the commits in the push event contains files which are not added in this PR/MR.// We use the compare API to get the file diffs and filter files by the diffs.+// TODO(dragonly): generate distinct file change list from the commits diff instead of filter.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,@@ -573,11 +574,6 @@ func (s *Server) filterFilesByCommitsDiff(ctx context.Context, repo *api.Reposit}}}- // Skip filtering for GitHub.- // TODO(dragonly): remove this when GetDiffFileList is also implemented for GitHub.- if fileDiffList == nil {- filteredDistinctFileList = distinctFileList- }return filteredDistinctFileList, nil}diff --git a/tests/fake/github.go b/tests/fake/github.goindex cf4088c43a..b1d884d80a 100644--- a/tests/fake/github.go+++ b/tests/fake/github.go@@ -54,6 +54,9 @@ type repositoryData struct {Files []*github.PullRequestFile*github.PullRequest}+ // commitsDiff is the map for commits compare.+ // The map key has the format "from...to" which is SHA or branch name.+ commitsDiff map[string]*github.CommitsDiff}// NewGitHub creates a new fake implementation of GitHub VCS provider.@@ -85,6 +88,7 @@ func NewGitHub(port int) VCSProvider {)g.PUT("/repos/:owner/:repo/actions/secrets/:keyName", gh.updateRepositoryPublicKey)g.GET("/repos/:owner/:repo/pulls/:prID/files", gh.listPullRequestFile)+ g.GET("/repos/:owner/:repo/compare/:baseHead", gh.compareCommits)return gh}@@ -391,6 +395,26 @@ func (gh *GitHub) listPullRequestFile(c echo.Context) error {return c.String(http.StatusOK, string(buf))}+func (gh *GitHub) compareCommits(c echo.Context) error {+ r, err := gh.validRepository(c)+ if err != nil {+ return err+ }++ key := c.Param("baseHead")+ diff, ok := r.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))+}+func (gh *GitHub) validRepository(c echo.Context) (*repositoryData, error) {repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))r, ok := gh.repositories[repositoryID]@@ -437,11 +461,35 @@ func (gh *GitHub) CreateRepository(id string) {Files []*github.PullRequestFile*github.PullRequest}{},+ commitsDiff: map[string]*github.CommitsDiff{},}}// AddCommitsDiff adds a commits diff.-func (*GitHub) AddCommitsDiff(_, _, _ string, _ []vcs.FileDiff) error {+func (gh *GitHub) AddCommitsDiff(repositoryID, fromCommit, toCommit string, fileDiffList []vcs.FileDiff) error {+ r, ok := gh.repositories[repositoryID]+ if !ok {+ return errors.Errorf("GitHub repository %s doesn't exist", repositoryID)+ }+ key := fmt.Sprintf("%s...%s", fromCommit, toCommit)+ commitsDiff := &github.CommitsDiff{+ Files: []github.PullRequestFile{},+ }+ for _, fileDiff := range fileDiffList {+ prFile := github.PullRequestFile{+ FileName: fileDiff.Path,+ }+ switch fileDiff.Type {+ case vcs.FileDiffTypeAdded:+ prFile.Status = "added"+ case vcs.FileDiffTypeModified:+ prFile.Status = "modified"+ case vcs.FileDiffTypeRemoved:+ prFile.Status = "removed"+ }+ commitsDiff.Files = append(commitsDiff.Files, prFile)+ }+ r.commitsDiff[key] = commitsDiffreturn nil}diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex f59a54641f..e83e63f9d6 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -473,7 +473,7 @@ func (gl *GitLab) compareCommits(c echo.Context) error {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)+ return errors.Errorf("GitLab project %s doesn't exist", projectID)}key := fmt.Sprintf("%s...%s", fromCommit, toCommit)commitsDiff := &gitlab.CommitsDiff{diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 87763fd078..bd5e4c9d72 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -480,12 +480,7 @@ 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)- 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)- }+ 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)_, err = ctl.patchIssueStatus(api.IssueStatusPatch{ID: issue.ID,@@ -630,59 +625,6 @@ 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 {