Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: add tests for azure (#11516)
ecmadaoa38d6f90626a
diff --git a/backend/api/gitops/azure.go b/backend/api/gitops/azure.goindex 294824c766..04304b573f 100644--- a/backend/api/gitops/azure.go+++ b/backend/api/gitops/azure.go@@ -50,8 +50,8 @@ func getAzurePullRequestInfo(ctx context.Context, vcsProvider *store.VCSProviderprInfo := &pullRequestInfo{// TODO(ed): get the email.url: pushEvent.Resource.Links.Web.Href,- title: pushEvent.Message.Text,- description: pushEvent.DetailedMessage.Text,+ title: pushEvent.Resource.Title,+ description: pushEvent.Resource.Description,changes: getChangesByFileList(mrFiles, vcsConnector.Payload.BaseDirectory),}diff --git a/backend/api/v1/vcs_connector_service.go b/backend/api/v1/vcs_connector_service.goindex b0ae8e4553..2e1dc4830f 100644--- a/backend/api/v1/vcs_connector_service.go+++ b/backend/api/v1/vcs_connector_service.go@@ -95,17 +95,13 @@ func (s *VCSConnectorService) CreateVCSConnector(ctx context.Context, request *v}// Check branch existence.- notFound, err := isBranchNotFound(+ if err := checkBranchExistence(ctx,vcsProvider,request.GetVcsConnector().ExternalId,request.GetVcsConnector().Branch,- )- if err != nil {- return nil, status.Errorf(codes.Internal, "failed to check branch %s with error: %v", request.GetVcsConnector().Branch, err.Error())- }- if notFound {- return nil, status.Errorf(codes.NotFound, "branch %s not found in repository %s", request.GetVcsConnector().Branch, request.GetVcsConnector().FullPath)+ ); err != nil {+ return nil, err}baseDir := request.GetVcsConnector().BaseDirectory@@ -307,20 +303,13 @@ func (s *VCSConnectorService) UpdateVCSConnector(ctx context.Context, request *v// Check branch existence.if v := update.Branch; v != nil {- if *v == "" {- return nil, status.Errorf(codes.InvalidArgument, "branch must be specified")- }- notFound, err := isBranchNotFound(+ if err := checkBranchExistence(ctx,vcsProvider,vcsConnector.Payload.ExternalId,*v,- )- if err != nil {- return nil, status.Errorf(codes.Internal, "failed to check branch: %v", err.Error())- }- if notFound {- return nil, status.Errorf(codes.NotFound, "branch %s not found in repository %s", *v, vcsConnector.Payload.FullPath)+ ); err != nil {+ return nil, err}}@@ -424,13 +413,17 @@ func convertStoreVCSConnector(ctx context.Context, stores *store.Store, vcsConnereturn v1VCSConnector, nil}-func isBranchNotFound(ctx context.Context, vcsProvider *store.VCSProviderMessage, externalID, branch string) (bool, error) {- _, err := vcs.Get(vcsProvider.Type, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).GetBranch(ctx, externalID, branch)-- if common.ErrorCode(err) == common.NotFound {- return true, nil+func checkBranchExistence(ctx context.Context, vcsProvider *store.VCSProviderMessage, externalID, branch string) error {+ if branch == "" {+ return status.Errorf(codes.InvalidArgument, "branch name is required")+ }+ if _, err := vcs.Get(vcsProvider.Type, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).GetBranch(ctx, externalID, branch); err != nil {+ if common.ErrorCode(err) == common.NotFound {+ return status.Errorf(codes.NotFound, "branch %s not found in repository %s", branch, externalID)+ }+ return status.Errorf(codes.Internal, "failed to check branch: %v", err.Error())}- return false, err+ return nil}func createVCSWebhook(ctx context.Context, vcsProvider *store.VCSProviderMessage, webhookEndpointID, webhookSecretToken, externalRepoID, bytebaseEndpointURL string) (string, error) {diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.goindex 7c2413df33..8e33efe526 100644--- a/backend/plugin/vcs/azure/azure.go+++ b/backend/plugin/vcs/azure/azure.go@@ -30,6 +30,7 @@ var _ vcs.Provider = (*Provider)(nil)type Provider struct {instanceURL stringauthToken string+ RootAPIURL string}func newProvider(config vcs.ProviderConfig) vcs.Provider {@@ -44,7 +45,16 @@ func (*Provider) APIURL(instanceURL string) string {return instanceURL}-type project struct {+func (p *Provider) rootAPIURL() string {+ if strings.HasPrefix(p.instanceURL, "http://localhost:") {+ // This is used for mock vcs server in test.+ // TODO: find better ways without changing the code.+ return p.instanceURL+ }+ return "https://app.vssps.visualstudio.com"+}++type Project struct {ID string `json:"id"`Name string `json:"name"`State string `json:"state"`@@ -58,34 +68,33 @@ type Repository struct {// The pipeline ci will use this url, so we need this urlRemoteURL string `json:"remoteUrl"`// WebURL is the repo url in https://dev.azure.com/{org name}/{project name}/_git/{repo name}- WebURL string `json:"webUrl"`- Project project `json:"project"`+ WebURL string `json:"webUrl"`+ Project *Project `json:"project"`}-// ChangesResponseChangeItem represents a Azure DevOps changes response change item.-type ChangesResponseChangeItem struct {+// CommitChangeItem represents a Azure DevOps changes response change item.+type CommitChangeItem struct {GitObjectType string `json:"gitObjectType"`Path string `json:"path"`CommitID string `json:"commitId"`}-// ChangesResponseChange represents a Azure DevOps changes response change.-type ChangesResponseChange struct {- Item ChangesResponseChangeItem `json:"item"`- ChangeType string `json:"changeType"`+// CommitChange represents a Azure DevOps changes response change.+type CommitChange struct {+ Item *CommitChangeItem `json:"item"`+ ChangeType string `json:"changeType"`}-// ChangesResponse represents a Azure DevOps changes response.-type ChangesResponse struct {- Changes []ChangesResponseChange `json:"changes"`+type changesResponse struct {+ Changes []*CommitChange `json:"changes"`}// getChangesByCommit gets the changes by commit ID, and returns the list of blob files changed in the specify commit.//// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get-changes?view=azure-devops-rest-7.0&tabs=HTTP// TODO(zp): We should GET the changes pagenated, otherwise it may hit the Azure DevOps API limit.-func (p *Provider) getChangesByCommit(ctx context.Context, externalRepositoryID, commitID string) (*ChangesResponse, error) {- apiURL, err := getRepositoryAPIURL(externalRepositoryID)+func (p *Provider) getChangesByCommit(ctx context.Context, externalRepositoryID, commitID string) (*changesResponse, error) {+ apiURL, err := p.getRepositoryAPIURL(externalRepositoryID)if err != nil {return nil, err}@@ -104,12 +113,12 @@ func (p *Provider) getChangesByCommit(ctx context.Context, externalRepositoryID,return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))}- changes := new(ChangesResponse)+ changes := new(changesResponse)if err := json.Unmarshal([]byte(body), changes); err != nil {return nil, errors.Wrapf(err, "unmarshal body")}- var result ChangesResponse+ var result changesResponsefor _, change := range changes.Changes {if change.Item.GitObjectType == "blob" {result.Changes = append(result.Changes, change)@@ -150,7 +159,7 @@ func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcurlParams.Set("api-version", "7.0")for _, organization := range organizations {if err := func() error {- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/git/repositories?%s", url.PathEscape(organization), urlParams.Encode())+ url := fmt.Sprintf("%s/%s/_apis/git/repositories?%s", p.APIURL(p.instanceURL), url.PathEscape(organization), urlParams.Encode())code, body, err := internal.Get(ctx, url, p.getAuthorization())if err != nil {return errors.Wrapf(err, "GET %s", url)@@ -180,7 +189,7 @@ func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcID: fmt.Sprintf("%s/%s/%s", organization, r.Project.ID, r.ID),Name: r.Name,FullPath: fmt.Sprintf("%s/%s/%s", organization, r.Project.Name, r.Name),- WebURL: r.RemoteURL,+ WebURL: r.WebURL,})}return nil@@ -200,6 +209,10 @@ func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcreturn result, nil}+type Profile struct {+ PublicAlias string `json:"publicAlias"`+}+// getAuthenticatedProfilePublicAlias gets the authenticated user's profile, and returns the public alias in the// profile response.//@@ -207,7 +220,7 @@ func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcfunc (p *Provider) getAuthenticatedProfilePublicAlias(ctx context.Context) (string, error) {values := &url.Values{}values.Set("api-version", "7.0")- url := fmt.Sprintf("https://app.vssps.visualstudio.com/_apis/profile/profiles/me?%s", values.Encode())+ url := fmt.Sprintf("%s/_apis/profile/profiles/me?%s", p.rootAPIURL(), values.Encode())code, body, err := internal.Get(ctx, url, p.getAuthorization())if err != nil {@@ -217,11 +230,7 @@ func (p *Provider) getAuthenticatedProfilePublicAlias(ctx context.Context) (strireturn "", errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))}- type profileAlias struct {- PublicAlias string `json:"publicAlias"`- }-- r := new(profileAlias)+ r := new(Profile)if err := json.Unmarshal([]byte(body), r); err != nil {return "", errors.Wrapf(err, "failed to unmarshal profile response body, code %v", code)}@@ -229,6 +238,10 @@ func (p *Provider) getAuthenticatedProfilePublicAlias(ctx context.Context) (strireturn r.PublicAlias, nil}+type Organization struct {+ AccountName string `json:"accountName"`+}+// listOrganizationsForMember lists all organization for a given member.//// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/account/accounts/list?view=azure-devops-rest-7.0&tabs=HTTP@@ -236,7 +249,7 @@ func (p *Provider) listOrganizationsForMember(ctx context.Context, memberID striurlParams := &url.Values{}urlParams.Set("memberId", memberID)urlParams.Set("api-version", "7.0")- url := fmt.Sprintf("https://app.vssps.visualstudio.com/_apis/accounts?%s", urlParams.Encode())+ url := fmt.Sprintf("%s/_apis/accounts?%s", p.rootAPIURL(), urlParams.Encode())code, body, err := internal.Get(ctx, url, p.getAuthorization())if err != nil {@@ -246,12 +259,9 @@ func (p *Provider) listOrganizationsForMember(ctx context.Context, memberID strireturn nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))}- type accountsValue struct {- AccountName string `json:"accountName"`- }type accountsResponse struct {Count int `json:"count"`- Value []accountsValue `json:"value"`+ Value []*Organization `json:"value"`}r := new(accountsResponse)@@ -271,7 +281,7 @@ func (p *Provider) listOrganizationsForMember(ctx context.Context, memberID stri//// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-7.0&tabs=HTTPfunc (p *Provider) ReadFileContent(ctx context.Context, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {- apiURL, err := getRepositoryAPIURL(repositoryID)+ apiURL, err := p.getRepositoryAPIURL(repositoryID)if err != nil {return "", err}@@ -307,6 +317,15 @@ func (p *Provider) ReadFileContent(ctx context.Context, repositoryID, filePath sreturn string(body), nil}+type BranchCommit struct {+ CommitID string `json:"commitId"`+}++type Branch struct {+ Name string `json:"name"`+ Commit *BranchCommit `json:"commit"`+}+// GetBranch try to retrieve the branch from the repository, and returns the last commit ID of the branch, if the branch// does not exist, it returns common.NotFound.// Args:@@ -315,11 +334,7 @@ func (p *Provider) ReadFileContent(ctx context.Context, repositoryID, filePath s//// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/stats/get?view=azure-devops-rest-7.0&tabs=HTTPfunc (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName string) (*vcs.BranchInfo, error) {- if branchName == "" {- return nil, errors.New("branch name is required")- }-- apiURL, err := getRepositoryAPIURL(repositoryID)+ apiURL, err := p.getRepositoryAPIURL(repositoryID)if err != nil {return nil, err}@@ -337,15 +352,7 @@ func (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName strinreturn nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))}- type branchStatResponseCommit struct {- CommitID string `json:"commitId"`- }- type branchStatResponse struct {- Name string `json:"name"`- Commit branchStatResponseCommit `json:"commit"`- }-- r := new(branchStatResponse)+ r := new(Branch)if err := json.Unmarshal([]byte(body), r); err != nil {return nil, errors.Wrapf(err, "failed to unmarshal get the static of the branch %s of the repository %s with response body, body: %s", branchName, repositoryID, string(body))}@@ -401,7 +408,7 @@ func (p *Provider) CreatePullRequestComment(ctx context.Context, repositoryID, preturn errors.Wrap(err, "failed to marshal request body for creating pull request comment")}- apiURL, err := getRepositoryAPIURL(repositoryID)+ apiURL, err := p.getRepositoryAPIURL(repositoryID)if err != nil {return err}@@ -432,12 +439,12 @@ func (p *Provider) CreateWebhook(ctx context.Context, externalRepositoryID strinorganizationName, _, _ := parts[0], parts[1], parts[2]urlParams := &url.Values{}urlParams.Set("api-version", "7.0")- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/hooks/subscriptions?%s", url.PathEscape(organizationName), urlParams.Encode())+ url := fmt.Sprintf("%s/%s/_apis/hooks/subscriptions?%s", p.APIURL(p.instanceURL), url.PathEscape(organizationName), urlParams.Encode())code, body, err := internal.Post(ctx, url, p.getAuthorization(), payload)if err != nil {return "", errors.Wrapf(err, "failed to create webhook")}- if code != http.StatusOK {+ if code >= 300 {return "", errors.Errorf("failed to create webhook, code: %v, body: %s", code, string(body))}@@ -464,7 +471,7 @@ func (p *Provider) DeleteWebhook(ctx context.Context, _, webhookID string) errorvalues := &url.Values{}values.Set("api-version", "7.0")- url := fmt.Sprintf("https://dev.azure.com/%s/_apis/hooks/subscriptions/%s?%s", url.PathEscape(organizationName), url.PathEscape(webhookID), values.Encode())+ url := fmt.Sprintf("%s/%s/_apis/hooks/subscriptions/%s?%s", p.APIURL(p.instanceURL), url.PathEscape(organizationName), url.PathEscape(webhookID), values.Encode())code, body, err := internal.Delete(ctx, url, p.getAuthorization())if err != nil {@@ -477,7 +484,7 @@ func (p *Provider) DeleteWebhook(ctx context.Context, _, webhookID string) errorreturn nil}-func getRepositoryAPIURL(repositoryID string) (string, error) {+func (p *Provider) getRepositoryAPIURL(repositoryID string) (string, error) {// By design, we encode the repository ID as <organization>/<projectID>/<repositoryID> for Azure DevOps.parts := strings.Split(repositoryID, "/")if len(parts) != 3 {@@ -485,7 +492,7 @@ func getRepositoryAPIURL(repositoryID string) (string, error) {}organizationName, projectName, repositoryID := parts[0], parts[1], parts[2]- return fmt.Sprintf("https://dev.azure.com/%s/%s/_apis/git/repositories/%s", url.PathEscape(organizationName), url.PathEscape(projectName), url.PathEscape(repositoryID)), nil+ return fmt.Sprintf("%s/%s/%s/_apis/git/repositories/%s", p.APIURL(p.instanceURL), url.PathEscape(organizationName), url.PathEscape(projectName), url.PathEscape(repositoryID)), nil}// getAuthorization returns the encoded azure token for authorization.diff --git a/backend/plugin/vcs/azure/webhook_events.go b/backend/plugin/vcs/azure/webhook_events.goindex 085c8dcd9a..b98aa9f993 100644--- a/backend/plugin/vcs/azure/webhook_events.go+++ b/backend/plugin/vcs/azure/webhook_events.go@@ -36,10 +36,6 @@ type PullRequestResource struct {CreatedBy *PullRequestCreatedBy `json:"createdBy"`}-type PullRequestMessage struct {- Text string `json:"text"`-}-// PullRequestEvent is the API message for pull request webhook event.//// Docs: https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#pull-request-merge-commit-created@@ -47,10 +43,8 @@ type PullRequestEvent struct {// ID is the webhook message id.ID string `json:"id"`// EventType should be "git.pullrequest.merged".- EventType string `json:"eventType"`- Message *PullRequestMessage `json:"message"`- DetailedMessage *PullRequestMessage `json:"detailedMessage"`- Resource *PullRequestResource `json:"resource"`+ EventType string `json:"eventType"`+ Resource *PullRequestResource `json:"resource"`}// WebhookCreateConsumerInputs represents the consumer inputs for creating a webhook.diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.goindex cdad12c890..c4b1115207 100644--- a/backend/plugin/vcs/github/github.go+++ b/backend/plugin/vcs/github/github.go@@ -138,11 +138,6 @@ type FileCommit struct {Author *CommitAuthor `json:"author,omitempty"`}-// CommitsDiff represents a GitHub API response for comparing two commits.-type CommitsDiff struct {- Files []PullRequestFile `json:"files"`-}-// FetchRepositoryList fetches all repositories where the authenticated user// has admin permissions, which is required to create webhook in the repository.//diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.goindex fd42edc9d3..a254a4b407 100644--- a/backend/plugin/vcs/gitlab/gitlab.go+++ b/backend/plugin/vcs/gitlab/gitlab.go@@ -131,11 +131,6 @@ type File struct {Content string}-// CommitsDiff represents a GitLab API response for comparing two commits.-type CommitsDiff struct {- FileDiffList []MergeRequestFile `json:"diffs"`-}-// Repository represents a GitLab API response for a repository.type Repository struct {ID int64 `json:"id"`diff --git a/backend/tests/fake/azure.go b/backend/tests/fake/azure.gonew file mode 100644index 0000000000..64759383b5--- /dev/null+++ b/backend/tests/fake/azure.go@@ -0,0 +1,384 @@+package fake++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/url"+ "strings"++ "github.com/labstack/echo/v4"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/vcs"+ "github.com/bytebase/bytebase/backend/plugin/vcs/azure"+)++// Azure is a fake implementation of Azure VCS provider.+type Azure struct {+ port int+ echo *echo.Echo++ client *http.Client++ nextWebhookID int+ repositories map[string]*azureRepositoryData+}++type azureRepositoryData struct {+ repository *azure.Repository+ webhooks []*azure.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]*azure.Branch+ commits map[string]struct {+ Changes []*azure.CommitChange+ }+}++// NewAzure creates a new fake implementation of Azure VCS provider.+func NewAzure(port int) VCSProvider {+ e := newEchoServer()+ az := &Azure{+ port: port,+ echo: e,+ client: &http.Client{},+ nextWebhookID: 20210113,+ repositories: make(map[string]*azureRepositoryData),+ }++ g := e.Group("")+ g.GET("/_apis/profile/profiles/me", az.getProfile)+ g.GET("/_apis/accounts", az.listOrgs)+ g.GET("/:organization/_apis/git/repositories", az.listRepositories)+ g.POST("/:organization/_apis/hooks/subscriptions", az.createRepositoryWebhook)+ g.DELETE("/:organization/_apis/hooks/subscriptions/:subscription", az.deleteRepositoryWebhook)++ repo := e.Group("/:organization/:project/_apis/git/repositories/:repo")+ repo.GET("/stats/branches", az.getRepositoryBranch)+ repo.POST("/pullRequests/:pr/threads", az.createIssueComment)+ repo.GET("/commits/:commit/changes", az.getCommitChanges)+ repo.GET("/items", az.readRepositoryFile)++ return az+}++func (*Azure) getResponse(c echo.Context, data any) error {+ buf, err := json.Marshal(data)+ if err != nil {+ return c.String(http.StatusInternalServerError, err.Error())+ }+ return c.String(http.StatusOK, string(buf))+}++func (az *Azure) getProfile(c echo.Context) error {+ resp := &azure.Profile{+ PublicAlias: "mock-az-profile",+ }+ return az.getResponse(c, resp)+}++func (az *Azure) listOrgs(c echo.Context) error {+ type accountsResponse struct {+ Count int `json:"count"`+ Value []*azure.Organization `json:"value"`+ }++ resp := &accountsResponse{}++ for name := range az.repositories {+ parts := strings.Split(name, "/")+ if len(parts) != 3 {+ return c.String(http.StatusInternalServerError, fmt.Sprintf("invalid repo name: %s", name))+ }+ resp.Value = append(resp.Value, &azure.Organization{+ AccountName: parts[0],+ })+ }+ resp.Count = len(resp.Value)++ return az.getResponse(c, resp)+}++func (az *Azure) listRepositories(c echo.Context) error {+ type listRepositoriesResponse struct {+ Count int `json:"count"`+ Value []*azure.Repository `json:"value"`+ }++ orgID := c.Param("organization")+ resp := &listRepositoriesResponse{}+ for name, item := range az.repositories {+ parts := strings.Split(name, "/")+ if len(parts) != 3 {+ return c.String(http.StatusInternalServerError, fmt.Sprintf("invalid repo name: %s", name))+ }+ if parts[0] != orgID {+ continue+ }+ resp.Value = append(resp.Value, item.repository)+ }+ resp.Count = len(resp.Value)++ return az.getResponse(c, resp)+}++func (az *Azure) getCommitChanges(c echo.Context) error {+ r, err := az.validRepository(c)+ if err != nil {+ return err+ }+ commitID := c.Param("commit")+ if _, ok := r.commits[commitID]; !ok {+ return c.String(http.StatusNotFound, fmt.Sprintf("commit not found: %v", commitID))+ }++ return az.getResponse(c, r.commits[commitID])+}++func (*Azure) deleteRepositoryWebhook(c echo.Context) error {+ return c.String(http.StatusNoContent, "")+}++func (az *Azure) createRepositoryWebhook(c echo.Context) error {+ 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 webhook: %v", err))+ }++ var webhookCreate azure.WebhookCreateOrUpdate+ if err = json.Unmarshal(body, &webhookCreate); err != nil {+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating repository webhook: %v", err))+ }++ orgID := c.Param("organization")+ projectID := webhookCreate.PublisherInputs.ProjectID+ repositoryID := webhookCreate.PublisherInputs.Repository+ repositoryName := fmt.Sprintf("%s/%s/%s", orgID, projectID, repositoryID)+ r, ok := az.repositories[repositoryName]+ if !ok {+ return c.String(http.StatusNotFound, fmt.Sprintf("Azure repository %q does not exist", repositoryName))+ }++ r.webhooks = append(r.webhooks, &webhookCreate)++ type createServiceResponse struct {+ ID string `json:"id"`+ }+ buf, err := json.Marshal(createServiceResponse{ID: fmt.Sprintf("%d", az.nextWebhookID)})+ if err != nil {+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for creating repository webhook: %v", err))+ }+ az.nextWebhookID+++ return c.String(http.StatusCreated, string(buf))+}++func (az *Azure) readRepositoryFile(c echo.Context) error {+ r, err := az.validRepository(c)+ if err != nil {+ return err+ }++ filePathEscaped := c.QueryParam("path")+ filePath, err := url.QueryUnescape(filePathEscaped)+ if err != nil {+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unescape file path %q: %v", filePathEscaped, err))+ }++ content, ok := r.files[filePath]+ if !ok {+ return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", filePath))+ }++ return c.String(http.StatusOK, content)+}++func (az *Azure) getRepositoryBranch(c echo.Context) error {+ r, err := az.validRepository(c)+ if err != nil {+ return err+ }++ branchNameEscaped := c.QueryParam("name")+ branchName, err := url.QueryUnescape(branchNameEscaped)+ if err != nil {+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unescape branch %q: %v", branchNameEscaped, err))+ }+ if _, ok := r.refs[fmt.Sprintf("refs/heads/%s", branchName)]; !ok {+ return c.String(http.StatusNotFound, fmt.Sprintf("branch not found: %v", branchName))+ }++ return az.getResponse(c, r.refs[fmt.Sprintf("refs/heads/%s", branchName)])+}++func (*Azure) createIssueComment(echo.Context) error {+ return nil+}++func (az *Azure) validRepository(c echo.Context) (*azureRepositoryData, error) {+ repositoryID := fmt.Sprintf("%s/%s/%s", c.Param("organization"), c.Param("project"), c.Param("repo"))+ r, ok := az.repositories[repositoryID]+ if !ok {+ return nil, c.String(http.StatusNotFound, fmt.Sprintf("Azure repository %q does not exist", repositoryID))+ }++ return r, nil+}++// Run starts the Azure VCS provider server.+func (az *Azure) Run() error {+ return az.echo.Start(fmt.Sprintf(":%d", az.port))+}++// Close shuts down the Azure VCS provider server.+func (az *Azure) Close() error {+ return az.echo.Close()+}++// ListenerAddr returns the Azure VCS provider server listener address.+func (az *Azure) ListenerAddr() net.Addr {+ return az.echo.ListenerAddr()+}++// CreateRepository creates a Azure repository with given ID.+func (az *Azure) CreateRepository(repository *vcs.Repository) error {+ parts := strings.Split(repository.ID, "/")+ if len(parts) != 3 {+ return errors.Errorf("invalid repo id: %s", repository.ID)+ }+ az.repositories[repository.FullPath] = &azureRepositoryData{+ repository: &azure.Repository{+ ID: parts[2],+ Name: repository.Name,+ Project: &azure.Project{+ State: "wellFormed",+ },+ },+ files: make(map[string]string),+ refs: map[string]*azure.Branch{},+ commits: make(map[string]struct{ Changes []*azure.CommitChange }),+ }+ return nil+}++// CreateBranch creates a new branch with the given name.+func (az *Azure) CreateBranch(id, branchName string) error {+ pd, ok := az.repositories[id]+ if !ok {+ return errors.Errorf("repo %q doesn't exist", id)+ }++ if _, ok := pd.refs[fmt.Sprintf("refs/heads/%s", branchName)]; ok {+ return errors.Errorf("branch %q already exists", branchName)+ }++ pd.refs[fmt.Sprintf("refs/heads/%s", branchName)] = &azure.Branch{+ Name: branchName,+ Commit: &azure.BranchCommit{+ CommitID: "fake_azure_commit_sha",+ },+ }++ return nil+}++// SendWebhookPush sends out a webhook for a push event for the Azure+// repository using given payload.+func (az *Azure) SendWebhookPush(repositoryID string, payload []byte) error {+ r, ok := az.repositories[repositoryID]+ if !ok {+ return errors.Errorf("Azure repository %q does not exist", repositoryID)+ }++ // Trigger all webhooks+ for _, webhook := range r.webhooks {+ if err := func() error {+ url := webhook.ConsumerInputs.URL+ req, err := http.NewRequest("POST", url, bytes.NewReader(payload))+ if err != nil {+ return errors.Wrapf(err, "failed to create a new POST request to %q", url)+ }++ headers := strings.Split(webhook.ConsumerInputs.HTTPHeaders, ": ")+ req.Header.Set(headers[0], headers[1])++ resp, err := az.client.Do(req)+ if err != nil {+ return errors.Wrapf(err, "failed to send POST request to %q", url)+ }+ defer resp.Body.Close()+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return errors.Wrap(err, "failed to read response body")+ }+ if resp.StatusCode != http.StatusOK {+ return errors.Errorf("unexpected response status code %d, body: %s", resp.StatusCode, body)+ }+ az.echo.Logger.Infof("SendWebhookPush response body %s\n", body)+ return nil+ }(); err != nil {+ return err+ }+ }+ return nil+}++// AddFiles adds given files to the Azure repository.+func (az *Azure) AddFiles(repositoryID string, files map[string]string) error {+ r, ok := az.repositories[repositoryID]+ if !ok {+ return errors.Errorf("Azure repository %q does not exist", repositoryID)+ }++ // Save or overwrite files+ for path, content := range files {+ filePath := az.validFilePath(path)+ r.files[filePath] = content+ }+ return nil+}++// AddPullRequest creates a new pull request and add changed files to it.+func (az *Azure) AddPullRequest(repositoryID string, commitID int, files []*vcs.PullRequestFile) error {+ r, ok := az.repositories[repositoryID]+ if !ok {+ return errors.Errorf("repository %q does not exist", repositoryID)+ }++ changes := []*azure.CommitChange{}+ for _, file := range files {+ changeType := ""+ if file.IsDeleted {+ changeType = "delete"+ }+ changes = append(changes, &azure.CommitChange{+ ChangeType: changeType,+ Item: &azure.CommitChangeItem{+ CommitID: fmt.Sprintf("%d", commitID),+ Path: az.validFilePath(file.Path),+ GitObjectType: "blob",+ },+ })+ }++ r.commits[fmt.Sprintf("%d", commitID)] = struct {+ Changes []*azure.CommitChange+ }{+ Changes: changes,+ }++ return nil+}++func (*Azure) validFilePath(filePath string) string {+ if !strings.HasPrefix(filePath, "/") {+ return fmt.Sprintf("/%s", filePath)+ }+ return filePath+}diff --git a/backend/tests/fake/bitbucket.go b/backend/tests/fake/bitbucket.goindex ef2cdb7a2b..63e7b4faa3 100644--- a/backend/tests/fake/bitbucket.go+++ b/backend/tests/fake/bitbucket.go@@ -38,9 +38,6 @@ type bitbucketRepositoryData struct {// refs is the map for repository branch. The map key is the branch ref, like// "refs/heads/main".refs map[string]*bitbucket.Branch- // diffStats is the map for commits compare. The map key has the format- // "to..from" which is SHA or branch name.- diffStats map[string][]*bitbucket.CommitDiffStat// pullRequests is the map for repository pull request.// the map key is the pull request id.pullRequests map[int]struct {@@ -62,11 +59,10 @@ func NewBitbucket(port int) VCSProvider {g := e.Group("/2.0")g.GET("/user/permissions/repositories", bb.listRepositories)g.POST("/repositories/:owner/:repo/hooks", bb.createRepositoryWebhook)+ g.DELETE("/repositories/:owner/:repo/hooks/:hook", bb.deleteRepositoryWebhook)g.GET("/repositories/:owner/:repo/commit/:commitID", bb.getRepositoryCommit)g.GET("/repositories/:owner/:repo/src/:ref/:filepath", bb.getRepositoryContent)- g.POST("/repositories/:owner/:repo/src", bb.createRepositoryFile)g.GET("/repositories/:owner/:repo/refs/branches/:branchName", bb.getRepositoryBranch)- g.GET("/repositories/:owner/:repo/diffstat/:baseHead", bb.compareCommits)g.GET("/repositories/:owner/:repo/pullrequests/:prID/diffstat", bb.listPullRequestFile)g.GET("/repositories/:owner/:repo/pullrequests/:prID/comments", bb.createPullRequestComment)return bb@@ -90,6 +86,10 @@ func (bb *Bitbucket) listRepositories(c echo.Context) error {return c.String(http.StatusOK, string(buf))}+func (*Bitbucket) deleteRepositoryWebhook(c echo.Context) error {+ return c.String(http.StatusOK, "")+}+func (bb *Bitbucket) createRepositoryWebhook(c echo.Context) error {r, err := bb.validRepository(c)if err != nil {@@ -156,25 +156,6 @@ func (bb *Bitbucket) getRepositoryContent(c echo.Context) error {return c.String(http.StatusOK, content)}-func (bb *Bitbucket) createRepositoryFile(c echo.Context) error {- r, err := bb.validRepository(c)- if err != nil {- return err- }-- params, err := c.FormParams()- if err != nil {- return c.String(http.StatusBadRequest, fmt.Sprintf("failed to get form params: %v", err))- }-- for k, v := range params {- if k != "parents" && k != "branch" && k != "message" {- r.files[k] = v[0]- }- }- return nil-}-func (bb *Bitbucket) getRepositoryBranch(c echo.Context) error {r, err := bb.validRepository(c)if err != nil {@@ -193,25 +174,6 @@ func (bb *Bitbucket) getRepositoryBranch(c echo.Context) error {return c.String(http.StatusOK, string(buf))}-func (bb *Bitbucket) compareCommits(c echo.Context) error {- r, err := bb.validRepository(c)- if err != nil {- return err- }-- key := c.Param("baseHead")- diff, ok := r.diffStats[key]- if !ok {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Cannot find the diff key %s", key))- }-- buf, err := json.Marshal(map[string]any{"values": diff})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal response body").SetInternal(err)- }- return c.String(http.StatusOK, string(buf))-}-func (bb *Bitbucket) validRepository(c echo.Context) (*bitbucketRepositoryData, error) {repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))r, ok := bb.repositories[repositoryID]@@ -237,11 +199,6 @@ func (bb *Bitbucket) ListenerAddr() net.Addr {return bb.echo.ListenerAddr()}-// APIURL returns the Bitbucket VCS provider API URL.-func (*Bitbucket) APIURL(string) string {- return "https://api.bitbucket.org/2.0"-}-// CreateRepository creates a Bitbucket repository with given ID.func (bb *Bitbucket) CreateRepository(repository *vcs.Repository) error {bb.repositories[repository.ID] = &bitbucketRepositoryData{@@ -250,9 +207,8 @@ func (bb *Bitbucket) CreateRepository(repository *vcs.Repository) error {Name: repository.Name,FullName: repository.FullPath,},- files: make(map[string]string),- refs: map[string]*bitbucket.Branch{},- diffStats: map[string][]*bitbucket.CommitDiffStat{},+ files: make(map[string]string),+ refs: map[string]*bitbucket.Branch{},pullRequests: map[int]struct {Files []*bitbucket.CommitDiffStat}{},@@ -280,34 +236,6 @@ func (bb *Bitbucket) CreateBranch(id, branchName string) error {return nil}-// AddCommitsDiff adds a commits diff.-func (bb *Bitbucket) AddCommitsDiff(repositoryID, fromCommit, toCommit string, fileDiffList []vcs.FileDiff) error {- r, ok := bb.repositories[repositoryID]- if !ok {- return errors.Errorf("Bitbucket repository %s doesn't exist", repositoryID)- }- key := fmt.Sprintf("%s..%s", toCommit, fromCommit)- var diffStats []*bitbucket.CommitDiffStat- for _, fileDiff := range fileDiffList {- diffStat := &bitbucket.CommitDiffStat{- New: bitbucket.CommitFile{- Path: fileDiff.Path,- },- }- switch fileDiff.Type {- case vcs.FileDiffTypeAdded:- diffStat.Status = "added"- case vcs.FileDiffTypeModified:- diffStat.Status = "modified"- case vcs.FileDiffTypeRemoved:- diffStat.Status = "removed"- }- diffStats = append(diffStats, diffStat)- }- r.diffStats[key] = diffStats- return nil-}-// SendWebhookPush sends out a webhook for a push event for the Bitbucket// repository using given payload.func (bb *Bitbucket) SendWebhookPush(repositoryID string, payload []byte) error {@@ -359,23 +287,6 @@ func (bb *Bitbucket) AddFiles(repositoryID string, files map[string]string) erroreturn nil}-// GetFiles returns files with given paths from the Bitbucket repository.-func (bb *Bitbucket) GetFiles(repositoryID string, filePaths ...string) (map[string]string, error) {- r, ok := bb.repositories[repositoryID]- if !ok {- return nil, errors.Errorf("Bitbucket repository %q does not exist", repositoryID)- }-- // Get files- files := make(map[string]string)- for _, path := range filePaths {- if content, ok := r.files[path]; ok {- files[path] = content- }- }- return files, nil-}-// AddPullRequest creates a new pull request and add changed files to it.func (bb *Bitbucket) AddPullRequest(repositoryID string, prID int, files []*vcs.PullRequestFile) error {r, ok := bb.repositories[repositoryID]diff --git a/backend/tests/fake/github.go b/backend/tests/fake/github.goindex cc69994b38..b9d1048d0f 100644--- a/backend/tests/fake/github.go+++ b/backend/tests/fake/github.go@@ -4,7 +4,6 @@ import ("bytes""crypto/hmac""crypto/sha256"- "encoding/base64""encoding/hex""encoding/json""fmt"@@ -48,9 +47,6 @@ type githubRepositoryData struct {Files []*github.PullRequestFile*github.PullRequest}- // commitsDiff is the map for commits compare.- // The map key has the format "from...to" which is SHA or branch name.- commitsDiff map[string]*github.CommitsDiff}// NewGitHub creates a new fake implementation of GitHub VCS provider.@@ -67,13 +63,12 @@ func NewGitHub(port int) VCSProvider {g := e.Group("/api/v3")g.GET("/user/repos", gh.listRepositories)g.POST("/repos/:owner/:repo/hooks", gh.createRepositoryWebhook)+ g.DELETE("/repos/:owner/:repo/hooks/:hook", gh.deleteRepositoryWebhook)g.GET("/repos/:owner/:repo/git/commits/:commitID", gh.getRepositoryCommit)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.GET("/repos/:owner/:repo/pulls/:prID/files", gh.listPullRequestFile)g.POST("/repos/:owner/:repo/issues/:prID/comments", gh.createIssueComment)- g.GET("/repos/:owner/:repo/compare/:baseHead", gh.compareCommits)return gh}@@ -89,6 +84,10 @@ func (gh *GitHub) listRepositories(c echo.Context) error {return c.String(http.StatusOK, string(buf))}+func (*GitHub) deleteRepositoryWebhook(c echo.Context) error {+ return c.String(http.StatusOK, "")+}+func (gh *GitHub) createRepositoryWebhook(c echo.Context) error {r, err := gh.validRepository(c)if err != nil {@@ -158,36 +157,6 @@ func (gh *GitHub) readRepositoryFile(c echo.Context) error {return c.String(http.StatusBadRequest, "must accept vnd.github.raw")}-func (gh *GitHub) createRepositoryFile(c echo.Context) error {- r, err := gh.validRepository(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 unescape file path %q: %v", filePathEscaped, 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 file: %v", err))- }-- var fileCommit github.FileCommit- if err = json.Unmarshal(body, &fileCommit); err != nil {- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating repository webhook: %v", err))- }-- content, err := base64.StdEncoding.DecodeString(fileCommit.Content)- if err != nil {- return c.String(http.StatusBadRequest, fmt.Sprintf("failed to decode file content for %q: %v", filePathEscaped, err))- }- r.files[filePath] = string(content)- return nil-}-func (gh *GitHub) getRepositoryBranch(c echo.Context) error {r, err := gh.validRepository(c)if err != nil {@@ -239,26 +208,6 @@ func (gh *GitHub) listPullRequestFile(c echo.Context) error {return c.String(http.StatusOK, string(buf))}-func (gh *GitHub) compareCommits(c echo.Context) error {- r, err := gh.validRepository(c)- if err != nil {- return err- }-- key := c.Param("baseHead")- diff, ok := r.commitsDiff[key]- if !ok {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Cannot find the diff key %s", key))- }-- buf, err := json.Marshal(diff)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal response body").SetInternal(err)- }-- return c.String(http.StatusOK, string(buf))-}-func (*GitHub) createIssueComment(echo.Context) error {return nil}@@ -288,11 +237,6 @@ func (gh *GitHub) ListenerAddr() net.Addr {return gh.echo.ListenerAddr()}-// APIURL returns the GitHub VCS provider API URL.-func (*GitHub) APIURL(instanceURL string) string {- return fmt.Sprintf("%s/api/v3", instanceURL)-}-// CreateRepository creates a GitHub repository with given ID.func (gh *GitHub) CreateRepository(repository *vcs.Repository) error {gh.repositories[repository.FullPath] = &githubRepositoryData{@@ -307,7 +251,6 @@ func (gh *GitHub) CreateRepository(repository *vcs.Repository) error {Files []*github.PullRequestFile*github.PullRequest}{},- commitsDiff: map[string]*github.CommitsDiff{},}return nil}@@ -333,34 +276,6 @@ func (gh *GitHub) CreateBranch(id, branchName string) error {return nil}-// AddCommitsDiff adds a commits diff.-func (gh *GitHub) AddCommitsDiff(repositoryID, fromCommit, toCommit string, fileDiffList []vcs.FileDiff) error {- r, ok := gh.repositories[repositoryID]- if !ok {- return errors.Errorf("GitHub repository %s doesn't exist", repositoryID)- }- key := fmt.Sprintf("%s...%s", fromCommit, toCommit)- commitsDiff := &github.CommitsDiff{- Files: []github.PullRequestFile{},- }- for _, fileDiff := range fileDiffList {- prFile := github.PullRequestFile{- FileName: fileDiff.Path,- }- switch fileDiff.Type {- case vcs.FileDiffTypeAdded:- prFile.Status = "added"- case vcs.FileDiffTypeModified:- prFile.Status = "modified"- case vcs.FileDiffTypeRemoved:- prFile.Status = "removed"- }- commitsDiff.Files = append(commitsDiff.Files, prFile)- }- r.commitsDiff[key] = commitsDiff- return nil-}-// SendWebhookPush sends out a webhook for a push event for the GitHub// repository using given payload.func (gh *GitHub) SendWebhookPush(repositoryID string, payload []byte) error {@@ -420,23 +335,6 @@ func (gh *GitHub) AddFiles(repositoryID string, files map[string]string) error {return nil}-// GetFiles returns files with given paths from the GitHub repository.-func (gh *GitHub) GetFiles(repositoryID string, filePaths ...string) (map[string]string, error) {- r, ok := gh.repositories[repositoryID]- if !ok {- return nil, errors.Errorf("GitHub repository %q does not exist", repositoryID)- }-- // Get files- files := make(map[string]string)- for _, path := range filePaths {- if content, ok := r.files[path]; ok {- files[path] = content- }- }- return files, nil-}-// AddPullRequest creates a new pull request and add changed files to it.func (gh *GitHub) AddPullRequest(repositoryID string, prID int, files []*vcs.PullRequestFile) error {r, ok := gh.repositories[repositoryID]diff --git a/backend/tests/fake/gitlab.go b/backend/tests/fake/gitlab.goindex 95d4bc7898..26c5652b47 100644--- a/backend/tests/fake/gitlab.go+++ b/backend/tests/fake/gitlab.go@@ -45,9 +45,6 @@ type projectData struct {*gitlab.MergeRequestChange*gitlab.MergeRequest}- // commitsDiff is the map for commits compare.- // The map key has the format "from...to" which is SHA or branch name.- commitsDiff map[string]*gitlab.CommitsDiff}// NewGitLab creates a new fake implementation of GitLab VCS provider.@@ -65,16 +62,14 @@ func NewGitLab(port int) VCSProvider {projectGroup := e.Group("/api/v4")projectGroup.GET("/projects", gl.listRepositories)projectGroup.POST("/projects/:id/hooks", gl.createProjectHook)+ projectGroup.DELETE("/projects/:id/hooks/:hook", gl.deleteRepositoryWebhook)projectGroup.GET("/projects/:id/repository/commits/:commitID", gl.getFakeCommit)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/merge_requests/:mrID/changes", gl.getMergeRequestChanges)projectGroup.GET("/projects/:id/merge_requests/:mrID/notes", gl.createMergeRequestComment)- projectGroup.GET("/projects/:id/repository/compare", gl.compareCommits)return gl}@@ -94,11 +89,6 @@ func (gl *GitLab) ListenerAddr() net.Addr {return gl.echo.ListenerAddr()}-// APIURL returns the GitLab VCS provider API URL.-func (*GitLab) APIURL(instanceURL string) string {- return fmt.Sprintf("%s/api/v4", instanceURL)-}-// CreateRepository creates a GitLab project with given ID.func (gl *GitLab) CreateRepository(repository *vcs.Repository) error {// GitLab repo id should be int64.@@ -118,7 +108,6 @@ func (gl *GitLab) CreateRepository(repository *vcs.Repository) error {*gitlab.MergeRequestChange*gitlab.MergeRequest}{},- commitsDiff: map[string]*gitlab.CommitsDiff{},}return nil}@@ -157,6 +146,10 @@ func (gl *GitLab) listRepositories(c echo.Context) error {return c.String(http.StatusOK, string(buf))}+func (*GitLab) deleteRepositoryWebhook(c echo.Context) error {+ return c.String(http.StatusOK, "")+}+// createProjectHook creates a project webhook.func (gl *GitLab) createProjectHook(c echo.Context) error {pd, err := gl.validProject(c)@@ -232,33 +225,6 @@ func (gl *GitLab) getFakeCommit(c echo.Context) error {return c.String(http.StatusOK, string(buf))}-// createProjectFile creates a project file.-func (gl *GitLab) createProjectFile(c echo.Context) error {- 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))- }- b, err := io.ReadAll(c.Request().Body)- if err != nil {- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read create project file request body, error: %v", err))- }- fileCommit := &gitlab.FileCommit{}- if err := json.Unmarshal(b, fileCommit); err != nil {- return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unmarshal create project file request body, error: %v", err))- }-- // 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]@@ -387,49 +353,6 @@ func (*GitLab) createMergeRequestComment(echo.Context) error {return nil}-func (gl *GitLab) compareCommits(c echo.Context) error {- pd, err := gl.validProject(c)- if err != nil {- return err- }- key := fmt.Sprintf("%s...%s", c.QueryParam("from"), c.QueryParam("to"))- diff, ok := pd.commitsDiff[key]- if !ok {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Cannot find the diff key %s", key))- }- buf, err := json.Marshal(diff)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal response body").SetInternal(err)- }- return c.String(http.StatusOK, string(buf))-}--// AddCommitsDiff adds a commits diff.-func (gl *GitLab) AddCommitsDiff(projectID, fromCommit, toCommit string, fileDiffList []vcs.FileDiff) error {- pd, ok := gl.projects[projectID]- if !ok {- return errors.Errorf("GitLab project %s doesn't exist", projectID)- }- key := fmt.Sprintf("%s...%s", fromCommit, toCommit)- commitsDiff := &gitlab.CommitsDiff{- FileDiffList: []gitlab.MergeRequestFile{},- }- for _, fileDiff := range fileDiffList {- mrFile := gitlab.MergeRequestFile{- NewPath: fileDiff.Path,- }- switch fileDiff.Type {- case vcs.FileDiffTypeAdded:- mrFile.NewFile = true- case vcs.FileDiffTypeRemoved:- mrFile.DeletedFile = true- }- commitsDiff.FileDiffList = append(commitsDiff.FileDiffList, mrFile)- }- pd.commitsDiff[key] = commitsDiff- return nil-}-// SendWebhookPush sends out a webhook for a push event for the GitLab project// using given payload.func (gl *GitLab) SendWebhookPush(projectID string, payload []byte) error {@@ -484,23 +407,6 @@ func (gl *GitLab) AddFiles(projectID string, files map[string]string) error {return nil}-// GetFiles returns files with given paths from the GitLab project.-func (gl *GitLab) GetFiles(projectID string, filePaths ...string) (map[string]string, error) {- pd, ok := gl.projects[projectID]- if !ok {- return nil, errors.Errorf("gitlab project %q doesn't exist", projectID)- }-- // Get files- files := make(map[string]string, len(filePaths))- for _, path := range filePaths {- if content, ok := pd.files[path]; ok {- files[path] = content- }- }- return files, nil-}-// AddPullRequest creates a new merge request and add changed files to it.func (gl *GitLab) AddPullRequest(projectID string, mrID int, files []*vcs.PullRequestFile) error {pd, ok := gl.projects[projectID]diff --git a/backend/tests/fake/provider.go b/backend/tests/fake/provider.goindex 25cd52a3b5..10317aebc3 100644--- a/backend/tests/fake/provider.go+++ b/backend/tests/fake/provider.go@@ -14,8 +14,6 @@ type VCSProvider interface {Close() error// ListenerAddr returns listener address of the server.ListenerAddr() net.Addr- // APIURL returns the API URL of the VCS provider.- APIURL(instanceURL string) string// CreateRepository creates a new repository with given ID.CreateRepository(repository *vcs.Repository) error@@ -26,12 +24,8 @@ type VCSProvider interface {SendWebhookPush(repositoryID string, payload []byte) error// AddFiles adds given files to the repository.AddFiles(repositoryID string, files map[string]string) error- // GetFiles returns files with given paths from the repository.- GetFiles(repositoryID string, filePaths ...string) (map[string]string, error)// AddPullRequest creates a new pull request and add changed files to it.AddPullRequest(repositoryID string, prID int, files []*vcs.PullRequestFile) error- // AddCommitsDiff adds a commits diff.- AddCommitsDiff(repositoryID, fromCommit, toCommit string, fileDiffList []vcs.FileDiff) error}// VCSProviderCreator a function to create a new VCSProvider.diff --git a/backend/tests/vcs_test.go b/backend/tests/vcs_test.goindex eef1e7f653..d8deb52edf 100644--- a/backend/tests/vcs_test.go+++ b/backend/tests/vcs_test.go@@ -11,6 +11,7 @@ import ("google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/plugin/vcs"+ "github.com/bytebase/bytebase/backend/plugin/vcs/azure""github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket""github.com/bytebase/bytebase/backend/plugin/vcs/github""github.com/bytebase/bytebase/backend/plugin/vcs/gitlab"@@ -114,6 +115,38 @@ func TestVCS(t *testing.T) {},},},+ {+ name: "Azure",+ vcsProviderCreator: fake.NewAzure,+ vcsType: v1pb.VCSType_AZURE_DEVOPS,+ repository: &vcs.Repository{+ ID: "bytebase/project/bb",+ Name: "bytebase/project/bb",+ FullPath: "bytebase/project/bb",+ },+ webhookPushEvent: azure.PullRequestEvent{+ ID: "mock_event_id",+ EventType: "git.pullrequest.merged",+ Resource: &azure.PullRequestResource{+ Repository: &azure.Repository{},+ Links: &azure.PullRequestLinks{+ Web: &azure.PullRequestWeb{+ Href: fmt.Sprintf("https://dev.azure.com/test/vcs/pull-requests/%d", pullRequestID),+ },+ },+ PullRequestID: pullRequestID,+ Status: "completed",+ Title: pullRequestTitle,+ Description: pullRequestDescription,+ SourceRefName: "mock-source-branch",+ TargetRefName: fmt.Sprintf("refs/heads/%s", branchName),+ MergeStatus: "succeeded",+ LastMergeCommit: &azure.PullRequestEventLastMergeCommit{+ CommitID: fmt.Sprintf("%d", pullRequestID),+ },+ },+ },+ },}for _, test := range tests {// Fix the problem that closure in a for loop will always use the last element.@@ -143,7 +176,7 @@ func TestVCS(t *testing.T) {Url: ctl.vcsURL,AccessToken: "testApplicationSecret",},- VcsProviderId: strings.ToLower(test.vcsType.String()),+ VcsProviderId: strings.ToLower(test.name),})a.NoError(err)err = ctl.vcsProvider.CreateBranch(test.repository.ID, branchName)@@ -171,7 +204,12 @@ func TestVCS(t *testing.T) {UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"base_directory"}},})a.NoError(err)- a.Equal(baseDirectory, vcsConnector.BaseDirectory)++ if evcs.Type == v1pb.VCSType_AZURE_DEVOPS {+ a.Equal(fmt.Sprintf("/%s", baseDirectory), vcsConnector.BaseDirectory)+ } else {+ a.Equal(baseDirectory, vcsConnector.BaseDirectory)+ }instanceName := "testInstance"instanceDir, err := ctl.provisionSQLiteInstance(t.TempDir(), instanceName)