Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(github): create project and receive webhooks (#1974)

Joe Chen8acd0a061e60
diff --git a/frontend/src/components/RepositorySelectionPanel.vue b/frontend/src/components/RepositorySelectionPanel.vue
index b902782128..7471e4a640 100644
--- a/frontend/src/components/RepositorySelectionPanel.vue
+++ b/frontend/src/components/RepositorySelectionPanel.vue
@@ -72,24 +72,22 @@ onMounted(() => {
});
const prepareRepositoryList = () => {
- if (props.config.vcs.type == "GITLAB_SELF_HOST") {
- useOAuthStore()
- .exchangeVCSTokenWithID({
- vcsId: props.config.vcs.id,
- code: props.config.code,
- })
- .then((token: OAuthToken) => {
- emit("set-token", token);
- gitlabStore
- .fetchProjectList({
- vcs: props.config.vcs,
- token: token,
- })
- .then((list) => {
- state.repositoryList = list;
- });
- });
- }
+ useOAuthStore()
+ .exchangeVCSTokenWithID({
+ vcsId: props.config.vcs.id,
+ code: props.config.code,
+ })
+ .then((token: OAuthToken) => {
+ emit("set-token", token);
+ gitlabStore
+ .fetchProjectList({
+ vcs: props.config.vcs,
+ token: token,
+ })
+ .then((list) => {
+ state.repositoryList = list;
+ });
+ });
};
const refreshRepositoryList = () => {
diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vue
index 4e0ca0b942..4991c4a057 100644
--- a/frontend/src/components/RepositorySetupWizard.vue
+++ b/frontend/src/components/RepositorySetupWizard.vue
@@ -176,6 +176,10 @@ export default defineComponent({
const tryFinishSetup = (allowFinishCallback: () => void) => {
const createFunc = () => {
+ let externalId = state.config.repositoryInfo.externalId;
+ if (state.config.vcs.type == "GITHUB_COM") {
+ externalId = state.config.repositoryInfo.fullPath;
+ }
const repositoryCreate: RepositoryCreate = {
vcsId: state.config.vcs.id,
name: state.config.repositoryInfo.name,
@@ -186,7 +190,7 @@ export default defineComponent({
filePathTemplate: state.config.repositoryConfig.filePathTemplate,
schemaPathTemplate: state.config.repositoryConfig.schemaPathTemplate,
sheetPathTemplate: state.config.repositoryConfig.sheetPathTemplate,
- externalId: state.config.repositoryInfo.externalId,
+ externalId: externalId,
accessToken: state.config.token.accessToken,
expiresTs: state.config.token.expiresTs,
refreshToken: state.config.token.refreshToken,
diff --git a/frontend/src/components/RepositoryVCSProviderPanel.vue b/frontend/src/components/RepositoryVCSProviderPanel.vue
index 6f966f8718..55f477ab0e 100644
--- a/frontend/src/components/RepositoryVCSProviderPanel.vue
+++ b/frontend/src/components/RepositoryVCSProviderPanel.vue
@@ -12,6 +12,9 @@
<template v-if="vcs.type.startsWith('GITLAB')">
<img class="h-6 w-auto" src="../assets/gitlab-logo.svg" />
</template>
+ <template v-if="vcs.type.startsWith('GITHUB')">
+ <img class="h-6 w-auto" src="../assets/github-logo.svg" />
+ </template>
<span>{{ vcs.name }}</span>
</button>
</template>
@@ -97,8 +100,13 @@ const isCurrentUserOwner = computed(() => {
const selectVCS = (vcs: VCS) => {
state.selectedVCS = vcs;
emit("set-vcs", vcs);
+
+ let authorizeUrl = `${vcs.instanceUrl}/oauth/authorize`;
+ if (vcs.type == "GITHUB_COM") {
+ authorizeUrl = `https://github.com/login/oauth/authorize`;
+ }
openWindowForOAuth(
- `${vcs.instanceUrl}/oauth/authorize`,
+ authorizeUrl,
vcs.applicationId,
"bb.oauth.link-vcs-repository",
vcs.type
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index 3654b92939..21c5097433 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -107,6 +107,14 @@ type File struct {
SHA string `json:"sha"`
}
+// WebhookType is the GitHub webhook type.
+type WebhookType string
+
+const (
+ // WebhookPush is the webhook type for push.
+ WebhookPush WebhookType = "push"
+)
+
// WebhookInfo represents a GitHub API response for the webhook information.
type WebhookInfo struct {
ID int `json:"id"`
@@ -144,6 +152,43 @@ type WebhookCreateOrUpdate struct {
Events []string `json:"events"`
}
+// WebhookRepository is the API message for webhook repository.
+type WebhookRepository struct {
+ ID int `json:"id"`
+ FullName string `json:"full_name"`
+ HTMLURL string `json:"html_url"`
+}
+
+// WebhookCommitAuthor is the API message for webhook commit author.
+type WebhookCommitAuthor struct {
+ Name string `json:"name"`
+ Email string `json:"email"`
+}
+
+// WebhookSender is the API message for webhook sender.
+type WebhookSender struct {
+ Login string `json:"login"`
+}
+
+// WebhookCommit is the API message for webhook commit.
+type WebhookCommit struct {
+ ID string `json:"id"`
+ Distinct bool `json:"distinct"`
+ Message string `json:"message"`
+ Timestamp time.Time `json:"timestamp"`
+ URL string `json:"url"`
+ Author WebhookCommitAuthor `json:"author"`
+ Added []string `json:"added"`
+}
+
+// WebhookPushEvent is the API message for webhook push event.
+type WebhookPushEvent struct {
+ Ref string `json:"ref"`
+ Repository WebhookRepository `json:"repository"`
+ Sender WebhookSender `json:"sender"`
+ Commits []WebhookCommit `json:"commits"`
+}
+
// fetchUserInfo fetches user information from the given resourceURI, which
// should be either "user" or "users/{username}".
func (p *Provider) fetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, resourceURI string) (*vcs.UserInfo, error) {
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index c48922e09c..86fb5a6832 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -32,7 +32,7 @@ const (
var _ vcs.Provider = (*Provider)(nil)
-// WebhookType is the gitlab webhook type.
+// WebhookType is the GitLab webhook type.
type WebhookType string
const (
diff --git a/server/project.go b/server/project.go
index 1fc857e66d..721f6828d2 100644
--- a/server/project.go
+++ b/server/project.go
@@ -244,7 +244,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
case vcsPlugin.GitHubCom:
webhookPost := github.WebhookCreateOrUpdate{
Config: github.WebhookConfig{
- URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, githubWebhookPath, repositoryCreate.WebhookEndpointID),
+ URL: fmt.Sprintf("%s/%s/%s", s.profile.BackendHost, githubWebhookPath, repositoryCreate.WebhookEndpointID),
ContentType: "json",
Secret: repositoryCreate.WebhookSecretToken,
InsecureSSL: 1, // TODO: Allow user to specify this value through api.RepositoryCreate
diff --git a/server/webhook.go b/server/webhook.go
index b323fb2a05..bef2a38c34 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -20,6 +20,7 @@ import (
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/vcs"
+ "github.com/bytebase/bytebase/plugin/vcs/github"
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
)
@@ -31,14 +32,13 @@ var (
func (s *Server) registerWebhookRoutes(g *echo.Group) {
g.POST("/gitlab/:id", func(c echo.Context) error {
ctx := c.Request().Context()
- var b []byte
- b, err := io.ReadAll(c.Request().Body)
+ body, err := io.ReadAll(c.Request().Body)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Failed to read webhook request").SetInternal(err)
}
pushEvent := &gitlab.WebhookPushEvent{}
- if err := json.Unmarshal(b, pushEvent); err != nil {
+ if err := json.Unmarshal(body, pushEvent); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)
}
@@ -69,192 +69,147 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch, got %d, want %s", pushEvent.Project.ID, repo.ExternalID))
}
- log.Debug("Processing gitlab webhook push event...",
+ log.Debug("Processing GitLab webhook push event...",
zap.String("project", repo.Project.Name),
)
distinctFileList := dedupMigrationFilesFromCommitList(pushEvent.CommitList)
- createdMessageList := []string{}
+ var createdMessageList []string
for _, item := range distinctFileList {
- commit := item.commit
- added := item.fileName
- addedEscaped := common.EscapeForLogging(added)
- log.Debug("Processing added file...",
- zap.String("file", addedEscaped),
- zap.String("commit", common.EscapeForLogging(commit.ID)),
+ createdMessage, created, httpErr := s.createIssueFromPushEvent(
+ ctx,
+ repo,
+ vcs.PushEvent{
+ VCSType: repo.VCS.Type,
+ BaseDirectory: repo.BaseDirectory,
+ Ref: pushEvent.Ref,
+ RepositoryID: strconv.Itoa(pushEvent.Project.ID),
+ RepositoryURL: pushEvent.Project.WebURL,
+ RepositoryFullPath: pushEvent.Project.FullPath,
+ AuthorName: pushEvent.AuthorName,
+ FileCommit: vcs.FileCommit{
+ ID: item.commit.ID,
+ Title: item.commit.Title,
+ Message: item.commit.Message,
+ CreatedTs: item.createdTime.Unix(),
+ URL: item.commit.URL,
+ AuthorName: item.commit.Author.Name,
+ AuthorEmail: item.commit.Author.Email,
+ Added: common.EscapeForLogging(item.fileName),
+ },
+ },
+ item.fileName,
+ webhookEndpointID,
)
-
- if !strings.HasPrefix(addedEscaped, repo.BaseDirectory) {
- log.Debug("Ignored committed file, not under base directory.", zap.String("file", addedEscaped), zap.String("base_directory", repo.BaseDirectory))
- continue
+ if httpErr != nil {
+ return httpErr
}
- // Ignore the schema file we auto generated to the repository.
- if isSkipGeneratedSchemaFile(repo, addedEscaped) {
- log.Debug("Ignored generated latest schema file.", zap.String("file", addedEscaped))
- continue
+ if created {
+ createdMessageList = append(createdMessageList, createdMessage)
}
+ }
- vcsPushEvent := vcs.PushEvent{
- VCSType: repo.VCS.Type,
- BaseDirectory: repo.BaseDirectory,
- Ref: pushEvent.Ref,
- RepositoryID: strconv.Itoa(pushEvent.Project.ID),
- RepositoryURL: pushEvent.Project.WebURL,
- RepositoryFullPath: pushEvent.Project.FullPath,
- AuthorName: pushEvent.AuthorName,
- FileCommit: vcs.FileCommit{
- ID: commit.ID,
- Title: commit.Title,
- Message: commit.Message,
- CreatedTs: item.createdTime.Unix(),
- URL: commit.URL,
- AuthorName: commit.Author.Name,
- AuthorEmail: commit.Author.Email,
- Added: addedEscaped,
- },
- }
+ if len(createdMessageList) == 0 {
+ msg := "Ignored push event. No applicable file found in the commit list."
+ log.Warn(msg,
+ zap.String("project", repo.Project.Name),
+ )
+ }
+ return c.String(http.StatusOK, strings.Join(createdMessageList, "\n"))
+ })
+ g.POST("/github/:id", func(c echo.Context) error {
+ ctx := c.Request().Context()
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read webhook request").SetInternal(err)
+ }
- // Create a WARNING project activity if committed file is ignored
- var createIgnoredFileActivity = func(err error) {
- log.Warn("Ignored committed file", zap.String("file", addedEscaped), zap.Error(err))
- bytes, marshalErr := json.Marshal(api.ActivityProjectRepositoryPushPayload{
- VCSPushEvent: vcsPushEvent,
- })
- if marshalErr != nil {
- log.Warn("Failed to construct project activity payload to record ignored repository committed file", zap.Error(marshalErr))
- return
- }
+ // This shouldn't happen as we only setup webhook to receive push event, just in case.
+ eventType := github.WebhookType(c.Request().Header.Get("X-GitHub-Event"))
+ if eventType != github.WebhookPush {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %s, want %s", eventType, github.WebhookPush))
+ }
- activityCreate := &api.ActivityCreate{
- CreatorID: api.SystemBotID,
- ContainerID: repo.ProjectID,
- Type: api.ActivityProjectRepositoryPush,
- Level: api.ActivityWarn,
- Comment: fmt.Sprintf("Ignored committed file %q, %s.", addedEscaped, err.Error()),
- Payload: string(bytes),
- }
- _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
- if err != nil {
- log.Warn("Failed to create project activity to record ignored repository committed file", zap.Error(err))
- }
- }
+ var pushEvent github.WebhookPushEvent
+ if err := json.Unmarshal(body, &pushEvent); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)
+ }
- mi, err := db.ParseMigrationInfo(addedEscaped, filepath.Join(repo.BaseDirectory, repo.FilePathTemplate))
- if err != nil {
- createIgnoredFileActivity(err)
- continue
- }
+ webhookEndpointID := c.Param("id")
+ repo, err := s.store.GetRepository(ctx, &api.RepositoryFind{WebhookEndpointID: &webhookEndpointID})
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointID)).SetInternal(err)
+ }
+ if repo == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Webhook endpoint not found: %v", webhookEndpointID))
+ }
- // Retrieve sql by reading the file content
+ if repo.VCS == nil {
+ err := fmt.Errorf("VCS not found for ID: %v", repo.VCSID)
+ return echo.NewHTTPError(http.StatusInternalServerError, err).SetInternal(err)
+ }
- // Retrieve the latest AccessToken and RefreshToken as the previous ReadFileContent call may have
- // updated the stored token pair. ReadFileContent will fetch and store the new token pair
- // if the existing token pair has expired.
- repo2, err := s.store.GetRepository(ctx, &api.RepositoryFind{WebhookEndpointID: &webhookEndpointID})
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointID)).SetInternal(err)
- }
- if repo2 == nil {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Webhook endpoint not found: %v", webhookEndpointID))
- }
+ //nolint:misspell
+ // TODO(unknwon): Validate webhook signature, https://linear.app/bbteam/issue/BYT-935
- content, err := vcs.Get(repo2.VCS.Type, vcs.ProviderConfig{}).ReadFileContent(
- ctx,
- common.OauthContext{
- ClientID: repo2.VCS.ApplicationID,
- ClientSecret: repo2.VCS.Secret,
- AccessToken: repo2.AccessToken,
- RefreshToken: repo2.RefreshToken,
- Refresher: s.refreshToken(ctx, repo2.ID),
- },
- repo2.VCS.InstanceURL,
- repo2.ExternalID,
- addedEscaped,
- commit.ID,
- )
- if err != nil {
- createIgnoredFileActivity(err)
- continue
- }
+ if pushEvent.Repository.FullName != repo.ExternalID {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project mismatch, got %s, want %s", pushEvent.Repository.FullName, repo.ExternalID))
+ }
- // Create schema update issue.
- creatorID := api.SystemBotID
- if commit.Author.Email != "" {
- committerPrinciple, err := s.store.GetPrincipalByEmail(ctx, commit.Author.Email)
- if err != nil {
- log.Error("failed to find the principal with committer email", zap.String("email", commit.Author.Email), zap.Error(err))
- }
- if committerPrinciple == nil {
- log.Debug("cannot find the principal with committer email, use system bot instead", zap.String("email", commit.Author.Email))
- } else {
- creatorID = committerPrinciple.ID
- }
- }
+ log.Debug("Processing GitHub webhook push event...",
+ zap.String("project", repo.Project.Name),
+ )
- var createContext string
- if repo.Project.TenantMode == api.TenantModeTenant {
- if !s.feature(api.FeatureMultiTenancy) {
- return echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())
- }
- createContext, err = s.createTenantSchemaUpdateIssue(mi, vcsPushEvent, content)
- } else {
- createContext, err = s.createSchemaUpdateIssue(ctx, repo, mi, vcsPushEvent, addedEscaped, content)
- }
- if err != nil {
- createIgnoredFileActivity(err)
+ var createdMessageList []string
+ for _, commit := range pushEvent.Commits {
+ // The Distinct is false if the commit is superseded by a later commit.
+ if !commit.Distinct {
continue
}
- issueType := api.IssueDatabaseSchemaUpdate
- if mi.Type == db.Data {
- issueType = api.IssueDatabaseDataUpdate
- }
- issueCreate := &api.IssueCreate{
- ProjectID: repo.ProjectID,
- Name: fmt.Sprintf("%s by %s", mi.Description, strings.TrimPrefix(addedEscaped, repo.BaseDirectory+"/")),
- Type: issueType,
- Description: commit.Message,
- AssigneeID: api.SystemBotID,
- CreateContext: 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"
+ for _, added := range commit.Added {
+ // 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]
+
+ createdMessage, created, httpErr := s.createIssueFromPushEvent(
+ ctx,
+ repo,
+ vcs.PushEvent{
+ VCSType: repo.VCS.Type,
+ BaseDirectory: repo.BaseDirectory,
+ Ref: pushEvent.Ref,
+ RepositoryID: strconv.Itoa(pushEvent.Repository.ID),
+ RepositoryURL: pushEvent.Repository.HTMLURL,
+ RepositoryFullPath: pushEvent.Repository.FullName,
+ AuthorName: pushEvent.Sender.Login,
+ FileCommit: vcs.FileCommit{
+ ID: commit.ID,
+ Title: messageTitle,
+ Message: commit.Message,
+ CreatedTs: commit.Timestamp.Unix(),
+ URL: commit.URL,
+ AuthorName: commit.Author.Name,
+ AuthorEmail: commit.Author.Email,
+ Added: common.EscapeForLogging(added),
+ },
+ },
+ added,
+ webhookEndpointID,
+ )
+ if httpErr != nil {
+ return httpErr
}
- return echo.NewHTTPError(http.StatusInternalServerError, errMsg).SetInternal(err)
- }
-
- createdMessageList = append(createdMessageList, fmt.Sprintf("Created issue %q on adding %s", issue.Name, addedEscaped))
-
- // Create a project activity after successfully creating the issue as the result of the push event
- bytes, err := json.Marshal(api.ActivityProjectRepositoryPushPayload{
- VCSPushEvent: vcsPushEvent,
- IssueID: issue.ID,
- IssueName: issue.Name,
- })
- if err != nil {
- return 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(bytes),
- }
- if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)
+ if created {
+ createdMessageList = append(createdMessageList, createdMessage)
+ }
}
}
if len(createdMessageList) == 0 {
- msg := "Ignored push event. No applicable file found in the commit list."
- log.Warn(msg,
+ log.Warn("Ignored push event. No applicable file found in the commit list.",
zap.String("project", repo.Project.Name),
)
}
@@ -425,6 +380,186 @@ func (s *Server) createTenantSchemaUpdateIssue(mi *db.MigrationInfo, vcsPushEven
return string(createContext), 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, repo *api.Repository, pushEvent vcs.PushEvent, file, webhookEndpointID string) (message string, created bool, _ error) {
+ fileEscaped := common.EscapeForLogging(file)
+ log.Debug("Processing added file...",
+ zap.String("file", fileEscaped),
+ zap.String("commit", common.EscapeForLogging(pushEvent.FileCommit.ID)),
+ )
+
+ if !strings.HasPrefix(fileEscaped, repo.BaseDirectory) {
+ log.Debug("Ignored committed file, not under base directory.",
+ zap.String("file", fileEscaped),
+ zap.String("base_directory", repo.BaseDirectory),
+ )
+ return "", false, nil
+ }
+
+ // Ignore the schema file we auto generated to the repository.
+ if isSkipGeneratedSchemaFile(repo, fileEscaped) {
+ log.Debug("Ignored generated latest schema file.",
+ zap.String("file", fileEscaped),
+ )
+ return "", false, nil
+ }
+
+ // Create a WARNING project activity if committed file is ignored
+ var createIgnoredFileActivity = func(err error) {
+ log.Warn("Ignored committed file",
+ zap.String("file", fileEscaped),
+ zap.Error(err),
+ )
+ bytes, marshalErr := json.Marshal(
+ api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: pushEvent,
+ },
+ )
+ if marshalErr != nil {
+ log.Warn("Failed to construct project activity payload to record ignored repository committed file",
+ zap.Error(marshalErr),
+ )
+ return
+ }
+
+ activityCreate := &api.ActivityCreate{
+ CreatorID: api.SystemBotID,
+ ContainerID: repo.ProjectID,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ActivityWarn,
+ Comment: fmt.Sprintf("Ignored committed file %q, %s.", fileEscaped, err.Error()),
+ Payload: string(bytes),
+ }
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
+ if err != nil {
+ log.Warn("Failed to create project activity to record ignored repository committed file",
+ zap.Error(err),
+ )
+ }
+ }
+
+ mi, err := db.ParseMigrationInfo(fileEscaped, filepath.Join(repo.BaseDirectory, repo.FilePathTemplate))
+ if err != nil {
+ createIgnoredFileActivity(err)
+ return "", false, nil
+ }
+
+ // Retrieve the latest AccessToken and RefreshToken as the previous
+ // ReadFileContent call may have updated the stored token pair. ReadFileContent
+ // will fetch and store the new token pair if the existing token pair has
+ // expired.
+ repo2, err := s.store.GetRepository(ctx, &api.RepositoryFind{WebhookEndpointID: &webhookEndpointID})
+ if err != nil {
+ return "", false, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to respond webhook event for endpoint: %v", webhookEndpointID)).SetInternal(err)
+ }
+ if repo2 == nil {
+ return "", false, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Webhook endpoint not found: %v", webhookEndpointID))
+ }
+
+ // Retrieve migration SQL script by reading the file content
+ content, err := vcs.Get(repo2.VCS.Type, vcs.ProviderConfig{}).ReadFileContent(
+ ctx,
+ common.OauthContext{
+ ClientID: repo2.VCS.ApplicationID,
+ ClientSecret: repo2.VCS.Secret,
+ AccessToken: repo2.AccessToken,
+ RefreshToken: repo2.RefreshToken,
+ Refresher: s.refreshToken(ctx, repo2.ID),
+ },
+ repo2.VCS.InstanceURL,
+ repo2.ExternalID,
+ fileEscaped,
+ pushEvent.FileCommit.ID,
+ )
+ if err != nil {
+ createIgnoredFileActivity(err)
+ return "", false, nil
+ }
+
+ // Create schema update issue.
+ creatorID := api.SystemBotID
+ if pushEvent.FileCommit.AuthorEmail != "" {
+ committerPrinciple, 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 committerPrinciple == nil {
+ log.Debug("cannot find the principal with committer email, use system bot instead",
+ zap.String("email", common.EscapeForLogging(pushEvent.FileCommit.AuthorEmail)),
+ )
+ } else {
+ creatorID = committerPrinciple.ID
+ }
+ }
+
+ var createContext string
+ if repo.Project.TenantMode == api.TenantModeTenant {
+ if !s.feature(api.FeatureMultiTenancy) {
+ return "", false, echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())
+ }
+ createContext, err = s.createTenantSchemaUpdateIssue(mi, pushEvent, content)
+ } else {
+ createContext, err = s.createSchemaUpdateIssue(ctx, repo, mi, pushEvent, fileEscaped, content)
+ }
+ if err != nil {
+ createIgnoredFileActivity(err)
+ return "", false, nil
+ }
+
+ issueType := api.IssueDatabaseSchemaUpdate
+ if mi.Type == db.Data {
+ issueType = api.IssueDatabaseDataUpdate
+ }
+ issueCreate := &api.IssueCreate{
+ ProjectID: repo.ProjectID,
+ Name: fmt.Sprintf("%s by %s", mi.Description, strings.TrimPrefix(file, repo.BaseDirectory+"/")),
+ Type: issueType,
+ Description: pushEvent.FileCommit.Message,
+ AssigneeID: api.SystemBotID,
+ CreateContext: 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, echo.NewHTTPError(http.StatusInternalServerError, errMsg).SetInternal(err)
+ }
+
+ // Create a project activity after successfully creating the issue as the result of the push event
+ bytes, err := json.Marshal(
+ api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: pushEvent,
+ IssueID: issue.ID,
+ IssueName: issue.Name,
+ },
+ )
+ if err != nil {
+ return "", false, 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(bytes),
+ }
+ if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {
+ return "", false, 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, fileEscaped), true, nil
+}
+
// We may write back the latest schema file to the repository after migration and we need to ignore
// this file from the webhook push event.
func isSkipGeneratedSchemaFile(repository *api.Repository, added string) bool {