Skip to content

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

Use file path template to match the commited file from webhook push event

天舟56b3bcb2a88e
diff --git a/api/activity.go b/api/activity.go
index 27e2309c39..9c898d51b5 100644
--- a/api/activity.go
+++ b/api/activity.go
@@ -139,6 +139,10 @@ type ActivityMemberActivateDeactivatePayload struct {
type ActivityProjectRepositoryPushPayload struct {
VCSPushEvent common.VCSPushEvent `json:"pushEvent"`
+ // Used by activity table to display info without paying the join cost
+ // IssueId/IssueName only exist if the push event leads to the issue creation.
+ IssueId int `json:"issueId,omitempty"`
+ IssueName string `json:"issueName,omitempty"`
}
type Activity struct {
diff --git a/frontend/src/components/ActivityTable.vue b/frontend/src/components/ActivityTable.vue
index 7bb8be3c95..0b18288d4e 100644
--- a/frontend/src/components/ActivityTable.vue
+++ b/frontend/src/components/ActivityTable.vue
@@ -72,18 +72,43 @@
</BBTableCell>
<BBTableCell class="w-8">
{{ activityName(activity.type) }}
- <template v-if="activityLink(activity)">
+ <template v-if="activityTypeLink(activity)">
<a
- :href="activityLink(activity).path"
+ v-if="activityTypeLink(activity).external"
+ :href="activityTypeLink(activity).path"
target="_blank"
class="normal-link"
>
- {{ activityLink(activity).title }}
+ {{ activityTypeLink(activity).title }}
</a>
+ <router-link
+ v-else
+ class="normal-link"
+ :to="activityTypeLink(activity).path"
+ >
+ {{ activityTypeLink(activity).title }}
+ </router-link>
</template>
</BBTableCell>
<BBTableCell class="w-24">
{{ activity.comment }}
+ <template v-if="activityCommentLink(activity)">
+ <a
+ v-if="activityCommentLink(activity).external"
+ :href="activityCommentLink(activity).path"
+ target="_blank"
+ class="normal-link"
+ >
+ {{ activityCommentLink(activity).title }}
+ </a>
+ <router-link
+ v-else
+ class="normal-link"
+ :to="activityCommentLink(activity).path"
+ >
+ {{ activityCommentLink(activity).title }}
+ </router-link>
+ </template>
</BBTableCell>
<BBTableCell class="w-8">
{{ humanizeTs(activity.createdTs) }}
@@ -102,11 +127,12 @@
import { PropType } from "vue";
import { BBTableColumn } from "../bbkit/types";
import { ActivityProjectRepositoryPushPayload, Activity } from "../types";
-import { activityName } from "../utils";
+import { activityName, issueSlug } from "../utils";
type Link = {
title: string;
path: string;
+ external: boolean;
};
const COLUMN_LIST: BBTableColumn[] = [
@@ -137,7 +163,7 @@ export default {
},
},
setup(props, ctx) {
- const activityLink = (activity: Activity): Link | undefined => {
+ const activityTypeLink = (activity: Activity): Link | undefined => {
switch (activity.type) {
case "bb.project.repository.push": {
const payload =
@@ -145,16 +171,36 @@ export default {
return {
title: payload.pushEvent.fileCommit.id.substring(0, 7),
path: payload.pushEvent.fileCommit.url,
+ external: true,
};
}
}
return undefined;
};
+ const activityCommentLink = (activity: Activity): Link | undefined => {
+ switch (activity.type) {
+ case "bb.project.repository.push": {
+ const payload =
+ activity.payload as ActivityProjectRepositoryPushPayload;
+ if (payload.issueId && payload.issueName) {
+ return {
+ title: `issue/${payload.issueId}`,
+ path: `/issue/${issueSlug(payload.issueName!, payload.issueId!)}`,
+ external: false,
+ };
+ }
+ break;
+ }
+ }
+ return undefined;
+ };
+
return {
activityName,
COLUMN_LIST,
- activityLink,
+ activityTypeLink,
+ activityCommentLink,
};
},
};
diff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vue
index f0d5fe265b..51b42e4b32 100644
--- a/frontend/src/components/RepositoryForm.vue
+++ b/frontend/src/components/RepositoryForm.vue
@@ -57,7 +57,8 @@
<div>
<div class="textlabel">Base directory</div>
<div class="mt-1 textinfolabel">
- The root directory where Bytebase observes the file change.
+ The root directory where Bytebase observes the file change. If empty,
+ then it observes the entire repository.
</div>
<input
id="basedirectory"
@@ -69,7 +70,16 @@
/>
</div>
<div>
- <div class="textlabel">File path template</div>
+ <div class="textlabel">
+ File path template <span class="text-red-600">*</span>
+ <a
+ href="https://docs.bytebase.com/use-bytebase/vcs-integration/organize-repository-files"
+ target="__blank"
+ class="font-normal normal-link"
+ >
+ config guide</a
+ >
+ </div>
<div class="mt-1 textinfolabel">
Bytebase only observes the file path name matching the template pattern
relative to the base directory.
@@ -82,6 +92,32 @@
:disabled="!allowEdit"
v-model="repositoryConfig.filePathTemplate"
/>
+ <div class="mt-2 textinfolabel">
+ <span class="text-red-600">*</span> Required placeholders:
+ {{ REQUIRED_PLACEHOLDER }}. Optional placeholders:
+ {{ OPTIONAL_PLACEHOLDER }}
+ </div>
+ <div class="mt-2 textinfolabel">Example:</div>
+ <div class="mt-2 textinfolabel">
+ File path for normal migration type:
+ {{
+ sampleFilePath(
+ repositoryConfig.baseDirectory,
+ repositoryConfig.filePathTemplate,
+ "migrate"
+ )
+ }}
+ </div>
+ <div class="mt-2 textinfolabel">
+ File path for baseline migration type:
+ {{
+ sampleFilePath(
+ repositoryConfig.baseDirectory,
+ repositoryConfig.filePathTemplate,
+ "baseline"
+ )
+ }}
+ </div>
</div>
</div>
</template>
@@ -91,6 +127,9 @@ import { reactive } from "@vue/reactivity";
import { PropType } from "@vue/runtime-core";
import { ExternalRepositoryInfo, RepositoryConfig, VCSType } from "../types";
+const REQUIRED_PLACEHOLDER = "{{VERSION}}, {{DB_NAME}}, {{TYPE}}";
+const OPTIONAL_PLACEHOLDER = "{{ENV_NAME}}, {{DESCRIPTION}}";
+
interface LocalState {}
export default {
@@ -126,8 +165,52 @@ export default {
setup(props, { emit }) {
const state = reactive<LocalState>({});
+ const sampleFilePath = (
+ baseDirectory: string,
+ filePathTemplate: string,
+ type: string
+ ): string => {
+ type Item = {
+ placeholder: string;
+ sampleText: string;
+ };
+
+ const placeholderList: Item[] = [
+ {
+ placeholder: "{{VERSION}}",
+ sampleText: "202101131000",
+ },
+ {
+ placeholder: "{{DB_NAME}}",
+ sampleText: "db1",
+ },
+ {
+ placeholder: "{{TYPE}}",
+ sampleText: type,
+ },
+ {
+ placeholder: "{{ENV_NAME}}",
+ sampleText: "env1",
+ },
+ {
+ placeholder: "{{DESCRIPTION}}",
+ sampleText: "create_tablefoo_for_bar",
+ },
+ ];
+
+ let result: string = `${baseDirectory}/${filePathTemplate}`;
+ for (const item of placeholderList) {
+ const re = new RegExp(item.placeholder, "g");
+ result = result.replace(re, item.sampleText);
+ }
+ return result;
+ };
+
return {
+ REQUIRED_PLACEHOLDER,
+ OPTIONAL_PLACEHOLDER,
state,
+ sampleFilePath,
};
},
};
diff --git a/frontend/src/components/RepositoryPanel.vue b/frontend/src/components/RepositoryPanel.vue
index 73d03cfd61..1650ca1444 100644
--- a/frontend/src/components/RepositoryPanel.vue
+++ b/frontend/src/components/RepositoryPanel.vue
@@ -9,9 +9,9 @@
}}</a
>. To make schema changes, a developer would create a migration script
matching file path pattern
- <span class="font-medium text-main"
- >/{{ state.repositoryConfig.baseDirectory }}</span
- >
+ <span class="font-medium text-main">{{
+ state.repositoryConfig.baseDirectory
+ }}</span>
<span class="font-medium text-main"
>/{{ state.repositoryConfig.filePathTemplate }}</span
>. After the script is review approved and merged into the
@@ -124,6 +124,7 @@ export default {
const allowUpdate = computed(() => {
return (
!isEmpty(state.repositoryConfig.branchFilter) &&
+ !isEmpty(state.repositoryConfig.filePathTemplate) &&
(props.repository.branchFilter != state.repositoryConfig.branchFilter ||
props.repository.baseDirectory !=
state.repositoryConfig.baseDirectory ||
diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vue
index 9980d9219b..3f1eeedf0e 100644
--- a/frontend/src/components/RepositorySetupWizard.vue
+++ b/frontend/src/components/RepositorySetupWizard.vue
@@ -51,7 +51,7 @@ import { projectSlug } from "../utils";
// Default file path template is to organize migration files from different environments under separate directories.
const DEFAULT_FILE_PATH_TEMPLATE =
- "{{envname}}/{{version}}__{{dbname}}__{{type}}__{{description}}.sql";
+ "{{ENV_NAME}}/{{VERSION}}__{{DB_NAME}}__{{TYPE}}__{{DESCRIPTION}}.sql";
const CHOOSE_PROVIDER_STEP = 0;
const CHOOSE_REPOSITORY_STEP = 1;
@@ -116,7 +116,10 @@ export default {
const allowNext = computed((): boolean => {
if (state.currentStep == CONFIGURE_DEPLOY_STEP) {
- return !isEmpty(state.config.repositoryConfig.branchFilter.trim());
+ return (
+ !isEmpty(state.config.repositoryConfig.branchFilter.trim()) &&
+ !isEmpty(state.config.repositoryConfig.filePathTemplate.trim())
+ );
}
return true;
});
@@ -138,8 +141,9 @@ export default {
name: state.config.repositoryInfo.name,
fullPath: state.config.repositoryInfo.fullPath,
webURL: state.config.repositoryInfo.webURL,
- baseDirectory: state.config.repositoryConfig.baseDirectory,
branchFilter: state.config.repositoryConfig.branchFilter,
+ baseDirectory: state.config.repositoryConfig.baseDirectory,
+ filePathTemplate: state.config.repositoryConfig.filePathTemplate,
externalId: state.config.repositoryInfo.externalId,
accessToken: state.config.token.accessToken,
expiresTs: state.config.token.expiresTs,
diff --git a/frontend/src/types/activity.ts b/frontend/src/types/activity.ts
index 716795ac2f..1d732adec5 100644
--- a/frontend/src/types/activity.ts
+++ b/frontend/src/types/activity.ts
@@ -83,6 +83,8 @@ export type ActivityMemberActivateDeactivatePayload = {
export type ActivityProjectRepositoryPushPayload = {
pushEvent: VCSPushEvent;
+ issueId?: number;
+ issueName?: string;
};
export type ActionPayloadType =
diff --git a/frontend/src/types/repository.ts b/frontend/src/types/repository.ts
index 843d84973c..60d8cb817b 100644
--- a/frontend/src/types/repository.ts
+++ b/frontend/src/types/repository.ts
@@ -40,8 +40,9 @@ export type RepositoryCreate = {
name: string;
fullPath: string;
webURL: string;
- baseDirectory: string;
branchFilter: string;
+ baseDirectory: string;
+ filePathTemplate: string;
externalId: string;
accessToken: string;
expiresTs: number;
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 6cd9f48c10..41df04564c 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -3,7 +3,7 @@ package db
import (
"context"
"fmt"
- "path/filepath"
+ "regexp"
"strings"
"sync"
@@ -142,56 +142,77 @@ type MigrationInfo struct {
Payload string
}
-// ParseMigrationInfo derives MigrationInfo from fullPath and baseDir
-// filepath is the full file path in the repository. The format is {{baseDir}}/[{{subdir}}/]/{{filename}}
-// Expected filename example, {{version}} can be arbitrary string without "__"
-// - {{version}}__db1 (a normal migration without description)
-// - {{version}}__db1__create_t1 (a normal migration with "create t1" as description)
-// - {{version}}__db1__baseline (a baseline migration without description)
-// - {{version}}__db1__baseline__create_t1 (a baseline migration with "create t1" as description)
-func ParseMigrationInfo(fullPath string, baseDir string) (*MigrationInfo, error) {
- filename := filepath.Base(fullPath)
- parentDir := filepath.Base(filepath.Clean(filepath.Dir(strings.TrimPrefix(fullPath, baseDir))))
- if parentDir == "." || parentDir == "/" {
- parentDir = ""
+// ParseMigrationInfo matches filePath against filePathTemplate
+// If filePath matches, then it will derive MigrationInfo from the filePath.
+// Both filePath and filePathTemplate are the full file path (including the base directory) of the repository.
+func ParseMigrationInfo(filePath string, filePathTemplate string) (*MigrationInfo, error) {
+ placeholderList := []string{
+ "ENV_NAME",
+ "VERSION",
+ "DB_NAME",
+ "TYPE",
+ "DESCRIPTION",
}
- parts := strings.Split(strings.TrimSuffix(filename, ".sql"), "__")
- if len(parts) < 2 {
- return nil, fmt.Errorf("invalid filename format, got %v, want {{version}}__{{dbname}}[__{{type}}][__{{description}}].sql", filename)
+ filePathRegex := filePathTemplate
+ for _, placeholder := range placeholderList {
+ filePathRegex = strings.ReplaceAll(filePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))
+ }
+ myRegex, err := regexp.Compile(filePathRegex)
+ if err != nil {
+ return nil, fmt.Errorf("invalid file path template: %q", filePathTemplate)
+ }
+ if !myRegex.MatchString(filePath) {
+ return nil, fmt.Errorf("file path %q does not match file path template %q", filePath, filePathTemplate)
}
mi := &MigrationInfo{
- Engine: VCS,
- Version: parts[0],
- Namespace: parts[1],
- Database: parts[1],
- Environment: parentDir,
+ Engine: VCS,
+ Type: Migrate,
}
-
- migrationType := Migrate
- description := ""
- if len(parts) > 2 {
- if parts[2] == "baseline" {
- migrationType = Baseline
- if len(parts) > 3 {
- description = strings.Join(parts[3:], " ")
+ matchList := myRegex.FindStringSubmatch(filePath)
+ for _, placeholder := range placeholderList {
+ index := myRegex.SubexpIndex(placeholder)
+ if index >= 0 {
+ if placeholder == "ENV_NAME" {
+ mi.Environment = matchList[index]
+ } else if placeholder == "VERSION" {
+ mi.Version = matchList[index]
+ } else if placeholder == "DB_NAME" {
+ mi.Namespace = matchList[index]
+ mi.Database = matchList[index]
+ } else if placeholder == "TYPE" {
+ if matchList[index] == "baseline" {
+ mi.Type = Baseline
+ } else if matchList[index] == "migrate" {
+ mi.Type = Migrate
+ } else {
+ return nil, fmt.Errorf("file path %q contains invalid migration type %q, must be 'baseline' or 'migrate'", filePath, matchList[index])
+ }
+ } else if placeholder == "DESCRIPTION" {
+ mi.Description = matchList[index]
}
- } else {
- description = strings.Join(parts[2:], " ")
}
}
- if description == "" {
- if migrationType == Baseline {
- description = fmt.Sprintf("Create %s baseline", mi.Database)
+
+ if mi.Version == "" {
+ return nil, fmt.Errorf("file path %q does not contain {{VERSION}}, configured file path template %q", filePath, filePathTemplate)
+ }
+ if mi.Namespace == "" {
+ return nil, fmt.Errorf("file path %q does not contain {{DB_NAME}}, configured file path template %q", filePath, filePathTemplate)
+ }
+
+ if mi.Description == "" {
+ if mi.Type == Baseline {
+ mi.Description = fmt.Sprintf("Create %s baseline", mi.Database)
} else {
- description = fmt.Sprintf("Create %s migration", mi.Database)
+ mi.Description = fmt.Sprintf("Create %s migration", mi.Database)
}
+ } else {
+ // Replace _ with space
+ mi.Description = strings.ReplaceAll(mi.Description, "_", " ")
+ // Capitalize first letter
+ mi.Description = strings.ToUpper(mi.Description[:1]) + mi.Description[1:]
}
- mi.Type = migrationType
- // Replace _ with space
- description = strings.ReplaceAll(description, "_", " ")
- // Capitalize first letter
- mi.Description = strings.ToUpper(description[:1]) + description[1:]
return mi, nil
}
diff --git a/plugin/db/driver_test.go b/plugin/db/driver_test.go
index ca6d958078..ff32216d02 100644
--- a/plugin/db/driver_test.go
+++ b/plugin/db/driver_test.go
@@ -8,128 +8,151 @@ import (
func TestParseMigrationInfo(t *testing.T) {
type test struct {
- fullPath string
- baseDir string
- want MigrationInfo
- wantErr string
+ filePath string
+ filePathTemplate string
+ want MigrationInfo
+ wantErr string
}
tests := []test{
{
- fullPath: "001foo__db1",
- baseDir: "",
+ filePath: "001foo__db1",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
Environment: "",
- Type: "SQL",
+ Engine: VCS,
+ Type: Migrate,
Description: "Create db1 migration",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "bytebase/001foo__db1",
- baseDir: "bytebase",
+ filePath: "1.2.3__db foo_+-=/_#?!$.",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}",
+ want: MigrationInfo{
+ Version: "1.2.3",
+ Namespace: "db foo_+-=/_#?!$.",
+ Database: "db foo_+-=/_#?!$.",
+ Environment: "",
+ Engine: VCS,
+ Type: Migrate,
+ Description: "Create db foo_+-=/_#?!$. migration",
+ Creator: "",
+ },
+ wantErr: "",
+ },
+ {
+ filePath: "bytebase/001foo__db1",
+ filePathTemplate: "bytebase/{{VERSION}}__{{DB_NAME}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
Environment: "",
- Type: "SQL",
+ Engine: VCS,
+ Type: Migrate,
Description: "Create db1 migration",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "bytebase/dev/001foo__db1",
- baseDir: "dev",
+ filePath: "bytebase/dev/001foo__db1",
+ filePathTemplate: "bytebase/{{ENV_NAME}}/{{VERSION}}__{{DB_NAME}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
Environment: "dev",
- Type: "SQL",
+ Engine: VCS,
+ Type: Migrate,
Description: "Create db1 migration",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "bytebase/dev/001foo__db1",
- baseDir: "",
+ filePath: "001foo__db1__create_t1",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}__{{DESCRIPTION}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
- Environment: "dev",
- Type: "SQL",
- Description: "Create db1 migration",
+ Environment: "",
+ Engine: VCS,
+ Type: Migrate,
+ Description: "Create t1",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "001foo__db1__create_t1",
- baseDir: "",
+ filePath: "001foo__db1__migrate",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}__{{TYPE}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
Environment: "",
- Type: "SQL",
- Description: "Create t1",
+ Engine: VCS,
+ Type: Migrate,
+ Description: "Create db1 migration",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "001foo__db1__baseline",
- baseDir: "",
+ filePath: "001foo__db1__baseline",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}__{{TYPE}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
Environment: "",
- Type: "BASELINE",
+ Engine: VCS,
+ Type: Baseline,
Description: "Create db1 baseline",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "001foo__db1__baseline__create_t1",
- baseDir: "",
+ filePath: "001foo__db1__baseline__create_t1",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}__{{TYPE}}__{{DESCRIPTION}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
Environment: "",
- Type: "BASELINE",
+ Engine: VCS,
+ Type: Baseline,
Description: "Create t1",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "001foo__db_shop1__baseline__create_t1",
- baseDir: "",
+ filePath: "001foo__db_shop1__baseline__create_t1",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}__{{TYPE}}__{{DESCRIPTION}}",
want: MigrationInfo{
Version: "001foo",
Namespace: "db_shop1",
Database: "db_shop1",
Environment: "",
- Type: "BASELINE",
+ Engine: VCS,
+ Type: Baseline,
Description: "Create t1",
Creator: "",
},
wantErr: "",
},
{
- fullPath: "001foo_db",
- baseDir: "",
+ filePath: "db",
+ filePathTemplate: "{{VERSION}}__{{DB_NAME}}",
want: MigrationInfo{
Version: "",
Namespace: "",
@@ -139,21 +162,21 @@ func TestParseMigrationInfo(t *testing.T) {
Description: "",
Creator: "",
},
- wantErr: "invalid filename format",
+ wantErr: "does not match file path template",
},
}
for _, tc := range tests {
- mi, err := ParseMigrationInfo(tc.fullPath, tc.baseDir)
+ mi, err := ParseMigrationInfo(tc.filePath, tc.filePathTemplate)
if err != nil {
if tc.wantErr == "" {
- t.Errorf("fullPath=%s, baseDir=%s: expected no error, got %w", tc.fullPath, tc.baseDir, err)
+ t.Errorf("filePath=%s, filePathTemplate=%s: expected no error, got %w", tc.filePath, tc.filePathTemplate, err)
} else if !strings.Contains(err.Error(), tc.wantErr) {
- t.Errorf("fullPath=%s, baseDir=%s: expected error %s, got %w", tc.fullPath, tc.baseDir, tc.wantErr, err)
+ t.Errorf("filePath=%s, filePathTemplate=%s: expected error %s, got %w", tc.filePath, tc.filePathTemplate, tc.wantErr, err)
}
} else {
if !reflect.DeepEqual(tc.want, *mi) {
- t.Errorf("fullPath=%s, baseDir=%s: expected %+v, got %+v", tc.fullPath, tc.baseDir, tc.want, *mi)
+ t.Errorf("filePath=%s, filePathTemplate=%s: expected %+v, got %+v", tc.filePath, tc.filePathTemplate, tc.want, *mi)
}
}
diff --git a/server/project.go b/server/project.go
index 3aa5752951..16b07e9315 100644
--- a/server/project.go
+++ b/server/project.go
@@ -148,6 +148,10 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create linked repository request").SetInternal(err)
}
+ if err := validateRepositoryFilePathTemplate(repositoryCreate.FilePathTemplate); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformatted create linked repository request: %s", err.Error()))
+ }
+
vcsFind := &api.VCSFind{
ID: &repositoryCreate.VCSId,
}
@@ -266,8 +270,15 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
}
if err := jsonapi.UnmarshalPayload(c.Request().Body, repositoryPatch); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch repository request").SetInternal(err)
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch linked repository request").SetInternal(err)
+ }
+
+ if repositoryPatch.FilePathTemplate != nil {
+ if err := validateRepositoryFilePathTemplate(*repositoryPatch.FilePathTemplate); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Malformatted patch linked repository request: %s", err.Error()))
+ }
}
+
// Remove enclosing /
if repositoryPatch.BaseDirectory != nil {
baseDir := strings.Trim(*repositoryPatch.BaseDirectory, "/")
@@ -452,3 +463,16 @@ func (s *Server) ComposeProjectRelationship(ctx context.Context, project *api.Pr
return nil
}
+
+func validateRepositoryFilePathTemplate(filePathTemplate string) error {
+ if !strings.Contains(filePathTemplate, "{{VERSION}}") {
+ return fmt.Errorf("missing {{VERSION}} in file path template")
+ }
+ if !strings.Contains(filePathTemplate, "{{DB_NAME}}") {
+ return fmt.Errorf("missing {{DB_NAME}} in file path template")
+ }
+ if !strings.Contains(filePathTemplate, "{{TYPE}}") {
+ return fmt.Errorf("missing {{TYPE}} in file path template")
+ }
+ return nil
+}
diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.go
index 4e0f9904ca..06cbe9bd93 100644
--- a/server/task_executor_schema_update.go
+++ b/server/task_executor_schema_update.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "path/filepath"
"strconv"
"strings"
@@ -66,7 +67,18 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
mi.Namespace = databaseName
mi.Description = task.Name
} else {
- mi, err = db.ParseMigrationInfo(payload.VCSPushEvent.FileCommit.Added, payload.VCSPushEvent.BaseDirectory)
+ repositoryFind := &api.RepositoryFind{
+ ProjectId: &task.Database.ProjectId,
+ }
+ repository, err := server.RepositoryService.FindRepository(context.Background(), repositoryFind)
+ if err != nil {
+ return true, "", fmt.Errorf("failed to find linked repository for database %q", databaseName)
+ }
+
+ mi, err = db.ParseMigrationInfo(
+ payload.VCSPushEvent.FileCommit.Added,
+ filepath.Join(payload.VCSPushEvent.BaseDirectory, repository.FilePathTemplate),
+ )
// This should not happen normally as we already check this when creating the issue. Just in case.
if err != nil {
return true, "", fmt.Errorf("failed to start schema migration, error: %w", err)
diff --git a/server/webhook.go b/server/webhook.go
index de0fee14a2..76a9c973d8 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -70,17 +70,13 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
for _, commit := range pushEvent.CommitList {
for _, added := range commit.AddedList {
if !strings.HasPrefix(added, repository.BaseDirectory) {
- s.l.Debug(fmt.Sprintf("Committed file %q is not under base directory: %q. Skip.", added, repository.BaseDirectory))
- continue
- }
- if filepath.Ext(added) != ".sql" {
- s.l.Debug(fmt.Sprintf("Committed file %q does not have .sql extension. Skip.", added))
+ s.l.Debug("Ignored committed file, not under base directory.", zap.String("file", added), zap.String("base_directory", repository.BaseDirectory))
continue
}
createdTime, err := time.Parse(time.RFC3339, commit.Timestamp)
if err != nil {
- s.l.Warn("Failed to parse timestamp. Skip", zap.String("file", added), zap.Error(err))
+ s.l.Warn("Ignored committed file, failed to parse commit timestamp.", zap.String("file", added), zap.String("timestamp", commit.Timestamp), zap.Error(err))
}
vcsPushEvent := common.VCSPushEvent{
VCSType: repository.VCS.Type,
@@ -101,35 +97,34 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
},
}
- mi, err := db.ParseMigrationInfo(added, repository.BaseDirectory)
- if err != nil {
- s.l.Warn("Invalid migration filename. Skip", zap.String("file", added), zap.Error(err))
-
- // Create a WARNING project activity if the committed file path doesn't match the expected pattern
- {
- bytes, marshalErr := json.Marshal(api.ActivityProjectRepositoryPushPayload{
- VCSPushEvent: vcsPushEvent,
- })
- if marshalErr != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(marshalErr)
- }
+ // Create a WARNING project activity if committed file is ignored
+ var createIgnoredFileActivity = func(err error) {
+ s.l.Warn("Ignored committed file", zap.String("file", added), zap.Error(err))
+ bytes, marshalErr := json.Marshal(api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: vcsPushEvent,
+ })
+ if marshalErr != nil {
+ s.l.Warn("Failed to construct project activity payload to record ignored repository committed file", zap.Error(marshalErr))
+ return
+ }
- activityCreate := &api.ActivityCreate{
- CreatorId: api.SYSTEM_BOT_ID,
- ContainerId: repository.ProjectId,
- Type: api.ActivityProjectRepositoryPush,
- Level: api.ACTIVITY_WARN,
- Comment: err.Error(),
- Payload: string(bytes),
- }
- _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
- if err != nil {
- return echo.NewHTTPError(
- http.StatusInternalServerError,
- "Failed to create project activity to record mismatch between committed file and expected pattern.").SetInternal(err)
- }
+ activityCreate := &api.ActivityCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ ContainerId: repository.ProjectId,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ACTIVITY_WARN,
+ Comment: fmt.Sprintf("Ignored committed file %q, %s.", added, err.Error()),
+ Payload: string(bytes),
}
+ _, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
+ if err != nil {
+ s.l.Warn("Failed to create project activity to record ignored repository committed file", zap.Error(err))
+ }
+ }
+ mi, err := db.ParseMigrationInfo(added, filepath.Join(repository.BaseDirectory, repository.FilePathTemplate))
+ if err != nil {
+ createIgnoredFileActivity(err)
continue
}
@@ -140,13 +135,13 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
repository.AccessToken,
)
if err != nil {
- s.l.Warn("Failed to read added repository file. Skip", zap.String("file", added), zap.Error(err))
+ createIgnoredFileActivity(fmt.Errorf("failed to read file: %w", err))
continue
}
b, err := io.ReadAll(resp.Body)
if err != nil {
- s.l.Warn("Failed to read added repository file response. Skip", zap.String("file", added), zap.Error(err))
+ createIgnoredFileActivity(fmt.Errorf("failed to read file response: %w", err))
continue
}
defer resp.Body.Close()
@@ -158,14 +153,10 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
databaseList, err := s.ComposeDatabaseListByFind(context.Background(), databaseFind)
if err != nil {
- s.l.Warn("Failed to find database matching added repository file. Skip", zap.String("file", added), zap.Error(err))
+ createIgnoredFileActivity(fmt.Errorf("failed to find database matching committed file database %q", mi.Database))
continue
} else if len(databaseList) == 0 {
- s.l.Warn("Project does not own this database. Skip",
- zap.Int("project_id", repository.ProjectId),
- zap.String("database_name", mi.Database),
- zap.String("file", added),
- )
+ createIgnoredFileActivity(fmt.Errorf("project ID %d does not own committed file database %q", repository.ProjectId, mi.Database))
continue
}
@@ -190,11 +181,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
}
if len(filterdDatabaseList) == 0 {
- s.l.Warn(fmt.Sprintf("Project ID %d does not contain database %s for environment %s. Skip", repository.ProjectId, mi.Database, mi.Environment),
- zap.Int("project_id", repository.ProjectId),
- zap.String("environment", mi.Environment),
- zap.String("file", added),
- )
+ createIgnoredFileActivity(fmt.Errorf("project does not contain committed file database %q for environment %q", mi.Database, mi.Environment))
continue
}
} else {
@@ -220,7 +207,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
if len(databaseList) > 1 {
multipleDatabaseForSameEnv = true
- s.l.Warn(fmt.Sprintf("Project ID %d contain multiple database %s for environment %d. Skip", repository.ProjectId, mi.Database, environemntId),
+ s.l.Warn(fmt.Sprintf("Ignored committed file, multiple ambiguous databases named %q for environment %d.", mi.Database, environemntId),
zap.Int("project_id", repository.ProjectId),
zap.String("file", added),
)
@@ -281,6 +268,8 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
{
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)
@@ -291,6 +280,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
ContainerId: repository.ProjectId,
Type: api.ActivityProjectRepositoryPush,
Level: api.ACTIVITY_INFO,
+ Comment: fmt.Sprintf("Created issue %q.", issue.Name),
Payload: string(bytes),
}
_, err = s.ActivityManager.CreateActivity(context.Background(), activityCreate, &ActivityMeta{})
diff --git a/store/seed/test/10180__repository.sql b/store/seed/test/10180__repository.sql
index 9abe2906e6..56309dfdbf 100644
--- a/store/seed/test/10180__repository.sql
+++ b/store/seed/test/10180__repository.sql
@@ -33,7 +33,7 @@ VALUES
"http://gitlab.bytebase.com/bytebase-demo/blog",
"master",
"bytebase",
- "{{envname}}/{{version}}__{{dbname}}__{{type}}__{{description}}.sql",
+ "{{ENV_NAME}}/{{VERSION}}__{{DB_NAME}}__{{TYPE}}__{{DESCRIPTION}}.sql",
-- Refers to the bytebase-demo/blog
"13",
-- Refers to the webhook in bytebase-demo/blog
@@ -80,7 +80,7 @@ VALUES
"http://gitlab.bytebase.com/bytebase-demo/shop",
"master",
"bytebase",
- "{{envname}}/{{version}}__{{dbname}}__{{type}}__{{description}}.sql",
+ "{{ENV_NAME}}/{{VERSION}}__{{DB_NAME}}__{{TYPE}}__{{DESCRIPTION}}.sql",
-- Refers to the bytebase-demo/shop
"14",
-- Refers to the webhook in bytebase-demo/shop