Skip to content

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

chore: update integration test for vcs sql review (#3069)

ecmadaofdd2e5e1ff30
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index db2f814d4d..41a68e41e3 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -888,17 +888,20 @@ func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, oauthCtx co
return prFiles, nil
}
-type githubBranchCreate struct {
+// BranchCreate is the API message to create the branch.
+type BranchCreate struct {
Ref string `json:"ref"`
SHA string `json:"sha"`
}
-type githubBranch struct {
+// Branch is the API message for GitHub branch.
+type Branch struct {
Ref string `json:"ref"`
- Object referenceObject `json:"object"`
+ Object ReferenceObject `json:"object"`
}
-type referenceObject struct {
+// ReferenceObject is the reference for the GitHub branch.
+type ReferenceObject struct {
SHA string `json:"sha"`
}
@@ -936,7 +939,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
)
}
- res := new(githubBranch)
+ res := new(Branch)
if err := json.Unmarshal([]byte(body), res); err != nil {
return nil, err
}
@@ -957,7 +960,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
// Docs: https://docs.github.com/en/rest/git/refs#create-a-reference
func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
body, err := json.Marshal(
- githubBranchCreate{
+ BranchCreate{
Ref: fmt.Sprintf("refs/heads/%s", branch.Name),
SHA: branch.LastCommitID,
},
@@ -1000,7 +1003,8 @@ func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContex
return nil
}
-type githubPullRequest struct {
+// PullRequest is the API message for GitHub pull request.
+type PullRequest struct {
HTMLURL string `json:"html_url"`
}
@@ -1044,7 +1048,7 @@ func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthC
)
}
- var res githubPullRequest
+ var res PullRequest
if err := json.Unmarshal([]byte(resp), &res); err != nil {
return nil, err
}
@@ -1054,7 +1058,8 @@ func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthC
}, nil
}
-type environmentVariable struct {
+// RepositorySecretUpdate is the API message to update the repository secret.
+type RepositorySecretUpdate struct {
EncryptedValue string `json:"encrypted_value"`
KeyID string `json:"key_id"`
}
@@ -1075,7 +1080,7 @@ func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx commo
}
body, err := json.Marshal(
- environmentVariable{
+ RepositorySecretUpdate{
KeyID: publicKey.KeyID,
EncryptedValue: encryptValue,
},
@@ -1166,7 +1171,8 @@ func encryptEnvironmentVariable(publicKey, value string) (string, error) {
return base64.StdEncoding.EncodeToString(out), nil
}
-type repositoryPublicKey struct {
+// RepositorySecret is the secret for repository.
+type RepositorySecret struct {
KeyID string `json:"key_id"`
Key string `json:"key"`
}
@@ -1174,7 +1180,7 @@ type repositoryPublicKey struct {
// getRepositoryPublicKey returns the public key in the GitHub repository.
//
// https://docs.github.com/en/rest/actions/secrets#get-a-repository-public-key
-func (p *Provider) getRepositoryPublicKey(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string) (*repositoryPublicKey, error) {
+func (p *Provider) getRepositoryPublicKey(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string) (*RepositorySecret, error) {
url := fmt.Sprintf("%s/repos/%s/actions/secrets/public-key", p.APIURL(instanceURL), repositoryID)
code, _, body, err := oauth.Get(
ctx,
@@ -1205,7 +1211,7 @@ func (p *Provider) getRepositoryPublicKey(ctx context.Context, oauthCtx common.O
)
}
- res := new(repositoryPublicKey)
+ res := new(RepositorySecret)
if err := json.Unmarshal([]byte(body), res); err != nil {
return nil, err
}
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index 32d8f45f03..ea08b0e277 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -821,17 +821,20 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.Oaut
return res, nil
}
-type gitlabBranch struct {
+// Branch is the API message for GitLab branch.
+type Branch struct {
Name string `json:"name"`
Commit Commit `json:"commit"`
}
-type gitlabBranchCreate struct {
+// BranchCreate is the API message to create the branch.
+type BranchCreate struct {
Branch string `json:"branch"`
Ref string `json:"ref"`
}
-type gitlabMergeRequestCreate struct {
+// MergeRequestCreate is the API message to create the merge request.
+type MergeRequestCreate struct {
Title string `json:"title"`
Description string `json:"description"`
SourceBranch string `json:"source_branch"`
@@ -873,7 +876,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
)
}
- branch := new(gitlabBranch)
+ branch := new(Branch)
if err := json.Unmarshal([]byte(body), branch); err != nil {
return nil, err
}
@@ -889,7 +892,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext,
// Docs: https://docs.gitlab.com/ee/api/branches.html#create-repository-branch
func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
body, err := json.Marshal(
- gitlabBranchCreate{
+ BranchCreate{
Branch: branch.Name,
Ref: branch.LastCommitID,
},
@@ -932,7 +935,8 @@ func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContex
return nil
}
-type gitlabMergeRequest struct {
+// MergeRequest is the API message for GitLab merge request.
+type MergeRequest struct {
WebURL string `json:"web_url"`
}
@@ -941,7 +945,7 @@ type gitlabMergeRequest struct {
// Docs: https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
body, err := json.Marshal(
- gitlabMergeRequestCreate{
+ MergeRequestCreate{
Title: pullRequestCreate.Title,
Description: pullRequestCreate.Body,
SourceBranch: pullRequestCreate.Head,
@@ -984,7 +988,7 @@ func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthC
)
}
- var res gitlabMergeRequest
+ var res MergeRequest
if err := json.Unmarshal([]byte(resp), &res); err != nil {
return nil, err
}
@@ -994,7 +998,8 @@ func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthC
}, nil
}
-type environmentVariable struct {
+// EnvironmentVariable is the API message for environment variable in GitLab project.
+type EnvironmentVariable struct {
Key string `json:"key"`
Value string `json:"value"`
}
@@ -1016,7 +1021,7 @@ func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx commo
// getEnvironmentVariable gets the environment variable in the repository.
//
// https://docs.gitlab.com/ee/api/project_level_variables.html#get-a-single-variable
-func (p *Provider) getEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key string) (*environmentVariable, error) {
+func (p *Provider) getEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key string) (*EnvironmentVariable, error) {
url := fmt.Sprintf("%s/projects/%s/variables/%s", p.APIURL(instanceURL), repositoryID, key)
code, _, body, err := oauth.Get(
ctx,
@@ -1048,7 +1053,7 @@ func (p *Provider) getEnvironmentVariable(ctx context.Context, oauthCtx common.O
)
}
- variable := new(environmentVariable)
+ variable := new(EnvironmentVariable)
if err := json.Unmarshal([]byte(body), variable); err != nil {
return nil, err
}
@@ -1062,7 +1067,7 @@ func (p *Provider) getEnvironmentVariable(ctx context.Context, oauthCtx common.O
func (p *Provider) createEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key, value string) error {
url := fmt.Sprintf("%s/projects/%s/variables", p.APIURL(instanceURL), repositoryID)
body, err := json.Marshal(
- environmentVariable{
+ EnvironmentVariable{
Key: key,
Value: value,
},
@@ -1107,7 +1112,7 @@ func (p *Provider) createEnvironmentVariable(ctx context.Context, oauthCtx commo
func (p *Provider) updateEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key, value string) error {
url := fmt.Sprintf("%s/projects/%s/variables/%s", p.APIURL(instanceURL), repositoryID, key)
body, err := json.Marshal(
- environmentVariable{
+ EnvironmentVariable{
Key: key,
Value: value,
},
diff --git a/tests/fake/github.go b/tests/fake/github.go
index e7eeec3b4b..33dcea5b11 100644
--- a/tests/fake/github.go
+++ b/tests/fake/github.go
@@ -19,6 +19,7 @@ import (
"github.com/labstack/echo/v4/middleware"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/plugin/vcs"
"github.com/bytebase/bytebase/plugin/vcs/github"
)
@@ -33,11 +34,22 @@ type GitHub struct {
repositories map[string]*repositoryData
}
+const publicKeyName = "public-key"
+
type repositoryData struct {
webhooks []*github.WebhookCreateOrUpdate
// files is a map that the full file path is the key and the file content is the
// value.
files map[string]string
+ // refs is the map for repository branch.
+ // the map key is the branch ref, like "refs/heads/main".
+ refs map[string]*github.Branch
+ // secrets is the map for repository secret.
+ // the map key is the secret name, like "public-key".
+ secrets map[string]*github.RepositorySecret
+ // pullRequests is the map for repository pull request.
+ // the map key is the pull request id.
+ pullRequests map[int]*github.PullRequest
}
// NewGitHub creates a new fake implementation of GitHub VCS provider.
@@ -60,14 +72,21 @@ func NewGitHub(port int) VCSProvider {
g.GET("/repos/:owner/:repo/git/trees/:ref", gh.getRepositoryTree)
g.GET("/repos/:owner/:repo/contents/:filePath", gh.readRepositoryFile)
g.PUT("/repos/:owner/:repo/contents/:filePath", gh.createRepositoryFile)
+ g.GET("/repos/:owner/:repo/git/ref/heads/:branchName", gh.getRepositoryBranch)
+ g.POST("/repos/:owner/:repo/git/refs", gh.createRepositoryBranch)
+ g.POST("/repos/:owner/:repo/pulls", gh.createRepositoryPullRequest)
+ g.GET(
+ fmt.Sprintf("/repos/:owner/:repo/actions/secrets/%s", publicKeyName),
+ gh.getRepositoryPublicKey,
+ )
+ g.PUT("/repos/:owner/:repo/actions/secrets/:keyName", gh.updateRepositoryPublicKey)
return gh
}
func (gh *GitHub) createRepositoryWebhook(c echo.Context) error {
- repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
- r, ok := gh.repositories[repositoryID]
- if !ok {
- return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
}
body, err := io.ReadAll(c.Request().Body)
@@ -90,9 +109,8 @@ func (gh *GitHub) createRepositoryWebhook(c echo.Context) error {
}
func (gh *GitHub) getRepositoryCommit(c echo.Context) error {
- repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
- if _, ok := gh.repositories[repositoryID]; !ok {
- return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ if _, err := gh.validRepository(c); err != nil {
+ return err
}
buf, err := json.Marshal(
@@ -111,10 +129,9 @@ func (gh *GitHub) getRepositoryCommit(c echo.Context) error {
}
func (gh *GitHub) getRepositoryTree(c echo.Context) error {
- repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
- r, ok := gh.repositories[repositoryID]
- if !ok {
- return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
}
var treeNodes []github.RepositoryTreeNode
@@ -138,10 +155,9 @@ func (gh *GitHub) getRepositoryTree(c echo.Context) error {
}
func (gh *GitHub) readRepositoryFile(c echo.Context) error {
- repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
- r, ok := gh.repositories[repositoryID]
- if !ok {
- return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
}
filePathEscaped := c.Param("filePath")
@@ -172,10 +188,9 @@ func (gh *GitHub) readRepositoryFile(c echo.Context) error {
}
func (gh *GitHub) createRepositoryFile(c echo.Context) error {
- repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
- r, ok := gh.repositories[repositoryID]
- if !ok {
- return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
}
filePathEscaped := c.Param("filePath")
@@ -202,6 +217,146 @@ func (gh *GitHub) createRepositoryFile(c echo.Context) error {
return nil
}
+func (gh *GitHub) getRepositoryBranch(c echo.Context) error {
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
+ }
+
+ branchName := c.Param("branchName")
+ r.refs[branchName] = &github.Branch{
+ Ref: fmt.Sprintf("refs/heads/%s", branchName),
+ Object: github.ReferenceObject{
+ SHA: "fake_github_commit_sha",
+ },
+ }
+
+ buf, err := json.Marshal(r.refs[branchName])
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository branch: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gh *GitHub) createRepositoryBranch(c echo.Context) error {
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating repository branch: %v", err))
+ }
+
+ var branchCreate github.BranchCreate
+ if err = json.Unmarshal(body, &branchCreate); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating repository branch: %v", err))
+ }
+
+ if _, ok := r.refs[branchCreate.Ref]; ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("the branch already exists: %v", branchCreate.Ref))
+ }
+
+ r.refs[branchCreate.Ref] = &github.Branch{
+ Ref: branchCreate.Ref,
+ Object: github.ReferenceObject{
+ SHA: branchCreate.SHA,
+ },
+ }
+
+ return c.String(http.StatusOK, "")
+}
+
+func (gh *GitHub) createRepositoryPullRequest(c echo.Context) error {
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating repository pull request: %v", err))
+ }
+
+ var pullRequestCreate vcs.PullRequestCreate
+ if err = json.Unmarshal(body, &pullRequestCreate); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating repository pull request: %v", err))
+ }
+
+ if _, ok := r.refs[fmt.Sprintf("refs/heads/%s", pullRequestCreate.Head)]; !ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("the head branch not exists: %v", pullRequestCreate.Head))
+ }
+
+ prID := len(r.pullRequests) + 1
+ r.pullRequests[prID] = &github.PullRequest{
+ HTMLURL: fmt.Sprintf("https://github.com/%s/%s/pull/%d", c.Param("owner"), c.Param("repo"), prID),
+ }
+
+ buf, err := json.Marshal(
+ r.pullRequests[prID],
+ )
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for creating repository pull request: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gh *GitHub) getRepositoryPublicKey(c echo.Context) error {
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
+ }
+
+ buf, err := json.Marshal(
+ r.secrets[publicKeyName],
+ )
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository public key: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gh *GitHub) updateRepositoryPublicKey(c echo.Context) error {
+ r, err := gh.validRepository(c)
+ if err != nil {
+ return err
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for updating repository secret: %v", err))
+ }
+
+ var secretUpdate github.RepositorySecretUpdate
+ if err = json.Unmarshal(body, &secretUpdate); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for updating repository secret: %v", err))
+ }
+
+ // The KeyID in RepositorySecretUpdate should be the repository public id.
+ if secretUpdate.KeyID != r.secrets[publicKeyName].KeyID {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("The key id not matched: %v", secretUpdate.KeyID))
+ }
+
+ keyName := c.Param("keyName")
+ r.secrets[keyName] = &github.RepositorySecret{
+ KeyID: fmt.Sprintf("%s_%d", keyName, time.Now().Unix()),
+ Key: secretUpdate.EncryptedValue,
+ }
+
+ return c.String(http.StatusOK, "")
+}
+
+func (gh *GitHub) validRepository(c echo.Context) (*repositoryData, error) {
+ repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return nil, c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ }
+
+ return r, nil
+}
+
// Run starts the GitHub VCS provider server.
func (gh *GitHub) Run() error {
return gh.echo.Start(fmt.Sprintf(":%d", gh.port))
@@ -226,6 +381,15 @@ func (*GitHub) APIURL(instanceURL string) string {
func (gh *GitHub) CreateRepository(id string) {
gh.repositories[id] = &repositoryData{
files: make(map[string]string),
+ secrets: map[string]*github.RepositorySecret{
+ publicKeyName: {
+ KeyID: fmt.Sprintf("publickeyid_%d", time.Now().Unix()),
+ // mock public key
+ Key: "YJf3Ojcv8TSEBCtR0wtTR/F2bD3nBl1lxiwkfV/TYQk=",
+ },
+ },
+ refs: map[string]*github.Branch{},
+ pullRequests: map[int]*github.PullRequest{},
}
}
diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.go
index a6454a50b1..2ef8ab3dfc 100644
--- a/tests/fake/gitlab.go
+++ b/tests/fake/gitlab.go
@@ -37,6 +37,15 @@ type projectData struct {
// files is a map that the full file path is the key and the file content is the
// value.
files map[string]string
+ // branches is the map for project branch.
+ // the map key is the project name, like "refs/heads/main".
+ branches map[string]*gitlab.Branch
+ // variables is the map for project environment variable.
+ // the map key is the variable name, like "public-key".
+ variables map[string]*gitlab.EnvironmentVariable
+ // mergeRequests is the map for project merge request.
+ // the map key is the merge request id.
+ mergeRequests map[int]*gitlab.MergeRequest
}
// NewGitLab creates a new fake implementation of GitLab VCS provider.
@@ -62,6 +71,12 @@ func NewGitLab(port int) VCSProvider {
projectGroup.GET("/projects/:id/repository/files/:filePath/raw", gl.readProjectFile)
projectGroup.POST("/projects/:id/repository/files/:filePath", gl.createProjectFile)
projectGroup.PUT("/projects/:id/repository/files/:filePath", gl.createProjectFile)
+ projectGroup.GET("/projects/:id/repository/branches/:branchName", gl.getProjectBranch)
+ projectGroup.POST("/projects/:id/repository/branches", gl.createProjectBranch)
+ projectGroup.POST("/projects/:id/merge_requests", gl.createProjectPullRequest)
+ projectGroup.GET("/projects/:id/variables/:variableKey", gl.getProjectEnvironmentVariable)
+ projectGroup.POST("/projects/:id/variables", gl.createProjectEnvironmentVariable)
+ projectGroup.PUT("/projects/:id/variables/:variableKey", gl.updateProjectEnvironmentVariable)
return gl
}
@@ -89,13 +104,20 @@ func (*GitLab) APIURL(instanceURL string) string {
// CreateRepository creates a GitLab project with given ID.
func (gl *GitLab) CreateRepository(id string) {
gl.projects[id] = &projectData{
- files: map[string]string{},
+ files: map[string]string{},
+ branches: map[string]*gitlab.Branch{},
+ variables: map[string]*gitlab.EnvironmentVariable{},
+ mergeRequests: map[int]*gitlab.MergeRequest{},
}
}
// createProjectHook creates a project webhook.
func (gl *GitLab) createProjectHook(c echo.Context) error {
- projectID := c.Param("id")
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
c.Logger().Infof("Create webhook for project %q", c.Param("id"))
b, err := io.ReadAll(c.Request().Body)
if err != nil {
@@ -105,10 +127,7 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {
if err := json.Unmarshal(b, webhookCreate); err != nil {
return errors.Wrap(err, "failed to unmarshal create project hook request body")
}
- pd, ok := gl.projects[projectID]
- if !ok {
- return errors.Errorf("gitlab project %q doesn't exist", projectID)
- }
+
pd.webhooks = append(pd.webhooks, webhookCreate)
gl.nextWebhookID++
@@ -120,13 +139,12 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {
// readProjectTree reads a project file nodes.
func (gl *GitLab) readProjectTree(c echo.Context) error {
- projectID := c.Param("id")
- path := c.QueryParam("path")
- pd, ok := gl.projects[projectID]
- if !ok {
- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
}
+ path := c.QueryParam("path")
fileNodes := []*vcs.RepositoryTreeNode{}
for filePath := range pd.files {
@@ -148,18 +166,17 @@ func (gl *GitLab) readProjectTree(c echo.Context) error {
// readProjectFile reads a project file.
func (gl *GitLab) readProjectFile(c echo.Context) error {
- projectID := c.Param("id")
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
filePathEscaped := c.Param("filePath")
filePath, err := url.QueryUnescape(filePathEscaped)
if err != nil {
return c.String(http.StatusBadRequest, fmt.Sprintf("failed to query unescape %q, error: %v", filePathEscaped, err))
}
- pd, ok := gl.projects[projectID]
- if !ok {
- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))
- }
-
fileName := filepath.Base(filePath)
content, ok := pd.files[filePath]
@@ -198,7 +215,11 @@ func (gl *GitLab) getFakeCommit(c echo.Context) error {
// createProjectFile creates a project file.
func (gl *GitLab) createProjectFile(c echo.Context) error {
- projectID := c.Param("id")
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
filePathEscaped := c.Param("filePath")
filePath, err := url.QueryUnescape(filePathEscaped)
if err != nil {
@@ -213,14 +234,180 @@ func (gl *GitLab) createProjectFile(c echo.Context) error {
return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unmarshal create project file request body, error %v", err))
}
- pd, ok := gl.projects[projectID]
+ // Save file.
+ pd.files[filePath] = fileCommit.Content
+
+ return c.String(http.StatusOK, "")
+}
+
+func (gl *GitLab) validProject(c echo.Context) (*projectData, error) {
+ projectID := c.Param("id")
+ project, ok := gl.projects[projectID]
if !ok {
- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))
+ return nil, c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))
}
- // Save file.
- pd.files[filePath] = fileCommit.Content
+ return project, nil
+}
+
+func (gl *GitLab) getProjectBranch(c echo.Context) error {
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
+ branchName := c.Param("branchName")
+ pd.branches[branchName] = &gitlab.Branch{
+ Name: branchName,
+ Commit: gitlab.Commit{
+ ID: "fake_gitlab_commit_id",
+ AuthorName: "fake_gitlab_bot",
+ CreatedAt: time.Now(),
+ },
+ }
+
+ buf, err := json.Marshal(pd.branches[branchName])
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting project branch: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gl *GitLab) createProjectBranch(c echo.Context) error {
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating project branch: %v", err))
+ }
+
+ var branchCreate gitlab.BranchCreate
+ if err = json.Unmarshal(body, &branchCreate); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating project branch: %v", err))
+ }
+
+ if _, ok := pd.branches[branchCreate.Branch]; ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("the branch already exists: %v", branchCreate.Ref))
+ }
+
+ pd.branches[branchCreate.Branch] = &gitlab.Branch{
+ Name: branchCreate.Branch,
+ Commit: gitlab.Commit{
+ ID: branchCreate.Ref,
+ AuthorName: "fake_gitlab_bot",
+ CreatedAt: time.Now(),
+ },
+ }
+
+ return c.String(http.StatusOK, "")
+}
+
+func (gl *GitLab) createProjectPullRequest(c echo.Context) error {
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating project merge request: %v", err))
+ }
+
+ var mergeRequestCreate gitlab.MergeRequestCreate
+ if err = json.Unmarshal(body, &mergeRequestCreate); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating project merge request: %v", err))
+ }
+
+ if _, ok := pd.branches[mergeRequestCreate.SourceBranch]; !ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("the source branch not exists: %v", mergeRequestCreate.SourceBranch))
+ }
+
+ mrID := len(pd.mergeRequests) + 1
+ pd.mergeRequests[mrID] = &gitlab.MergeRequest{
+ // TODO: the URL for merge request is invalid.
+ WebURL: fmt.Sprintf("http://gitlab.example.com/my-group/my-project/merge_requests/%d", mrID),
+ }
+
+ buf, err := json.Marshal(
+ pd.mergeRequests[mrID],
+ )
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for creating project merge request: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gl *GitLab) getProjectEnvironmentVariable(c echo.Context) error {
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
+ variableKey := c.Param("variableKey")
+ variable, ok := pd.variables[variableKey]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("failed to find variable %s", variableKey))
+ }
+
+ buf, err := json.Marshal(variable)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting project environment variable: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gl *GitLab) createProjectEnvironmentVariable(c echo.Context) error {
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating project environment variable: %v", err))
+ }
+
+ var environmentVariable gitlab.EnvironmentVariable
+ if err = json.Unmarshal(body, &environmentVariable); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating project environment variable: %v", err))
+ }
+
+ if _, ok := pd.variables[environmentVariable.Key]; ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("environment variable already exists %s", environmentVariable.Key))
+ }
+
+ pd.variables[environmentVariable.Key] = &environmentVariable
+ return c.String(http.StatusOK, "")
+}
+
+func (gl *GitLab) updateProjectEnvironmentVariable(c echo.Context) error {
+ pd, err := gl.validProject(c)
+ if err != nil {
+ return err
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating project environment variable: %v", err))
+ }
+
+ var environmentVariable gitlab.EnvironmentVariable
+ if err = json.Unmarshal(body, &environmentVariable); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating project environment variable: %v", err))
+ }
+
+ variableKey := c.Param("variableKey")
+ if _, ok := pd.variables[variableKey]; !ok {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to find environment variable %s", variableKey))
+ }
+ if variableKey != environmentVariable.Key {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("invalid environment variable %s", environmentVariable.Key))
+ }
+ pd.variables[environmentVariable.Key] = &environmentVariable
return c.String(http.StatusOK, "")
}
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index 578a0daa45..cc5940261c 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -394,6 +394,7 @@ func TestVCS(t *testing.T) {
ExternalID: test.externalID,
AccessToken: "accessToken1",
RefreshToken: "refreshToken1",
+ EnableSQLReviewCI: true,
},
)
a.NoError(err)
@@ -748,6 +749,7 @@ func TestVCS_SDL(t *testing.T) {
ExternalID: test.externalID,
AccessToken: "accessToken1",
RefreshToken: "refreshToken1",
+ EnableSQLReviewCI: true,
},
)
a.NoError(err)
@@ -1266,6 +1268,7 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {
ExternalID: externalID,
AccessToken: "accessToken1",
RefreshToken: "refreshToken1",
+ EnableSQLReviewCI: true,
},
)
a.NoError(err)