Skip to content

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

chore: delete unused code (#11413)

Danny Xue3f9f3290135
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index 5d58055d18..a93d427b4a 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -25,10 +25,6 @@ func init() {
vcs.Register(vcs.AzureDevOps, newProvider)
}
-const (
- apiPageSize = 100
-)
-
var _ vcs.Provider = (*Provider)(nil)
// Provider is a Azure DevOps VCS provider.
@@ -206,137 +202,6 @@ func GetChangesByCommit(ctx context.Context, oauthCtx *common.OauthContext, exte
return &result, nil
}
-// FetchCommitByID fetches the commit data by its ID from the repository.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx *common.OauthContext, _, externalRepositoryID, commitID string) (*vcs.Commit, error) {
- apiURL, err := getRepositoryAPIURL(externalRepositoryID)
- if err != nil {
- return nil, err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- url := fmt.Sprintf("%s/commits/%s?%s", apiURL, url.PathEscape(commitID), values.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, fmt.Sprintf("commit %q does not exist in the repository %s", commitID, externalRepositoryID))
- }
- if code != http.StatusOK {
- return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
- }
-
- type fetchCommitByIDResponse struct {
- CommitID string `json:"commitId"`
- Author CommitAuthor `json:"author"`
- RemoteURL string `json:"remoteUrl"`
- }
-
- commit := new(fetchCommitByIDResponse)
- if err := json.Unmarshal([]byte(body), commit); err != nil {
- return nil, errors.Wrapf(err, "unmarshal body")
- }
-
- return &vcs.Commit{
- ID: commit.CommitID,
- AuthorName: commit.Author.Name,
- CreatedTs: commit.Author.Date.Unix(),
- URL: commit.RemoteURL,
- }, nil
-}
-
-// GetDiffFileList gets the diff files list between two commits.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/diffs/get?view=azure-devops-rest-7.0&tabs=HTTP#between-commit-ids
-func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string, repositoryID string, beforeCommit string, afterCommit string) ([]vcs.FileDiff, error) {
- var result []vcs.FileDiff
- page := 0
- for {
- files, hasMore, err := p.getPaginatedDiffFileList(ctx, oauthCtx, instanceURL, repositoryID, beforeCommit, afterCommit, page)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get paginated diff file list")
- }
- result = append(result, files...)
- if !hasMore {
- break
- }
- page++
- }
- return result, nil
-}
-
-// getPaginatedDiffFileList gets the diff file list between two commits with pagination.
-func (p *Provider) getPaginatedDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, _ string, repositoryID string, beforeCommit string, afterCommit string, page int) ([]vcs.FileDiff, bool, error) {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return nil, false, err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- values.Set("$top", fmt.Sprintf("%d", apiPageSize))
- values.Set("$skip", fmt.Sprintf("%d", page*apiPageSize))
- if beforeCommit != "" {
- values.Set("baseVersion", beforeCommit)
- values.Set("baseVersionType", "commit")
- }
- values.Set("targetVersion", afterCommit)
- values.Set("targetVersionType", "commit")
- values.Set("diffCommonCommit", "false")
-
- url := fmt.Sprintf("%s/diffs/commits?%s", apiURL, values.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
- if err != nil {
- return nil, false, errors.Wrapf(err, "GET %s", url)
- }
-
- if code != http.StatusOK {
- return nil, false, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
- }
-
- type diffFileResponseChangeItem struct {
- Path string `json:"path"`
- }
- type diffFileResponseChange struct {
- Item diffFileResponseChangeItem `json:"item"`
- ChangeType string `json:"changeType"`
- }
- type diffFileResponse struct {
- Changes []diffFileResponseChange `json:"changes"`
- }
-
- r := new(diffFileResponse)
- if err := json.Unmarshal([]byte(body), r); err != nil {
- return nil, false, errors.Wrapf(err, "failed to unmarshal get diff file list response body, code %v", code)
- }
-
- result := make([]vcs.FileDiff, 0, len(r.Changes))
- for _, c := range r.Changes {
- var changeType vcs.FileDiffType
- switch c.ChangeType {
- case "add":
- changeType = vcs.FileDiffTypeAdded
- case "delete":
- changeType = vcs.FileDiffTypeRemoved
- case "edit":
- changeType = vcs.FileDiffTypeModified
- case "rename":
- changeType = vcs.FileDiffTypeAdded
- default:
- changeType = vcs.FileDiffTypeUnknown
- }
- result = append(result, vcs.FileDiff{
- Path: c.Item.Path,
- Type: changeType,
- })
- }
-
- return result, len(r.Changes) == apiPageSize, nil
-}
-
// FetchAllRepositoryList fetches all projects where the authenticated use has permissions, which is required
// to create webhook in the repository.
//
@@ -531,170 +396,6 @@ func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx *common
return result, nil
}
-// CreateFile creates a file at given path in the repository.
-func (p *Provider) CreateFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- return p.createOrUpdateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate, true)
-}
-
-// OverwriteFile overwrites an existing file at given path in the repository.
-func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- create := true
- if fileCommitCreate.LastCommitID != "" {
- create = false
- }
- return p.createOrUpdateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate, create)
-}
-
-func (p *Provider) getLatestCommitIDOnBranch(ctx context.Context, oauthCtx *common.OauthContext, repositoryID, branchName string) (string, error) {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return "", err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- values.Set("searchCriteria.itemVersion.version", branchName)
-
- url := fmt.Sprintf("%s/commits?%s", apiURL, values.Encode())
- code, _, body, err := oauth.Get(ctx, p.client, url, oauthCtx.AccessToken)
- if err != nil {
- return "", errors.Wrapf(err, "GET %s", url)
- }
- if code != http.StatusOK {
- return "", errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
- }
-
- type getCommitsOnBranchResponseValue struct {
- CommitID string `json:"commitId"`
- }
- type getCommitsOnBranchResponse struct {
- Value []getCommitsOnBranchResponseValue `json:"value"`
- }
-
- g := new(getCommitsOnBranchResponse)
- if err := json.Unmarshal([]byte(body), g); err != nil {
- return "", errors.Wrapf(err, "failed to unmarshal get commits on branch response body, code %v", code)
- }
-
- return g.Value[0].CommitID, nil
-}
-
-// createOrUpdateFile update or create the file.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) createOrUpdateFile(ctx context.Context, oauthCtx *common.OauthContext, _, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate, create bool) error {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return err
- }
-
- changeType := "edit"
- if create {
- changeType = "add"
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- url := fmt.Sprintf("%s/pushes?%s", apiURL, values.Encode())
-
- type createFileReqeustCommitChangesItem struct {
- Path string `json:"path"`
- }
- type createFileReqeustCommitChangesNewContent struct {
- Content string `json:"content"`
- ContentType string `json:"contentType"`
- }
- type createFileReqeustCommitChanges struct {
- ChangeType string `json:"changeType"`
- Item createFileReqeustCommitChangesItem `json:"item"`
- NewContent createFileReqeustCommitChangesNewContent `json:"newContent"`
- }
- type createFileReqeustCommitAuthor struct {
- Date string `json:"date"`
- Name string `json:"name"`
- Email string `json:"email"`
- }
- type createFileReqeustCommit struct {
- Comment string `json:"comment"`
- Changes []createFileReqeustCommitChanges `json:"changes"`
- Author *createFileReqeustCommitAuthor `json:"author,omitempty"`
- Committer *createFileReqeustCommitAuthor `json:"committer,omitempty"`
- }
- type createFileRequestRefUpdates struct {
- Name string `json:"name"`
- OldObjectID string `json:"oldObjectId"`
- }
- type createFileRequest struct {
- RefUpdates []createFileRequestRefUpdates `json:"refUpdates"`
- Commits []createFileReqeustCommit `json:"commits"`
- }
-
- for i := 0; i < 3; i++ {
- branchCommit, err := p.getLatestCommitIDOnBranch(ctx, oauthCtx, repositoryID, fileCommitCreate.Branch)
- if err != nil {
- return errors.Wrapf(err, "failed to get latest commit ID on branch %q", fileCommitCreate.Branch)
- }
-
- requestBody := &createFileRequest{
- RefUpdates: []createFileRequestRefUpdates{
- {
- Name: fmt.Sprintf("refs/heads/%s", fileCommitCreate.Branch),
- OldObjectID: branchCommit,
- },
- },
- Commits: []createFileReqeustCommit{
- {
- Comment: fileCommitCreate.CommitMessage,
- Changes: []createFileReqeustCommitChanges{
- {
- ChangeType: changeType,
- Item: createFileReqeustCommitChangesItem{
- Path: filePath,
- },
- NewContent: createFileReqeustCommitChangesNewContent{
- Content: fileCommitCreate.Content,
- ContentType: "rawtext",
- },
- },
- },
- },
- },
- }
- if fileCommitCreate.AuthorName != "" && fileCommitCreate.AuthorEmail != "" {
- requestBody.Commits[0].Author = &createFileReqeustCommitAuthor{
- Date: time.Now().Format(time.RFC3339),
- Name: fileCommitCreate.AuthorName,
- Email: fileCommitCreate.AuthorEmail,
- }
- requestBody.Commits[0].Committer = &createFileReqeustCommitAuthor{
- Date: time.Now().Format(time.RFC3339),
- Name: fileCommitCreate.AuthorName,
- Email: fileCommitCreate.AuthorEmail,
- }
- }
-
- marshalBody, err := json.Marshal(requestBody)
- if err != nil {
- return errors.Wrapf(err, "failed to marshal create file request body, request body: %+v", requestBody)
- }
- code, _, body, err := oauth.Post(ctx, p.client, url, oauthCtx.AccessToken, bytes.NewReader(marshalBody))
- if err != nil {
- return errors.Wrapf(err, "POST %s", url)
- }
- if code == http.StatusBadRequest {
- slog.Info("Failed to create file, retrying", slog.String("url", url), slog.String("body", string(body)))
- continue
- }
- if code != http.StatusCreated {
- return errors.Errorf("non-201 POST %s status code %d with body %q", url, code, string(body))
- }
-
- return nil
- }
-
- return errors.Errorf("failed to create file after 3 retries")
-}
-
// ReadFileMeta reads the metadata of the given file in the repository.
//
// Docs:
@@ -880,58 +581,6 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
}, nil
}
-// CreateBranch creates the branch in the repository.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-7.1
-func (p *Provider) CreateBranch(ctx context.Context, oauthCtx *common.OauthContext, _, repositoryID string, branch *vcs.BranchInfo) error {
- type refUpdate struct {
- Name string `json:"name"`
- OldObjectID string `json:"oldObjectId"`
- NewObjectID string `json:"newObjectId"`
- }
- body, err := json.Marshal(
- []*refUpdate{
- {
- Name: fmt.Sprintf("refs/heads/%s", branch.Name),
- OldObjectID: strings.Repeat("0", 40),
- NewObjectID: branch.LastCommitID,
- },
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal branch create")
- }
-
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return err
- }
-
- urlParams := &url.Values{}
- urlParams.Set("api-version", "7.0")
- url := fmt.Sprintf("%s/refs?%s", apiURL, urlParams.Encode())
-
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "GET %s", url)
- }
- if code >= 300 {
- return errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
-
- return nil
-}
-
// 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
@@ -989,78 +638,6 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
return files, nil
}
-// CreatePullRequest creates the pull request in the repository.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/create?view=azure-devops-rest-7.1&tabs=HTTP
-func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx *common.OauthContext, _, repositoryID string, pullRequestCreate *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
- type azurePullRequest struct {
- Title string `json:"title"`
- Description string `json:"description"`
- URL string `json:"url"`
- SourceRefName string `json:"sourceRefName"`
- TargetRefName string `json:"targetRefName"`
- Repository *repository `json:"repository,omitempty"`
- }
-
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return nil, err
- }
-
- urlParams := &url.Values{}
- urlParams.Set("api-version", "7.0")
- url := fmt.Sprintf("%s/pullrequests?%s", apiURL, urlParams.Encode())
-
- body, err := json.Marshal(
- azurePullRequest{
- Title: pullRequestCreate.Title,
- Description: pullRequestCreate.Body,
- SourceRefName: fmt.Sprintf("refs/heads/%s", pullRequestCreate.Head),
- TargetRefName: fmt.Sprintf("refs/heads/%s", pullRequestCreate.Base),
- },
- )
- if err != nil {
- return nil, errors.Wrap(err, "marshal branch create")
- }
-
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return nil, errors.Wrapf(err, "POST %s", url)
- }
-
- if code >= 300 {
- return nil, errors.Errorf("failed to create pull request from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
-
- var res azurePullRequest
- if err := json.Unmarshal([]byte(resp), &res); err != nil {
- return nil, err
- }
-
- urlSections := strings.Split(res.URL, "/")
- prID := urlSections[len(urlSections)-1]
-
- return &vcs.PullRequest{
- URL: fmt.Sprintf("%s/pullrequest/%s", res.Repository.WebURL, prID),
- }, nil
-}
-
-// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
-func (*Provider) UpsertEnvironmentVariable(context.Context, *common.OauthContext, string, string, string, string) error {
- // We will set the variable in pipeline. Check sql_review.go/createSQLReviewPipeline function.
- return nil
-}
-
// CreateWebhook creates a webhook in the organization, and returns the webhook ID which can be used in PatchWebhook.
// API Version 7.0 do not specify the OAuth scope for creating webhook explicitly, but it works.
//
@@ -1098,16 +675,6 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
return fmt.Sprintf("%s/%s", organizationName, c.ID), nil
}
-// PatchWebhook patches the webhook in the repository.
-// Due to the Azure DevOps API do not provide an endpoint the update the webhook,
-// so we should set the webhook full configuration in the payload.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/hooks/subscriptions/replace-subscription?view=azure-devops-rest-7.0&tabs=HTTP
-// (2023/07/07, zp): It seems that the PatchWebhook API of each provider is not used by Bytebase, should we remove it?
-func (*Provider) PatchWebhook(_ context.Context, _ *common.OauthContext, _, _, _ string, _ []byte) error {
- return errors.New("not implemented")
-}
-
// 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
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index ffe22cc22f..c83f8766f4 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -6,7 +6,6 @@ import (
"context"
"encoding/json"
"fmt"
- "mime/multipart"
"net/http"
"net/url"
"path"
@@ -77,39 +76,6 @@ type Commit struct {
Date time.Time `json:"date"`
}
-// FetchCommitByID fetches the commit data by its ID from the repository.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-commit-commit-get
-func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, commitID string) (*vcs.Commit, error) {
- url := fmt.Sprintf("%s/repositories/%s/commit/%s", p.APIURL(instanceURL), url.PathEscape(repositoryID), commitID)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrap(err, "GET")
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to fetch commit data from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s", url, code, body)
- }
-
- commit := &Commit{}
- if err := json.Unmarshal([]byte(body), commit); err != nil {
- return nil, errors.Wrap(err, "unmarshal body")
- }
-
- return &vcs.Commit{
- ID: commit.Hash,
- AuthorName: commit.Author.User.DisplayName,
- CreatedTs: commit.Date.Unix(),
- }, nil
-}
-
// CommitFile represents a Bitbucket Cloud API response for a file at a commit.
type CommitFile struct {
Path string `json:"path"`
@@ -124,46 +90,6 @@ type CommitDiffStat struct {
New CommitFile `json:"new"`
}
-// GetDiffFileList gets the diff files list between two commits.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-diffstat-spec-get
-func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]vcs.FileDiff, error) {
- var bbcDiffs []*CommitDiffStat
- next := fmt.Sprintf("%s/repositories/%s/diffstat/%s..%s?pagelen=%d", p.APIURL(instanceURL), repositoryID, afterCommit, beforeCommit, apiPageSize)
- for next != "" {
- var err error
- var diffs []*CommitDiffStat
- diffs, next, err = p.fetchPaginatedDiffFileList(ctx, oauthCtx, instanceURL, next)
- if err != nil {
- return nil, errors.Wrap(err, "fetch paginated list")
- }
- bbcDiffs = append(bbcDiffs, diffs...)
- }
-
- var diffs []vcs.FileDiff
- for _, d := range bbcDiffs {
- diff := vcs.FileDiff{
- Path: d.New.Path,
- }
- switch d.Status {
- case "added":
- diff.Type = vcs.FileDiffTypeAdded
- case "modified":
- diff.Type = vcs.FileDiffTypeModified
- case "removed":
- diff.Type = vcs.FileDiffTypeRemoved
- // To be consistent with GitLab, we treat renamed as added.
- case "renamed":
- diff.Type = vcs.FileDiffTypeAdded
- default:
- // Skip because we don't care about file diff in other status
- continue
- }
- diffs = append(diffs, diff)
- }
- return diffs, nil
-}
-
func (p *Provider) fetchPaginatedDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, url string) (diffs []*CommitDiffStat, next string, err error) {
code, _, body, err := oauth.Get(
ctx,
@@ -367,59 +293,6 @@ func (p *Provider) fetchPaginatedRepositoryFileList(ctx context.Context, oauthCt
return resp.Values, resp.Next, nil
}
-// CreateFile creates a file at given path in the repository.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#api-repositories-workspace-repo-slug-src-post
-func (p *Provider) CreateFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- var body bytes.Buffer
- w := multipart.NewWriter(&body)
- part, err := w.CreateFormField(filePath)
- if err != nil {
- return errors.Wrap(err, "failed to create form file")
- }
- _, err = part.Write([]byte(fileCommitCreate.Content))
- if err != nil {
- return errors.Wrap(err, "failed to write file to form")
- }
- _ = w.WriteField("message", fileCommitCreate.CommitMessage)
- _ = w.WriteField("parents", fileCommitCreate.LastCommitID)
- _ = w.WriteField("branch", fileCommitCreate.Branch)
- _ = w.Close()
-
- url := fmt.Sprintf("%s/repositories/%s/src", p.APIURL(instanceURL), repositoryID)
- code, _, resp, err := oauth.PostWithHeader(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- &body,
- map[string]string{
- "Content-Type": w.FormDataContentType(),
- },
- )
- if err != nil {
- return errors.Wrapf(err, "POST %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create/update file through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
-// OverwriteFile overwrites an existing file at given path in the repository.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#api-repositories-workspace-repo-slug-src-post
-func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- return p.CreateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate)
-}
-
// ReadFileMeta reads the metadata of the given file in the repository.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#file-meta-data
@@ -538,53 +411,6 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
}, nil
}
-type branchCreateTarget struct {
- Hash string `json:"hash"`
-}
-
-type branchCreate struct {
- Name string `json:"name"`
- Target branchCreateTarget `json:"target"`
-}
-
-// CreateBranch creates the branch in the repository.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-post
-func (p *Provider) CreateBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
- body, err := json.Marshal(
- branchCreate{
- Name: branch.Name,
- Target: branchCreateTarget{Hash: branch.LastCommitID},
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal branch create")
- }
-
- url := fmt.Sprintf("%s/repositories/%s/refs/branches", p.APIURL(instanceURL), repositoryID)
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "POST %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create branch from URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
// 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
@@ -625,219 +451,6 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx *common.Oau
return files, nil
}
-type pullRequestCreateBranch struct {
- Name string `json:"name"`
-}
-type pullRequestCreateTarget struct {
- Branch pullRequestCreateBranch `json:"branch"`
-}
-
-type pullRequestCreate struct {
- Title string `json:"title"`
- Description string `json:"description"`
- CloseSourceBranch bool `json:"close_source_branch"`
- Source pullRequestCreateTarget `json:"source"`
- Destination pullRequestCreateTarget `json:"destination"`
-}
-
-// CreatePullRequest creates the pull request in the repository.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pullrequests/#api-repositories-workspace-repo-slug-pullrequests-post
-func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, create *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
- payload, err := json.Marshal(
- pullRequestCreate{
- Title: create.Title,
- Description: create.Body,
- CloseSourceBranch: create.RemoveHeadAfterMerged,
- Source: pullRequestCreateTarget{
- Branch: pullRequestCreateBranch{Name: create.Head},
- },
- Destination: pullRequestCreateTarget{
- Branch: pullRequestCreateBranch{Name: create.Base},
- },
- },
- )
- if err != nil {
- return nil, errors.Wrap(err, "marshal pull request create")
- }
-
- url := fmt.Sprintf("%s/repositories/%s/pullrequests", p.APIURL(instanceURL), repositoryID)
- code, _, body, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(payload),
- )
- if err != nil {
- return nil, errors.Wrapf(err, "POST %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to create pull request from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to create pull request from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- var resp struct {
- Links struct {
- HTML struct {
- Href string `json:"href"`
- } `json:"html"`
- } `json:"links"`
- }
- if err := json.Unmarshal([]byte(body), &resp); err != nil {
- return nil, err
- }
-
- return &vcs.PullRequest{
- URL: resp.Links.HTML.Href,
- }, nil
-}
-
-type pipelineVariable struct {
- // Type should always be "pipeline_variable"
- Type string `json:"type,omitempty"`
- UUID string `json:"uuid,omitempty"`
- Key string `json:"key,omitempty"`
- Value string `json:"value,omitempty"`
- Secured bool `json:"secured,omitempty"`
-}
-
-type listPipelineVariable struct {
- Values []*pipelineVariable `json:"values"`
-}
-
-// UpsertEnvironmentVariable creates or updates the pipeline variable in the repository.
-func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
- existed, err := p.getPipelineVariable(ctx, oauthCtx, instanceURL, repositoryID, key)
- if err != nil {
- return err
- }
-
- if existed == nil {
- return p.createPipelineVariable(ctx, oauthCtx, instanceURL, repositoryID, key, value)
- }
- return p.updatePipelineVariable(ctx, oauthCtx, instanceURL, repositoryID, existed.UUID, value)
-}
-
-// getPipelineVariable gets the pipeline variable in the repository.
-//
-// https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-variables-get.
-func (p *Provider) getPipelineVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key string) (*pipelineVariable, error) {
- url := fmt.Sprintf("%s/repositories/%s/pipelines_config/variables", p.APIURL(instanceURL), repositoryID)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, nil
- } else if code >= 300 {
- return nil,
- errors.Errorf("failed to found variable from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- variables := new(listPipelineVariable)
- if err := json.Unmarshal([]byte(body), variables); err != nil {
- return nil, err
- }
-
- for _, variable := range variables.Values {
- if variable.Key == key {
- return variable, nil
- }
- }
-
- return nil, nil
-}
-
-// createPipelineVariable creates the pipeline variable in the repository.
-//
-// https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-variables-post.
-func (p *Provider) createPipelineVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
- url := fmt.Sprintf("%s/repositories/%s/pipelines_config/variables", p.APIURL(instanceURL), repositoryID)
- body, err := json.Marshal(
- pipelineVariable{
- Type: "pipeline_variable",
- Key: key,
- Value: value,
- Secured: true,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal variable create")
- }
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "POST %s", url)
- }
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create pipeline variable through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create pipeline variable through URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
-// updatePipelineVariable updates the environment variable in the repository.
-//
-// https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-config-variables-variable-uuid-put.
-func (p *Provider) updatePipelineVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, variableID, value string) error {
- url := fmt.Sprintf("%s/repositories/%s/pipelines_config/variables/%s", p.APIURL(instanceURL), repositoryID, variableID)
- body, err := json.Marshal(
- pipelineVariable{
- Value: value,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal variable update")
- }
- code, _, resp, err := oauth.Put(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to update pipeline variable through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to update pipeline variable through URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
// Link is the API message for link.
type Link struct {
Href string `json:"href"`
@@ -936,34 +549,6 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
return resp.UUID, nil
}
-// PatchWebhook patches the webhook in the repository with given payload.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-hooks-uid-put
-func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error {
- url := fmt.Sprintf("%s/repositories/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
- code, _, body, err := oauth.Put(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(payload),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to patch webhook through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
- return nil
-}
-
// 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
diff --git a/backend/plugin/vcs/bitbucket/bitbucket_test.go b/backend/plugin/vcs/bitbucket/bitbucket_test.go
index 1a0775e03d..f7ae8414a4 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket_test.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket_test.go
@@ -14,184 +14,6 @@ import (
"github.com/bytebase/bytebase/backend/plugin/vcs"
)
-func TestProvider_FetchCommitByID(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/bitbucket/geordi/commit/f7591a1", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-commit-commit-get
- Body: io.NopCloser(strings.NewReader(`
-{
- "rendered": {
- "message": {
- "raw": "Add a GEORDI_OUTPUT_DIR setting",
- "markup": "markdown",
- "html": "<p>Add a GEORDI_OUTPUT_DIR setting</p>",
- "type": "rendered"
- }
- },
- "hash": "f7591a13eda445d9a9167f98eb870319f4b6c2d8",
- "repository": {
- "name": "geordi",
- "type": "repository",
- "full_name": "bitbucket/geordi",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi"
- },
- "html": {
- "href": "https://bitbucket.org/bitbucket/geordi"
- },
- "avatar": {
- "href": "https://bytebucket.org/ravatar/%7B85d08b4e-571d-44e9-a507-fa476535aa98%7D?ts=1730260"
- }
- },
- "uuid": "{85d08b4e-571d-44e9-a507-fa476535aa98}"
- },
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
- },
- "comments": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8/comments"
- },
- "patch": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/patch/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
- },
- "html": {
- "href": "https://bitbucket.org/bitbucket/geordi/commits/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
- },
- "diff": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/diff/f7591a13eda445d9a9167f98eb870319f4b6c2d8"
- },
- "approve": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8/approve"
- },
- "statuses": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f7591a13eda445d9a9167f98eb870319f4b6c2d8/statuses"
- }
- },
- "author": {
- "raw": "Brodie Rao <[email protected]>",
- "type": "author",
- "user": {
- "display_name": "Brodie Rao",
- "uuid": "{9484702e-c663-4afd-aefb-c93a8cd31c28}",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/users/%7B9484702e-c663-4afd-aefb-c93a8cd31c28%7D"
- },
- "html": {
- "href": "https://bitbucket.org/%7B9484702e-c663-4afd-aefb-c93a8cd31c28%7D/"
- },
- "avatar": {
- "href": "https://avatar-management--avatars.us-west-2.prod.public.atl-paas.net/557058:3aae1e05-702a-41e5-81c8-f36f29afb6ca/613070db-28b0-421f-8dba-ae8a87e2a5c7/128"
- }
- },
- "type": "user",
- "nickname": "brodie",
- "account_id": "557058:3aae1e05-702a-41e5-81c8-f36f29afb6ca"
- }
- },
- "summary": {
- "raw": "Add a GEORDI_OUTPUT_DIR setting",
- "markup": "markdown",
- "html": "<p>Add a GEORDI_OUTPUT_DIR setting</p>",
- "type": "rendered"
- },
- "participants": [],
- "parents": [
- {
- "type": "commit",
- "hash": "f06941fec4ef6bcb0c2456927a0cf258fa4f899b",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/bitbucket/geordi/commit/f06941fec4ef6bcb0c2456927a0cf258fa4f899b"
- },
- "html": {
- "href": "https://bitbucket.org/bitbucket/geordi/commits/f06941fec4ef6bcb0c2456927a0cf258fa4f899b"
- }
- }
- }
- ],
- "date": "2012-07-16T19:37:54+00:00",
- "message": "Add a GEORDI_OUTPUT_DIR setting",
- "type": "commit"
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.FetchCommitByID(ctx, &common.OauthContext{}, bitbucketCloudURL, "bitbucket/geordi", "f7591a1")
- require.NoError(t, err)
-
- want := &vcs.Commit{
- ID: "f7591a13eda445d9a9167f98eb870319f4b6c2d8",
- AuthorName: "Brodie Rao",
- CreatedTs: 1342467474,
- }
- assert.Equal(t, want, got)
-}
-
-func TestProvider_GetDiffFileList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/1/diffstat/after_sha..before_sha", 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.GetDiffFileList(ctx, &common.OauthContext{}, bitbucketCloudURL, "1", "before_sha", "after_sha")
- require.NoError(t, err)
-
- want := []vcs.FileDiff{
- {
- Path: "setup.py",
- Type: vcs.FileDiffTypeModified,
- },
- }
- assert.Equal(t, want, got)
-}
-
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)
@@ -325,69 +147,6 @@ func TestProvider_FetchRepositoryFileList(t *testing.T) {
})
}
-func TestProvider_CreateFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/username/slug/src", r.URL.Path)
- assert.Contains(t, r.Header.Get("Content-Type"), "multipart/form-data; boundary=")
- assert.Equal(t, "Initial commit", r.FormValue("message"))
- assert.Empty(t, r.FormValue("parents"))
- assert.Equal(t, "main", r.FormValue("branch"))
- assert.Equal(t, "#!/bin/sh\nhalt", r.FormValue("repo/path/to/image.png"))
- return &http.Response{
- StatusCode: http.StatusCreated,
- Body: io.NopCloser(strings.NewReader("")),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.CreateFile(
- ctx,
- &common.OauthContext{},
- bitbucketCloudURL,
- "username/slug",
- "repo/path/to/image.png",
- vcs.FileCommitCreate{
- Branch: "main",
- Content: "#!/bin/sh\nhalt",
- CommitMessage: "Initial commit",
- },
- )
- require.NoError(t, err)
-}
-
-func TestProvider_OverwriteFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/username/slug/src", r.URL.Path)
- assert.Contains(t, r.Header.Get("Content-Type"), "multipart/form-data; boundary=")
- assert.Equal(t, "Initial commit", r.FormValue("message"))
- assert.Equal(t, "7638417db6d59f3c431d3e1f261cc637155684cd", r.FormValue("parents"))
- assert.Equal(t, "main", r.FormValue("branch"))
- assert.Equal(t, "#!/bin/sh\nhalt", r.FormValue("repo/path/to/image.png"))
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader("")),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.OverwriteFile(
- ctx,
- &common.OauthContext{},
- bitbucketCloudURL,
- "username/slug",
- "repo/path/to/image.png",
- vcs.FileCommitCreate{
- Branch: "main",
- Content: "#!/bin/sh\nhalt",
- CommitMessage: "Initial commit",
- LastCommitID: "7638417db6d59f3c431d3e1f261cc637155684cd",
- },
- )
- require.NoError(t, err)
-}
-
func TestProvider_ReadFileMeta(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)
@@ -589,35 +348,6 @@ func TestProvider_GetBranch(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_CreateBranch(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/seanfarley/hg/refs/branches", r.URL.Path)
-
- body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
- wantBody := `{"name":"smf/create-feature","target":{"hash":"aa218f56b14c9653891f9e74264a383fa43fefbd"}}`
- assert.Equal(t, wantBody, string(body))
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader("")),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.CreateBranch(
- ctx,
- &common.OauthContext{},
- bitbucketCloudURL,
- "seanfarley/hg",
- &vcs.BranchInfo{
- Name: "smf/create-feature",
- LastCommitID: "aa218f56b14c9653891f9e74264a383fa43fefbd",
- },
- )
- require.NoError(t, err)
-}
-
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)
@@ -676,73 +406,6 @@ func TestProvider_ListPullRequestFile(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_CreatePullRequest(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/octocat/Hello-World/pullrequests", r.URL.Path)
-
- body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
- wantBody := `{"title":"Amazing new feature","description":"Please pull these awesome changes in!","close_source_branch":true,"source":{"branch":{"name":"new-topic"}},"destination":{"branch":{"name":"master"}}}`
- assert.Equal(t, wantBody, string(body))
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader(`
-{
- "links": {
- "self": {
- "href": "<string>",
- "name": "<string>"
- },
- "html": {
- "href": "https://bitbucket.org/octocat/Hello-World/pull-requests/108"
- }
- },
- "id": 108,
- "title": "Amazing new feature",
- "state": "OPEN",
- "source": {
- "branch": {
- "name": "new-topic",
- "merge_strategies": [
- "merge_commit"
- ]
- }
- },
- "destination": {
- "branch": {
- "name": "master",
- "merge_strategies": [
- "merge_commit"
- ]
- }
- },
- "comment_count": 51,
- "task_count": 53,
- "close_source_branch": true
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.CreatePullRequest(
- ctx,
- &common.OauthContext{},
- bitbucketCloudURL,
- "octocat/Hello-World",
- &vcs.PullRequestCreate{
- Title: "Amazing new feature",
- Body: "Please pull these awesome changes in!",
- Head: "new-topic",
- Base: "master",
- RemoveHeadAfterMerged: true,
- },
- )
- require.NoError(t, err)
- assert.Equal(t, "https://bitbucket.org/octocat/Hello-World/pull-requests/108", got.URL)
-}
-
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)
@@ -788,22 +451,6 @@ func TestProvider_CreateWebhook(t *testing.T) {
assert.Equal(t, "6611a7e9-6890-4e8e-84c5-b9707397da8b", got)
}
-func TestProvider_PatchWebhook(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, http.MethodPut, 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.PatchWebhook(ctx, &common.OauthContext{}, bitbucketCloudURL, "1", "1", []byte(""))
- require.NoError(t, err)
-}
-
func TestProvider_DeleteWebhook(t *testing.T) {
p := newMockProvider(func(r *http.Request) (*http.Response, error) {
assert.Equal(t, http.MethodDelete, r.Method)
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index 0c7a06ba1a..4967476558 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -4,8 +4,6 @@ package github
import (
"bytes"
"context"
- "crypto/rand"
- "encoding/base64"
"encoding/json"
"fmt"
"log/slog"
@@ -15,9 +13,6 @@ import (
"strings"
"time"
- "golang.org/x/crypto/blake2b"
- "golang.org/x/crypto/nacl/box"
-
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/common"
@@ -226,89 +221,11 @@ type FileCommit struct {
Author *CommitAuthor `json:"author,omitempty"`
}
-// FetchCommitByID fetches the commit data by its ID from the repository.
-func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, commitID string) (*vcs.Commit, error) {
- url := fmt.Sprintf("%s/repos/%s/git/commits/%s", p.APIURL(instanceURL), repositoryID, commitID)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrap(err, "GET")
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to fetch commit data from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s", url, code, body)
- }
-
- commit := &Commit{}
- if err := json.Unmarshal([]byte(body), commit); err != nil {
- return nil, errors.Wrap(err, "unmarshal body")
- }
-
- return &vcs.Commit{
- ID: commit.SHA,
- AuthorName: commit.Author.Name,
- CreatedTs: commit.Author.Date.Unix(),
- }, nil
-}
-
// CommitsDiff represents a GitHub API response for comparing two commits.
type CommitsDiff struct {
Files []PullRequestFile `json:"files"`
}
-// GetDiffFileList gets the diff files list between two commits.
-func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]vcs.FileDiff, error) {
- url := fmt.Sprintf("%s/repos/%s/compare/%s...%s", p.APIURL(instanceURL), repositoryID, beforeCommit, afterCommit)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to get file diff list from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to get file diff list from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- diffs := &CommitsDiff{}
- if err := json.Unmarshal([]byte(body), diffs); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal file diff data from GitHub instance %s", instanceURL)
- }
-
- var ret []vcs.FileDiff
- for _, file := range diffs.Files {
- item := vcs.FileDiff{
- Path: file.FileName,
- }
- switch file.Status {
- case "added":
- item.Type = vcs.FileDiffTypeAdded
- case "modified":
- item.Type = vcs.FileDiffTypeModified
- case "removed":
- item.Type = vcs.FileDiffTypeRemoved
- }
- ret = append(ret, item)
- }
-
- return ret, nil
-}
-
// FetchAllRepositoryList fetches all repositories where the authenticated user
// has admin permissions, which is required to create webhook in the repository.
//
@@ -443,58 +360,6 @@ func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx *common
return allTreeNodes, nil
}
-// CreateFile creates a file at given path in the repository.
-//
-// Docs: https://docs.github.com/en/rest/repos/contents#create-or-update-file-contents
-func (p *Provider) CreateFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- fileCommit := FileCommit{
- Message: fileCommitCreate.CommitMessage,
- Content: base64.StdEncoding.EncodeToString([]byte(fileCommitCreate.Content)),
- Branch: fileCommitCreate.Branch,
- SHA: fileCommitCreate.SHA,
- }
- if fileCommitCreate.AuthorName != "" && fileCommitCreate.AuthorEmail != "" {
- fileCommit.Author = &CommitAuthor{
- Name: fileCommitCreate.AuthorName,
- Email: fileCommitCreate.AuthorEmail,
- }
- }
- body, err := json.Marshal(fileCommit)
- if err != nil {
- return errors.Wrap(err, "marshal file commit")
- }
-
- url := fmt.Sprintf("%s/repos/%s/contents/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))
- code, _, resp, err := oauth.Put(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create/update file through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
-// OverwriteFile overwrites an existing file at given path in the repository.
-//
-// Docs: https://docs.github.com/en/rest/repos/contents#create-or-update-file-contents
-func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- return p.CreateFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, fileCommitCreate)
-}
-
// ReadFileMeta reads the metadata of the given file in the repository.
//
// Docs: https://docs.github.com/en/rest/repos/contents#get-repository-content
@@ -767,234 +632,11 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
}, nil
}
-// CreateBranch creates the branch in the repository.
-//
-// Docs: https://docs.github.com/en/rest/git/refs#create-a-reference
-func (p *Provider) CreateBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
- body, err := json.Marshal(
- BranchCreate{
- Ref: fmt.Sprintf("refs/heads/%s", branch.Name),
- SHA: branch.LastCommitID,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal branch create")
- }
-
- url := fmt.Sprintf("%s/repos/%s/git/refs", p.APIURL(instanceURL), repositoryID)
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create branch from URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
-
- return nil
-}
-
// PullRequest is the API message for GitHub pull request.
type PullRequest struct {
HTMLURL string `json:"html_url"`
}
-// CreatePullRequest creates the pull request in the repository.
-//
-// Docs: https://docs.github.com/en/rest/pulls/pulls#create-a-pull-request
-func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
- body, err := json.Marshal(pullRequestCreate)
- if err != nil {
- return nil, errors.Wrap(err, "marshal pull request create")
- }
-
- url := fmt.Sprintf("%s/repos/%s/pulls", p.APIURL(instanceURL), repositoryID)
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return nil, errors.Wrapf(err, "POST %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to create pull request from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to create pull request from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
-
- var res PullRequest
- if err := json.Unmarshal([]byte(resp), &res); err != nil {
- return nil, err
- }
-
- return &vcs.PullRequest{
- URL: res.HTMLURL,
- }, nil
-}
-
-// RepositorySecretUpdate is the API message to update the repository secret.
-type RepositorySecretUpdate struct {
- EncryptedValue string `json:"encrypted_value"`
- KeyID string `json:"key_id"`
-}
-
-// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
-//
-// https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
-func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
- // We have to encrypt the secret value using the public key in the repository.
- // Docs: https://docs.github.com/en/rest/actions/secrets#example-encrypting-a-secret-using-nodejs
- publicKey, err := p.getRepositoryPublicKey(ctx, oauthCtx, instanceURL, repositoryID)
- if err != nil {
- return errors.Wrapf(err, "Failed to get public key")
- }
- encryptValue, err := encryptEnvironmentVariable(publicKey.Key, value)
- if err != nil {
- return errors.Wrapf(err, "Failed to encrypt environment variable")
- }
-
- body, err := json.Marshal(
- RepositorySecretUpdate{
- KeyID: publicKey.KeyID,
- EncryptedValue: encryptValue,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal environment variable")
- }
-
- url := fmt.Sprintf("%s/repos/%s/actions/secrets/%s", p.APIURL(instanceURL), repositoryID, key)
- code, _, resp, err := oauth.Put(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to upsert environment variable from URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to upsert environment variable from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
-
- return nil
-}
-
-// encryptEnvironmentVariable encrypt the value with public key
-//
-// https://github.com/jefflinse/githubsecret
-func encryptEnvironmentVariable(publicKey, value string) (string, error) {
- const keySize = 32
- const nonceSize = 24
-
- // decode the provided public key from base64
- recipientKey := new([keySize]byte)
- b, err := base64.StdEncoding.DecodeString(publicKey)
- if err != nil {
- return "", err
- } else if size := len(b); size != keySize {
- return "", errors.Errorf("Public key has invalid length, expect %d bytes but found %d", keySize, size)
- }
-
- copy(recipientKey[:], b)
-
- // create an ephemeral key pair
- pubKey, privKey, err := box.GenerateKey(rand.Reader)
- if err != nil {
- return "", err
- }
-
- // create the nonce by hashing together the two public keys
- nonce := new([nonceSize]byte)
- nonceHash, err := blake2b.New(nonceSize, nil)
- if err != nil {
- return "", err
- }
-
- if _, err := nonceHash.Write(pubKey[:]); err != nil {
- return "", err
- }
-
- if _, err := nonceHash.Write(recipientKey[:]); err != nil {
- return "", err
- }
-
- copy(nonce[:], nonceHash.Sum(nil))
-
- // begin the output with the ephemeral public key and append the encrypted content
- out := box.Seal(pubKey[:], []byte(value), nonce, recipientKey, privKey)
-
- // base64-encode the final output
- return base64.StdEncoding.EncodeToString(out), nil
-}
-
-// RepositorySecret is the secret for repository.
-type RepositorySecret struct {
- KeyID string `json:"key_id"`
- Key string `json:"key"`
-}
-
-// getRepositoryPublicKey returns the public key in the GitHub repository.
-//
-// https://docs.github.com/en/rest/actions/secrets#get-a-repository-public-key
-func (p *Provider) getRepositoryPublicKey(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string) (*RepositorySecret, error) {
- url := fmt.Sprintf("%s/repos/%s/actions/secrets/public-key", p.APIURL(instanceURL), repositoryID)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to get repo public key from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to get repo public key from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- res := new(RepositorySecret)
- if err := json.Unmarshal([]byte(body), res); err != nil {
- return nil, err
- }
-
- return res, nil
-}
-
// CreateWebhook creates a webhook in the repository with given payload.
//
// Docs: https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook
@@ -1032,34 +674,6 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
return strconv.Itoa(webhookInfo.ID), nil
}
-// PatchWebhook patches the webhook in the repository with given payload.
-//
-// Docs: https://docs.github.com/en/rest/webhooks/repos#update-a-repository-webhook
-func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error {
- url := fmt.Sprintf("%s/repos/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
- code, _, body, err := oauth.Patch(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(payload),
- )
- if err != nil {
- return errors.Wrapf(err, "PATCH %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to patch webhook through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
- return nil
-}
-
// DeleteWebhook deletes the webhook from the repository.
//
// Docs: https://docs.github.com/en/rest/webhooks/repos#delete-a-repository-webhook
@@ -1086,40 +700,3 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx *common.OauthCont
}
return nil
}
-
-// ToVCS returns the push event in VCS format.
-func (p WebhookPushEvent) ToVCS() vcs.PushEvent {
- var commitList []vcs.Commit
- for _, commit := range p.Commits {
- // The Distinct is false if the commit has not been pushed before.
- if !commit.Distinct {
- continue
- }
- // Per Git convention, the message title and body are separated by two new line characters.
- messages := strings.SplitN(commit.Message, "\n\n", 2)
- messageTitle := messages[0]
-
- commitList = append(commitList, vcs.Commit{
- ID: commit.ID,
- Title: messageTitle,
- Message: commit.Message,
- CreatedTs: commit.Timestamp.Unix(),
- URL: commit.URL,
- AuthorName: commit.Author.Name,
- AuthorEmail: commit.Author.Email,
- AddedList: commit.Added,
- ModifiedList: commit.Modified,
- })
- }
- return vcs.PushEvent{
- VCSType: vcs.GitHub,
- Ref: p.Ref,
- Before: p.Before,
- After: p.After,
- RepositoryID: p.Repository.FullName,
- RepositoryURL: p.Repository.HTMLURL,
- RepositoryFullPath: p.Repository.FullName,
- AuthorName: p.Sender.Login,
- CommitList: commitList,
- }
-}
diff --git a/backend/plugin/vcs/github/github_test.go b/backend/plugin/vcs/github/github_test.go
index 9c5f0b92d8..f4d696f51f 100644
--- a/backend/plugin/vcs/github/github_test.go
+++ b/backend/plugin/vcs/github/github_test.go
@@ -7,7 +7,6 @@ import (
"strings"
"testing"
- "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -15,64 +14,6 @@ import (
"github.com/bytebase/bytebase/backend/plugin/vcs"
)
-func TestProvider_FetchCommitByID(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/git/commits#get-a-commit
- Body: io.NopCloser(strings.NewReader(`
-{
- "sha": "7638417db6d59f3c431d3e1f261cc637155684cd",
- "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd",
- "html_url": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd",
- "author": {
- "date": "2014-11-07T22:01:45Z",
- "name": "Monalisa Octocat",
- "email": "[email protected]"
- },
- "committer": {
- "date": "2014-11-07T22:01:45Z",
- "name": "Monalisa Octocat",
- "email": "[email protected]"
- },
- "message": "added readme, because im a good github citizen",
- "tree": {
- "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb",
- "sha": "691272480426f78a0138979dd3ce63b77f706feb"
- },
- "parents": [
- {
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5",
- "sha": "1acc419d4d6a9ce985db7be48c6349a0475975b5",
- "html_url": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd"
- }
- ],
- "verification": {
- "verified": false,
- "reason": "unsigned",
- "signature": null,
- "payload": null
- }
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.FetchCommitByID(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "7638417db6d59f3c431d3e1f261cc637155684cd")
- require.NoError(t, err)
-
- want := &vcs.Commit{
- ID: "7638417db6d59f3c431d3e1f261cc637155684cd",
- AuthorName: "Monalisa Octocat",
- CreatedTs: 1415397705,
- }
- assert.Equal(t, want, got)
-}
-
func TestProvider_FetchAllRepositoryList(t *testing.T) {
p := newMockProvider(func(r *http.Request) (*http.Response, error) {
assert.Equal(t, "/user/repos", r.URL.Path)
@@ -326,177 +267,6 @@ func TestProvider_FetchRepositoryFileList(t *testing.T) {
})
}
-func TestProvider_CreateFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/octocat/Hello-World/contents/notes%2Fhello.txt", r.URL.RawPath)
-
- body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
- wantBody := `{"message":"my commit message","content":"bXkgbmV3IGZpbGUgY29udGVudHM=","branch":"master"}`
- assert.Equal(t, wantBody, string(body))
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/repos/contents#create-or-update-file-contents
- Body: io.NopCloser(strings.NewReader(`
-{
- "content": {
- "name": "hello.txt",
- "path": "notes/hello.txt",
- "sha": "95b966ae1c166bd92f8ae7d1c313e738c731dfc3",
- "size": 9,
- "url": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt",
- "html_url": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt",
- "git_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3",
- "download_url": "https://raw.githubusercontent.com/octocat/HelloWorld/master/notes/hello.txt",
- "type": "file",
- "_links": {
- "self": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt",
- "git": "https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3",
- "html": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt"
- }
- },
- "commit": {
- "sha": "7638417db6d59f3c431d3e1f261cc637155684cd",
- "node_id": "MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA==",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd",
- "html_url": "https://github.com/octocat/Hello-World/git/commit/7638417db6d59f3c431d3e1f261cc637155684cd",
- "author": {
- "date": "2014-11-07T22:01:45Z",
- "name": "Monalisa Octocat",
- "email": "[email protected]"
- },
- "committer": {
- "date": "2014-11-07T22:01:45Z",
- "name": "Monalisa Octocat",
- "email": "[email protected]"
- },
- "message": "my commit message",
- "tree": {
- "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb",
- "sha": "691272480426f78a0138979dd3ce63b77f706feb"
- },
- "parents": [
- {
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5",
- "html_url": "https://github.com/octocat/Hello-World/git/commit/1acc419d4d6a9ce985db7be48c6349a0475975b5",
- "sha": "1acc419d4d6a9ce985db7be48c6349a0475975b5"
- }
- ],
- "verification": {
- "verified": false,
- "reason": "unsigned",
- "signature": null,
- "payload": null
- }
- }
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.CreateFile(
- ctx,
- &common.OauthContext{},
- githubComURL,
- "octocat/Hello-World",
- "notes/hello.txt",
- vcs.FileCommitCreate{
- Branch: "master",
- Content: "my new file contents",
- CommitMessage: "my commit message",
- },
- )
- require.NoError(t, err)
-}
-
-func TestProvider_OverwriteFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/octocat/Hello-World/contents/notes%2Fhello.txt", r.URL.RawPath)
-
- body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
- wantBody := `{"message":"update file","content":"bXkgbmV3IGZpbGUgY29udGVudHM=","sha":"7638417db6d59f3c431d3e1f261cc637155684cd","branch":"master"}`
- assert.Equal(t, wantBody, string(body))
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/repos/contents#create-or-update-file-contents
- Body: io.NopCloser(strings.NewReader(`
-{
- "content": {
- "name": "hello.txt",
- "path": "notes/hello.txt",
- "sha": "95b966ae1c166bd92f8ae7d1c313e738c731dfc3",
- "size": 9,
- "url": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt",
- "html_url": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt",
- "git_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3",
- "download_url": "https://raw.githubusercontent.com/octocat/HelloWorld/master/notes/hello.txt",
- "type": "file",
- "_links": {
- "self": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt",
- "git": "https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3",
- "html": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt"
- }
- },
- "commit": {
- "sha": "7638417db6d59f3c431d3e1f261cc637155684cd",
- "node_id": "MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA==",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd",
- "html_url": "https://github.com/octocat/Hello-World/git/commit/7638417db6d59f3c431d3e1f261cc637155684cd",
- "author": {
- "date": "2014-11-07T22:01:45Z",
- "name": "Monalisa Octocat",
- "email": "[email protected]"
- },
- "committer": {
- "date": "2014-11-07T22:01:45Z",
- "name": "Monalisa Octocat",
- "email": "[email protected]"
- },
- "message": "my commit message",
- "tree": {
- "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb",
- "sha": "691272480426f78a0138979dd3ce63b77f706feb"
- },
- "parents": [
- {
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5",
- "html_url": "https://github.com/octocat/Hello-World/git/commit/1acc419d4d6a9ce985db7be48c6349a0475975b5",
- "sha": "1acc419d4d6a9ce985db7be48c6349a0475975b5"
- }
- ],
- "verification": {
- "verified": false,
- "reason": "unsigned",
- "signature": null,
- "payload": null
- }
- }
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.OverwriteFile(
- ctx,
- &common.OauthContext{},
- githubComURL,
- "octocat/Hello-World",
- "notes/hello.txt",
- vcs.FileCommitCreate{
- Branch: "master",
- Content: "my new file contents",
- CommitMessage: "update file",
- SHA: "7638417db6d59f3c431d3e1f261cc637155684cd",
- },
- )
- require.NoError(t, err)
-}
-
func TestProvider_ReadFileMeta(t *testing.T) {
p := newMockProvider(func(r *http.Request) (*http.Response, error) {
switch r.URL.Path {
@@ -642,21 +412,6 @@ func TestProvider_CreateWebhook(t *testing.T) {
assert.Equal(t, "12345678", got)
}
-func TestProvider_PatchWebhook(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.PatchWebhook(ctx, &common.OauthContext{}, githubComURL, "1", "1", []byte(""))
- require.NoError(t, err)
-}
-
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)
@@ -706,184 +461,6 @@ func TestProvider_GetBranch(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_CreateBranch(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "POST", r.Method)
- assert.Equal(t, "/repos/octocat/Hello-World/git/refs", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/git/refs#create-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()
- err := p.CreateBranch(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", &vcs.BranchInfo{
- Name: "featureA",
- LastCommitID: "aa218f56b14c9653891f9e74264a383fa43fefbd",
- })
- require.NoError(t, err)
-}
-
-func TestProvider_CreatePullRequest(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "POST", r.Method)
- assert.Equal(t, "/repos/octocat/Hello-World/pulls", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/pulls/pulls#create-a-pull-request
- Body: io.NopCloser(strings.NewReader(`
-{
- "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347",
- "id": 1,
- "node_id": "MDExOlB1bGxSZXF1ZXN0MQ==",
- "html_url": "https://github.com/octocat/Hello-World/pull/1347",
- "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff",
- "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch",
- "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347",
- "commits_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits",
- "review_comments_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments",
- "review_comment_url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}",
- "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments",
- "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e",
- "number": 1347,
- "state": "open",
- "locked": true,
- "title": "Amazing new feature",
- "body": "Please pull these awesome changes in!",
- "active_lock_reason": "too heated",
- "created_at": "2011-01-26T19:01:12Z",
- "updated_at": "2011-01-26T19:01:12Z",
- "closed_at": "2011-01-26T19:01:12Z",
- "merged_at": "2011-01-26T19:01:12Z",
- "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6",
- "head": {
- "label": "octocat:new-topic",
- "ref": "new-topic",
- "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
- "user": {
- "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
- }
- },
- "base": {
- "label": "octocat:master",
- "ref": "master",
- "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
- "user": {
- "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
- }
- },
- "author_association": "OWNER",
- "auto_merge": null,
- "draft": false,
- "merged": false,
- "mergeable": true,
- "rebaseable": true,
- "mergeable_state": "clean",
- "comments": 10,
- "review_comments": 0,
- "maintainer_can_modify": true,
- "commits": 3,
- "additions": 100,
- "deletions": 3,
- "changed_files": 5
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- res, err := p.CreatePullRequest(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", &vcs.PullRequestCreate{
- Title: "Amazing new feature",
- Body: "Please pull these awesome changes in!",
- Head: "new-topic",
- Base: "master",
- RemoveHeadAfterMerged: true,
- })
- require.NoError(t, err)
- assert.Equal(t, "https://github.com/octocat/Hello-World/pull/1347", res.URL)
-}
-
-func TestProvider_UpsertEnvironmentVariable(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- switch r.URL.Path {
- case "/repos/octocat/Hello-World/actions/secrets/public-key":
- assert.Equal(t, "GET", r.Method)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/actions/secrets#get-a-repository-public-key
- Body: io.NopCloser(strings.NewReader(`
-{
- "key_id": "568250167242549743",
- "key": "YJf3Ojcv8TSEBCtR0wtTR/F2bD3nBl1lxiwkfV/TYQk="
-}
-`)),
- }, nil
- case "/repos/octocat/Hello-World/actions/secrets/1":
- assert.Equal(t, "PUT", r.Method)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
- Body: io.NopCloser(strings.NewReader("")),
- }, nil
- }
-
- return nil, errors.Errorf("Invalid request. %s: %s", r.Method, r.URL.Path)
- },
- )
-
- ctx := context.Background()
- err := p.UpsertEnvironmentVariable(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "1", "new value")
- require.NoError(t, err)
-}
-
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)
@@ -929,46 +506,6 @@ func TestProvider_ListPullRequestFile(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_GetDiffFileList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v3/repos/1/compare/before_sha...after_sha", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/commits/commits#compare-two-commits
- Body: io.NopCloser(strings.NewReader(`
-{
- "files": [
- {
- "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.GetDiffFileList(ctx, &common.OauthContext{}, "", "1", "before_sha", "after_sha")
- require.NoError(t, err)
-
- want := []vcs.FileDiff{
- {
- Path: "file1.txt",
- Type: vcs.FileDiffTypeAdded,
- },
- }
- assert.Equal(t, want, got)
-}
-
func newMockProvider(mockRoundTrip func(r *http.Request) (*http.Response, error)) vcs.Provider {
return newProvider(
vcs.ProviderConfig{
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index bf392fe52d..ad4e5983c9 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -237,86 +237,6 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
return repos, len(repos) >= apiPageSize, nil
}
-// FetchCommitByID fetches the commit data by its ID from the repository.
-func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, commitID string) (*vcs.Commit, error) {
- url := fmt.Sprintf("%s/projects/%s/repository/commits/%s", p.APIURL(instanceURL), repositoryID, commitID)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrap(err, "GET")
- }
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to fetch commit data from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- commit := &Commit{}
- if err := json.Unmarshal([]byte(body), commit); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal commit data from GitLab instance %s", instanceURL)
- }
-
- return &vcs.Commit{
- ID: commit.ID,
- AuthorName: commit.AuthorName,
- CreatedTs: commit.CreatedAt.Unix(),
- }, nil
-}
-
-// GetDiffFileList gets the diff files list between two commits.
-func (p *Provider) GetDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]vcs.FileDiff, error) {
- url := fmt.Sprintf("%s/projects/%s/repository/compare?from=%s&to=%s", p.APIURL(instanceURL), repositoryID, beforeCommit, afterCommit)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to get diff file list from URL %s", url)
- } else if code >= 300 {
- return nil,
- errors.Errorf("failed to get diff file list from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- diffs := &CommitsDiff{}
- if err := json.Unmarshal([]byte(body), diffs); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal file diff data from GitLab instance %s", instanceURL)
- }
-
- var ret []vcs.FileDiff
- for _, diff := range diffs.FileDiffList {
- item := vcs.FileDiff{
- Path: diff.NewPath,
- }
- if diff.NewFile {
- item.Type = vcs.FileDiffTypeAdded
- } else if diff.DeletedFile {
- item.Type = vcs.FileDiffTypeRemoved
- } else {
- item.Type = vcs.FileDiffTypeModified
- }
- ret = append(ret, item)
- }
- return ret, nil
-}
-
// FetchRepositoryFileList fetches the all files from the given repository tree
// recursively.
//
@@ -388,89 +308,6 @@ func (p *Provider) fetchPaginatedRepositoryFileList(ctx context.Context, oauthCt
return treeNodes, len(treeNodes) >= apiPageSize, nil
}
-// CreateFile creates a file at given path in the repository.
-//
-// Docs: https://docs.gitlab.com/ee/api/repository_files.html#create-new-file-in-repository
-func (p *Provider) CreateFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- body, err := json.Marshal(
- FileCommit{
- Branch: fileCommitCreate.Branch,
- CommitMessage: fileCommitCreate.CommitMessage,
- Content: fileCommitCreate.Content,
- AuthorName: fileCommitCreate.AuthorName,
- AuthorEmail: fileCommitCreate.AuthorEmail,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal file commit")
- }
-
- url := fmt.Sprintf("%s/projects/%s/repository/files/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "POST %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create file through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create file through URL %s, status code: %d, response body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
-// OverwriteFile overwrites an existing file at given path in the repository.
-//
-// Docs: https://docs.gitlab.com/ee/api/repository_files.html#update-existing-file-in-repository
-func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
- body, err := json.Marshal(
- FileCommit{
- Branch: fileCommitCreate.Branch,
- Content: fileCommitCreate.Content,
- CommitMessage: fileCommitCreate.CommitMessage,
- LastCommitID: fileCommitCreate.LastCommitID,
- AuthorName: fileCommitCreate.AuthorName,
- AuthorEmail: fileCommitCreate.AuthorEmail,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal file commit")
- }
-
- url := fmt.Sprintf("%s/projects/%s/repository/files/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))
- code, _, resp, err := oauth.Put(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to overwrite file through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to overwrite file through URL %s, status code: %d, response body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
// ReadFileMeta reads the metadata of the given file in the repository.
//
// Docs: https://docs.gitlab.com/ee/api/repository_files.html#get-file-from-repository
@@ -609,225 +446,11 @@ func (p *Provider) GetBranch(ctx context.Context, oauthCtx *common.OauthContext,
}, nil
}
-// CreateBranch creates the branch in the repository.
-//
-// Docs: https://docs.gitlab.com/ee/api/branches.html#create-repository-branch
-func (p *Provider) CreateBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
- body, err := json.Marshal(
- BranchCreate{
- Branch: branch.Name,
- Ref: branch.LastCommitID,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal branch create")
- }
-
- url := fmt.Sprintf("%s/projects/%s/repository/branches", p.APIURL(instanceURL), repositoryID)
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create branch from URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
-
- return nil
-}
-
// MergeRequest is the API message for GitLab merge request.
type MergeRequest struct {
WebURL string `json:"web_url"`
}
-// CreatePullRequest creates the pull request in the repository.
-//
-// Docs: https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
-func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *vcs.PullRequestCreate) (*vcs.PullRequest, error) {
- body, err := json.Marshal(
- MergeRequestCreate{
- Title: pullRequestCreate.Title,
- Description: pullRequestCreate.Body,
- SourceBranch: pullRequestCreate.Head,
- TargetBranch: pullRequestCreate.Base,
- RemoveSourceBranch: pullRequestCreate.RemoveHeadAfterMerged,
- },
- )
- if err != nil {
- return nil, errors.Wrap(err, "marshal pull request create")
- }
-
- url := fmt.Sprintf("%s/projects/%s/merge_requests", p.APIURL(instanceURL), repositoryID)
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to create merge request from URL %s", url)
- } else if code >= 300 {
- return nil, errors.Errorf("failed to create merge request from URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
-
- var res MergeRequest
- if err := json.Unmarshal([]byte(resp), &res); err != nil {
- return nil, err
- }
-
- return &vcs.PullRequest{
- URL: res.WebURL,
- }, nil
-}
-
-// EnvironmentVariable is the API message for environment variable in GitLab project.
-type EnvironmentVariable struct {
- Key string `json:"key"`
- Value string `json:"value"`
-}
-
-// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
-func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
- _, err := p.getEnvironmentVariable(ctx, oauthCtx, instanceURL, repositoryID, key)
- if err != nil {
- if common.ErrorCode(err) == common.NotFound {
- return p.createEnvironmentVariable(ctx, oauthCtx, instanceURL, repositoryID, key, value)
- }
-
- return err
- }
-
- return p.updateEnvironmentVariable(ctx, oauthCtx, instanceURL, repositoryID, key, value)
-}
-
-// getEnvironmentVariable gets the environment variable in the repository.
-//
-// https://docs.gitlab.com/ee/api/project_level_variables.html#get-a-single-variable
-func (p *Provider) getEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key string) (*EnvironmentVariable, error) {
- url := fmt.Sprintf("%s/projects/%s/variables/%s", p.APIURL(instanceURL), repositoryID, key)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to found variable from URL %s", url)
- } else if code >= 300 {
- return nil,
- errors.Errorf("failed to found variable from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- variable := new(EnvironmentVariable)
- if err := json.Unmarshal([]byte(body), variable); err != nil {
- return nil, err
- }
-
- return variable, nil
-}
-
-// createEnvironmentVariable creates the environment variable in the repository.
-//
-// https://docs.gitlab.com/ee/api/project_level_variables.html#create-a-variable
-func (p *Provider) createEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
- url := fmt.Sprintf("%s/projects/%s/variables", p.APIURL(instanceURL), repositoryID)
- body, err := json.Marshal(
- EnvironmentVariable{
- Key: key,
- Value: value,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal environment create")
- }
- code, _, resp, err := oauth.Post(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "POST %s", url)
- }
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to create environment variable through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to create environment variable through URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
-// updateEnvironmentVariable updates the environment variable in the repository.
-//
-// https://docs.gitlab.com/ee/api/project_level_variables.html#update-a-variable
-func (p *Provider) updateEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, key, value string) error {
- url := fmt.Sprintf("%s/projects/%s/variables/%s", p.APIURL(instanceURL), repositoryID, key)
- body, err := json.Marshal(
- EnvironmentVariable{
- Key: key,
- Value: value,
- },
- )
- if err != nil {
- return errors.Wrap(err, "marshal environment update")
- }
- code, _, resp, err := oauth.Put(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(body),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to update environment variable through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to update environment variable through URL %s, status code: %d, body: %s",
- url,
- code,
- resp,
- )
- }
- return nil
-}
-
// CreateWebhook creates a webhook in the repository with given payload.
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#add-project-hook
@@ -870,34 +493,6 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx *common.OauthCont
return strconv.Itoa(webhookInfo.ID), nil
}
-// PatchWebhook patches the webhook in the repository with given payload.
-//
-// Docs: https://docs.gitlab.com/ee/api/projects.html#edit-project-hook
-func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error {
- url := fmt.Sprintf("%s/projects/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)
- code, _, body, err := oauth.Put(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- bytes.NewReader(payload),
- )
- if err != nil {
- return errors.Wrapf(err, "PUT %s", url)
- }
-
- if code == http.StatusNotFound {
- return common.Errorf(common.NotFound, "failed to patch webhook through URL %s", url)
- } else if code >= 300 {
- return errors.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
- return nil
-}
-
// DeleteWebhook deletes the webhook from the repository.
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#delete-project-hook
@@ -960,36 +555,3 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx *common.OauthContext,
LastCommitID: header.Get("x-gitlab-last-commit-id"),
}, nil
}
-
-// ToVCS returns the push event in VCS format.
-func (p WebhookPushEvent) ToVCS() (vcs.PushEvent, error) {
- var commitList []vcs.Commit
- for _, commit := range p.CommitList {
- createdTime, err := time.Parse(time.RFC3339, commit.Timestamp)
- if err != nil {
- return vcs.PushEvent{}, errors.Wrapf(err, "failed to parse commit %q's timestamp %q", commit.ID, commit.Timestamp)
- }
- commitList = append(commitList, vcs.Commit{
- ID: commit.ID,
- Title: commit.Title,
- Message: commit.Message,
- CreatedTs: createdTime.Unix(),
- URL: commit.URL,
- AuthorName: commit.Author.Name,
- AuthorEmail: commit.Author.Email,
- AddedList: commit.AddedList,
- ModifiedList: commit.ModifiedList,
- })
- }
- return vcs.PushEvent{
- VCSType: vcs.GitLab,
- Ref: p.Ref,
- Before: p.Before,
- After: p.After,
- RepositoryID: fmt.Sprintf("%v", p.Project.ID),
- RepositoryURL: p.Project.WebURL,
- RepositoryFullPath: p.Project.FullPath,
- AuthorName: p.AuthorName,
- CommitList: commitList,
- }, nil
-}
diff --git a/backend/plugin/vcs/gitlab/gitlab_test.go b/backend/plugin/vcs/gitlab/gitlab_test.go
index 20ac4b8512..52c7de0015 100644
--- a/backend/plugin/vcs/gitlab/gitlab_test.go
+++ b/backend/plugin/vcs/gitlab/gitlab_test.go
@@ -7,7 +7,6 @@ import (
"strings"
"testing"
- "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -15,59 +14,6 @@ import (
"github.com/bytebase/bytebase/backend/plugin/vcs"
)
-func TestProvider_FetchCommitByID(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/5/repository/commits/6104942438c14ec7bd21c6cd5bd995272b3faff6", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/commits.html#get-a-single-commit
- Body: io.NopCloser(strings.NewReader(`
-{
- "id": "6104942438c14ec7bd21c6cd5bd995272b3faff6",
- "short_id": "6104942438c",
- "title": "Sanitize for network graph",
- "author_name": "randx",
- "author_email": "[email protected]",
- "committer_name": "Dmitriy",
- "committer_email": "[email protected]",
- "created_at": "2021-09-20T09:06:12.300+03:00",
- "message": "Sanitize for network graph",
- "committed_date": "2021-09-20T09:06:12.300+03:00",
- "authored_date": "2021-09-20T09:06:12.420+03:00",
- "parent_ids": [
- "ae1d9fb46aa2b07ee9836d49862ec4e2c46fbbba"
- ],
- "last_pipeline" : {
- "id": 8,
- "ref": "master",
- "sha": "2dc6aa325a317eda67812f05600bdf0fcdc70ab0",
- "status": "created"
- },
- "stats": {
- "additions": 15,
- "deletions": 10,
- "total": 25
- },
- "status": "running",
- "web_url": "https://gitlab.example.com/thedude/gitlab-foss/-/commit/6104942438c14ec7bd21c6cd5bd995272b3faff6"
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.FetchCommitByID(ctx, &common.OauthContext{}, "", "5", "6104942438c14ec7bd21c6cd5bd995272b3faff6")
- require.NoError(t, err)
-
- want := &vcs.Commit{
- ID: "6104942438c14ec7bd21c6cd5bd995272b3faff6",
- AuthorName: "randx",
- CreatedTs: 1632117972,
- }
- assert.Equal(t, want, got)
-}
-
func TestProvider_FetchAllRepositoryList(t *testing.T) {
p := newMockProvider(func(r *http.Request) (*http.Response, error) {
assert.Equal(t, "/api/v4/projects", r.URL.Path)
@@ -165,81 +111,6 @@ func TestProvider_FetchRepositoryFileList(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_CreateFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/repository/files/lib%2Fclass.rb", r.URL.RawPath)
-
- body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
- wantBody := `{"branch":"master","content":"some content","commit_message":"create a new file"}`
- assert.Equal(t, wantBody, string(body))
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/repository_files.html#create-new-file-in-repository
- Body: io.NopCloser(strings.NewReader(`
-{
- "file_path": "app/project.rb",
- "branch": "master"
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.CreateFile(
- ctx,
- &common.OauthContext{},
- "",
- "1",
- "lib/class.rb",
- vcs.FileCommitCreate{
- Branch: "master",
- Content: "some content",
- CommitMessage: "create a new file",
- },
- )
- require.NoError(t, err)
-}
-
-func TestProvider_OverwriteFile(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/repository/files/lib%2Fclass.rb", r.URL.RawPath)
-
- body, err := io.ReadAll(r.Body)
- require.NoError(t, err)
- wantBody := `{"branch":"master","content":"some content","commit_message":"update file","last_commit_id":"7638417db6d59f3c431d3e1f261cc637155684cd"}`
- assert.Equal(t, wantBody, string(body))
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/repository_files.html#update-existing-file-in-repository
- Body: io.NopCloser(strings.NewReader(`
-{
- "file_path": "app/project.rb",
- "branch": "master"
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.OverwriteFile(
- ctx,
- &common.OauthContext{},
- "",
- "1",
- "lib/class.rb",
- vcs.FileCommitCreate{
- Branch: "master",
- Content: "some content",
- CommitMessage: "update file",
- LastCommitID: "7638417db6d59f3c431d3e1f261cc637155684cd",
- },
- )
- require.NoError(t, err)
-}
-
func TestProvider_ReadFileMeta(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)
@@ -352,21 +223,6 @@ func TestProvider_CreateWebhook(t *testing.T) {
assert.Equal(t, "1", got)
}
-func TestProvider_PatchWebhook(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.PatchWebhook(ctx, &common.OauthContext{}, "", "1", "1", []byte(""))
- require.NoError(t, err)
-}
-
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)
@@ -431,221 +287,6 @@ func TestProvider_GetBranch(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_CreateBranch(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "POST", r.Method)
- assert.Equal(t, "/api/v4/projects/1/repository/branches", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/branches.html#create-repository-branch
- Body: io.NopCloser(strings.NewReader(`
-{
- "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"
- ]
- },
- "name": "newbranch",
- "merged": false,
- "protected": false,
- "default": false,
- "developers_can_push": false,
- "developers_can_merge": false,
- "can_push": true,
- "web_url": "https://gitlab.example.com/my-group/my-project/-/tree/newbranch"
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- err := p.CreateBranch(ctx, &common.OauthContext{}, "", "1", &vcs.BranchInfo{
- Name: "newbranch",
- LastCommitID: "7b5c3cc8be40ee161ae89a06bba6229da1032a0c",
- })
- require.NoError(t, err)
-}
-
-func TestProvider_CreatePullRequest(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/merge_requests", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
- Body: io.NopCloser(strings.NewReader(`
-{
- "id": 1,
- "iid": 1,
- "project_id": 3,
- "title": "test1",
- "description": "fixed login page css paddings",
- "state": "merged",
- "created_at": "2017-04-29T08:46:00Z",
- "updated_at": "2017-04-29T08:46:00Z",
- "target_branch": "master",
- "source_branch": "test1",
- "upvotes": 0,
- "downvotes": 0,
- "author": {
- "id": 1,
- "name": "Administrator",
- "username": "admin",
- "state": "active",
- "avatar_url": null,
- "web_url" : "https://gitlab.example.com/admin"
- },
- "assignee": {
- "id": 1,
- "name": "Administrator",
- "username": "admin",
- "state": "active",
- "avatar_url": null,
- "web_url" : "https://gitlab.example.com/admin"
- },
- "source_project_id": 2,
- "target_project_id": 3,
- "labels": [
- "Community contribution",
- "Manage"
- ],
- "draft": false,
- "work_in_progress": false,
- "merge_when_pipeline_succeeds": true,
- "merge_status": "can_be_merged",
- "merge_error": null,
- "sha": "8888888888888888888888888888888888888888",
- "merge_commit_sha": null,
- "squash_commit_sha": null,
- "user_notes_count": 1,
- "discussion_locked": null,
- "should_remove_source_branch": true,
- "force_remove_source_branch": false,
- "allow_collaboration": false,
- "allow_maintainer_to_push": false,
- "web_url": "http://gitlab.example.com/my-group/my-project/merge_requests/1",
- "references": {
- "short": "!1",
- "relative": "!1",
- "full": "my-group/my-project!1"
- },
- "time_stats": {
- "time_estimate": 0,
- "total_time_spent": 0,
- "human_time_estimate": null,
- "human_total_time_spent": null
- },
- "squash": false,
- "subscribed": false,
- "changes_count": "1",
- "closed_by": null,
- "closed_at": null,
- "latest_build_started_at": "2018-09-07T07:27:38.472Z",
- "latest_build_finished_at": "2018-09-07T08:07:06.012Z",
- "first_deployed_to_production_at": null,
- "pipeline": {
- "id": 29626725,
- "sha": "2be7ddb704c7b6b83732fdd5b9f09d5a397b5f8f",
- "ref": "patch-28",
- "status": "success",
- "web_url": "https://gitlab.example.com/my-group/my-project/pipelines/29626725"
- },
- "diff_refs": {
- "base_sha": "c380d3acebd181f13629a25d2e2acca46ffe1e00",
- "head_sha": "2be7ddb704c7b6b83732fdd5b9f09d5a397b5f8f",
- "start_sha": "c380d3acebd181f13629a25d2e2acca46ffe1e00"
- },
- "diverged_commits_count": 2
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- res, err := p.CreatePullRequest(ctx, &common.OauthContext{}, "", "1", &vcs.PullRequestCreate{
- Title: "test1",
- Body: "fixed login page css paddings",
- Head: "test1",
- Base: "master",
- RemoveHeadAfterMerged: true,
- })
- require.NoError(t, err)
- assert.Equal(t, "http://gitlab.example.com/my-group/my-project/merge_requests/1", res.URL)
-}
-
-func TestProvider_UpsertEnvironmentVariable(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- switch r.URL.Path {
- case "/api/v4/projects/1/variables/1":
- if r.Method == "GET" {
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/project_level_variables.html#get-a-single-variable
- Body: io.NopCloser(strings.NewReader(`
-{
- "variable_type": "env_var",
- "key": "1",
- "value": "new value",
- "protected": false,
- "masked": false,
- "environment_scope": "*"
-}
-`)),
- }, nil
- } else if r.Method == "PUT" {
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/project_level_variables.html#update-a-variable
- Body: io.NopCloser(strings.NewReader(`
-{
- "variable_type": "env_var",
- "key": "1",
- "value": "new value",
- "protected": false,
- "masked": false,
- "environment_scope": "*"
-}
-`)),
- }, nil
- }
- case "/api/v4/projects/1/variables":
- assert.Equal(t, "POST", r.Method)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/project_level_variables.html#create-a-variable
- Body: io.NopCloser(strings.NewReader(`
-{
- "variable_type": "env_var",
- "key": "1",
- "value": "new value",
- "protected": false,
- "masked": false,
- "environment_scope": "*"
-}
-`)),
- }, nil
- }
-
- return nil, errors.Errorf("Invalid request. %s: %s", r.Method, r.URL.Path)
- },
- )
-
- ctx := context.Background()
- err := p.UpsertEnvironmentVariable(ctx, &common.OauthContext{}, "", "1", "1", "new value")
- require.NoError(t, err)
-}
-
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)
@@ -706,62 +347,6 @@ func TestProvider_ListPullRequestFile(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_GetDiffFileList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/repository/compare", r.URL.Path)
- assert.Equal(t, "from=before_sha&to=after_sha", r.URL.RawQuery)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/repositories.html#compare-branches-tags-or-commits
- Body: io.NopCloser(strings.NewReader(`
-{
- "commit": {
- "id": "12d65c8dd2b2676fa3ac47d955accc085a37a9c1",
- "short_id": "12d65c8dd2b",
- "title": "JS fix",
- "author_name": "Example User",
- "author_email": "[email protected]",
- "created_at": "2014-02-27T10:27:00+02:00"
- },
- "commits": [{
- "id": "12d65c8dd2b2676fa3ac47d955accc085a37a9c1",
- "short_id": "12d65c8dd2b",
- "title": "JS fix",
- "author_name": "Example User",
- "author_email": "[email protected]",
- "created_at": "2014-02-27T10:27:00+02:00"
- }],
- "diffs": [{
- "old_path": "files/js/application.js",
- "new_path": "files/js/application.js",
- "a_mode": null,
- "b_mode": "100644",
- "diff": "--- a/files/js/application.js\n+++ b/files/js/application.js\n@@ -24,8 +24,10 @@\n //= require g.raphael-min\n //= require g.bar-min\n //= require branch-graph\n-//= require highlightjs.min\n-//= require ace/ace\n //= require_tree .\n //= require d3\n //= require underscore\n+\n+function fix() { \n+ alert(\"Fixed\")\n+}",
- "new_file": false,
- "renamed_file": false,
- "deleted_file": false
- }],
- "compare_timeout": false,
- "compare_same_ref": false,
- "web_url": "https://gitlab.example.com/janedoe/gitlab-foss/-/compare/ae73cb07c9eeaf35924a10f713b364d32b2dd34f...0b4bc9a49b562e85de7cc9e834518ea6828729b9"
-}
-`)),
- }, nil
- },
- )
- ctx := context.Background()
- got, err := p.GetDiffFileList(ctx, &common.OauthContext{}, "", "1", "before_sha", "after_sha")
- require.NoError(t, err)
-
- want := []vcs.FileDiff{
- {
- Path: "files/js/application.js",
- Type: vcs.FileDiffTypeModified,
- },
- }
- assert.Equal(t, want, got)
-}
-
func newMockProvider(mockRoundTrip func(r *http.Request) (*http.Response, error)) vcs.Provider {
return newProvider(
vcs.ProviderConfig{
diff --git a/backend/plugin/vcs/util.go b/backend/plugin/vcs/util.go
index 239899f1b7..eb8175fd49 100644
--- a/backend/plugin/vcs/util.go
+++ b/backend/plugin/vcs/util.go
@@ -2,7 +2,6 @@
package vcs
import (
- "log/slog"
"strings"
"github.com/pkg/errors"
@@ -18,95 +17,3 @@ func Branch(ref string) (string, error) {
return "", errors.Errorf("invalid Git ref: %s", ref)
}
-
-// FileItemType is the type of a file item.
-type FileItemType string
-
-// The list of file item types.
-const (
- FileItemTypeAdded FileItemType = "added"
- FileItemTypeModified FileItemType = "modified"
-)
-
-// DistinctFileItem is an item for distinct file in push event commits.
-// We are observing the push webhook event so that we will receive the event either when:
-// 1. A commit is directly pushed to a branch.
-// 2. One or more commits are merged to a branch.
-//
-// There is a complication to deal with the 2nd type. A typical workflow is a developer first
-// commits the migration file to the feature branch, and at a later point, she creates a merge
-// request to merge the commit to the main branch. Even the developer only creates a single commit
-// on the feature branch, that merge request may contain multiple commits (unless both squash and fast-forward merge are used):
-// 1. The original commit on the feature branch.
-// 2. The merge request commit.
-//
-// And both commits would include that added migration file. Since we create an issue per migration file,
-// we need to filter the commit list to prevent creating a duplicated issue. GitLab has a limitation to distinguish
-// whether the commit is a merge commit (https://gitlab.com/gitlab-org/gitlab/-/issues/30914), so we need to dedup
-// ourselves. Below is the filtering algorithm:
-// 1. If we observe the same migration file multiple times, then we should use the latest migration file. This does not matter
-// for change-based migration since a developer would always create different migration file with incremental names, while it
-// will be important for the state-based migration, since the file name is always the same and we need to use the latest snapshot.
-// 2. Maintain the relative commit order between different migration files. If migration file A happens before migration file B,
-// then we should create an issue for migration file A first.
-type DistinctFileItem struct {
- CreatedTs int64
- Commit Commit
- FileName string
- ItemType FileItemType
- IsYAML bool
-}
-
-// GetDistinctFileList gets the distinct files from push event commits.
-// The caller should ensure the commit list is logically organized.
-func (p PushEvent) GetDistinctFileList() []DistinctFileItem {
- // Use list instead of map because we need to maintain the relative commit order in the source branch.
- var distinctFileList []DistinctFileItem
- for _, commit := range p.CommitList {
- slog.Debug("Pre-processing commit to dedup migration files...",
- slog.String("id", commit.ID),
- slog.String("title", commit.Title),
- )
-
- addDistinctFile := func(fileName string, itemType FileItemType) {
- item := DistinctFileItem{
- CreatedTs: commit.CreatedTs,
- Commit: commit,
- FileName: fileName,
- ItemType: itemType,
- IsYAML: strings.HasSuffix(fileName, ".yml"),
- }
- for i, file := range distinctFileList {
- // For the migration file with the same name, keep the one from the latest commit
- if item.FileName != file.FileName {
- continue
- }
- isPreviousCommit := file.CreatedTs >= commit.CreatedTs
- if isPreviousCommit {
- // The VCS may reverse the commit order in the commit list, so the index of modified file commit is less than the added file commit.
- // In this case, we should modified the existing distinctFileList item's ItemType to modified.
- if item.ItemType == FileItemTypeAdded {
- distinctFileList[i].ItemType = FileItemTypeAdded
- }
- } else {
- // A file can be added and then modified in a later commit. We should consider the item as added.
- if file.ItemType == FileItemTypeAdded {
- item.ItemType = FileItemTypeAdded
- }
- distinctFileList[i] = item
- }
- // The fileName should be unique within the distinctFileList.
- return
- }
- distinctFileList = append(distinctFileList, item)
- }
-
- for _, added := range commit.AddedList {
- addDistinctFile(added, FileItemTypeAdded)
- }
- for _, modified := range commit.ModifiedList {
- addDistinctFile(modified, FileItemTypeModified)
- }
- }
- return distinctFileList
-}
diff --git a/backend/plugin/vcs/util_test.go b/backend/plugin/vcs/util_test.go
index 7e11899dff..1597169f61 100644
--- a/backend/plugin/vcs/util_test.go
+++ b/backend/plugin/vcs/util_test.go
@@ -2,7 +2,6 @@ package vcs
import (
"testing"
- "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -39,442 +38,3 @@ func TestBranch(t *testing.T) {
assert.Equal(t, result, test.want)
}
}
-
-func TestGetDistinctFileList(t *testing.T) {
- timestamp1 := "2021-01-13T00:00:00+00:00"
- timestamp2 := "2021-01-14T00:00:00+00:00"
- timestamp3 := "2021-01-15T00:00:00+00:00"
- time1, _ := time.Parse(time.RFC3339, timestamp1)
- time2, _ := time.Parse(time.RFC3339, timestamp2)
- time3, _ := time.Parse(time.RFC3339, timestamp3)
- ts1 := time1.Unix()
- ts2 := time2.Unix()
- ts3 := time3.Unix()
-
- tests := []struct {
- name string
- commitList []Commit
- want []DistinctFileItem
- }{
- {
- name: "Empty",
- commitList: []Commit{},
- want: nil,
- },
- {
- name: "Single commit, single file",
- commitList: []Commit{
- {
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- },
- },
- },
- want: []DistinctFileItem{
- {
- CreatedTs: ts1,
- Commit: Commit{
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- },
- },
- FileName: "v1.sql",
- ItemType: FileItemTypeAdded,
- },
- },
- },
- {
- name: "Single commit, multiple files",
- commitList: []Commit{
- {
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- },
- },
- },
- want: []DistinctFileItem{
- {
- CreatedTs: ts1,
- Commit: Commit{
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- },
- },
- FileName: "v1.sql",
- ItemType: FileItemTypeAdded,
- },
- {
- CreatedTs: ts1,
- Commit: Commit{
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- },
- },
- FileName: "v2.sql",
- ItemType: FileItemTypeAdded,
- },
- },
- },
- {
- name: "Multi commits, single file",
- commitList: []Commit{
- {
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- },
- },
- {
- ID: "2",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts2,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- },
- },
- },
- want: []DistinctFileItem{
- {
- CreatedTs: ts2,
- Commit: Commit{
- ID: "2",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts2,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- },
- },
- FileName: "v1.sql",
- ItemType: FileItemTypeAdded,
- },
- },
- },
- {
- name: "Multi commits, single file, direct push",
- commitList: []Commit{
- {
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- },
- },
- {
- ID: "2",
- Title: "Commit 2",
- Message: "Update 2",
- CreatedTs: ts2,
- URL: "example.com",
- AuthorName: "bob",
- ModifiedList: []string{
- "v1.sql",
- },
- },
- },
- want: []DistinctFileItem{
- {
- CreatedTs: ts2,
- Commit: Commit{
- ID: "2",
- Title: "Commit 2",
- Message: "Update 2",
- CreatedTs: ts2,
- URL: "example.com",
- AuthorName: "bob",
- ModifiedList: []string{
- "v1.sql",
- },
- },
- FileName: "v1.sql",
- ItemType: FileItemTypeAdded,
- },
- },
- },
- {
- name: "Multi commits, multi files",
- commitList: []Commit{
- {
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- },
- },
- {
- ID: "2",
- Title: "Commit 2",
- Message: "Update 2",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v3.sql",
- },
- },
- {
- ID: "3",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- },
- },
- want: []DistinctFileItem{
- {
- CreatedTs: ts3,
- Commit: Commit{
- ID: "3",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- },
- FileName: "v1.sql",
- ItemType: FileItemTypeAdded,
- },
- {
- CreatedTs: ts3,
- Commit: Commit{
- ID: "3",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- },
- FileName: "v2.sql",
- ItemType: FileItemTypeAdded,
- },
- {
- CreatedTs: ts3,
- Commit: Commit{
- ID: "3",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- },
- FileName: "v3.sql",
- ItemType: FileItemTypeAdded,
- },
- },
- },
- {
- name: "Multi commits, multi files, include modified",
- commitList: []Commit{
- {
- ID: "1",
- Title: "Commit 1",
- Message: "Update 1",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- },
- },
- {
- ID: "2",
- Title: "Commit 2",
- Message: "Update 2",
- CreatedTs: ts1,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v3.sql",
- },
- },
- {
- ID: "3",
- Title: "Commit 3",
- Message: "Update 3",
- CreatedTs: ts2,
- URL: "example.com",
- AuthorName: "bob",
- ModifiedList: []string{
- "v3.sql",
- "v4.sql",
- },
- },
- {
- ID: "4",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- // This file is both added and modified in the commits above.
- // GitLab will treat this as added in the merge commit.
- "v3.sql",
- },
- ModifiedList: []string{"v4.sql"},
- },
- },
- want: []DistinctFileItem{
- {
- CreatedTs: ts3,
- Commit: Commit{
- ID: "4",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- ModifiedList: []string{"v4.sql"},
- },
- FileName: "v1.sql",
- ItemType: FileItemTypeAdded,
- },
- {
- CreatedTs: ts3,
- Commit: Commit{
- ID: "4",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- ModifiedList: []string{"v4.sql"},
- },
- FileName: "v2.sql",
- ItemType: FileItemTypeAdded,
- },
- {
- CreatedTs: ts3,
- Commit: Commit{
- ID: "4",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- ModifiedList: []string{"v4.sql"},
- },
- FileName: "v3.sql",
- ItemType: FileItemTypeAdded,
- },
- {
- CreatedTs: ts3,
- Commit: Commit{
- ID: "4",
- Title: "Merge branch",
- Message: "Merge update",
- CreatedTs: ts3,
- URL: "example.com",
- AuthorName: "bob",
- AddedList: []string{
- "v1.sql",
- "v2.sql",
- "v3.sql",
- },
- ModifiedList: []string{"v4.sql"},
- },
- FileName: "v4.sql",
- ItemType: FileItemTypeModified,
- },
- },
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- p := PushEvent{CommitList: tt.commitList}
- got := p.GetDistinctFileList()
- assert.Equal(t, tt.want, got)
- })
- }
-}
diff --git a/backend/plugin/vcs/vcs.go b/backend/plugin/vcs/vcs.go
index 2dfc5c309b..2d0e1d81c0 100644
--- a/backend/plugin/vcs/vcs.go
+++ b/backend/plugin/vcs/vcs.go
@@ -209,22 +209,6 @@ type Provider interface {
// Returns the API URL for a given VCS instance URL
APIURL(instanceURL string) string
- // Fetch the commit data by id
- //
- // oauthCtx: OAuth context to fetch commit
- // instanceURL: VCS instance URL
- // externalRepositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
- // commitID: the commit ID
- FetchCommitByID(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, externalRepositoryID, commitID string) (*Commit, error)
- // Get the diff files list between two commits
- //
- // oauthCtx: OAuth context to fetch commit
- // 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)
- // beforeCommit: the previous commit
- // afterCommit: the current commit
- GetDiffFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, beforeCommit, afterCommit string) ([]FileDiff, error)
-
// Fetch all repository within a given user's scope
//
// oauthCtx: OAuth context to write the file content
@@ -240,18 +224,6 @@ type Provider interface {
// filePath: the path inside repository, used to get content of subdirectories
FetchRepositoryFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*RepositoryTreeNode, error)
- // Commits a new file
- //
- // oauthCtx: OAuth context to write 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 written
- // fileCommit: the new file commit info
- CreateFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommit FileCommitCreate) error
- // Overwrites an existing file
- //
- // Similar to CreateFile except it overwrites an existing file. The fileCommit should includes the "LastCommitID" field which is used to detect conflicting writes.
- OverwriteFile(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, fileCommit FileCommitCreate) error
// Reads the file metadata
//
// oauthCtx: OAuth context to fetch the file metadata
@@ -260,6 +232,7 @@ type Provider interface {
// filePath: file path to be read
// ref: the specific file version to be read, could be a name of branch, tag or commit
ReadFileMeta(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo RefInfo) (*FileMeta, error)
+
// Reads the file content
//
// oauthCtx: OAuth context to read the file content
@@ -268,6 +241,7 @@ type Provider interface {
// 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)
+
// GetBranch gets the given branch in the repository.
//
// oauthCtx: OAuth context to create the webhook
@@ -275,13 +249,7 @@ type Provider interface {
// 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)
- // CreateBranch creates the 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)
- // branch: the new branch info
- CreateBranch(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, branch *BranchInfo) error
+
// CreatePullRequest creates the pull request in the repository.
//
// oauthCtx: OAuth context to create the webhook
@@ -289,16 +257,7 @@ type Provider interface {
// 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)
- // pullRequestCreate: the new pull request info
- CreatePullRequest(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *PullRequestCreate) (*PullRequest, error)
- // UpsertEnvironmentVariable creates or updates the environment variable 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)
- // key: the environment variable name
- // value: the environment variable value
- UpsertEnvironmentVariable(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID string, key, value string) error
+
// Creates a webhook. Returns the created webhook ID on success.
//
// oauthCtx: OAuth context to create the webhook
@@ -306,10 +265,7 @@ type Provider interface {
// 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)
- // Patches a webhook.
- //
- // The payload stores the patched field(s).
- PatchWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error
+
// Deletes a webhook.
DeleteWebhook(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, webhookID string) error
}
diff --git a/backend/plugin/vcs/vcs_test.go b/backend/plugin/vcs/vcs_test.go
deleted file mode 100644
index 2e4d6ccd3a..0000000000
--- a/backend/plugin/vcs/vcs_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package vcs
-
-import (
- "testing"
-
- "encoding/json"
-
- "github.com/stretchr/testify/require"
-
- "google.golang.org/protobuf/encoding/protojson"
-
- storepb "github.com/bytebase/bytebase/proto/generated-go/store"
-)
-
-func TestPushEventUnmarshalToProto(t *testing.T) {
- a := require.New(t)
- vcsPushEvent := &PushEvent{
- VCSType: GitLab,
- Ref: "refs/heads/master",
- Before: "beforea",
- After: "afterb",
- RepositoryID: "id-123",
- RepositoryURL: "sptth://123",
- RepositoryFullPath: "utlenme",
- AuthorName: "me",
- CommitList: []Commit{
- {
- ID: "1",
- Title: "123",
- Message: "file",
- CreatedTs: 123,
- URL: "terw",
- AuthorName: "hi",
- AuthorEmail: "none",
- AddedList: []string{"123"},
- ModifiedList: []string{"321"},
- },
- },
- }
- bytes, err := json.Marshal(vcsPushEvent)
- a.NoError(err)
- var pushEvent storepb.PushEvent
- err = protojson.Unmarshal(bytes, &pushEvent)
- a.NoError(err)
- a.Equal(storepb.VcsType_GITLAB, pushEvent.VcsType)
-}
diff --git a/backend/tests/fake/github.go b/backend/tests/fake/github.go
index d3a4eb9d44..51291d817b 100644
--- a/backend/tests/fake/github.go
+++ b/backend/tests/fake/github.go
@@ -34,8 +34,6 @@ type GitHub struct {
repositories map[string]*githubRepositoryData
}
-const publicKeyName = "public-key"
-
type githubRepositoryData struct {
webhooks []*github.WebhookCreateOrUpdate
// files is a map that the full file path is the key and the file content is the
@@ -44,9 +42,6 @@ type githubRepositoryData struct {
// refs is the map for repository branch.
// the map key is the branch ref, like "refs/heads/main".
refs map[string]*github.Branch
- // secrets is the map for repository secret.
- // the map key is the secret name, like "public-key".
- secrets map[string]*github.RepositorySecret
// pullRequests is the map for repository pull request.
// the map key is the pull request id.
pullRequests map[int]struct {
@@ -78,11 +73,6 @@ func NewGitHub(port int) VCSProvider {
g.GET("/repos/:owner/:repo/git/ref/heads/:branchName", gh.getRepositoryBranch)
g.POST("/repos/:owner/:repo/git/refs", gh.createRepositoryBranch)
g.POST("/repos/:owner/:repo/pulls", gh.createRepositoryPullRequest)
- g.GET(
- fmt.Sprintf("/repos/:owner/:repo/actions/secrets/%s", publicKeyName),
- gh.getRepositoryPublicKey,
- )
- g.PUT("/repos/:owner/:repo/actions/secrets/:keyName", gh.updateRepositoryPublicKey)
g.GET("/repos/:owner/:repo/pulls/:prID/files", gh.listPullRequestFile)
g.GET("/repos/:owner/:repo/compare/:baseHead", gh.compareCommits)
return gh
@@ -314,51 +304,6 @@ func (gh *GitHub) createRepositoryPullRequest(c echo.Context) error {
return c.String(http.StatusOK, string(buf))
}
-func (gh *GitHub) getRepositoryPublicKey(c echo.Context) error {
- r, err := gh.validRepository(c)
- if err != nil {
- return err
- }
-
- buf, err := json.Marshal(
- r.secrets[publicKeyName],
- )
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository public key: %v", err))
- }
- return c.String(http.StatusOK, string(buf))
-}
-
-func (gh *GitHub) updateRepositoryPublicKey(c echo.Context) error {
- r, err := gh.validRepository(c)
- if err != nil {
- return err
- }
-
- body, err := io.ReadAll(c.Request().Body)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for updating repository secret: %v", err))
- }
-
- var secretUpdate github.RepositorySecretUpdate
- if err = json.Unmarshal(body, &secretUpdate); err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for updating repository secret: %v", err))
- }
-
- // The KeyID in RepositorySecretUpdate should be the repository public id.
- if secretUpdate.KeyID != r.secrets[publicKeyName].KeyID {
- return c.String(http.StatusBadRequest, fmt.Sprintf("The key id not matched: %v", secretUpdate.KeyID))
- }
-
- keyName := c.Param("keyName")
- r.secrets[keyName] = &github.RepositorySecret{
- KeyID: fmt.Sprintf("%s_%d", keyName, time.Now().Unix()),
- Key: secretUpdate.EncryptedValue,
- }
-
- return c.String(http.StatusOK, "")
-}
-
func (gh *GitHub) listPullRequestFile(c echo.Context) error {
r, err := gh.validRepository(c)
if err != nil {
@@ -446,14 +391,7 @@ func (*GitHub) APIURL(instanceURL string) string {
func (gh *GitHub) CreateRepository(id string) {
gh.repositories[id] = &githubRepositoryData{
files: make(map[string]string),
- secrets: map[string]*github.RepositorySecret{
- publicKeyName: {
- KeyID: fmt.Sprintf("publickeyid_%d", time.Now().Unix()),
- // mock public key
- Key: "YJf3Ojcv8TSEBCtR0wtTR/F2bD3nBl1lxiwkfV/TYQk=",
- },
- },
- refs: map[string]*github.Branch{},
+ refs: map[string]*github.Branch{},
pullRequests: map[int]struct {
Files []*github.PullRequestFile
*github.PullRequest
diff --git a/backend/tests/fake/gitlab.go b/backend/tests/fake/gitlab.go
index 8106f6c664..6dc6d431a5 100644
--- a/backend/tests/fake/gitlab.go
+++ b/backend/tests/fake/gitlab.go
@@ -39,9 +39,6 @@ type projectData struct {
// branches is the map for project branch.
// the map key is the project name, like "refs/heads/main".
branches map[string]*gitlab.Branch
- // variables is the map for project environment variable.
- // the map key is the variable name, like "public-key".
- variables map[string]*gitlab.EnvironmentVariable
// mergeRequests is the map for project merge request.
// the map key is the merge request id.
mergeRequests map[int]struct {
@@ -75,9 +72,6 @@ func NewGitLab(port int) VCSProvider {
projectGroup.GET("/projects/:id/repository/branches/:branchName", gl.getProjectBranch)
projectGroup.POST("/projects/:id/repository/branches", gl.createProjectBranch)
projectGroup.POST("/projects/:id/merge_requests", gl.createProjectPullRequest)
- projectGroup.GET("/projects/:id/variables/:variableKey", gl.getProjectEnvironmentVariable)
- projectGroup.POST("/projects/:id/variables", gl.createProjectEnvironmentVariable)
- projectGroup.PUT("/projects/:id/variables/:variableKey", gl.updateProjectEnvironmentVariable)
projectGroup.GET("/projects/:id/merge_requests/:mrID/changes", gl.getMergeRequestChanges)
projectGroup.GET("/projects/:id/repository/compare", gl.compareCommits)
@@ -107,9 +101,8 @@ func (*GitLab) APIURL(instanceURL string) string {
// CreateRepository creates a GitLab project with given ID.
func (gl *GitLab) CreateRepository(id string) {
gl.projects[id] = &projectData{
- files: map[string]string{},
- branches: map[string]*gitlab.Branch{},
- variables: map[string]*gitlab.EnvironmentVariable{},
+ files: map[string]string{},
+ branches: map[string]*gitlab.Branch{},
mergeRequests: map[int]struct {
*gitlab.MergeRequestChange
*gitlab.MergeRequest
@@ -370,77 +363,6 @@ func (gl *GitLab) createProjectPullRequest(c echo.Context) error {
return c.String(http.StatusOK, string(buf))
}
-func (gl *GitLab) getProjectEnvironmentVariable(c echo.Context) error {
- pd, err := gl.validProject(c)
- if err != nil {
- return err
- }
-
- variableKey := c.Param("variableKey")
- variable, ok := pd.variables[variableKey]
- if !ok {
- return c.String(http.StatusNotFound, fmt.Sprintf("failed to find variable %s", variableKey))
- }
-
- buf, err := json.Marshal(variable)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting project environment variable: %v", err))
- }
- return c.String(http.StatusOK, string(buf))
-}
-
-func (gl *GitLab) createProjectEnvironmentVariable(c echo.Context) error {
- pd, err := gl.validProject(c)
- if err != nil {
- return err
- }
-
- body, err := io.ReadAll(c.Request().Body)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating project environment variable: %v", err))
- }
-
- var environmentVariable gitlab.EnvironmentVariable
- if err = json.Unmarshal(body, &environmentVariable); err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating project environment variable: %v", err))
- }
-
- if _, ok := pd.variables[environmentVariable.Key]; ok {
- return c.String(http.StatusBadRequest, fmt.Sprintf("environment variable already exists %s", environmentVariable.Key))
- }
-
- pd.variables[environmentVariable.Key] = &environmentVariable
- return c.String(http.StatusOK, "")
-}
-
-func (gl *GitLab) updateProjectEnvironmentVariable(c echo.Context) error {
- pd, err := gl.validProject(c)
- if err != nil {
- return err
- }
-
- body, err := io.ReadAll(c.Request().Body)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating project environment variable: %v", err))
- }
-
- var environmentVariable gitlab.EnvironmentVariable
- if err = json.Unmarshal(body, &environmentVariable); err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating project environment variable: %v", err))
- }
-
- variableKey := c.Param("variableKey")
- if _, ok := pd.variables[variableKey]; !ok {
- return c.String(http.StatusBadRequest, fmt.Sprintf("failed to find environment variable %s", variableKey))
- }
- if variableKey != environmentVariable.Key {
- return c.String(http.StatusBadRequest, fmt.Sprintf("invalid environment variable %s", environmentVariable.Key))
- }
-
- pd.variables[environmentVariable.Key] = &environmentVariable
- return c.String(http.StatusOK, "")
-}
-
func (gl *GitLab) getMergeRequestChanges(c echo.Context) error {
pd, err := gl.validProject(c)
if err != nil {