Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Update repository base directory and branch filter
天舟08431bf707ba
diff --git a/backend/api/repository.go b/backend/api/repository.goindex a7a99c9cad..98c2f788ff 100644--- a/backend/api/repository.go+++ b/backend/api/repository.go@@ -70,7 +70,7 @@ func (find *RepositoryFind) String() string {}type RepositoryPatch struct {- ID int+ ID int `jsonapi:"primary,repositoryPatch"`// Standard fields// Value is assigned from the jwt subject field passed by the client.@@ -83,6 +83,8 @@ type RepositoryPatch struct {type RepositoryDelete struct {// Related fields+ // When deleting the repository, we need to update the correponding project workflow type to "UI",+ // thus we use ProjectId here.ProjectId int// Standard fieldsdiff --git a/backend/external/gitlab/gitlab.go b/backend/external/gitlab/gitlab.goindex b943af1a23..ebdc381f2f 100644--- a/backend/external/gitlab/gitlab.go+++ b/backend/external/gitlab/gitlab.go@@ -2,7 +2,7 @@ package gitlabimport ("fmt"- "log"+ "io""net/http")@@ -10,9 +10,32 @@ const (ApiPath = "/api/v4")-func Delete(instanceURL string, resourcePath string, token string) (*http.Response, error) {+type WebhookPut struct {+ URL string `json:"url"`+ PushEventsBranchFilter string `json:"push_events_branch_filter"`+}++func PUT(instanceURL string, resourcePath string, token string, body io.Reader) (*http.Response, error) {+ url := fmt.Sprintf("%s%s%s", instanceURL, ApiPath, resourcePath)+ req, err := http.NewRequest("PUT",+ url, body)+ if err != nil {+ return nil, fmt.Errorf("failed to construct PUT %v (%w)", url, err)+ }++ req.Header.Set("Content-Type", "application/json")+ req.Header.Add("Authorization", "Bearer "+token)+ client := &http.Client{}+ resp, err := client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("failed PUT %v (%w)", url, err)+ }++ return resp, nil+}++func DELETE(instanceURL string, resourcePath string, token string) (*http.Response, error) {url := fmt.Sprintf("%s%s%s", instanceURL, ApiPath, resourcePath)- log.Printf("url: %s token: %s\n", url, token)req, err := http.NewRequest("DELETE",url, nil)if err != nil {diff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csvindex 9ba6e41c1e..3591906e2a 100644--- a/backend/server/acl_casbin_policy_dba.csv+++ b/backend/server/acl_casbin_policy_dba.csv@@ -8,6 +8,7 @@ p, DBA, /project/{id}, GETp, DBA, /project/{id}, PATCHp, DBA, /project/{id}/repository, GETp, DBA, /project/{id}/repository, POST+p, DBA, /project/{id}/repository, PATCHp, DBA, /project/{id}/repository, DELETEp, DBA, /project/{projectId}/member, POSTp, DBA, /project/{projectId}/member/{memberId}, PATCHdiff --git a/backend/server/acl_casbin_policy_developer.csv b/backend/server/acl_casbin_policy_developer.csvindex b3d2ac576e..3dac02f7f7 100644--- a/backend/server/acl_casbin_policy_developer.csv+++ b/backend/server/acl_casbin_policy_developer.csv@@ -8,6 +8,7 @@ p, DEVELOPER, /project/{id}, GETp, DEVELOPER, /project/{id}, PATCHp, DEVELOPER, /project/{id}/repository, GETp, DEVELOPER, /project/{id}/repository, POST+p, DEVELOPER, /project/{id}/repository, PATCHp, DEVELOPER, /project/{id}/repository, DELETEp, DEVELOPER, /project/{projectId}/member, POSTp, DEVELOPER, /project/{projectId}/member/{memberId}, PATCHdiff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csvindex b663aedc94..f8ff165d42 100644--- a/backend/server/acl_casbin_policy_owner.csv+++ b/backend/server/acl_casbin_policy_owner.csv@@ -13,6 +13,7 @@ p, OWNER, /project/{id}, GETp, OWNER, /project/{id}, PATCHp, OWNER, /project/{id}/repository, GETp, OWNER, /project/{id}/repository, POST+p, OWNER, /project/{id}/repository, PATCHp, OWNER, /project/{id}/repository, DELETEp, OWNER, /project/{projectId}/member, POSTp, OWNER, /project/{projectId}/member/{memberId}, PATCHdiff --git a/backend/server/project.go b/backend/server/project.goindex 28956fd152..97529ab7fc 100644--- a/backend/server/project.go+++ b/backend/server/project.go@@ -1,7 +1,9 @@package serverimport (+ "bytes""context"+ "encoding/json""fmt""net/http""strconv"@@ -155,22 +157,22 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {// 1. repository also contains project, which would cause circular dependency when composing it.// 2. repository info is only needed when fetching a particular project by id, thus it's unnecessary to include it in the project list response.g.GET("/project/:projectId/repository", func(c echo.Context) error {- id, err := strconv.Atoi(c.Param("projectId"))+ projectId, err := strconv.Atoi(c.Param("projectId"))if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)}repositoryFind := &api.RepositoryFind{- ProjectId: &id,+ ProjectId: &projectId,}list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectId)).SetInternal(err)}// Just be defensive, this shouldn't happen because we set UNIQUE constraint on project_idif len(list) > 1 {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(list), id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(list), projectId)).SetInternal(err)}for _, repository := range list {@@ -181,31 +183,119 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", projectId)).SetInternal(err)+ }+ return nil+ })++ // When we unlink the repository with the project, we will also change the project workflow type to UI+ g.PATCH("/project/:projectId/repository", func(c echo.Context) error {+ projectId, err := strconv.Atoi(c.Param("projectId"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)+ }++ repositoryPatch := &api.RepositoryPatch{+ 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)+ }++ repositoryFind := &api.RepositoryFind{+ ProjectId: &projectId,+ }+ list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectId)).SetInternal(err)+ }++ // Just be defensive, this shouldn't happen because we set UNIQUE constraint on project_id+ if len(list) > 1 {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(list), projectId)).SetInternal(err)+ } else if len(list) == 0 {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", projectId))+ }++ repository := list[0]+ repositoryPatch.ID = repository.ID+ updatedRepository, err := s.RepositoryService.PatchRepository(context.Background(), repositoryPatch)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectId)).SetInternal(err)+ }++ if repositoryPatch.BranchFilter != nil {+ vcsFind := &api.VCSFind{+ ID: &repository.VCSId,+ }+ vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update repository for project ID: %d", projectId)).SetInternal(err)+ }+ // Updates the webhook after we successfully update the repository.+ // This is because in case the webhook update fails, we can still have a reconcile process to reconcile the webhook state.+ // If we update it before we update the repository, then if the repository update fails, then the reconcile process will reconcile the webhook to the pre-update state which is likely not intended.+ switch vcs.Type {+ case "GITLAB_SELF_HOST":+ webhookPut := gitlab.WebhookPut{+ URL: updatedRepository.WebhookURL,+ PushEventsBranchFilter: *repositoryPatch.BranchFilter,+ }+ json, err := json.Marshal(webhookPut)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal put request for updating webhook %s for project ID: %v", repository.WebhookId, projectId)).SetInternal(err)+ }+ resourcePath := fmt.Sprintf("/projects/%s/hooks/%s", repository.ExternalId, repository.WebhookId)+ resp, err := gitlab.PUT(vcs.InstanceURL, resourcePath, vcs.AccessToken, bytes.NewBuffer(json))+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update webhook ID %s for project ID: %v", repository.WebhookId, projectId)).SetInternal(err)+ }++ // Just emits a warning since we have already updated the repository entry. We will have a separate process to reconcile the state.+ if resp.StatusCode >= 300 {+ s.l.Error(("failed to update gitlab webhook when updating repository for project"),+ zap.Int("status_code", resp.StatusCode),+ zap.String("status", resp.Status),+ zap.Int("project_id", projectId),+ zap.Int("repository_id", repository.ID),+ zap.String("resource_path", resourcePath),+ zap.String("body", string(json)),+ )+ }+ }+ }++ if err := s.ComposeRepositoryRelationship(context.Background(), updatedRepository, c.Get(getIncludeKey()).([]string)); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to updating repository for project").SetInternal(err)+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, updatedRepository); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project repository response: %v", projectId)).SetInternal(err)}return nil})// When we unlink the repository with the project, we will also change the project workflow type to UIg.DELETE("/project/:projectId/repository", func(c echo.Context) error {- id, err := strconv.Atoi(c.Param("projectId"))+ projectId, err := strconv.Atoi(c.Param("projectId"))if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectId"))).SetInternal(err)}repositoryFind := &api.RepositoryFind{- ProjectId: &id,+ ProjectId: &projectId,}list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for project ID: %d", projectId)).SetInternal(err)}// Just be defensive, this shouldn't happen because we set UNIQUE constraint on project_idif len(list) > 1 {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(list), id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Retrieved %d repository list for project ID: %d, expect at most 1", len(list), projectId)).SetInternal(err)} else if len(list) == 0 {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", id))+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found for project ID: %d", projectId))}repository := list[0]@@ -214,32 +304,32 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {}vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectId)).SetInternal(err)}repositoryDelete := &api.RepositoryDelete{- ProjectId: id,+ ProjectId: projectId,DeleterId: c.Get(GetPrincipalIdContextKey()).(int),}if err := s.RepositoryService.DeleteRepository(context.Background(), repositoryDelete); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete repository for project ID: %d", projectId)).SetInternal(err)}// Deletes the webhook after we successfully delete the repository.- // This is because in case the webhook deletion fails, we can still have a cleanup processor to cleanup the orphaned webhook.+ // This is because in case the webhook deletion fails, we can still have a cleanup process to cleanup the orphaned webhook.// If we delete it before we delete the repository, then if the repository deletion fails, we will have a broken repository with no webhook.switch vcs.Type {case "GITLAB_SELF_HOST":- resp, err := gitlab.Delete(vcs.InstanceURL, fmt.Sprintf("/projects/%s/hooks/%s", repository.ExternalId, repository.WebhookId), vcs.AccessToken)+ resp, err := gitlab.DELETE(vcs.InstanceURL, fmt.Sprintf("/projects/%s/hooks/%s", repository.ExternalId, repository.WebhookId), vcs.AccessToken)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete webhook ID %s for project ID: %v", repository.WebhookId, id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete webhook ID %s for project ID: %v", repository.WebhookId, projectId)).SetInternal(err)}- // Just emits a warning since we have already removed the repository entry. We will have a separate processor to cleanup the orphaned webhook.+ // Just emits a warning since we have already removed the repository entry. We will have a separate process to cleanup the orphaned webhook.if resp.StatusCode >= 300 {s.l.Error(("failed to delete gitlab webhook when unlinking repository from project"),zap.Int("status_code", resp.StatusCode),- zap.Int("project_id", id),+ zap.Int("project_id", projectId),zap.Int("repository_id", repository.ID),zap.String("gitlab_project_id", repository.ExternalId),zap.String("gitlab_webhook_id", repository.WebhookId))diff --git a/frontend/src/components/RepositoryDetail.vue b/frontend/src/components/RepositoryDetail.vueindex 9e7d99df9b..b4bda7e1ff 100644--- a/frontend/src/components/RepositoryDetail.vue+++ b/frontend/src/components/RepositoryDetail.vue@@ -7,10 +7,10 @@<a class="normal-link" :href="repository.webURL" target="_blank">{{repository.fullPath}}</a- >. To make schema changes, a developer would create a migration script and- submit for review there. After the script is approved and merged into the- branch matching pattern- <span class="text-main">{{ repository.branchFilter }}</span+ >. To make schema changes, a developer would create a migration script under+ base directory <span class="text-main">/{{ repository.baseDirectory }}</span+ >. After the script is review approved and merged into the branch matching+ pattern <span class="text-main">{{ repository.branchFilter }}</span>, Bytebase will automatically kicks off the task to apply the new schemachange.</div>@@ -19,7 +19,7 @@:vcsType="repository.vcs.type":vcsName="repository.vcs.name":repositoryInfo="repositoryInfo"- :repositoryConfig="repositoryConfig"+ :repositoryConfig="state.repositoryConfig"/><div class="mt-4 pt-4 flex border-t justify-between"><BBButtonConfirm@@ -32,13 +32,6 @@@confirm="restoreToUIWorkflowType"/><div>- <button- type="button"- class="btn-normal py-2 px-4"- @click.prevent="cancel"- >- Cancel- </button><buttontype="button"class="btn-primary ml-3 inline-flex justify-center py-2 px-4"@@ -52,17 +45,21 @@</template><script lang="ts">-import { computed, PropType } from "vue";-import { useRouter } from "vue-router";+import { computed, PropType, reactive, watch } from "vue";import RepositoryForm from "./RepositoryForm.vue";import {Repository,+ RepositoryPatch,ExternalRepositoryInfo,RepositoryConfig,Project,} from "../types";import { useStore } from "vuex";+interface LocalState {+ repositoryConfig: RepositoryConfig;+}+export default {name: "RepositoryDetail",components: { RepositoryForm },@@ -78,7 +75,22 @@ export default {},setup(props, ctx) {const store = useStore();- const router = useRouter();+ const state = reactive<LocalState>({+ repositoryConfig: {+ baseDirectory: props.repository.baseDirectory,+ branchFilter: props.repository.branchFilter,+ },+ });++ watch(+ () => props.repository,+ (cur, _) => {+ state.repositoryConfig = {+ baseDirectory: cur.baseDirectory,+ branchFilter: cur.branchFilter,+ };+ }+ );const repositoryInfo = computed((): ExternalRepositoryInfo => {return {@@ -86,39 +98,61 @@ export default {name: props.repository.name,fullPath: props.repository.fullPath,webURL: props.repository.webURL,- defaultBranch: "",- };- });-- const repositoryConfig = computed((): RepositoryConfig => {- return {- baseDirectory: props.repository.baseDirectory,- branchFilter: props.repository.branchFilter,};});const allowUpdate = computed(() => {- return true;+ return (+ props.repository.baseDirectory !=+ state.repositoryConfig.baseDirectory ||+ props.repository.branchFilter != state.repositoryConfig.branchFilter+ );});const restoreToUIWorkflowType = () => {- store.dispatch(- "repository/deleteRepositoryByProjectId",- props.project.id- );+ store+ .dispatch("repository/deleteRepositoryByProjectId", props.project.id)+ .then(() => {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: `Successfully restored to UI workflow`,+ });+ });};- const doUpdate = () => {};-- const cancel = () => {};+ const doUpdate = () => {+ const repositoryPatch: RepositoryPatch = {};+ if (+ props.repository.baseDirectory != state.repositoryConfig.baseDirectory+ ) {+ repositoryPatch.baseDirectory = state.repositoryConfig.baseDirectory;+ }+ if (+ props.repository.branchFilter != state.repositoryConfig.branchFilter+ ) {+ repositoryPatch.branchFilter = state.repositoryConfig.branchFilter;+ }+ store+ .dispatch("repository/updateRepositoryByProjectId", {+ projectId: props.project.id,+ repositoryPatch,+ })+ .then(() => {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: `Successfully updated version control config`,+ });+ });+ };return {+ state,repositoryInfo,- repositoryConfig,allowUpdate,restoreToUIWorkflowType,doUpdate,- cancel,};},};diff --git a/frontend/src/store/modules/repository.ts b/frontend/src/store/modules/repository.tsindex dd1d253b24..044fe7603f 100644--- a/frontend/src/store/modules/repository.ts+++ b/frontend/src/store/modules/repository.ts@@ -11,6 +11,8 @@ import {Project,ProjectId,VCS,+ ProjectPatch,+ RepositoryPatch,} from "../../types";function convert(@@ -141,6 +143,34 @@ const actions = {return unknown("REPOSITORY") as Repository;},+ async updateRepositoryByProjectId(+ { commit, rootGetters }: any,+ {+ projectId,+ repositoryPatch,+ }: {+ projectId: ProjectId;+ repositoryPatch: RepositoryPatch;+ }+ ) {+ const data = (+ await axios.patch(`/api/project/${projectId}/repository`, {+ data: {+ type: "repositoryPatch",+ attributes: repositoryPatch,+ },+ })+ ).data;++ const updatedRepository = convert(data.data, data.included, rootGetters);+ commit("setRepositoryByProjectId", {+ projectId,+ repository: updatedRepository,+ });++ return updatedRepository;+ },+async deleteRepositoryByProjectId({ dispatch, commit }: any,projectId: ProjectIddiff --git a/frontend/src/types/repository.ts b/frontend/src/types/repository.tsindex ce5bb9d0b0..097552cc00 100644--- a/frontend/src/types/repository.ts+++ b/frontend/src/types/repository.ts@@ -45,6 +45,11 @@ export type RepositoryCreate = {webhookURL: string;};+export type RepositoryPatch = {+ baseDirectory?: string;+ branchFilter?: string;+};+export type RepositoryConfig = {baseDirectory: string;branchFilter: string;