Skip to content

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

Repository config

天舟e5f55e6c2a71
diff --git a/backend/api/project.go b/backend/api/project.go
index 871f3b4908..cc09cbd63a 100644
--- a/backend/api/project.go
+++ b/backend/api/project.go
@@ -2,6 +2,7 @@ package api
import (
"context"
+ "database/sql"
"encoding/json"
)
@@ -93,4 +94,6 @@ type ProjectService interface {
FindProjectList(ctx context.Context, find *ProjectFind) ([]*Project, error)
FindProject(ctx context.Context, find *ProjectFind) (*Project, error)
PatchProject(ctx context.Context, patch *ProjectPatch) (*Project, error)
+ // This is specifically used to update the ProjectWorkflowType when linking/unlinking the repository.
+ PatchProjectWithTx(ctx context.Context, tx *sql.Tx, patch *ProjectPatch) (*Project, error)
}
diff --git a/backend/api/repository.go b/backend/api/repository.go
index 7ab9f988ee..6952fe0d98 100644
--- a/backend/api/repository.go
+++ b/backend/api/repository.go
@@ -18,6 +18,7 @@ type Repository struct {
// Related fields
VCSId int
+ VCS *VCS `jsonapi:"relation,vcs"`
ProjectId int
Project *Project `jsonapi:"relation,project"`
@@ -28,7 +29,7 @@ type Repository struct {
BaseDirectory string `jsonapi:"attr,baseDirectory"`
BranchFilter string `jsonapi:"attr,branchFilter"`
ExternalId string `jsonapi:"attr,externalId"`
- WebhookId string `jsonapi:"attr,webhookId"`
+ WebhookId string
// Because we normalize the data, thus we fetch below info from vcs table.
VCSName string `jsonapi:"attr,vcsName"`
VCSType VCSType `jsonapi:"attr,vcsType"`
diff --git a/backend/cmd/echo/main.go b/backend/cmd/echo/main.go
index 3f33a3cbd0..f4b2c239a5 100644
--- a/backend/cmd/echo/main.go
+++ b/backend/cmd/echo/main.go
@@ -60,7 +60,7 @@ func (m *Main) Run() error {
server.ActivityService = store.NewActivityService(m.l, db)
server.BookmarkService = store.NewBookmarkService(m.l, db)
server.VCSService = store.NewVCSService(m.l, db)
- server.RepositoryService = store.NewRepositoryService(m.l, db)
+ server.RepositoryService = store.NewRepositoryService(m.l, db, server.ProjectService)
m.server = server
if err := server.Run(); err != nil {
diff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csv
index 6e6467de2f..8713de584c 100644
--- a/backend/server/acl_casbin_policy_dba.csv
+++ b/backend/server/acl_casbin_policy_dba.csv
@@ -6,6 +6,8 @@ p, DBA, /project, POST
p, DBA, /project, GET
p, DBA, /project/{id}, GET
p, DBA, /project/{id}, PATCH
+p, DBA, /project/{id}/repository, GET
+p, DBA, /project/{id}/repository, POST
p, DBA, /project/{projectId}/member, POST
p, DBA, /project/{projectId}/member/{memberId}, PATCH
p, DBA, /project/{projectId}/member/{memberId}, DELETE
diff --git a/backend/server/acl_casbin_policy_developer.csv b/backend/server/acl_casbin_policy_developer.csv
index 4f6143f1ef..0c85731be6 100644
--- a/backend/server/acl_casbin_policy_developer.csv
+++ b/backend/server/acl_casbin_policy_developer.csv
@@ -6,6 +6,8 @@ p, DEVELOPER, /project, POST
p, DEVELOPER, /project, GET
p, DEVELOPER, /project/{id}, GET
p, DEVELOPER, /project/{id}, PATCH
+p, DEVELOPER, /project/{id}/repository, GET
+p, DEVELOPER, /project/{id}/repository, POST
p, DEVELOPER, /project/{projectId}/member, POST
p, DEVELOPER, /project/{projectId}/member/{memberId}, PATCH
p, DEVELOPER, /project/{projectId}/member/{memberId}, DELETE
diff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csv
index 53fe0de26d..054c518e05 100644
--- a/backend/server/acl_casbin_policy_owner.csv
+++ b/backend/server/acl_casbin_policy_owner.csv
@@ -11,6 +11,8 @@ p, OWNER, /project, POST
p, OWNER, /project, GET
p, OWNER, /project/{id}, GET
p, OWNER, /project/{id}, PATCH
+p, OWNER, /project/{id}/repository, GET
+p, OWNER, /project/{id}/repository, POST
p, OWNER, /project/{projectId}/member, POST
p, OWNER, /project/{projectId}/member/{memberId}, PATCH
p, OWNER, /project/{projectId}/member/{memberId}, DELETE
diff --git a/backend/server/project.go b/backend/server/project.go
index fe406e07d9..f9c4e29e68 100644
--- a/backend/server/project.go
+++ b/backend/server/project.go
@@ -122,6 +122,67 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
}
return nil
})
+
+ // When we link the repository with the project, we will also change the project workflow type to VCS
+ g.POST("/project/:projectId/repository", func(c echo.Context) error {
+ repositoryCreate := &api.RepositoryCreate{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, repositoryCreate); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create linked repository request").SetInternal(err)
+ }
+ repositoryCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
+ repository, err := s.RepositoryService.CreateRepository(context.Background(), repositoryCreate)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ECONFLICT {
+ return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Project %d has already linked repository", repositoryCreate.ProjectId))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to link project repository").SetInternal(err)
+ }
+
+ if err := s.ComposeRepositoryRelationship(context.Background(), repository, c.Get(getIncludeKey()).([]string)); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create project").SetInternal(err)
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, repository); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal link project repository response").SetInternal(err)
+ }
+ return nil
+ })
+
+ // Requires a separate API to return the repository, we do this because
+ // 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"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
+ }
+
+ repositoryFind := &api.RepositoryFind{
+ ProjectId: &id,
+ }
+ 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)
+ }
+
+ // 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), id)).SetInternal(err)
+ }
+
+ for _, repository := range list {
+ if err := s.ComposeRepositoryRelationship(context.Background(), repository, c.Get(getIncludeKey()).([]string)); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository relationship: %v", repository.Name)).SetInternal(err)
+ }
+ }
+
+ 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 nil
+ })
}
func (s *Server) ComposeProjectlById(ctx context.Context, id int, includeList []string) (*api.Project, error) {
diff --git a/backend/server/repository.go b/backend/server/repository.go
index 71e6cb8991..1c9d746441 100644
--- a/backend/server/repository.go
+++ b/backend/server/repository.go
@@ -19,6 +19,11 @@ func (s *Server) ComposeRepositoryRelationship(ctx context.Context, repository *
return err
}
+ repository.VCS, err = s.ComposeVCSById(context.Background(), repository.VCSId, includeList)
+ if err != nil {
+ return err
+ }
+
repository.Project, err = s.ComposeProjectlById(context.Background(), repository.ProjectId, includeList)
if err != nil {
return err
diff --git a/backend/server/vcs.go b/backend/server/vcs.go
index 5b9a4eb910..61b9b0fce0 100644
--- a/backend/server/vcs.go
+++ b/backend/server/vcs.go
@@ -68,10 +68,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
}
- vcsFind := &api.VCSFind{
- ID: &id,
- }
- vcs, err := s.VCSService.FindVCS(context.Background(), vcsFind)
+ vcs, err := s.ComposeVCSById(context.Background(), id, c.Get(getIncludeKey()).([]string))
if err != nil {
if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS ID not found: %d", id))
@@ -79,10 +76,6 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch vcs ID: %v", id)).SetInternal(err)
}
- if err := s.ComposeVCSRelationship(context.Background(), vcs, c.Get(getIncludeKey()).([]string)); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch created VCS relationship").SetInternal(err)
- }
-
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, vcs); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal vcs ID response: %v", id)).SetInternal(err)
@@ -157,7 +150,7 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
}
list, err := s.RepositoryService.FindRepositoryList(context.Background(), repositoryFind)
if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository for vcs ID: %v", id)).SetInternal(err)
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository list for vcs ID: %v", id)).SetInternal(err)
}
for _, repository := range list {
@@ -174,6 +167,22 @@ func (s *Server) registerVCSRoutes(g *echo.Group) {
})
}
+func (s *Server) ComposeVCSById(ctx context.Context, id int, includeList []string) (*api.VCS, error) {
+ vcsFind := &api.VCSFind{
+ ID: &id,
+ }
+ vcs, err := s.VCSService.FindVCS(ctx, vcsFind)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := s.ComposeVCSRelationship(ctx, vcs, includeList); err != nil {
+ return nil, err
+ }
+
+ return vcs, nil
+}
+
func (s *Server) ComposeVCSRelationship(ctx context.Context, vcs *api.VCS, includeList []string) error {
var err error
diff --git a/backend/store/project.go b/backend/store/project.go
index 8f6c5a7e47..05aa7949a4 100644
--- a/backend/store/project.go
+++ b/backend/store/project.go
@@ -2,6 +2,7 @@ package store
import (
"context"
+ "database/sql"
"fmt"
"strings"
@@ -91,7 +92,7 @@ func (s *ProjectService) PatchProject(ctx context.Context, patch *api.ProjectPat
}
defer tx.Rollback()
- project, err := patchProject(ctx, tx, patch)
+ project, err := patchProject(ctx, tx.Tx, patch)
if err != nil {
return nil, FormatError(err)
}
@@ -103,6 +104,12 @@ func (s *ProjectService) PatchProject(ctx context.Context, patch *api.ProjectPat
return project, nil
}
+// PatchProjectWithTx updates an existing project by ID.
+// Returns ENOTFOUND if project does not exist.
+func (s *ProjectService) PatchProjectWithTx(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch) (*api.Project, error) {
+ return patchProject(ctx, tx, patch)
+}
+
// createProject creates a new project.
func createProject(ctx context.Context, tx *Tx, create *api.ProjectCreate) (*api.Project, error) {
// Insert row into database.
@@ -209,7 +216,7 @@ func findProjectList(ctx context.Context, tx *Tx, find *api.ProjectFind) (_ []*a
}
// patchProject updates a project by ID. Returns the new state of the project after update.
-func patchProject(ctx context.Context, tx *Tx, patch *api.ProjectPatch) (*api.Project, error) {
+func patchProject(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch) (*api.Project, error) {
// Build UPDATE clause.
set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
if v := patch.RowStatus; v != nil {
@@ -221,6 +228,9 @@ func patchProject(ctx context.Context, tx *Tx, patch *api.ProjectPatch) (*api.Pr
if v := patch.Key; v != nil {
set, args = append(set, "`key` = ?"), append(args, *v)
}
+ if v := patch.WorkflowType; v != nil {
+ set, args = append(set, "`workflow_type` = ?"), append(args, *v)
+ }
args = append(args, patch.ID)
diff --git a/backend/store/repository.go b/backend/store/repository.go
index c370b91a35..29994b26e1 100644
--- a/backend/store/repository.go
+++ b/backend/store/repository.go
@@ -18,11 +18,13 @@ var (
type RepositoryService struct {
l *zap.Logger
db *DB
+
+ ProjectService api.ProjectService
}
// NewRepositoryService returns a new instance of RepositoryService.
-func NewRepositoryService(logger *zap.Logger, db *DB) *RepositoryService {
- return &RepositoryService{l: logger, db: db}
+func NewRepositoryService(logger *zap.Logger, db *DB, projectService api.ProjectService) *RepositoryService {
+ return &RepositoryService{l: logger, db: db, ProjectService: projectService}
}
// CreateRepository creates a new repository.
@@ -33,7 +35,7 @@ func (s *RepositoryService) CreateRepository(ctx context.Context, create *api.Re
}
defer tx.Rollback()
- repository, err := createRepository(ctx, tx, create)
+ repository, err := s.createRepository(ctx, tx, create)
if err != nil {
return nil, err
}
@@ -125,7 +127,18 @@ func (s *RepositoryService) DeleteRepository(ctx context.Context, delete *api.Re
}
// createRepository creates a new repository.
-func createRepository(ctx context.Context, tx *Tx, create *api.RepositoryCreate) (*api.Repository, error) {
+func (s *RepositoryService) createRepository(ctx context.Context, tx *Tx, create *api.RepositoryCreate) (*api.Repository, error) {
+ // Updates the project workflow_type to "VCS"
+ workflowType := api.VCS_WORKFLOW
+ projectPatch := api.ProjectPatch{
+ ID: create.ProjectId,
+ UpdaterId: create.CreatorId,
+ WorkflowType: &workflowType,
+ }
+ if _, err := s.ProjectService.PatchProjectWithTx(ctx, tx.Tx, &projectPatch); err != nil {
+ return nil, err
+ }
+
// Insert row into database.
row, err := tx.QueryContext(ctx, `
INSERT INTO repo (
@@ -192,6 +205,12 @@ func findRepositoryList(ctx context.Context, tx *Tx, find *api.RepositoryFind) (
if v := find.ID; v != nil {
where, args = append(where, "id = ?"), append(args, *v)
}
+ if v := find.VCSId; v != nil {
+ where, args = append(where, "vcs_id = ?"), append(args, *v)
+ }
+ if v := find.ProjectId; v != nil {
+ where, args = append(where, "project_id = ?"), append(args, *v)
+ }
rows, err := tx.QueryContext(ctx, `
SELECT
diff --git a/backend/store/seed/0030_project.sql b/backend/store/seed/0030_project.sql
index 05f6a6a4a7..7df37b2eba 100644
--- a/backend/store/seed/0030_project.sql
+++ b/backend/store/seed/0030_project.sql
@@ -14,7 +14,7 @@ VALUES
1001,
'project 1',
'PRJ1',
- 'UI'
+ 'VCS'
);
INSERT INTO
diff --git a/backend/store/seed/0160_vcs.sql b/backend/store/seed/0160_vcs.sql
index 4db18eb546..28c205ae09 100644
--- a/backend/store/seed/0160_vcs.sql
+++ b/backend/store/seed/0160_vcs.sql
@@ -21,4 +21,29 @@ VALUES
'http://gitlab.bytebase.com/api/v4',
'0d1f706e68e3bf22be6712752726a3eec2a9684ec098a9695015f484165ed922',
'77deb508304dd73fa9b6868d319e1832889c6fc8ea087f400e6efe35d7c6dd87'
+ );
+
+INSERT INTO
+ vcs (
+ id,
+ creator_id,
+ updater_id,
+ name,
+ `type`,
+ instance_url,
+ api_url,
+ application_id,
+ secret
+ )
+VALUES
+ (
+ 16002,
+ 1001,
+ 1001,
+ 'GitLab Bytebase2',
+ 'GITLAB_SELF_HOST',
+ 'http://gitlab.bytebase.com',
+ 'http://gitlab.bytebase.com/api/v4',
+ '0d1f706e68e3bf22be6712752726a3eec2a9684ec098a9695015f484165ed922',
+ '77deb508304dd73fa9b6868d319e1832889c6fc8ea087f400e6efe35d7c6dd87'
);
\ No newline at end of file
diff --git a/backend/store/sqlite.go b/backend/store/sqlite.go
index 82698758fd..0d264085ee 100644
--- a/backend/store/sqlite.go
+++ b/backend/store/sqlite.go
@@ -256,6 +256,8 @@ func FormatError(err error) error {
return bytebase.Errorf(bytebase.ECONFLICT, "data source name already exists")
case "UNIQUE constraint failed: bookmark.creator_id, bookmark.link":
return bytebase.Errorf(bytebase.ECONFLICT, "bookmark already exists")
+ case "UNIQUE constraint failed: repo.project_id":
+ return bytebase.Errorf(bytebase.ECONFLICT, "project has already linked repository")
default:
return err
}
diff --git a/frontend/src/components/ProjectVCSPanel.vue b/frontend/src/components/ProjectVCSPanel.vue
index cb048d7820..3176aea57f 100644
--- a/frontend/src/components/ProjectVCSPanel.vue
+++ b/frontend/src/components/ProjectVCSPanel.vue
@@ -1,16 +1,168 @@
<template>
- <RepositorySetupWizard />
+ <template v-if="state.showWizard">
+ <RepositorySetupWizard
+ :project="project"
+ @cancel="cancelWizard"
+ @finish="finishWizard"
+ />
+ </template>
+ <template v-else>
+ <!-- Use the persistent workflowType here -->
+ <template v-if="project.workflowType == 'UI'">
+ <div class="text-lg leading-6 font-medium text-main">
+ Current workflow
+ </div>
+ <div class="mt-4 flex flex-col space-y-4">
+ <div class="flex space-x-4">
+ <input
+ name="UI workflow"
+ tabindex="-1"
+ type="radio"
+ class="btn"
+ value="UI"
+ v-model="state.workflowType"
+ />
+ <div class="-mt-0.5">
+ <div class="textlabel">UI workflow (no version control)</div>
+ <div class="mt-1 textinfolabel">
+ Classic SQL Review workflow where the developer submits a SQL
+ review ticket directly from Bytebase and waits for the assigned
+ DBA or peer developer to review. Bytebase applies the SQL change
+ after review approved.
+ </div>
+ </div>
+ </div>
+ <div class="flex space-x-4">
+ <input
+ name="Version control workflow"
+ tabindex="-1"
+ type="radio"
+ class="btn"
+ value="VCS"
+ v-model="state.workflowType"
+ />
+ <div class="-mt-0.5">
+ <div class="textlabel">Version control workflow</div>
+ <div class="mt-1 textinfolabel">
+ Database migration scripts are stored in a git repository. To make
+ schema changes, a developer would create a migration script and
+ submit for review in the corresponding VCS such as GitLab. After
+ the script is approved and merged into the configured branch,
+ Bytebase will automatically kicks off the task to apply the new
+ schema change.
+ </div>
+ </div>
+ </div>
+ </div>
+ <template v-if="state.workflowType == 'VCS'">
+ <div class="mt-4 flex items-center justify-end">
+ <button
+ type="button"
+ class="btn-primary inline-flex justify-center py-2 px-2"
+ @click.prevent="enterWizard"
+ >
+ Config workflow
+ <svg
+ class="ml-1 w-5 h-5"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M9 5l7 7-7 7"
+ ></path>
+ </svg>
+ </button>
+ </div>
+ </template>
+ </template>
+ <template v-else-if="project.workflowType == 'VCS'">
+ <RepositoryDetail :repository="repository" />
+ </template>
+ </template>
</template>
<script lang="ts">
+import { reactive, watchEffect, watch } from "vue";
+import { computed, PropType } from "@vue/runtime-core";
import RepositorySetupWizard from "./RepositorySetupWizard.vue";
+import RepositoryDetail from "./RepositoryDetail.vue";
+import { Project, ProjectWorkflowType, Repository, UNKNOWN_ID } from "../types";
+import { useStore } from "vuex";
+
+interface LocalState {
+ workflowType: ProjectWorkflowType;
+ showWizard: boolean;
+}
export default {
name: "ProjectVCSPanel",
components: {
RepositorySetupWizard,
+ RepositoryDetail,
+ },
+ props: {
+ project: {
+ required: true,
+ type: Object as PropType<Project>,
+ },
+ },
+ async setup(props) {
+ const store = useStore();
+ const state = reactive<LocalState>({
+ workflowType: props.project.workflowType,
+ showWizard: false,
+ });
+
+ const prepareRepository = () => {
+ store.dispatch("repository/fetchRepositoryByProjectId", props.project.id);
+ };
+
+ watchEffect(prepareRepository);
+
+ watch(
+ () => props.project,
+ (cur, _) => {
+ state.workflowType = cur.workflowType;
+ }
+ );
+
+ const repository = computed((): Repository => {
+ return store.getters["repository/repositoryByProjectId"](
+ props.project.id
+ );
+ });
+
+ const enterWizard = () => {
+ state.showWizard = true;
+ };
+
+ const cancelWizard = () => {
+ state.workflowType = "UI";
+ state.showWizard = false;
+ };
+
+ const finishWizard = () => {
+ state.showWizard = false;
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: `Successfully enabled version control workflow for '${props.project.name}'`,
+ });
+ };
+
+ return {
+ state,
+ UNKNOWN_ID,
+ repository,
+ enterWizard,
+ cancelWizard,
+ finishWizard,
+ };
},
- props: {},
- async setup(props) {},
};
</script>
diff --git a/frontend/src/components/RepositoryConfigPanel.vue b/frontend/src/components/RepositoryConfigPanel.vue
index b129aa18f6..b3488f1141 100644
--- a/frontend/src/components/RepositoryConfigPanel.vue
+++ b/frontend/src/components/RepositoryConfigPanel.vue
@@ -1,23 +1,17 @@
<template>
- <div class="text-lg leading-6 font-medium text-control">Base directory</div>
- <BBTextField
- class="mt-2 w-full"
- :value="config.baseDirectory"
- @input="config.baseDirectory = $event.target.value"
- />
- <div class="mt-4 text-lg leading-6 font-medium text-control">Branch</div>
- <BBTextField
- class="mt-2 w-full"
- :placeholder="'Default branch (normally \'master\' or \'main\')'"
- :value="config.branchFilter"
- @input="config.branchFilter = $event.target.value"
+ <RepositoryForm
+ :vcsType="config.vcs.type"
+ :vcsName="config.vcs.name"
+ :repositoryInfo="config.repositoryInfo"
+ :repositoryConfig="config.repositoryConfig"
/>
</template>
<script lang="ts">
import { reactive } from "@vue/reactivity";
import { PropType } from "@vue/runtime-core";
-import { ProjectRepoConfig } from "../types";
+import RepositoryForm from "./RepositoryForm.vue";
+import { ProjectRepositoryConfig } from "../types";
interface LocalState {}
@@ -27,10 +21,10 @@ export default {
props: {
config: {
required: true,
- type: Object as PropType<ProjectRepoConfig>,
+ type: Object as PropType<ProjectRepositoryConfig>,
},
},
- components: {},
+ components: { RepositoryForm },
setup(props, { emit }) {
const state = reactive<LocalState>({});
diff --git a/frontend/src/components/RepositoryDetail.vue b/frontend/src/components/RepositoryDetail.vue
new file mode 100644
index 0000000000..5c317fd9b6
--- /dev/null
+++ b/frontend/src/components/RepositoryDetail.vue
@@ -0,0 +1,44 @@
+<template>
+ <RepositoryForm
+ :vcsType="repository.vcs.type"
+ :vcsName="repository.vcs.name"
+ :repositoryInfo="repositoryInfo"
+ :repositoryConfig="repositoryConfig"
+ />
+</template>
+
+<script lang="ts">
+import { PropType } from "vue";
+import { useRouter } from "vue-router";
+import RepositoryForm from "./RepositoryForm.vue";
+import { Repository, ExternalRepositoryInfo, RepositoryConfig } from "../types";
+
+export default {
+ name: "RepositoryDetail",
+ components: { RepositoryForm },
+ props: {
+ repository: {
+ required: true,
+ type: Object as PropType<Repository>,
+ },
+ },
+ setup(props, ctx) {
+ const router = useRouter();
+
+ const repositoryInfo: ExternalRepositoryInfo = {
+ externalId: props.repository.externalId,
+ name: props.repository.name,
+ fullPath: props.repository.fullPath,
+ webURL: props.repository.webURL,
+ defaultBranch: "",
+ };
+
+ const repositoryConfig: RepositoryConfig = {
+ baseDirectory: props.repository.baseDirectory,
+ branchFilter: props.repository.branchFilter,
+ };
+
+ return { repositoryInfo, repositoryConfig };
+ },
+};
+</script>
diff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vue
new file mode 100644
index 0000000000..4225f297ee
--- /dev/null
+++ b/frontend/src/components/RepositoryForm.vue
@@ -0,0 +1,124 @@
+<template>
+ <div class="space-y-4">
+ <div>
+ <div class="flex flex-row space-x-2 items-center">
+ <label for="gitprovider" class="textlabel"> Git provider </label>
+ <template v-if="vcsType.startsWith('GITLAB')">
+ <img class="h-4 w-auto" src="../assets/gitlab-logo.svg" />
+ </template>
+ </div>
+ <input
+ id="gitprovider"
+ name="gitprovider"
+ type="text"
+ class="textfield mt-1 w-full"
+ disabled="true"
+ :value="vcsName"
+ />
+ </div>
+ <div>
+ <div class="flex flex-row space-x-2 items-center">
+ <label for="repository" class="textlabel"> Repository </label>
+ <button
+ class="ml-1 btn-icon"
+ @click.prevent="window.open(urlfy(repositoryInfo.webURL), '_blank')"
+ >
+ <svg
+ class="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
+ ></path>
+ </svg>
+ </button>
+ </div>
+ <input
+ id="repository"
+ name="repository"
+ type="text"
+ class="textfield mt-1 w-full"
+ disabled="true"
+ :value="repositoryInfo.fullPath"
+ />
+ </div>
+ <div>
+ <div class="textlabel">Base directory</div>
+ <div class="mt-1 textinfolabel">
+ The directory and all its sub-directories that Bytebase will observe the
+ SQL file (.sql) change. If empty, then Bytebase will observe the entire
+ repository.
+ </div>
+ <input
+ id="basedirectory"
+ name="basedirectory"
+ type="text"
+ class="textfield mt-2 w-full"
+ v-model="repositoryConfig.baseDirectory"
+ />
+ </div>
+ <div>
+ <div class="textlabel">Branch</div>
+ <div class="mt-1 textinfolabel">
+ The branch where Bytebase will observe the SQL file (.sql) change. If
+ empty, then Bytebase will observe the default branch (normally it's the
+ 'master' or 'main' branch).
+ </div>
+ <input
+ id="branch"
+ name="branch"
+ type="text"
+ class="textfield mt-2 w-full"
+ placeholder="'Default branch (normally \'master\' or \'main\')'"
+ v-model="repositoryConfig.branchFilter"
+ />
+ <div v-if="vcsType == 'GITLAB_SELF_HOST'" class="mt-2 textinfolabel">
+ Tip: You can also use wildcard like 'feature/*'
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts">
+import { reactive } from "@vue/reactivity";
+import { PropType } from "@vue/runtime-core";
+import { ExternalRepositoryInfo, RepositoryConfig, VCSType } from "../types";
+
+interface LocalState {}
+
+export default {
+ name: "RepositoryForm",
+ props: {
+ vcsType: {
+ required: true,
+ type: Object as PropType<VCSType>,
+ },
+ vcsName: {
+ required: true,
+ type: Object as PropType<String>,
+ },
+ repositoryInfo: {
+ required: true,
+ type: Object as PropType<ExternalRepositoryInfo>,
+ },
+ repositoryConfig: {
+ required: true,
+ type: Object as PropType<RepositoryConfig>,
+ },
+ },
+ components: {},
+ setup(props, { emit }) {
+ const state = reactive<LocalState>({});
+
+ return {
+ state,
+ };
+ },
+};
+</script>
diff --git a/frontend/src/components/RepositorySelectionPanel.vue b/frontend/src/components/RepositorySelectionPanel.vue
index 7d8a037a99..e39fe6a586 100644
--- a/frontend/src/components/RepositorySelectionPanel.vue
+++ b/frontend/src/components/RepositorySelectionPanel.vue
@@ -1,12 +1,15 @@
<template>
- <div class="space-y-2 divide-y divide-block-border">
+ <BBAttention :description="attentionText" />
+ <div class="mt-4 space-y-2">
<div class="flex justify-end items-center">
<BBTableSearch
:placeholder="'Search repository'"
@change-text="(text) => changeSearchText(text)"
/>
</div>
- <div class="bg-white shadow overflow-hidden sm:rounded-md">
+ <div
+ class="bg-white overflow-hidden rounded-sm border border-control-border"
+ >
<ul class="divide-y divide-control-border">
<li
v-for="(repository, index) in repositoryList"
@@ -14,7 +17,7 @@
class="block hover:bg-control-bg-hover cursor-pointer"
@click.prevent="selectRepository(repository)"
>
- <div class="flex items-center px-4 py-4 sm:px-6">
+ <div class="flex items-center px-4 py-3">
<div class="min-w-0 flex-1 flex items-center">
{{ repository.fullPath }}
</div>
@@ -45,10 +48,10 @@
import { reactive } from "@vue/reactivity";
import { useStore } from "vuex";
import { computed, PropType, watchEffect } from "@vue/runtime-core";
-import { ExternalRepository, ProjectRepoConfig } from "../types";
+import { ExternalRepositoryInfo, ProjectRepositoryConfig } from "../types";
interface LocalState {
- repositoryList: ExternalRepository[];
+ repositoryList: ExternalRepositoryInfo[];
searchText: string;
}
@@ -58,7 +61,7 @@ export default {
props: {
config: {
required: true,
- type: Object as PropType<ProjectRepoConfig>,
+ type: Object as PropType<ProjectRepositoryConfig>,
},
},
components: {},
@@ -70,14 +73,16 @@ export default {
});
const prepareRepositoryList = () => {
- store
- .dispatch("gitlab/fetchProjectList", {
- vcs: props.config.vcs,
- token: props.config.accessToken,
- })
- .then((list) => {
- state.repositoryList = list;
- });
+ if (props.config.vcs.type == "GITLAB_SELF_HOST") {
+ store
+ .dispatch("gitlab/fetchProjectList", {
+ vcs: props.config.vcs,
+ token: props.config.accessToken,
+ })
+ .then((list) => {
+ state.repositoryList = list;
+ });
+ }
};
watchEffect(prepareRepositoryList);
@@ -86,13 +91,22 @@ export default {
if (state.searchText == "") {
return state.repositoryList;
}
- return state.repositoryList.filter((repository: ExternalRepository) => {
- return repository.fullPath.toLowerCase().includes(state.searchText);
- });
+ return state.repositoryList.filter(
+ (repository: ExternalRepositoryInfo) => {
+ return repository.fullPath.toLowerCase().includes(state.searchText);
+ }
+ );
+ });
+
+ const attentionText = computed((): string => {
+ if (props.config.vcs.type == "GITLAB_SELF_HOST") {
+ return "Bytebase only lists GitLab projects where you have at least the maintainer role, which allows to configure the project webhook to observe the code push event.";
+ }
+ return "";
});
- const selectRepository = (repository: ExternalRepository) => {
- props.config.repository = repository;
+ const selectRepository = (repository: ExternalRepositoryInfo) => {
+ props.config.repositoryInfo = repository;
emit("next");
};
@@ -104,6 +118,7 @@ export default {
state,
selectRepository,
repositoryList,
+ attentionText,
changeSearchText,
};
},
diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vue
index 697a346077..e9d0082d48 100644
--- a/frontend/src/components/RepositorySetupWizard.vue
+++ b/frontend/src/components/RepositorySetupWizard.vue
@@ -1,32 +1,51 @@
<template>
- <BBStepTab
- :stepItemList="stepList"
- @try-change-step="tryChangeStep"
- @try-finish="tryFinishSetup"
- >
- <template v-slot:0="{ next }">
- <RepositoryVCSPanel :config="state.config" @next="next()" />
- </template>
- <template v-slot:1="{ next }">
- <RepositorySelectionPanel :config="state.config" @next="next()" />
- </template>
- <template v-slot:2>
- <RepositoryConfigPanel :config="state.config" />
- </template>
- </BBStepTab>
+ <div>
+ <BBStepTab
+ :stepItemList="stepList"
+ @try-change-step="tryChangeStep"
+ @try-finish="tryFinishSetup"
+ @cancel="cancel"
+ >
+ <template v-slot:0="{ next }">
+ <RepositoryVCSPanel :config="state.config" @next="next()" />
+ </template>
+ <template v-slot:1="{ next }">
+ <RepositorySelectionPanel :config="state.config" @next="next()" />
+ </template>
+ <template v-slot:2>
+ <RepositoryConfigPanel :config="state.config" />
+ </template>
+ </BBStepTab>
+ </div>
</template>
<script lang="ts">
import { reactive } from "@vue/reactivity";
+import { PropType } from "@vue/runtime-core";
import { BBStepTabItem } from "../bbkit/types";
import { useStore } from "vuex";
+import { useRouter } from "vue-router";
+import isEmpty from "lodash-es/isEmpty";
import RepositoryVCSPanel from "./RepositoryVCSPanel.vue";
import RepositorySelectionPanel from "./RepositorySelectionPanel.vue";
import RepositoryConfigPanel from "./RepositoryConfigPanel.vue";
-import { ProjectRepoConfig, Repository, unknown, VCS } from "../types";
+import {
+ Project,
+ ProjectRepositoryConfig,
+ Repository,
+ RepositoryCreate,
+ unknown,
+ VCS,
+} from "../types";
+import { projectSlug } from "../utils";
+
+const CHOOSE_PROVIDER_STEP = 0;
+const CHOOSE_REPOSITORY_STEP = 1;
+const CONFIGURE_DEPLOY_STEP = 2;
interface LocalState {
- config: ProjectRepoConfig;
+ config: ProjectRepositoryConfig;
+ currentStep: number;
}
const stepList: BBStepTabItem[] = [
@@ -37,47 +56,98 @@ const stepList: BBStepTabItem[] = [
export default {
name: "RepositorySetupWizard",
+ emits: ["cancel", "finish"],
components: {
RepositoryVCSPanel,
RepositorySelectionPanel,
RepositoryConfigPanel,
},
- setup(props, ctx) {
+ props: {
+ project: {
+ required: true,
+ type: Object as PropType<Project>,
+ },
+ },
+ setup(props, { emit }) {
+ const router = useRouter();
const store = useStore();
const state = reactive<LocalState>({
config: {
vcs: unknown("VCS") as VCS,
code: "",
accessToken: "",
- repository: unknown("REPOSITORY") as Repository,
- baseDirectory: "",
- branchFilter: "",
+ repositoryInfo: {
+ externalId: "",
+ name: "",
+ fullPath: "",
+ webURL: "",
+ defaultBranch: "",
+ },
+ repositoryConfig: {
+ baseDirectory: "",
+ branchFilter: "",
+ },
},
+ currentStep: CHOOSE_PROVIDER_STEP,
});
- const tryChangeStep = (oldStep: number, newStep: number) => {
- console.log("select step", newStep);
+ const tryChangeStep = (
+ oldStep: number,
+ newStep: number,
+ allowChangeCallback: () => void
+ ) => {
+ state.currentStep = newStep;
+ allowChangeCallback();
};
const tryFinishSetup = (allowFinishCallback: () => void) => {
- console.log("finish", state.config);
store
.dispatch("gitlab/createWebhook", {
vcs: state.config.vcs,
- projectId: state.config.repository.externalId,
- branchFilter: state.config.branchFilter,
+ projectId: state.config.repositoryInfo.externalId,
+ branchFilter: state.config.repositoryConfig.branchFilter,
token: state.config.accessToken,
})
- .then((createdHook) => {
- allowFinishCallback();
+ .then((createdWebhookId) => {
+ const repositoryCreate: RepositoryCreate = {
+ vcsId: state.config.vcs.id,
+ projectId: props.project.id,
+ name: state.config.repositoryInfo.name,
+ fullPath: state.config.repositoryInfo.fullPath,
+ webURL: state.config.repositoryInfo.webURL,
+ baseDirectory: state.config.repositoryConfig.baseDirectory,
+ branchFilter: isEmpty(state.config.repositoryConfig.branchFilter)
+ ? state.config.repositoryInfo.defaultBranch
+ : state.config.repositoryConfig.branchFilter,
+ externalId: state.config.repositoryInfo.externalId,
+ webhookId: createdWebhookId,
+ };
+ store
+ .dispatch("repository/createRepository", repositoryCreate)
+ .then(() => {
+ allowFinishCallback();
+ emit("finish");
+ });
});
};
+ const cancel = () => {
+ emit("cancel");
+ router.push({
+ name: "workspace.project.detail",
+ params: {
+ projectSlug: projectSlug(props.project),
+ },
+ hash: "#version-control",
+ });
+ };
+
return {
state,
stepList,
tryChangeStep,
tryFinishSetup,
+ cancel,
};
},
};
diff --git a/frontend/src/components/RepositoryVCSPanel.vue b/frontend/src/components/RepositoryVCSPanel.vue
index cd18cac26f..f61437d452 100644
--- a/frontend/src/components/RepositoryVCSPanel.vue
+++ b/frontend/src/components/RepositoryVCSPanel.vue
@@ -1,15 +1,36 @@
<template>
- <div v-for="(vcs, index) in vcsList" :key="index">
- <button
- type="button"
- class="btn-normal items-center space-x-2"
- @click.prevent="selectVCS(vcs)"
- >
- <template v-if="vcs.type.startsWith('GITLAB')">
- <img class="h-6 w-auto" src="../assets/gitlab-logo.svg" />
- </template>
- <span>{{ vcs.name }}</span>
- </button>
+ <div class="textlabel">
+ Choose the Git provider where your database schema scripts (.sql) are
+ hosted. When you push the scripts change to the Git repository, Bytebase
+ will automatically applies the script change to the database.
+ </div>
+ <div class="mt-4 flex flex-wrap">
+ <template v-for="(vcs, index) in vcsList" :key="index">
+ <button
+ type="button"
+ class="btn-normal items-center space-x-2 mx-2 my-2"
+ @click.prevent="selectVCS(vcs)"
+ >
+ <template v-if="vcs.type.startsWith('GITLAB')">
+ <img class="h-6 w-auto" src="../assets/gitlab-logo.svg" />
+ </template>
+ <span>{{ vcs.name }}</span>
+ </button>
+ </template>
+ </div>
+ <div class="mt-2 textinfolabel">
+ <template v-if="isCurrentUserOwner">
+ Visit
+ <router-link class="normal-link" to="/setting/version-control"
+ >Workspace Version Control</router-link
+ >
+ setting to add more Git providers.
+ </template>
+ <template v-else>
+ Contact your Bytebase owner if you want other Git providers to appear
+ here. Bytebase currently supports self-host GitLab EE/CE, and plan to add
+ GitLab.com, GitHub Enterprise and GitHub.com later.
+ </template>
</div>
</template>
@@ -28,10 +49,11 @@ import {
OAuthWindowEvent,
OAuthWindowEventPayload,
openWindowForOAuth,
- ProjectRepoConfig,
+ ProjectRepositoryConfig,
redirectURL,
VCS,
} from "../types";
+import { isOwner } from "../utils";
interface LocalState {
selectedVCS?: VCS;
@@ -43,7 +65,7 @@ export default {
props: {
config: {
required: true,
- type: Object as PropType<ProjectRepoConfig>,
+ type: Object as PropType<ProjectRepositoryConfig>,
},
},
components: {},
@@ -51,6 +73,8 @@ export default {
const store = useStore();
const state = reactive<LocalState>({});
+ const currentUser = computed(() => store.getters["auth/currentUser"]());
+
const prepareVCSList = () => {
store.dispatch("vcs/fetchVCSList");
};
@@ -94,6 +118,10 @@ export default {
window.removeEventListener(OAuthWindowEvent, eventListener);
});
+ const isCurrentUserOwner = computed(() => {
+ return isOwner(currentUser.value.role);
+ });
+
const selectVCS = (vcs: VCS) => {
state.selectedVCS = vcs;
const newWindow = openWindowForOAuth(
@@ -107,7 +135,9 @@ export default {
return {
state,
+ currentUser,
vcsList,
+ isCurrentUserOwner,
selectVCS,
};
},
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index 8193cfd9f1..6197311590 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -20,6 +20,7 @@ import pipeline from "./modules/pipeline";
import stage from "./modules/stage";
import task from "./modules/task";
import vcs from "./modules/vcs";
+import repository from "./modules/repository";
import gitlab from "./modules/gitlab";
// Following states are persisted in local storage
@@ -56,6 +57,7 @@ export const store: Store<any> = createStore({
stage,
task,
vcs,
+ repository,
gitlab,
uistate,
router,
diff --git a/frontend/src/store/modules/gitlab.ts b/frontend/src/store/modules/gitlab.ts
index c37be3b78f..f845646563 100644
--- a/frontend/src/store/modules/gitlab.ts
+++ b/frontend/src/store/modules/gitlab.ts
@@ -1,17 +1,18 @@
import axios from "axios";
-import { ExternalRepository, VCS, OAuthConfig } from "../../types";
+import { ExternalRepositoryInfo, VCS, OAuthConfig } from "../../types";
const GITLAB_API_PATH = "api/v4";
const GITLAB_WEBHOOK_PATH = "hook/gitlab";
const getters = {};
-function convertGitLabProject(project: any): ExternalRepository {
+function convertGitLabProject(project: any): ExternalRepositoryInfo {
return {
externalId: project.id.toString(),
name: project.name,
fullPath: project.path_with_namespace,
webURL: project.web_url,
+ defaultBranch: project.default_branch,
};
}
@@ -41,7 +42,7 @@ const actions = {
async fetchProjectList(
{}: any,
{ vcs, token }: { vcs: VCS; token: string }
- ): Promise<ExternalRepository[]> {
+ ): Promise<ExternalRepositoryInfo[]> {
console.log(
"req",
`${vcs.instanceURL}/${GITLAB_API_PATH}/projects?membership=true&simple=true`
diff --git a/frontend/src/store/modules/project.ts b/frontend/src/store/modules/project.ts
index 6d193d244c..9c9996ee3b 100644
--- a/frontend/src/store/modules/project.ts
+++ b/frontend/src/store/modules/project.ts
@@ -43,6 +43,7 @@ function convert(
createdTs: attrs.createdTs,
updatedTs: attrs.updatedTs,
memberList: [],
+ workflowType: attrs.workflowType,
};
const memberList: ProjectMember[] = [];
diff --git a/frontend/src/store/modules/repository.ts b/frontend/src/store/modules/repository.ts
new file mode 100644
index 0000000000..58e972e6df
--- /dev/null
+++ b/frontend/src/store/modules/repository.ts
@@ -0,0 +1,179 @@
+import axios from "axios";
+import {
+ VCSId,
+ RepositoryState,
+ ResourceObject,
+ ResourceIdentifier,
+ unknown,
+ Principal,
+ Repository,
+ RepositoryCreate,
+ Project,
+ ProjectId,
+ VCS,
+} from "../../types";
+
+function convert(
+ respository: ResourceObject,
+ includedList: ResourceObject[],
+ rootGetters: any
+): Repository {
+ const creator = respository.attributes.creator as Principal;
+ const updater = respository.attributes.updater as Principal;
+
+ const vcsId = (respository.relationships!.vcs.data as ResourceIdentifier).id;
+ let vcs: VCS = unknown("VCS") as VCS;
+ vcs.id = parseInt(vcsId);
+
+ const projectId = (
+ respository.relationships!.project.data as ResourceIdentifier
+ ).id;
+ let project: Project = unknown("PROJECT") as Project;
+ project.id = parseInt(projectId);
+
+ for (const item of includedList || []) {
+ if (item.type == "vcs" && item.id == vcsId) {
+ vcs = rootGetters["vcs/convert"](item);
+ }
+ if (item.type == "project" && item.id == projectId) {
+ project = rootGetters["project/convert"](item, includedList);
+ }
+ }
+
+ return {
+ ...(respository.attributes as Omit<
+ Repository,
+ "id" | "creator" | "updater" | "vcs" | "project"
+ >),
+ id: parseInt(respository.id),
+ creator,
+ updater,
+ vcs,
+ project,
+ };
+}
+
+const state: () => RepositoryState = () => ({
+ repositoryListByVCSId: new Map(),
+ repositoryByProjectId: new Map(),
+});
+
+const getters = {
+ repositoryListByVCSId:
+ (state: RepositoryState) =>
+ (vcsId: VCSId): Repository[] => {
+ return state.repositoryListByVCSId.get(vcsId) || [];
+ },
+
+ repositoryByProjectId:
+ (state: RepositoryState) =>
+ (projectId: ProjectId): Repository => {
+ return (
+ state.repositoryByProjectId.get(projectId) ||
+ (unknown("REPOSITORY") as Repository)
+ );
+ },
+};
+
+const actions = {
+ async createRepository(
+ { dispatch, commit, rootGetters }: any,
+ repositoryCreate: RepositoryCreate
+ ): Promise<Repository> {
+ const data = (
+ await axios.post(
+ `/api/project/${repositoryCreate.projectId}/repository`,
+ {
+ data: {
+ type: "RepositoryCreate",
+ attributes: repositoryCreate,
+ },
+ }
+ )
+ ).data;
+
+ const createdRepository = convert(data.data, data.included, rootGetters);
+ commit("setRepositoryByProjectId", {
+ projectId: repositoryCreate.projectId,
+ repository: createdRepository,
+ });
+
+ // Refetch the project as the project workflow type has been updated to "VCS"
+ dispatch("project/fetchProjectById", repositoryCreate.projectId, {
+ root: true,
+ });
+
+ return createdRepository;
+ },
+
+ async fetchRepositoryListByVCSId(
+ { commit, rootGetters }: any,
+ vcsId: VCSId
+ ): Promise<Repository[]> {
+ const data = (await axios.get(`/api/vcs/${vcsId}/repository`)).data;
+
+ const repositoryList = data.data.map((repository: ResourceObject) => {
+ return convert(repository, data.included, rootGetters);
+ });
+
+ commit("setRepositoryListByVCSId", { vcsId, repositoryList });
+ return repositoryList;
+ },
+
+ async fetchRepositoryByProjectId(
+ { commit, rootGetters }: any,
+ projectId: ProjectId
+ ): Promise<Repository> {
+ const data = (await axios.get(`/api/project/${projectId}/repository`)).data;
+ const repositoryList = data.data.map((repository: ResourceObject) => {
+ return convert(repository, data.included, rootGetters);
+ });
+
+ // Expect server to return at most one item, otherwise it will throw error
+ if (repositoryList.length > 0) {
+ commit("setRepositoryByProjectId", {
+ projectId,
+ repository: repositoryList[0],
+ });
+ return repositoryList[0];
+ }
+
+ return unknown("REPOSITORY") as Repository;
+ },
+};
+
+const mutations = {
+ setRepositoryListByVCSId(
+ state: RepositoryState,
+ {
+ vcsId,
+ repositoryList,
+ }: {
+ vcsId: VCSId;
+ repositoryList: Repository[];
+ }
+ ) {
+ state.repositoryListByVCSId.set(vcsId, repositoryList);
+ },
+
+ setRepositoryByProjectId(
+ state: RepositoryState,
+ {
+ projectId,
+ repository,
+ }: {
+ projectId: ProjectId;
+ repository: Repository;
+ }
+ ) {
+ state.repositoryByProjectId.set(projectId, repository);
+ },
+};
+
+export default {
+ namespaced: true,
+ state,
+ getters,
+ actions,
+ mutations,
+};
diff --git a/frontend/src/store/modules/vcs.ts b/frontend/src/store/modules/vcs.ts
index 629452d003..2f1cd3f1d7 100644
--- a/frontend/src/store/modules/vcs.ts
+++ b/frontend/src/store/modules/vcs.ts
@@ -15,38 +15,6 @@ import {
Project,
} from "../../types";
-function convertRepository(
- respository: ResourceObject,
- includedList: ResourceObject[],
- rootGetters: any
-): Repository {
- const creator = respository.attributes.creator as Principal;
- const updater = respository.attributes.updater as Principal;
-
- const projectId = (
- respository.relationships!.project.data as ResourceIdentifier
- ).id;
- let project: Project = unknown("PROJECT") as Project;
- project.id = parseInt(projectId);
-
- for (const item of includedList || []) {
- if (item.type == "project" && item.id == projectId) {
- project = rootGetters["project/convert"](item, includedList);
- }
- }
-
- return {
- ...(respository.attributes as Omit<
- Repository,
- "id" | "creator" | "updater" | "project"
- >),
- id: parseInt(respository.id),
- creator,
- updater,
- project,
- };
-}
-
function convert(vcs: ResourceObject): VCS {
const creator = vcs.attributes.creator as Principal;
const updater = vcs.attributes.updater as Principal;
@@ -64,6 +32,12 @@ const state: () => VCSState = () => ({
});
const getters = {
+ convert:
+ (state: VCSState, getters: any, rootState: any, rootGetters: any) =>
+ (vcs: ResourceObject): VCS => {
+ return convert(vcs);
+ },
+
vcsList: (state: VCSState) => (): VCS[] => {
const list = [];
for (const [_, vcs] of state.vcsById) {
@@ -83,12 +57,6 @@ const getters = {
return state.vcsById.get(vcsId) || (unknown("VCS") as VCS);
},
-
- repositoryListByVCSId:
- (state: VCSState) =>
- (vcsId: VCSId): Repository[] => {
- return state.repositoryListByVCSId.get(vcsId) || [];
- },
};
const actions = {
@@ -171,17 +139,6 @@ const actions = {
commit("deleteVCSById", vcsId);
},
-
- async fetchRepositoryListByVCS({ commit, rootGetters }: any, vcs: VCS) {
- const data = (await axios.get(`/api/vcs/${vcs.id}/repository`)).data;
-
- const repositoryList = data.data.map((repository: ResourceObject) => {
- return convertRepository(repository, data.included, rootGetters);
- });
-
- commit("setRepositoryListByVCSId", { vcsId: vcs.id, repositoryList });
- return repositoryList;
- },
};
const mutations = {
@@ -207,19 +164,6 @@ const mutations = {
deleteVCSById(state: VCSState, vcsId: VCSId) {
state.vcsById.delete(vcsId);
},
-
- setRepositoryListByVCSId(
- state: VCSState,
- {
- vcsId,
- repositoryList,
- }: {
- vcsId: VCSId;
- repositoryList: Repository[];
- }
- ) {
- state.repositoryListByVCSId.set(vcsId, repositoryList);
- },
};
export default {
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index c8a3236806..83af896f9a 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -159,6 +159,7 @@ export const unknown = (
createdTs: 0,
updatedTs: 0,
memberList: [],
+ workflowType: "UI",
};
const UNKNOWN_PROJECT_MEMBER: ProjectMember = {
@@ -324,11 +325,14 @@ export const unknown = (
updater: UNKNOWN_PRINCIPAL,
createdTs: 0,
updatedTs: 0,
+ vcs: UNKNOWN_VCS,
project: UNKNOWN_PROJECT,
- externalId: UNKNOWN_ID.toString(),
name: "",
fullPath: "",
webURL: "",
+ baseDirectory: "",
+ branchFilter: "",
+ externalId: UNKNOWN_ID.toString(),
};
switch (type) {
@@ -433,6 +437,7 @@ export const empty = (
createdTs: 0,
updatedTs: 0,
memberList: [],
+ workflowType: "UI",
};
const EMPTY_PROJECT_MEMBER: ProjectMember = {
@@ -598,11 +603,14 @@ export const empty = (
updater: EMPTY_PRINCIPAL,
createdTs: 0,
updatedTs: 0,
+ vcs: EMPTY_VCS,
project: EMPTY_PROJECT,
- externalId: EMPTY_ID.toString(),
name: "",
fullPath: "",
webURL: "",
+ baseDirectory: "",
+ branchFilter: "",
+ externalId: EMPTY_ID.toString(),
};
switch (type) {
diff --git a/frontend/src/types/project.ts b/frontend/src/types/project.ts
index 491816de69..caff7187b4 100644
--- a/frontend/src/types/project.ts
+++ b/frontend/src/types/project.ts
@@ -1,11 +1,13 @@
import { RowStatus } from "./common";
import { MemberId, PrincipalId, ProjectId } from "./id";
import { Principal } from "./principal";
-import { ExternalRepository, Repository } from "./repository";
+import { ExternalRepositoryInfo, RepositoryConfig } from "./repository";
import { VCS } from "./vcs";
export type ProjectRoleType = "OWNER" | "DEVELOPER";
+export type ProjectWorkflowType = "UI" | "VCS";
+
// Project
export type Project = {
id: ProjectId;
@@ -23,6 +25,7 @@ export type Project = {
// Returns the member list directly because we need it quite frequently in order
// to do various access check.
memberList: ProjectMember[];
+ workflowType: ProjectWorkflowType;
};
export type ProjectCreate = {
@@ -79,11 +82,10 @@ export type ProjectMemberPatch = {
role: ProjectRoleType;
};
-export type ProjectRepoConfig = {
+export type ProjectRepositoryConfig = {
vcs: VCS;
code: string;
accessToken: string;
- repository: ExternalRepository;
- baseDirectory: string;
- branchFilter: string;
+ repositoryInfo: ExternalRepositoryInfo;
+ repositoryConfig: RepositoryConfig;
};
diff --git a/frontend/src/types/repository.ts b/frontend/src/types/repository.ts
index b4b917cee9..1f63cd2999 100644
--- a/frontend/src/types/repository.ts
+++ b/frontend/src/types/repository.ts
@@ -1,6 +1,7 @@
-import { RepositoryId } from "./id";
+import { RepositoryId, VCSId, ProjectId } from "./id";
import { Principal } from "./principal";
import { Project } from "./project";
+import { VCS } from "./vcs";
export type Repository = {
id: RepositoryId;
@@ -12,20 +13,43 @@ export type Repository = {
updatedTs: number;
// Related fields
+ vcs: VCS;
project: Project;
// Domain specific fields
- // e.g. In GitLab, this is the corresponding project id.
- externalId: string;
// e.g. sample-project
name: string;
// e.g. bytebase/sample-project
fullPath: string;
// e.g. http://gitlab.bytebase.com/bytebase/sample-project
webURL: string;
+ baseDirectory: string;
+ branchFilter: string;
+ // e.g. In GitLab, this is the corresponding project id.
+ externalId: string;
+};
+
+export type RepositoryCreate = {
+ // Related fields
+ vcsId: VCSId;
+ projectId: ProjectId;
+
+ // Domain specific fields
+ name: string;
+ fullPath: string;
+ webURL: string;
+ baseDirectory: string;
+ branchFilter: string;
+ externalId: string;
+ webhookId: string;
+};
+
+export type RepositoryConfig = {
+ baseDirectory: string;
+ branchFilter: string;
};
-export type ExternalRepository = {
+export type ExternalRepositoryInfo = {
// e.g. In GitLab, this is the corresponding project id. e.g. 123
externalId: string;
// e.g. sample-project
@@ -34,4 +58,6 @@ export type ExternalRepository = {
fullPath: string;
// e.g. http://gitlab.bytebase.com/bytebase/sample-project
webURL: string;
+ // e.g. master
+ defaultBranch: string;
};
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index 9c4714bbed..00db676d5e 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -101,7 +101,13 @@ export interface TableState {
export interface VCSState {
vcsById: Map<VCSId, VCS>;
+}
+
+export interface RepositoryState {
+ // repositoryListByVCSId are used in workspace version control panel, while repositoryByProjectId are used in project version control panel.
+ // Because they are used separately, so we don't need to worry about repository inconsistency issue betweem them.
repositoryListByVCSId: Map<VCSId, Repository[]>;
+ repositoryByProjectId: Map<ProjectId, Repository>;
}
export interface NotificationState {
diff --git a/frontend/src/views/ProjectDetail.vue b/frontend/src/views/ProjectDetail.vue
index f77afe6149..6c6102fcc0 100644
--- a/frontend/src/views/ProjectDetail.vue
+++ b/frontend/src/views/ProjectDetail.vue
@@ -40,7 +40,7 @@
</div>
</div>
<template v-else-if="state.selectedIndex == VERSION_CONTROL_TAB">
- <ProjectVCSPanel />
+ <ProjectVCSPanel :project="project" />
</template>
<template v-else-if="state.selectedIndex == SETTING_TAB">
<div class="max-w-3xl mx-auto space-y-4">
diff --git a/frontend/src/views/SettingWorkspaceVCSDetail.vue b/frontend/src/views/SettingWorkspaceVCSDetail.vue
index b40f34ee2d..49165b20cd 100644
--- a/frontend/src/views/SettingWorkspaceVCSDetail.vue
+++ b/frontend/src/views/SettingWorkspaceVCSDetail.vue
@@ -203,7 +203,7 @@ export default {
};
const prepareRepositoryList = () => {
- store.dispatch("vcs/fetchRepositoryListByVCS", vcs.value);
+ store.dispatch("repository/fetchRepositoryListByVCSId", vcs.value.id);
};
watchEffect(prepareRepositoryList);
@@ -216,7 +216,7 @@ export default {
});
const repositoryList = computed(() =>
- store.getters["vcs/repositoryListByVCSId"](vcs.value.id)
+ store.getters["repository/repositoryListByVCSId"](vcs.value.id)
);
const allowUpdate = computed(() => {