Skip to content

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

refactor: auth (#11421)

Danny Xu56cf7bbb9e1f
diff --git a/backend/api/gitops/github.go b/backend/api/gitops/github.go
index cda3113002..47a8cbb161 100644
--- a/backend/api/gitops/github.go
+++ b/backend/api/gitops/github.go
@@ -9,7 +9,6 @@ import (
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/vcs"
"github.com/bytebase/bytebase/backend/plugin/vcs/github"
@@ -32,11 +31,8 @@ func getGitHubPullRequestInfo(ctx context.Context, vcsProvider *store.VCSProvide
if pushEvent.PullRequest.Base.Ref != vcsConnector.Payload.Branch {
return nil, errors.Errorf("committed to branch %q, want branch %q", pushEvent.PullRequest.Base.Ref, vcsConnector.Payload.Branch)
}
- oauthContext := &common.OauthContext{
- AccessToken: vcsProvider.AccessToken,
- }
- mrFiles, err := vcs.Get(vcs.GitHub, vcs.ProviderConfig{}).ListPullRequestFile(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, fmt.Sprintf("%d", pushEvent.Number))
+ mrFiles, err := vcs.Get(vcs.GitHub, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).ListPullRequestFile(ctx, vcsConnector.Payload.ExternalId, fmt.Sprintf("%d", pushEvent.Number))
if err != nil {
return nil, errors.Errorf("failed to list merge %q request files, error %v", pushEvent.PullRequest.URL, err)
}
@@ -64,7 +60,7 @@ func getGitHubPullRequestInfo(ctx context.Context, vcsProvider *store.VCSProvide
}
}
for _, file := range prInfo.changes {
- content, err := vcs.Get(vcs.GitHub, vcs.ProviderConfig{}).ReadFileContent(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, file.path, vcs.RefInfo{RefType: vcs.RefTypeCommit, RefName: pushEvent.PullRequest.Head.SHA})
+ content, err := vcs.Get(vcs.GitHub, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).ReadFileContent(ctx, vcsConnector.Payload.ExternalId, file.path, vcs.RefInfo{RefType: vcs.RefTypeCommit, RefName: pushEvent.PullRequest.Head.SHA})
if err != nil {
return nil, errors.Errorf("failed read file content, merge request %q, file %q, error %v", pushEvent.PullRequest.URL, file.path, err)
}
diff --git a/backend/api/gitops/gitlab.go b/backend/api/gitops/gitlab.go
index 13b4a8079b..96bcb203f9 100644
--- a/backend/api/gitops/gitlab.go
+++ b/backend/api/gitops/gitlab.go
@@ -9,7 +9,6 @@ import (
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/vcs"
"github.com/bytebase/bytebase/backend/plugin/vcs/gitlab"
@@ -36,11 +35,8 @@ func getGitLabPullRequestInfo(ctx context.Context, vcsProvider *store.VCSProvide
if pushEvent.ObjectAttributes.TargetBranch != vcsConnector.Payload.Branch {
return nil, errors.Errorf("committed to branch %q, want branch %q", pushEvent.ObjectAttributes.TargetBranch, vcsConnector.Payload.Branch)
}
- oauthContext := &common.OauthContext{
- AccessToken: vcsProvider.AccessToken,
- }
- mrFiles, err := vcs.Get(vcs.GitLab, vcs.ProviderConfig{}).ListPullRequestFile(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, fmt.Sprintf("%d", pushEvent.ObjectAttributes.IID))
+ mrFiles, err := vcs.Get(vcs.GitLab, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).ListPullRequestFile(ctx, vcsConnector.Payload.ExternalId, fmt.Sprintf("%d", pushEvent.ObjectAttributes.IID))
if err != nil {
return nil, errors.Errorf("failed to list merge %q request files, error %v", pushEvent.ObjectAttributes.URL, err)
}
@@ -68,7 +64,7 @@ func getGitLabPullRequestInfo(ctx context.Context, vcsProvider *store.VCSProvide
}
}
for _, file := range prInfo.changes {
- content, err := vcs.Get(vcs.GitLab, vcs.ProviderConfig{}).ReadFileContent(ctx, oauthContext, vcsProvider.InstanceURL, vcsConnector.Payload.ExternalId, file.path, vcs.RefInfo{RefType: vcs.RefTypeCommit, RefName: pushEvent.ObjectAttributes.LastCommit.ID})
+ content, err := vcs.Get(vcs.GitLab, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).ReadFileContent(ctx, vcsConnector.Payload.ExternalId, file.path, vcs.RefInfo{RefType: vcs.RefTypeCommit, RefName: pushEvent.ObjectAttributes.LastCommit.ID})
if err != nil {
return nil, errors.Errorf("failed read file content, merge request %q, file %q, error %v", pushEvent.ObjectAttributes.URL, file.path, err)
}
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index 4ec5b58dfe..5d593c28ed 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -2,7 +2,6 @@ package v1
import (
"context"
- "encoding/json"
"fmt"
"log/slog"
"reflect"
@@ -24,11 +23,6 @@ import (
"github.com/bytebase/bytebase/backend/component/iam"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
- vcsplugin "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"
webhookplugin "github.com/bytebase/bytebase/backend/plugin/webhook"
"github.com/bytebase/bytebase/backend/store"
"github.com/bytebase/bytebase/backend/utils"
@@ -2081,106 +2075,3 @@ func validateMember(member string) error {
}
return errors.Errorf("invalid user %s", member)
}
-
-func isBranchNotFound(
- ctx context.Context,
- vcs *store.VCSProviderMessage,
- accessToken, externalID, branch string,
-) (bool, error) {
- oauthContext := &common.OauthContext{
- AccessToken: accessToken,
- }
- _, err := vcsplugin.Get(vcs.Type, vcsplugin.ProviderConfig{}).GetBranch(ctx,
- oauthContext,
- vcs.InstanceURL, externalID, branch)
-
- if common.ErrorCode(err) == common.NotFound {
- return true, nil
- }
- return false, err
-}
-
-func createVCSWebhook(ctx context.Context, vcsType vcsplugin.Type, webhookEndpointID, secretToken, accessToken, instanceURL, externalRepoID, bytebaseEndpointURL string) (string, error) {
- // Create a new webhook and retrieve the created webhook ID
- var webhookCreatePayload []byte
- var err error
- switch vcsType {
- case vcsplugin.GitLab:
- webhookCreate := gitlab.WebhookCreate{
- URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
- SecretToken: secretToken,
- MergeRequestsEvents: true,
- NoteEvents: true,
- EnableSSLVerification: false,
- }
- webhookCreatePayload, err = json.Marshal(webhookCreate)
- if err != nil {
- return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
- }
- case vcsplugin.GitHub:
- webhookPost := github.WebhookCreateOrUpdate{
- Config: github.WebhookConfig{
- URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
- ContentType: "json",
- Secret: secretToken,
- InsecureSSL: 1,
- },
- Events: []string{"pull_request", "pull_request_review_comment"},
- }
- webhookCreatePayload, err = json.Marshal(webhookPost)
- if err != nil {
- return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
- }
- case vcsplugin.Bitbucket:
- webhookPost := bitbucket.WebhookCreateOrUpdate{
- Description: "Bytebase GitOps",
- URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
- Active: true,
- Events: []string{"pullrequest:created", "pullrequest:updated", "pullrequest:fulfilled", "pullrequest:comment_created"},
- }
- webhookCreatePayload, err = json.Marshal(webhookPost)
- if err != nil {
- return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
- }
- case vcsplugin.AzureDevOps:
- part := strings.Split(externalRepoID, "/")
- if len(part) != 3 {
- return "", errors.Errorf("invalid external repo id %q", externalRepoID)
- }
- projectID, repositoryID := part[1], part[2]
-
- webhookPost := azure.WebhookCreateOrUpdate{
- ConsumerActionID: "httpRequest",
- ConsumerID: "webHooks",
- ConsumerInputs: azure.WebhookCreateConsumerInputs{
- URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
- AcceptUntrustedCerts: true,
- },
- EventType: "git.pullrequest.merged",
- PublisherID: "tfs",
- PublisherInputs: azure.WebhookCreatePublisherInputs{
- Repository: repositoryID,
- Branch: "", /* Any branches */
- PushedBy: "", /* Any users */
- ProjectID: projectID,
- },
- }
- webhookCreatePayload, err = json.Marshal(webhookPost)
- if err != nil {
- return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
- }
- }
- webhookID, err := vcsplugin.Get(vcsType, vcsplugin.ProviderConfig{}).CreateWebhook(
- ctx,
- &common.OauthContext{
- AccessToken: accessToken,
- },
- instanceURL,
- externalRepoID,
- webhookCreatePayload,
- )
- if err != nil {
- return "", errors.Wrap(err, "failed to create webhook")
- }
- return webhookID, nil
-}
diff --git a/backend/api/v1/vcs_connector_service.go b/backend/api/v1/vcs_connector_service.go
index 821e152838..57fa0077a0 100644
--- a/backend/api/v1/vcs_connector_service.go
+++ b/backend/api/v1/vcs_connector_service.go
@@ -2,6 +2,7 @@ package v1
import (
"context"
+ "encoding/json"
"fmt"
"log/slog"
"strings"
@@ -11,9 +12,14 @@ import (
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/timestamppb"
+ "github.com/pkg/errors"
+
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
- vcsplugin "github.com/bytebase/bytebase/backend/plugin/vcs"
+ "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"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -80,19 +86,18 @@ func (s *VCSConnectorService) CreateVCSConnector(ctx context.Context, request *v
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
- vcs, err := s.store.GetVCSProvider(ctx, &store.FindVCSProviderMessage{ResourceID: &vcsResourceID})
+ vcsProvider, err := s.store.GetVCSProvider(ctx, &store.FindVCSProviderMessage{ResourceID: &vcsResourceID})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to find vcs: %s", err.Error())
}
- if vcs == nil {
+ if vcsProvider == nil {
return nil, status.Errorf(codes.NotFound, "vcs %s not found", vcsResourceID)
}
// Check branch existence.
notFound, err := isBranchNotFound(
ctx,
- vcs,
- vcs.AccessToken,
+ vcsProvider,
request.GetVcsConnector().ExternalId,
request.GetVcsConnector().Branch,
)
@@ -105,7 +110,7 @@ func (s *VCSConnectorService) CreateVCSConnector(ctx context.Context, request *v
baseDir := request.GetVcsConnector().BaseDirectory
// Azure DevOps base directory should start with /.
- if vcs.Type == vcsplugin.AzureDevOps {
+ if vcsProvider.Type == vcs.AzureDevOps {
if !strings.HasPrefix(baseDir, "/") {
baseDir = "/" + request.GetVcsConnector().BaseDirectory
}
@@ -122,12 +127,11 @@ func (s *VCSConnectorService) CreateVCSConnector(ctx context.Context, request *v
return nil, status.Errorf(codes.Internal, "failed to generate random secret token for vcs with error: %v", err.Error())
}
vcsConnectorCreate := &store.VCSConnectorMessage{
- ProjectID: project.ResourceID,
- ResourceID: request.VcsConnectorId,
- CreatorID: principalID,
-
- VCSUID: vcs.ID,
- VCSResourceID: vcs.ResourceID,
+ ProjectID: project.ResourceID,
+ ResourceID: request.VcsConnectorId,
+ CreatorID: principalID,
+ VCSUID: vcsProvider.ID,
+ VCSResourceID: vcsProvider.ResourceID,
Payload: &storepb.VCSConnector{
Title: request.GetVcsConnector().Title,
FullPath: request.GetVcsConnector().FullPath,
@@ -145,7 +149,7 @@ func (s *VCSConnectorService) CreateVCSConnector(ctx context.Context, request *v
bytebaseEndpointURL = setting.ExternalUrl
}
webhookEndpointID := fmt.Sprintf("workspaces/%s/projects/%s/vcsConnectors/%s", workspaceID, project.ResourceID, request.VcsConnectorId)
- webhookID, err := createVCSWebhook(ctx, vcs.Type, webhookEndpointID, secretToken, vcs.AccessToken, vcs.InstanceURL, vcsConnectorCreate.Payload.ExternalId, bytebaseEndpointURL)
+ webhookID, err := createVCSWebhook(ctx, vcsProvider, webhookEndpointID, secretToken, vcsConnectorCreate.Payload.ExternalId, bytebaseEndpointURL)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create webhook for project %s with error: %v", vcsConnectorCreate.ProjectID, err.Error())
}
@@ -255,11 +259,11 @@ func (s *VCSConnectorService) UpdateVCSConnector(ctx context.Context, request *v
return nil, status.Errorf(codes.NotFound, "vcs connector %q not found", vcsConnectorID)
}
- vcs, err := s.store.GetVCSProvider(ctx, &store.FindVCSProviderMessage{ResourceID: &vcsConnector.VCSResourceID})
+ vcsProvider, err := s.store.GetVCSProvider(ctx, &store.FindVCSProviderMessage{ResourceID: &vcsConnector.VCSResourceID})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to find vcs: %s", err.Error())
}
- if vcs == nil {
+ if vcsProvider == nil {
return nil, status.Errorf(codes.NotFound, "vcs %s not found", vcsConnector.VCSResourceID)
}
@@ -280,7 +284,7 @@ func (s *VCSConnectorService) UpdateVCSConnector(ctx context.Context, request *v
case "base_directory":
baseDir := request.GetVcsConnector().BaseDirectory
// Azure DevOps base directory should start with /.
- if vcs.Type == vcsplugin.AzureDevOps {
+ if vcsProvider.Type == vcs.AzureDevOps {
if !strings.HasPrefix(baseDir, "/") {
baseDir = "/" + request.GetVcsConnector().BaseDirectory
}
@@ -298,8 +302,7 @@ func (s *VCSConnectorService) UpdateVCSConnector(ctx context.Context, request *v
}
notFound, err := isBranchNotFound(
ctx,
- vcs,
- vcs.AccessToken,
+ vcsProvider,
vcsConnector.Payload.ExternalId,
*v,
)
@@ -350,11 +353,11 @@ func (s *VCSConnectorService) DeleteVCSConnector(ctx context.Context, request *v
return nil, status.Errorf(codes.NotFound, "vcs connector %q not found", vcsConnectorID)
}
- vcs, err := s.store.GetVCSProvider(ctx, &store.FindVCSProviderMessage{ResourceID: &vcsConnector.VCSResourceID})
+ vcsProvider, err := s.store.GetVCSProvider(ctx, &store.FindVCSProviderMessage{ResourceID: &vcsConnector.VCSResourceID})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to find vcs: %s", err.Error())
}
- if vcs == nil {
+ if vcsProvider == nil {
return nil, status.Errorf(codes.NotFound, "vcs %d not found", vcsConnector.UID)
}
@@ -363,12 +366,11 @@ func (s *VCSConnectorService) DeleteVCSConnector(ctx context.Context, request *v
}
// Delete the webhook, and fail-open.
- if err = vcsplugin.Get(vcs.Type, vcsplugin.ProviderConfig{}).DeleteWebhook(
+ if err = vcs.Get(
+ vcsProvider.Type,
+ vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
+ ).DeleteWebhook(
ctx,
- &common.OauthContext{
- AccessToken: vcs.AccessToken,
- },
- vcs.InstanceURL,
vcsConnector.Payload.ExternalId,
vcsConnector.Payload.ExternalWebhookId,
); err != nil {
@@ -409,3 +411,93 @@ func convertStoreVCSConnector(ctx context.Context, stores *store.Store, vcsConne
}
return 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
+ }
+ return false, err
+}
+
+func createVCSWebhook(ctx context.Context, vcsProvider *store.VCSProviderMessage, webhookEndpointID, webhookSecretToken, externalRepoID, bytebaseEndpointURL string) (string, error) {
+ // Create a new webhook and retrieve the created webhook ID
+ var webhookCreatePayload []byte
+ var err error
+ switch vcsProvider.Type {
+ case vcs.GitLab:
+ webhookCreate := gitlab.WebhookCreate{
+ URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
+ SecretToken: webhookSecretToken,
+ MergeRequestsEvents: true,
+ NoteEvents: true,
+ EnableSSLVerification: false,
+ }
+ webhookCreatePayload, err = json.Marshal(webhookCreate)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
+ }
+ case vcs.GitHub:
+ webhookPost := github.WebhookCreateOrUpdate{
+ Config: github.WebhookConfig{
+ URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
+ ContentType: "json",
+ Secret: webhookSecretToken,
+ InsecureSSL: 1,
+ },
+ Events: []string{"pull_request", "pull_request_review_comment"},
+ }
+ webhookCreatePayload, err = json.Marshal(webhookPost)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
+ }
+ case vcs.Bitbucket:
+ webhookPost := bitbucket.WebhookCreateOrUpdate{
+ Description: "Bytebase GitOps",
+ URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
+ Active: true,
+ Events: []string{"pullrequest:created", "pullrequest:updated", "pullrequest:fulfilled", "pullrequest:comment_created"},
+ }
+ webhookCreatePayload, err = json.Marshal(webhookPost)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
+ }
+ case vcs.AzureDevOps:
+ part := strings.Split(externalRepoID, "/")
+ if len(part) != 3 {
+ return "", errors.Errorf("invalid external repo id %q", externalRepoID)
+ }
+ projectID, repositoryID := part[1], part[2]
+
+ webhookPost := azure.WebhookCreateOrUpdate{
+ ConsumerActionID: "httpRequest",
+ ConsumerID: "webHooks",
+ ConsumerInputs: azure.WebhookCreateConsumerInputs{
+ URL: fmt.Sprintf("%s/hook/%s", bytebaseEndpointURL, webhookEndpointID),
+ AcceptUntrustedCerts: true,
+ },
+ EventType: "git.pullrequest.merged",
+ PublisherID: "tfs",
+ PublisherInputs: azure.WebhookCreatePublisherInputs{
+ Repository: repositoryID,
+ Branch: "", /* Any branches */
+ PushedBy: "", /* Any users */
+ ProjectID: projectID,
+ },
+ }
+ webhookCreatePayload, err = json.Marshal(webhookPost)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal request body for creating webhook")
+ }
+ }
+ webhookID, err := vcs.Get(vcsProvider.Type, vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken}).CreateWebhook(
+ ctx,
+ externalRepoID,
+ webhookCreatePayload,
+ )
+ if err != nil {
+ return "", errors.Wrap(err, "failed to create webhook")
+ }
+ return webhookID, nil
+}
diff --git a/backend/api/v1/vcs_provider_service.go b/backend/api/v1/vcs_provider_service.go
index d09384dc44..f6187f93b2 100644
--- a/backend/api/v1/vcs_provider_service.go
+++ b/backend/api/v1/vcs_provider_service.go
@@ -131,13 +131,10 @@ func (s *VCSProviderService) SearchVCSProviderProjects(ctx context.Context, requ
return nil, err
}
- apiExternalProjectList, err := vcs.Get(vcsProvider.Type, vcs.ProviderConfig{}).FetchAllRepositoryList(
- ctx,
- &common.OauthContext{
- AccessToken: vcsProvider.AccessToken,
- },
- vcsProvider.InstanceURL,
- )
+ apiExternalProjectList, err := vcs.Get(
+ vcsProvider.Type,
+ vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
+ ).FetchAllRepositoryList(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to fetch external project list: %v", err)
}
diff --git a/backend/common/oauth.go b/backend/common/oauth.go
deleted file mode 100644
index f5d7d98d51..0000000000
--- a/backend/common/oauth.go
+++ /dev/null
@@ -1,6 +0,0 @@
-package common
-
-// OauthContext encapsulated the oauth info.
-type OauthContext struct {
- AccessToken string
-}
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index c7647b6a4e..f442956a2d 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -27,15 +27,16 @@ var _ vcs.Provider = (*Provider)(nil)
// Provider is a Azure DevOps VCS provider.
type Provider struct {
- client *http.Client
+ client *http.Client
+ instanceURL string
+ authToken string
}
func newProvider(config vcs.ProviderConfig) vcs.Provider {
- if config.Client == nil {
- config.Client = &http.Client{}
- }
return &Provider{
- client: config.Client,
+ client: &http.Client{},
+ instanceURL: config.InstanceURL,
+ authToken: config.AuthToken,
}
}
@@ -165,7 +166,7 @@ type ChangesResponse struct {
//
// 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 getChangesByCommit(ctx context.Context, oauthCtx *common.OauthContext, externalRepositoryID, commitID string) (*ChangesResponse, error) {
+func (p *Provider) getChangesByCommit(ctx context.Context, externalRepositoryID, commitID string) (*ChangesResponse, error) {
client := &http.Client{}
apiURL, err := getRepositoryAPIURL(externalRepositoryID)
if err != nil {
@@ -175,7 +176,7 @@ func getChangesByCommit(ctx context.Context, oauthCtx *common.OauthContext, exte
values := &url.Values{}
values.Set("api-version", "7.0")
url := fmt.Sprintf("%s/commits/%s/changes?%s", apiURL, url.PathEscape(commitID), values.Encode())
- code, _, body, err := internal.Get(ctx, client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, client, url, p.authToken)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
}
@@ -210,13 +211,13 @@ func getChangesByCommit(ctx context.Context, oauthCtx *common.OauthContext, exte
// The request included in this function requires the following scopes:
// vso.profile, vso.project.
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories/list?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, _ string) ([]*vcs.Repository, error) {
- publicAlias, err := p.getAuthenticatedProfilePublicAlias(ctx, oauthCtx)
+func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
+ publicAlias, err := p.getAuthenticatedProfilePublicAlias(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get authenticated profile public alias")
}
- organizations, err := p.listOrganizationsForMember(ctx, oauthCtx, publicAlias)
+ organizations, err := p.listOrganizationsForMember(ctx, publicAlias)
if err != nil {
return nil, errors.Wrap(err, "failed to list organizations for member")
}
@@ -233,7 +234,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
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())
- code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, p.authToken)
if err != nil {
return errors.Wrapf(err, "GET %s", url)
}
@@ -283,12 +284,12 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
// profile response.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/profile/profiles/get?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) getAuthenticatedProfilePublicAlias(ctx context.Context, oauthCtx *common.OauthContext) (string, error) {
+func (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())
- code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, p.authToken)
if err != nil {
return "", errors.Wrapf(err, "GET %s", url)
}
@@ -311,13 +312,13 @@ func (p *Provider) getAuthenticatedProfilePublicAlias(ctx context.Context, oauth
// 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
-func (p *Provider) listOrganizationsForMember(ctx context.Context, oauthCtx *common.OauthContext, memberID string) ([]string, error) {
+func (p *Provider) listOrganizationsForMember(ctx context.Context, memberID string) ([]string, error) {
urlParams := &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())
- code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, p.authToken)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
}
@@ -349,7 +350,7 @@ func (p *Provider) listOrganizationsForMember(ctx context.Context, oauthCtx *com
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthContext, _ string, repositoryID string, filePath string, refInfo vcs.RefInfo) (string, error) {
+func (p *Provider) ReadFileContent(ctx context.Context, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
apiURL, err := getRepositoryAPIURL(repositoryID)
if err != nil {
return "", err
@@ -376,7 +377,7 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthCo
values.Set("versionDescriptor.version", refInfo.RefName)
url := fmt.Sprintf("%s/items?%s", apiURL, values.Encode())
- code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, p.authToken)
if err != nil {
return "", errors.Wrapf(err, "GET %s", url)
}
@@ -393,7 +394,7 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthCo
// - branchName: The branch name.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/stats/get?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext, _, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+func (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName string) (*vcs.BranchInfo, error) {
if branchName == "" {
return nil, errors.New("branch name is required")
}
@@ -408,7 +409,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
urlParams.Set("api-version", "7.0")
url := fmt.Sprintf("%s/stats/branches?%s", apiURL, urlParams.Encode())
- code, _, body, err := internal.Get(ctx, p.client, url, oauthCtx.AccessToken)
+ code, _, body, err := internal.Get(ctx, p.client, url, p.authToken)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
}
@@ -437,7 +438,7 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
// ListPullRequestFile lists the changed files in the pull request.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/get-pull-request?view=azure-devops-rest-7.1
-func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, _, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
+func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
type mergeCommit struct {
CommitID string `json:"commitId"`
}
@@ -458,7 +459,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
@@ -476,7 +477,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
return nil, err
}
- changeResponse, err := getChangesByCommit(ctx, oauthCtx, repositoryID, res.LastMergeCommit.CommitID)
+ changeResponse, err := p.getChangesByCommit(ctx, repositoryID, res.LastMergeCommit.CommitID)
if err != nil {
return nil, err
}
@@ -495,7 +496,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
// API Version 7.0 do not specify the OAuth scope for creating webhook explicitly, but it works.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/hooks/subscriptions/create?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, _, externalRepositoryID string, payload []byte) (string, error) {
+func (p *Provider) CreateWebhook(ctx context.Context, externalRepositoryID string, payload []byte) (string, error) {
parts := strings.Split(externalRepositoryID, "/")
if len(parts) != 3 {
return "", errors.Errorf("invalid repository ID %q", externalRepositoryID)
@@ -508,7 +509,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
payload,
)
if err != nil {
@@ -531,7 +532,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
// DeleteWebhook deletes the webhook in the repository.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/hooks/subscriptions/delete?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, _, _, webhookID string) error {
+func (p *Provider) DeleteWebhook(ctx context.Context, _, webhookID string) error {
// By design, we encode the webhook ID as <organization>/<webhookID> for Azure DevOps.
parts := strings.Split(webhookID, "/")
if len(parts) != 2 {
@@ -547,7 +548,7 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthCont
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return errors.Wrapf(err, "failed to send delete webhook request")
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index 5faa8caac7..faadb1de95 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -34,15 +34,16 @@ var _ vcs.Provider = (*Provider)(nil)
// Provider is a Bitbucket Cloud VCS provider.
type Provider struct {
- client *http.Client
+ client *http.Client
+ instanceURL string
+ authToken string
}
func newProvider(config vcs.ProviderConfig) vcs.Provider {
- if config.Client == nil {
- config.Client = &http.Client{}
- }
return &Provider{
- client: config.Client,
+ client: &http.Client{},
+ instanceURL: config.InstanceURL,
+ authToken: config.AuthToken,
}
}
@@ -88,12 +89,12 @@ type CommitDiffStat struct {
New CommitFile `json:"new"`
}
-func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, url string) (diffs []*CommitDiffStat, next string, err error) {
+func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, url string) (diffs []*CommitDiffStat, next string, err error) {
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, "", errors.Wrapf(err, "GET %s", url)
@@ -114,7 +115,7 @@ func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, oauthCtx *com
Next string `json:"next"`
}
if err := json.Unmarshal([]byte(body), &resp); err != nil {
- return nil, "", errors.Wrapf(err, "failed to unmarshal file diff data from Bitbucket Cloud instance %s", instanceURL)
+ return nil, "", errors.Wrapf(err, "failed to unmarshal file diff data from Bitbucket Cloud instance %s", url)
}
return resp.Values, resp.Next, nil
}
@@ -137,16 +138,16 @@ type RepositoryPermission struct {
// has admin permissions, which is required to create webhook in the repository.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-user-permissions-repositories-get
-func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {
+func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
var bbcRepos []*Repository
params := url.Values{}
params.Add("q", `permission="admin"`)
params.Add("pagelen", strconv.Itoa(apiPageSize))
- next := fmt.Sprintf(`%s/user/permissions/repositories?%s`, p.APIURL(instanceURL), params.Encode())
+ next := fmt.Sprintf(`%s/user/permissions/repositories?%s`, p.APIURL(p.instanceURL), params.Encode())
for next != "" {
var err error
var repos []*Repository
- repos, next, err = p.fetchPaginatedRepositoryList(ctx, oauthCtx, next)
+ repos, next, err = p.fetchPaginatedRepositoryList(ctx, next)
if err != nil {
return nil, errors.Wrap(err, "fetch paginated list")
}
@@ -160,7 +161,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
ID: r.UUID,
Name: r.Name,
FullPath: r.FullName,
- WebURL: fmt.Sprintf("%s/%s", instanceURL, r.FullName),
+ WebURL: fmt.Sprintf("%s/%s", p.instanceURL, r.FullName),
},
)
}
@@ -170,12 +171,12 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
// fetchPaginatedRepositoryList fetches repositories in given page. It returns
// the paginated results along with a string indicating the URL of the next page
// (if exists).
-func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, url string) (repos []*Repository, next string, err error) {
+func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, url string) (repos []*Repository, next string, err error) {
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, "", errors.Wrapf(err, "GET %s", url)
@@ -215,13 +216,13 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#raw-file-contents
-func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
- url := fmt.Sprintf("%s/repositories/%s/src/%s/%s", p.APIURL(instanceURL), repositoryID, url.PathEscape(refInfo.RefName), url.PathEscape(filePath))
+func (p *Provider) ReadFileContent(ctx context.Context, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
+ url := fmt.Sprintf("%s/repositories/%s/src/%s/%s", p.APIURL(p.instanceURL), repositoryID, url.PathEscape(refInfo.RefName), url.PathEscape(filePath))
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return "", errors.Wrapf(err, "GET %s", url)
@@ -254,13 +255,13 @@ type Branch struct {
// GetBranch gets the given branch in the repository.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-name-get
-func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
- url := fmt.Sprintf("%s/repositories/%s/refs/branches/%s", p.APIURL(instanceURL), repositoryID, branchName)
+func (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+ url := fmt.Sprintf("%s/repositories/%s/refs/branches/%s", p.APIURL(p.instanceURL), repositoryID, branchName)
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
@@ -290,13 +291,13 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
// ListPullRequestFile lists the changed files in the pull request.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pullrequests/#api-repositories-workspace-repo-slug-pullrequests-pull-request-id-diffstat-get
-func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
+func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
var bbcDiffs []*CommitDiffStat
- next := fmt.Sprintf("%s/repositories/%s/pullrequests/%s/diffstat?pagelen=%d", p.APIURL(instanceURL), url.PathEscape(repositoryID), pullRequestID, apiPageSize)
+ next := fmt.Sprintf("%s/repositories/%s/pullrequests/%s/diffstat?pagelen=%d", p.APIURL(p.instanceURL), url.PathEscape(repositoryID), pullRequestID, apiPageSize)
for next != "" {
var err error
var diffs []*CommitDiffStat
- diffs, next, err = p.fetchPaginatedDiffFileList(ctx, oauthCtx, instanceURL, next)
+ diffs, next, err = p.fetchPaginatedDiffFileList(ctx, next)
if err != nil {
return nil, errors.Wrap(err, "fetch paginated list")
}
@@ -391,13 +392,13 @@ type Webhook struct {
// CreateWebhook creates a webhook in the repository with given payload.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-post
-func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
- url := fmt.Sprintf("%s/repositories/%s/hooks", p.APIURL(instanceURL), repositoryID)
+func (p *Provider) CreateWebhook(ctx context.Context, repositoryID string, payload []byte) (string, error) {
+ url := fmt.Sprintf("%s/repositories/%s/hooks", p.APIURL(p.instanceURL), repositoryID)
code, _, body, err := internal.Post(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
payload,
)
if err != nil {
@@ -428,13 +429,13 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
// DeleteWebhook deletes the webhook from the repository.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-uid-delete
-func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error {
- url := fmt.Sprintf("%s/repositories/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
+func (p *Provider) DeleteWebhook(ctx context.Context, repositoryID, webhookID string) error {
+ url := fmt.Sprintf("%s/repositories/%s/hooks/%s", p.APIURL(p.instanceURL), repositoryID, webhookID)
code, _, body, err := internal.Delete(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return errors.Wrapf(err, "DELETE %s", url)
diff --git a/backend/plugin/vcs/bitbucket/bitbucket_test.go b/backend/plugin/vcs/bitbucket/bitbucket_test.go
deleted file mode 100644
index ecd062acc5..0000000000
--- a/backend/plugin/vcs/bitbucket/bitbucket_test.go
+++ /dev/null
@@ -1,343 +0,0 @@
-package bitbucket
-
-import (
- "context"
- "io"
- "net/http"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/plugin/vcs"
-)
-
-func TestProvider_FetchAllRepositoryList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/user/permissions/repositories", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-user-permissions-repositories-get
- Body: io.NopCloser(strings.NewReader(`
-{
- "pagelen": 10,
- "values": [
- {
- "type": "repository_permission",
- "user": {
- "type": "user",
- "nickname": "evzijst",
- "display_name": "Erik van Zijst",
- "uuid": "{d301aafa-d676-4ee0-88be-962be7417567}"
- },
- "repository": {
- "type": "repository",
- "name": "geordi",
- "full_name": "bitbucket/geordi",
- "uuid": "{85d08b4e-571d-44e9-a507-fa476535aa98}"
- },
- "permission": "admin"
- }
- ],
- "page": 1,
- "size": 1
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.FetchAllRepositoryList(ctx, &common.OauthContext{}, bitbucketCloudURL)
- require.NoError(t, err)
-
- want := []*vcs.Repository{
- {
- ID: "{85d08b4e-571d-44e9-a507-fa476535aa98}",
- Name: "geordi",
- FullPath: "bitbucket/geordi",
- WebURL: "https://bitbucket.org/bitbucket/geordi",
- },
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_ReadFileContent(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/tests/__init__.py", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader("#!/bin/sh\nhalt")),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.ReadFileContent(ctx, &common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "tests/__init__.py", vcs.RefInfo{
- RefType: vcs.RefTypeCommit,
- RefName: "eefd5ef",
- })
- require.NoError(t, err)
-
- want := "#!/bin/sh\nhalt"
- assert.Equal(t, want, got)
-}
-
-func TestProvider_GetBranch(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/atlassian/aui/refs/branches/master", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-name-get
- Body: io.NopCloser(strings.NewReader(`
-{
- "name": "master",
- "links": {
- "commits": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commits/master"
- },
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/refs/branches/master"
- },
- "html": {
- "href": "https://bitbucket.org/atlassian/aui/branch/master"
- }
- },
- "default_merge_strategy": "squash",
- "merge_strategies": [
- "merge_commit",
- "squash",
- "fast_forward"
- ],
- "type": "branch",
- "target": {
- "hash": "e7d158ff7ed5538c28f94cd97a9ad569680fc94e",
- "repository": {
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui"
- },
- "html": {
- "href": "https://bitbucket.org/atlassian/aui"
- },
- "avatar": {
- "href": "https://bytebucket.org/ravatar/%7B585074de-7b60-4fd1-81ed-e0bc7fafbda5%7D?ts=86317"
- }
- },
- "type": "repository",
- "name": "aui",
- "full_name": "atlassian/aui",
- "uuid": "{585074de-7b60-4fd1-81ed-e0bc7fafbda5}"
- },
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
- },
- "comments": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e/comments"
- },
- "patch": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/patch/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
- },
- "html": {
- "href": "https://bitbucket.org/atlassian/aui/commits/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
- },
- "diff": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/diff/e7d158ff7ed5538c28f94cd97a9ad569680fc94e"
- },
- "approve": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e/approve"
- },
- "statuses": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/e7d158ff7ed5538c28f94cd97a9ad569680fc94e/statuses"
- }
- },
- "author": {
- "raw": "psre-renovate-bot <[email protected]>",
- "type": "author",
- "user": {
- "display_name": "psre-renovate-bot",
- "uuid": "{250a442a-3ab3-4fcb-87c3-3c8f3df65ec7}",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/users/%7B250a442a-3ab3-4fcb-87c3-3c8f3df65ec7%7D"
- },
- "html": {
- "href": "https://bitbucket.org/%7B250a442a-3ab3-4fcb-87c3-3c8f3df65ec7%7D/"
- },
- "avatar": {
- "href": "https://secure.gravatar.com/avatar/6972ee037c9f36360170a86f544071a2?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FP-3.png"
- }
- },
- "nickname": "Renovate Bot",
- "type": "user",
- "account_id": "5d5355e8c6b9320d9ea5b28d"
- }
- },
- "parents": [
- {
- "hash": "eab868a309e75733de80969a7bed1ec6d4651e06",
- "type": "commit",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/eab868a309e75733de80969a7bed1ec6d4651e06"
- },
- "html": {
- "href": "https://bitbucket.org/atlassian/aui/commits/eab868a309e75733de80969a7bed1ec6d4651e06"
- }
- }
- }
- ],
- "date": "2021-04-12T06:44:38+00:00",
- "message": "Merged in issue/NONE-renovate-master-babel-monorepo (pull request #2883)",
- "type": "commit"
- }
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.GetBranch(ctx, &common.OauthContext{}, bitbucketCloudURL, "atlassian/aui", "master")
- require.NoError(t, err)
-
- want := &vcs.BranchInfo{
- Name: "master",
- LastCommitID: "e7d158ff7ed5538c28f94cd97a9ad569680fc94e",
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_ListPullRequestFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/1/pullrequests/10086/diffstat", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#sample-output
- Body: io.NopCloser(strings.NewReader(`
-{
- "pagelen": 500,
- "values": [
- {
- "type": "diffstat",
- "status": "modified",
- "lines_removed": 1,
- "lines_added": 2,
- "old": {
- "path": "setup.py",
- "escaped_path": "setup.py",
- "type": "commit_file",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/src/e1749643d655d7c7014001a6c0f58abaf42ad850/setup.py"
- }
- }
- },
- "new": {
- "path": "setup.py",
- "escaped_path": "setup.py",
- "type": "commit_file",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/src/d222fa235229c55dad20b190b0b571adf737d5a6/setup.py"
- }
- }
- }
- }
- ],
- "page": 1,
- "size": 1
-}
-`)),
- }, nil
- },
- )
- ctx := context.Background()
- got, err := p.ListPullRequestFile(ctx, &common.OauthContext{}, bitbucketCloudURL, "1", "10086")
- require.NoError(t, err)
-
- want := []*vcs.PullRequestFile{
- {
- Path: "setup.py",
- LastCommitID: "d222fa235229c55dad20b190b0b571adf737d5a6",
- IsDeleted: false,
- },
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_CreateWebhook(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/1/hooks", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusCreated,
- Body: io.NopCloser(strings.NewReader(`
-{
- "uuid": "6611a7e9-6890-4e8e-84c5-b9707397da8b",
- "description": "Webhook Description",
- "url": "https://example.com/",
- "subject_type": "repository",
- "active": true,
- "events": [
- "repo:push",
- "issue:created",
- "issue:updated"
- ]
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.CreateWebhook(
- ctx,
- &common.OauthContext{},
- bitbucketCloudURL,
- "1",
- []byte(`
-{
- "description": "Webhook Description",
- "url": "https://example.com/",
- "active": true,
- "events": [
- "repo:push",
- "issue:created",
- "issue:updated"
- ]
-}`),
- )
- require.NoError(t, err)
- assert.Equal(t, "6611a7e9-6890-4e8e-84c5-b9707397da8b", got)
-}
-
-func TestProvider_DeleteWebhook(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, http.MethodDelete, r.Method)
- assert.Equal(t, "/2.0/repositories/1/hooks/1", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader("")),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.DeleteWebhook(ctx, &common.OauthContext{}, bitbucketCloudURL, "1", "1")
- require.NoError(t, err)
-}
-
-func newMockProvider(mockRoundTrip func(r *http.Request) (*http.Response, error)) vcs.Provider {
- return newProvider(
- vcs.ProviderConfig{
- Client: &http.Client{
- Transport: &common.MockRoundTripper{
- MockRoundTrip: mockRoundTrip,
- },
- },
- },
- )
-}
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index 26cb78c01c..c5d5f9a8de 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -35,15 +35,16 @@ var _ vcs.Provider = (*Provider)(nil)
// Provider is a GitHub VCS provider.
type Provider struct {
- client *http.Client
+ client *http.Client
+ instanceURL string
+ authToken string
}
func newProvider(config vcs.ProviderConfig) vcs.Provider {
- if config.Client == nil {
- config.Client = &http.Client{}
- }
return &Provider{
- client: config.Client,
+ client: &http.Client{},
+ instanceURL: config.InstanceURL,
+ authToken: config.AuthToken,
}
}
@@ -149,11 +150,11 @@ type CommitsDiff struct {
// the `permissions.admin` field.
//
// Docs: https://docs.github.com/en/rest/repos/repos#list-repositories-for-the-authenticated-user
-func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {
+func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
var githubRepos []Repository
page := 1
for {
- repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, oauthCtx, instanceURL, page)
+ repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, page)
if err != nil {
return nil, errors.Wrap(err, "fetch paginated list")
}
@@ -185,13 +186,13 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
// fetchPaginatedRepositoryList fetches repositories where the authenticated
// user has access to in given page. It returns the paginated results along
// with a boolean indicating whether the next page exists.
-func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string, page int) (repos []Repository, hasNextPage bool, err error) {
- url := fmt.Sprintf("%s/user/repos?page=%d&per_page=%d", p.APIURL(instanceURL), page, apiPageSize)
+func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, page int) (repos []Repository, hasNextPage bool, err error) {
+ url := fmt.Sprintf("%s/user/repos?page=%d&per_page=%d", p.APIURL(p.instanceURL), page, apiPageSize)
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, false, errors.Wrapf(err, "GET %s", url)
@@ -222,13 +223,13 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://docs.github.com/en/rest/repos/contents#get-repository-content
-func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
- url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), refInfo.RefName)
+func (p *Provider) ReadFileContent(ctx context.Context, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
+ url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", p.APIURL(p.instanceURL), repositoryID, url.QueryEscape(filePath), refInfo.RefName)
code, _, body, err := internal.GetWithHeader(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
map[string]string{
"Accept": "application/vnd.github.raw",
},
@@ -265,11 +266,11 @@ type PullRequestFile struct {
// ListPullRequestFile lists the changed files in the pull request.
//
// Docs: https://docs.github.com/en/rest/pulls/pulls#list-pull-requests-files
-func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
+func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
var allPRFiles []PullRequestFile
page := 1
for {
- fileList, err := p.listPaginatedPullRequestFile(ctx, oauthCtx, instanceURL, repositoryID, pullRequestID, page)
+ fileList, err := p.listPaginatedPullRequestFile(ctx, repositoryID, pullRequestID, page)
if err != nil {
return nil, errors.Wrap(err, "Failed to list pull request file")
}
@@ -318,13 +319,13 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
}
// listPaginatedPullRequestFile lists the changed files in the pull request with pagination.
-func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string, page int) ([]PullRequestFile, error) {
- requestURL := fmt.Sprintf("%s/repos/%s/pulls/%s/files?per_page=%d&page=%d", p.APIURL(instanceURL), repositoryID, pullRequestID, apiPageSize, page)
+func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, repositoryID, pullRequestID string, page int) ([]PullRequestFile, error) {
+ requestURL := fmt.Sprintf("%s/repos/%s/pulls/%s/files?per_page=%d&page=%d", p.APIURL(p.instanceURL), repositoryID, pullRequestID, apiPageSize, page)
code, _, body, err := internal.Get(
ctx,
p.client,
requestURL,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", requestURL)
@@ -366,13 +367,13 @@ type ReferenceObject struct {
// GetBranch gets the given branch in the repository.
//
// Docs: https://docs.github.com/en/rest/git/refs#get-a-reference
-func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
- url := fmt.Sprintf("%s/repos/%s/git/ref/heads/%s", p.APIURL(instanceURL), repositoryID, branchName)
+func (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+ url := fmt.Sprintf("%s/repos/%s/git/ref/heads/%s", p.APIURL(p.instanceURL), repositoryID, branchName)
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
@@ -412,13 +413,13 @@ type PullRequest struct {
// CreateWebhook creates a webhook in the repository with given payload.
//
// Docs: https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook
-func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
- url := fmt.Sprintf("%s/repos/%s/hooks", p.APIURL(instanceURL), repositoryID)
+func (p *Provider) CreateWebhook(ctx context.Context, repositoryID string, payload []byte) (string, error) {
+ url := fmt.Sprintf("%s/repos/%s/hooks", p.APIURL(p.instanceURL), repositoryID)
code, _, body, err := internal.Post(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
payload,
)
if err != nil {
@@ -449,13 +450,13 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
// DeleteWebhook deletes the webhook from the repository.
//
// Docs: https://docs.github.com/en/rest/webhooks/repos#delete-a-repository-webhook
-func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error {
- url := fmt.Sprintf("%s/repos/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
+func (p *Provider) DeleteWebhook(ctx context.Context, repositoryID, webhookID string) error {
+ url := fmt.Sprintf("%s/repos/%s/hooks/%s", p.APIURL(p.instanceURL), repositoryID, webhookID)
code, _, body, err := internal.Delete(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return errors.Wrapf(err, "DELETE %s", url)
diff --git a/backend/plugin/vcs/github/github_test.go b/backend/plugin/vcs/github/github_test.go
deleted file mode 100644
index a52329e3d3..0000000000
--- a/backend/plugin/vcs/github/github_test.go
+++ /dev/null
@@ -1,361 +0,0 @@
-package github
-
-import (
- "context"
- "io"
- "net/http"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/plugin/vcs"
-)
-
-func TestProvider_FetchAllRepositoryList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/user/repos", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response derived from https://docs.github.com/en/rest/repos/repos#list-repositories-for-the-authenticated-user
- Body: io.NopCloser(strings.NewReader(`
-[
- {
- "id": 1296269,
- "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
- "name": "Hello-World",
- "full_name": "octocat/Hello-World",
- "owner": {
- "login": "octocat",
- "id": 1,
- "node_id": "MDQ6VXNlcjE=",
- "avatar_url": "https://github.com/images/error/octocat_happy.gif",
- "gravatar_id": "",
- "url": "https://api.github.com/users/octocat",
- "html_url": "https://github.com/octocat",
- "followers_url": "https://api.github.com/users/octocat/followers",
- "following_url": "https://api.github.com/users/octocat/following{/other_user}",
- "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
- "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
- "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
- "organizations_url": "https://api.github.com/users/octocat/orgs",
- "repos_url": "https://api.github.com/users/octocat/repos",
- "events_url": "https://api.github.com/users/octocat/events{/privacy}",
- "received_events_url": "https://api.github.com/users/octocat/received_events",
- "type": "User",
- "site_admin": false
- },
- "private": false,
- "html_url": "https://github.com/octocat/Hello-World",
- "description": "This your first repo!",
- "fork": false,
- "url": "https://api.github.com/repos/octocat/Hello-World",
- "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
- "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}",
- "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
- "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}",
- "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}",
- "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}",
- "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}",
- "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}",
- "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}",
- "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors",
- "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments",
- "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads",
- "events_url": "https://api.github.com/repos/octocat/Hello-World/events",
- "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks",
- "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}",
- "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}",
- "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}",
- "git_url": "git:github.com/octocat/Hello-World.git",
- "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}",
- "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}",
- "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}",
- "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}",
- "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}",
- "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages",
- "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges",
- "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}",
- "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}",
- "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}",
- "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}",
- "ssh_url": "[email protected]:octocat/Hello-World.git",
- "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers",
- "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}",
- "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers",
- "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription",
- "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags",
- "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams",
- "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
- "clone_url": "https://github.com/octocat/Hello-World.git",
- "mirror_url": "git:git.example.com/octocat/Hello-World",
- "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks",
- "svn_url": "https://svn.github.com/octocat/Hello-World",
- "homepage": "https://github.com",
- "language": null,
- "forks_count": 9,
- "stargazers_count": 80,
- "watchers_count": 80,
- "size": 108,
- "default_branch": "master",
- "open_issues_count": 0,
- "is_template": true,
- "topics": [
- "octocat",
- "atom",
- "electron",
- "api"
- ],
- "has_issues": true,
- "has_projects": true,
- "has_wiki": true,
- "has_pages": false,
- "has_downloads": true,
- "archived": false,
- "disabled": false,
- "visibility": "public",
- "pushed_at": "2011-01-26T19:06:43Z",
- "created_at": "2011-01-26T19:01:12Z",
- "updated_at": "2011-01-26T19:14:43Z",
- "permissions": {
- "admin": true,
- "push": true,
- "pull": true
- },
- "allow_rebase_merge": true,
- "template_repository": null,
- "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O",
- "allow_squash_merge": true,
- "allow_auto_merge": false,
- "delete_branch_on_merge": true,
- "allow_merge_commit": true,
- "subscribers_count": 42,
- "network_count": 0,
- "license": {
- "key": "mit",
- "name": "MIT License",
- "url": "https://api.github.com/licenses/mit",
- "spdx_id": "MIT",
- "node_id": "MDc6TGljZW5zZW1pdA==",
- "html_url": "https://github.com/licenses/mit"
- },
- "forks": 1,
- "open_issues": 1,
- "watchers": 1
- },
- {
- "id": 1296270,
- "name": "Hello-World2",
- "full_name": "octocat/Hello-World2",
- "html_url": "https://github.com/octocat/Hello-World2",
- "permissions": {
- "admin": false,
- "push": false,
- "pull": true
- }
- }
-]
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.FetchAllRepositoryList(ctx, &common.OauthContext{}, githubComURL)
- require.NoError(t, err)
-
- // Repositories without admin permissions should be excluded
- want := []*vcs.Repository{
- {
- ID: "1296269",
- Name: "Hello-World",
- FullPath: "octocat/Hello-World",
- WebURL: "https://github.com/octocat/Hello-World",
- },
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_ReadFileContent(t *testing.T) {
- const want = `# Sample GitLab Project
-
-This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,
-named and filled with lorem ipsum.
-
-You can look around to get an idea how to structure your project and, when done, you can safely delete this project.
-
-[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)
-`
-
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/octocat/Hello-World/contents/README.md", r.URL.Path)
- assert.Equal(t, "application/vnd.github.raw", r.Header.Get("Accept"))
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response derived from https://docs.github.com/en/rest/repos/contents#get-repository-content
- Body: io.NopCloser(strings.NewReader(want)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.ReadFileContent(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "README.md", vcs.RefInfo{
- RefType: vcs.RefTypeBranch,
- RefName: "master",
- })
- require.NoError(t, err)
-
- assert.Equal(t, want, got)
-}
-
-func TestProvider_CreateWebhook(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/1/hooks", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusCreated,
- // Example response taken from https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook
- Body: io.NopCloser(strings.NewReader(`
-{
- "type": "Repository",
- "id": 12345678,
- "name": "web",
- "active": true,
- "events": [
- "push",
- "pull_request"
- ],
- "config": {
- "content_type": "json",
- "insecure_ssl": "0",
- "url": "https://example.com/webhook"
- },
- "updated_at": "2019-06-03T00:57:16Z",
- "created_at": "2019-06-03T00:57:16Z",
- "url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678",
- "test_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/test",
- "ping_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/pings",
- "deliveries_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/deliveries",
- "last_response": {
- "code": null,
- "status": "unused",
- "message": null
- }
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.CreateWebhook(ctx, &common.OauthContext{}, githubComURL, "1", []byte(""))
- require.NoError(t, err)
- assert.Equal(t, "12345678", got)
-}
-
-func TestProvider_DeleteWebhook(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/1/hooks/1", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader("")),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.DeleteWebhook(ctx, &common.OauthContext{}, githubComURL, "1", "1")
- require.NoError(t, err)
-}
-
-func TestProvider_GetBranch(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "GET", r.Method)
- assert.Equal(t, "/repos/octocat/Hello-World/git/ref/heads/featureA", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/git/refs#get-a-reference
- Body: io.NopCloser(strings.NewReader(`
-{
- "ref": "refs/heads/featureA",
- "node_id": "MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlQQ==",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/refs/heads/featureA",
- "object": {
- "type": "commit",
- "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
- }
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.GetBranch(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "featureA")
- require.NoError(t, err)
-
- want := &vcs.BranchInfo{
- Name: "featureA",
- LastCommitID: "aa218f56b14c9653891f9e74264a383fa43fefbd",
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_ListPullRequestFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/octocat/Hello-World/pulls/1/files", r.URL.Path)
- if r.URL.Query().Get("page") == "2" {
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader(`[]`)),
- }, nil
- }
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/pulls/pulls#list-pull-requests-files
- Body: io.NopCloser(strings.NewReader(`
-[
- {
- "sha": "bbcd538c8e72b8c175046e27cc8f907076331401",
- "filename": "file1.txt",
- "status": "added",
- "additions": 103,
- "deletions": 21,
- "changes": 124,
- "blob_url": "https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt",
- "raw_url": "https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt",
- "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e",
- "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"
- }
-]
-`)),
- }, nil
- },
- )
- ctx := context.Background()
- got, err := p.ListPullRequestFile(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "1")
- require.NoError(t, err)
-
- want := []*vcs.PullRequestFile{
- {
- Path: "file1.txt",
- LastCommitID: "6dcb09b5b57875f334f61aebed695e2e4193db5e",
- IsDeleted: false,
- },
- }
- assert.Equal(t, want, got)
-}
-
-func newMockProvider(mockRoundTrip func(r *http.Request) (*http.Response, error)) vcs.Provider {
- return newProvider(
- vcs.ProviderConfig{
- Client: &http.Client{
- Transport: &common.MockRoundTripper{
- MockRoundTrip: mockRoundTrip,
- },
- },
- },
- )
-}
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index 4e11f356ee..4805765dbc 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -145,15 +145,16 @@ func init() {
// Provider is a GitLab self host VCS provider.
type Provider struct {
- client *http.Client
+ client *http.Client
+ instanceURL string
+ authToken string
}
func newProvider(config vcs.ProviderConfig) vcs.Provider {
- if config.Client == nil {
- config.Client = &http.Client{}
- }
return &Provider{
- client: config.Client,
+ client: &http.Client{},
+ instanceURL: config.InstanceURL,
+ authToken: config.AuthToken,
}
}
@@ -166,11 +167,11 @@ func (*Provider) APIURL(instanceURL string) string {
// has a maintainer role, which is required to create webhook in the project.
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#list-all-projects
-func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string) ([]*vcs.Repository, error) {
+func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
var gitlabRepos []gitLabRepository
page := 1
for {
- repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, oauthCtx, instanceURL, page)
+ repos, hasNextPage, err := p.fetchPaginatedRepositoryList(ctx, page)
if err != nil {
return nil, errors.Wrap(err, "fetch paginated list")
}
@@ -199,15 +200,15 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx *common.
// fetchPaginatedRepositoryList fetches repositories where the authenticated
// user has a maintainer role in given page. It return the paginated results
// along with a boolean indicating whether the next page exists.
-func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string, page int) (repos []gitLabRepository, hasNextPage bool, err error) {
+func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, page int) (repos []gitLabRepository, hasNextPage bool, err error) {
// We will use user's token to create webhook in the project, which requires the
// token owner to be at least the project maintainer(40).
- url := fmt.Sprintf("%s/projects?membership=true&simple=true&min_access_level=40&page=%d&per_page=%d", p.APIURL(instanceURL), page, apiPageSize)
+ url := fmt.Sprintf("%s/projects?membership=true&simple=true&min_access_level=40&page=%d&per_page=%d", p.APIURL(p.instanceURL), page, apiPageSize)
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, false, errors.Wrapf(err, "GET %s", url)
@@ -238,8 +239,8 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://docs.gitlab.com/ee/api/repository_files.html#get-file-from-repository
-func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
- file, err := p.readFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, refInfo)
+func (p *Provider) ReadFileContent(ctx context.Context, repositoryID, filePath string, refInfo vcs.RefInfo) (string, error) {
+ file, err := p.readFile(ctx, repositoryID, filePath, refInfo)
if err != nil {
return "", errors.Wrap(err, "read file")
}
@@ -264,13 +265,13 @@ type MergeRequestFile struct {
//
// TODO(d): migrate to diff API.
// Docs: https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr-changes
-func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
- url := fmt.Sprintf("%s/projects/%s/merge_requests/%s/changes", p.APIURL(instanceURL), repositoryID, pullRequestID)
+func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {
+ url := fmt.Sprintf("%s/projects/%s/merge_requests/%s/changes", p.APIURL(p.instanceURL), repositoryID, pullRequestID)
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
@@ -326,13 +327,13 @@ type MergeRequestCreate struct {
// GetBranch gets the given branch in the repository.
//
// Docs: https://docs.gitlab.com/ee/api/branches.html#get-single-repository-branch
-func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
- url := fmt.Sprintf("%s/projects/%s/repository/branches/%s", p.APIURL(instanceURL), repositoryID, branchName)
+func (p *Provider) GetBranch(ctx context.Context, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+ url := fmt.Sprintf("%s/projects/%s/repository/branches/%s", p.APIURL(p.instanceURL), repositoryID, branchName)
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
@@ -367,13 +368,13 @@ type MergeRequest struct {
// CreateWebhook creates a webhook in the repository with given payload.
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#add-project-hook
-func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {
- url := fmt.Sprintf("%s/projects/%s/hooks", p.APIURL(instanceURL), repositoryID)
+func (p *Provider) CreateWebhook(ctx context.Context, repositoryID string, payload []byte) (string, error) {
+ url := fmt.Sprintf("%s/projects/%s/hooks", p.APIURL(p.instanceURL), repositoryID)
code, _, body, err := internal.Post(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
payload,
)
if err != nil {
@@ -409,13 +410,13 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
// DeleteWebhook deletes the webhook from the repository.
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#delete-project-hook
-func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error {
- url := fmt.Sprintf("%s/projects/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
+func (p *Provider) DeleteWebhook(ctx context.Context, repositoryID, webhookID string) error {
+ url := fmt.Sprintf("%s/projects/%s/hooks/%s", p.APIURL(p.instanceURL), repositoryID, webhookID)
code, _, body, err := internal.Delete(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return errors.Wrapf(err, "DELETE %s", url)
@@ -437,16 +438,16 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthCont
//
// TODO: The same GitLab API endpoint supports using the HEAD request to only
// get the file metadata.
-func (p *Provider) readFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (*File, error) {
+func (p *Provider) readFile(ctx context.Context, repositoryID, filePath string, refInfo vcs.RefInfo) (*File, error) {
// GitLab is often deployed behind a reverse proxy, which may have compression enabled that is transparent to the GitLab instance.
// In such cases, the HTTP header "Content-Encoding" will, for example, be changed to "gzip" and makes the value of "Content-Length" untrustworthy.
// We can avoid dealing with this type of problem by using the raw API instead of the typical JSON API.
- url := fmt.Sprintf("%s/projects/%s/repository/files/%s/raw?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), url.QueryEscape(refInfo.RefName))
+ url := fmt.Sprintf("%s/projects/%s/repository/files/%s/raw?ref=%s", p.APIURL(p.instanceURL), repositoryID, url.QueryEscape(filePath), url.QueryEscape(refInfo.RefName))
code, _, body, err := internal.Get(
ctx,
p.client,
url,
- oauthCtx.AccessToken,
+ p.authToken,
)
if err != nil {
return nil, errors.Wrapf(err, "GET %s", url)
diff --git a/backend/plugin/vcs/gitlab/gitlab_test.go b/backend/plugin/vcs/gitlab/gitlab_test.go
deleted file mode 100644
index e848e023de..0000000000
--- a/backend/plugin/vcs/gitlab/gitlab_test.go
+++ /dev/null
@@ -1,288 +0,0 @@
-package gitlab
-
-import (
- "context"
- "io"
- "net/http"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-
- "github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/plugin/vcs"
-)
-
-func TestProvider_FetchAllRepositoryList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/projects.html#list-all-projects
- Body: io.NopCloser(strings.NewReader(`
-[
- {
- "id": 4,
- "description": null,
- "default_branch": "master",
- "ssh_url_to_repo": "[email protected]:diaspora/diaspora-client.git",
- "http_url_to_repo": "http://example.com/diaspora/diaspora-client.git",
- "web_url": "http://example.com/diaspora/diaspora-client",
- "readme_url": "http://example.com/diaspora/diaspora-client/blob/master/README.md",
- "tag_list": [
- "example",
- "disapora client"
- ],
- "topics": [
- "example",
- "disapora client"
- ],
- "name": "Diaspora Client",
- "name_with_namespace": "Diaspora / Diaspora Client",
- "path": "diaspora-client",
- "path_with_namespace": "diaspora/diaspora-client",
- "created_at": "2013-09-30T13:46:02Z",
- "last_activity_at": "2013-09-30T13:46:02Z",
- "forks_count": 0,
- "avatar_url": "http://example.com/uploads/project/avatar/4/uploads/avatar.png",
- "star_count": 0
- }
-]
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.FetchAllRepositoryList(ctx, &common.OauthContext{}, "")
- require.NoError(t, err)
-
- want := []*vcs.Repository{
- {
- ID: "4",
- Name: "Diaspora Client",
- FullPath: "diaspora/diaspora-client",
- WebURL: "http://example.com/diaspora/diaspora-client",
- },
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_ReadFileContent(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/repository/files/app%2Fmodels%2Fkey.rb/raw", r.URL.RawPath)
- header := http.Header{}
- header.Set("x-gitlab-file-name", "key.rb")
- header.Set("x-gitlab-file-path", "app/models/key.rb")
- header.Set("x-gitlab-size", "3")
- header.Set("x-gitlab-last-commit-id", "27329d3afac51fbf2762428e12f2635d1137c549")
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response derived from https://docs.gitlab.com/ee/api/repository_files.html#get-file-from-repository
- Body: io.NopCloser(strings.NewReader(`# Sample GitLab Project
-
-This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,
-named and filled with lorem ipsum.
-
-You can look around to get an idea how to structure your project and, when done, you can safely delete this project.
-
-[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)
-`)),
- Header: header,
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.ReadFileContent(ctx, &common.OauthContext{}, "", "1", "app/models/key.rb", vcs.RefInfo{
- RefType: vcs.RefTypeBranch,
- RefName: "master",
- })
- require.NoError(t, err)
-
- want := `# Sample GitLab Project
-
-This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,
-named and filled with lorem ipsum.
-
-You can look around to get an idea how to structure your project and, when done, you can safely delete this project.
-
-[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)
-`
- assert.Equal(t, want, got)
-}
-
-func TestProvider_CreateWebhook(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/hooks", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusCreated,
- // Example response taken from https://docs.gitlab.com/ee/api/projects.html#get-project-hook
- Body: io.NopCloser(strings.NewReader(`
-{
- "id": 1,
- "url": "http://example.com/hook",
- "project_id": 3,
- "push_events": true,
- "push_events_branch_filter": "",
- "issues_events": true,
- "confidential_issues_events": true,
- "merge_requests_events": true,
- "tag_push_events": true,
- "note_events": true,
- "confidential_note_events": true,
- "job_events": true,
- "pipeline_events": true,
- "wiki_page_events": true,
- "deployment_events": true,
- "releases_events": true,
- "enable_ssl_verification": true,
- "created_at": "2012-10-12T17:04:47Z"
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.CreateWebhook(ctx, &common.OauthContext{}, "", "1", []byte(""))
- require.NoError(t, err)
- assert.Equal(t, "1", got)
-}
-
-func TestProvider_DeleteWebhook(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/hooks/1", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader("")),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.DeleteWebhook(ctx, &common.OauthContext{}, "", "1", "1")
- require.NoError(t, err)
-}
-
-func TestProvider_GetBranch(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "GET", r.Method)
- assert.Equal(t, "/api/v4/projects/1/repository/branches/main", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/branches.html#get-single-repository-branch
- Body: io.NopCloser(strings.NewReader(`
-{
- "name": "main",
- "merged": false,
- "protected": true,
- "default": true,
- "developers_can_push": false,
- "developers_can_merge": false,
- "can_push": true,
- "web_url": "https://gitlab.example.com/my-group/my-project/-/tree/main",
- "commit": {
- "author_email": "[email protected]",
- "author_name": "John Smith",
- "authored_date": "2012-06-27T05:51:39-07:00",
- "committed_date": "2012-06-28T03:44:20-07:00",
- "committer_email": "[email protected]",
- "committer_name": "John Smith",
- "id": "7b5c3cc8be40ee161ae89a06bba6229da1032a0c",
- "short_id": "7b5c3cc",
- "title": "add projects API",
- "message": "add projects API",
- "parent_ids": [
- "4ad91d3c1144c406e50c7b33bae684bd6837faf8"
- ]
- }
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.GetBranch(ctx, &common.OauthContext{}, "", "1", "main")
- require.NoError(t, err)
-
- want := &vcs.BranchInfo{
- Name: "main",
- LastCommitID: "7b5c3cc8be40ee161ae89a06bba6229da1032a0c",
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_ListPullRequestFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/merge_requests/1/changes", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr-changes
- Body: io.NopCloser(strings.NewReader(`
-{
- "id": 21,
- "iid": 1,
- "project_id": 4,
- "title": "Blanditiis beatae suscipit hic assumenda et molestias nisi asperiores repellat et.",
- "state": "reopened",
- "created_at": "2015-02-02T19:49:39.159Z",
- "updated_at": "2015-02-02T20:08:49.959Z",
- "target_branch": "secret_token",
- "source_branch": "version-1-9",
- "source_project_id": 4,
- "target_project_id": 4,
- "labels": [ ],
- "description": "Qui voluptatibus placeat ipsa alias quasi. Deleniti rem ut sint. Optio velit qui distinctio.",
- "draft": false,
- "work_in_progress": false,
- "merge_when_pipeline_succeeds": true,
- "merge_status": "can_be_merged",
- "subscribed" : true,
- "sha": "8888888888888888888888888888888888888888",
- "merge_commit_sha": null,
- "squash_commit_sha": null,
- "changes": [
- {
- "old_path": "VERSION",
- "new_path": "VERSION",
- "a_mode": "100644",
- "b_mode": "100644",
- "new_file": false,
- "renamed_file": false,
- "deleted_file": false
- }
- ],
- "overflow": false
-}
-`)),
- }, nil
- },
- )
- ctx := context.Background()
- got, err := p.ListPullRequestFile(ctx, &common.OauthContext{}, "", "1", "1")
- require.NoError(t, err)
-
- want := []*vcs.PullRequestFile{
- {
- Path: "VERSION",
- LastCommitID: "8888888888888888888888888888888888888888",
- IsDeleted: false,
- },
- }
- assert.Equal(t, want, got)
-}
-
-func newMockProvider(mockRoundTrip func(r *http.Request) (*http.Response, error)) vcs.Provider {
- return newProvider(
- vcs.ProviderConfig{
- Client: &http.Client{
- Transport: &common.MockRoundTripper{
- MockRoundTrip: mockRoundTrip,
- },
- },
- },
- )
-}
diff --git a/backend/plugin/vcs/vcs.go b/backend/plugin/vcs/vcs.go
index 8187609a51..691c2e584e 100644
--- a/backend/plugin/vcs/vcs.go
+++ b/backend/plugin/vcs/vcs.go
@@ -2,10 +2,7 @@ package vcs
import (
"context"
- "net/http"
"sync"
-
- "github.com/bytebase/bytebase/backend/common"
)
// Type is the type of a VCS.
@@ -210,46 +207,22 @@ type Provider interface {
APIURL(instanceURL string) string
// Fetch all repository within a given user's scope
- //
- // oauthCtx: OAuth context to write the file content
- // instanceURL: VCS instance URL
- FetchAllRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string) ([]*Repository, error)
+ FetchAllRepositoryList(ctx context.Context) ([]*Repository, error)
// Reads the file content
- //
- // oauthCtx: OAuth context to read the file content
- // instanceURL: VCS instance URL
- // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
- // filePath: file path to be read
- // ref: the specific file version to be read, could be a name of branch, tag or commit
- ReadFileContent(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo RefInfo) (string, error)
+ ReadFileContent(ctx context.Context, repositoryID, filePath string, refInfo RefInfo) (string, error)
// GetBranch gets the given branch in the repository.
- //
- // oauthCtx: OAuth context to create the webhook
- // instanceURL: VCS instance URL
- // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
- // branchName: the target branch name
- GetBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, branchName string) (*BranchInfo, error)
+ GetBranch(ctx context.Context, repositoryID, branchName string) (*BranchInfo, error)
// CreatePullRequest creates the pull request in the repository.
- //
- // oauthCtx: OAuth context to create the webhook
- // instanceURL: VCS instance URL
- // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
- // pullRequestID: the pull request id
- ListPullRequestFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*PullRequestFile, error)
+ ListPullRequestFile(ctx context.Context, repositoryID, pullRequestID string) ([]*PullRequestFile, error)
// Creates a webhook. Returns the created webhook ID on success.
- //
- // oauthCtx: OAuth context to create the webhook
- // instanceURL: VCS instance URL
- // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
- // payload: the webhook payload
- CreateWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error)
+ CreateWebhook(ctx context.Context, repositoryID string, payload []byte) (string, error)
// Deletes a webhook.
- DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error
+ DeleteWebhook(ctx context.Context, repositoryID, webhookID string) error
}
var (
@@ -259,7 +232,8 @@ var (
// ProviderConfig is the provider configuration.
type ProviderConfig struct {
- Client *http.Client
+ InstanceURL string
+ AuthToken string
}
type providerFunc func(ProviderConfig) Provider