Skip to content

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

chore: vcs cleanup (#11414)

Danny Xu9db83b94b53b
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index a93d427b4a..1ef71542af 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -9,7 +9,6 @@ import (
"log/slog"
"net/http"
"net/url"
- "path/filepath"
"sort"
"strings"
"time"
@@ -347,152 +346,6 @@ func (p *Provider) listOrganizationsForMember(ctx context.Context, oauthCtx *com
return result, nil
}
-// FetchRepositoryFileList fetches the all files from the given repository tree recursively.
-//
-// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/trees/get?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx *common.OauthContext, _ string, repositoryID string, ref string, filePath string) ([]*vcs.RepositoryTreeNode, error) {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return nil, err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- values.Set("recursive", "true")
- url := fmt.Sprintf("%s/trees/%s?%s", apiURL, url.PathEscape(ref), 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.StatusOK {
- return nil, errors.Errorf("non-200 GET %s status code %d with body %q", url, code, string(body))
- }
-
- type getTreesResponseTreeEntries struct {
- RelativePath string `json:"relativePath"`
- GitObjectType string `json:"gitObjectType"`
- }
- type getTreesResponse struct {
- TreeEntries []getTreesResponseTreeEntries `json:"treeEntries"`
- }
-
- r := new(getTreesResponse)
- if err := json.Unmarshal([]byte(body), r); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal get trees response body, code %v", code)
- }
-
- result := make([]*vcs.RepositoryTreeNode, 0, len(r.TreeEntries))
- for _, e := range r.TreeEntries {
- if e.GitObjectType != "blob" || !strings.HasPrefix(e.RelativePath, filePath) {
- continue
- }
- result = append(result, &vcs.RepositoryTreeNode{
- Path: e.RelativePath,
- Type: e.GitObjectType,
- })
- }
- return result, nil
-}
-
-// ReadFileMeta reads the metadata of the given file in the repository.
-//
-// Docs:
-// - https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-7.0&tabs=HTTP
-// - https://learn.microsoft.com/en-us/rest/api/azure/devops/git/blobs/get-blob?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx *common.OauthContext, _, repositoryID, filePath string, refInfo vcs.RefInfo) (*vcs.FileMeta, error) {
- apiURL, err := getRepositoryAPIURL(repositoryID)
- if err != nil {
- return nil, err
- }
-
- values := &url.Values{}
- values.Set("api-version", "7.0")
- values.Set("scopePath", filePath)
- values.Set("$format", "json")
- var refType string
- switch refInfo.RefType {
- case vcs.RefTypeBranch:
- refType = "branch"
- case vcs.RefTypeTag:
- refType = "tag"
- case vcs.RefTypeCommit:
- refType = "commit"
- default:
- return nil, errors.Errorf("invalid ref type %q", refInfo.RefType)
- }
- values.Set("versionDescriptor.versionType", refType)
- values.Set("versionDescriptor.version", refInfo.RefName)
-
- itemsURL := fmt.Sprintf("%s/items?%s", apiURL, values.Encode())
-
- type fileMetaResponseValue struct {
- ObjectID string `json:"objectId"`
- CommitID string `json:"commitId"`
- Path string `json:"path"`
- URL string `json:"url"`
- }
- type fileMetaResponse struct {
- Value []fileMetaResponseValue `json:"value"`
- }
-
- code, _, body, err := oauth.Get(ctx, p.client, itemsURL, oauthCtx.AccessToken)
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", itemsURL)
- }
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to read file meta from URL %s", itemsURL)
- }
- if code != http.StatusOK {
- return nil, errors.Errorf("non-200 GET %s status code %d with body %q", itemsURL, code, string(body))
- }
-
- r := new(fileMetaResponse)
- if err := json.Unmarshal([]byte(body), r); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal get file meta response body, code %v", code)
- }
-
- // Validate Presumption: The response should only contain one file meta.
- if len(r.Value) != 1 {
- return nil, errors.Wrapf(err, fmt.Sprintf("expect to get one file meta, but got %d, response: %+v", len(r.Value), r))
- }
-
- values = &url.Values{}
- values.Set("api-version", "7.0")
- values.Set("$format", "json")
- blobURL := fmt.Sprintf("%s/blobs/%s?%s", apiURL, url.PathEscape(r.Value[0].ObjectID), values.Encode())
-
- type blobsResponse struct {
- Size int64 `json:"size"`
- }
-
- code, _, body, err = oauth.Get(ctx, p.client, blobURL, oauthCtx.AccessToken)
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", blobURL)
- }
-
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to read file size from URL %s", blobURL)
- }
- if code != http.StatusOK {
- return nil, errors.Errorf("non-200 GET %s status code %d with body %q", blobURL, code, string(body))
- }
-
- b := new(blobsResponse)
- if err := json.Unmarshal([]byte(body), b); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal get file meta response body, code %v", code)
- }
-
- return &vcs.FileMeta{
- Name: filepath.Base(r.Value[0].Path),
- Path: r.Value[0].Path,
- Size: b.Size,
- LastCommitID: r.Value[0].CommitID,
- SHA: r.Value[0].ObjectID,
- }, nil
-}
-
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-7.0&tabs=HTTP
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index c83f8766f4..8ad3f5fcdb 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -8,7 +8,6 @@ import (
"fmt"
"net/http"
"net/url"
- "path"
"strconv"
"strings"
"time"
@@ -214,128 +213,6 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
return repos, resp.Next, nil
}
-// TreeEntry represents a Bitbucket Cloud API response for a repository tree
-// entry.
-type TreeEntry struct {
- Type string `json:"type"`
- Path string `json:"path"`
- Size int64 `json:"size"`
- Commit Commit `json:"commit"`
-}
-
-// FetchRepositoryFileList fetches the all files from the given repository tree
-// recursively.
-//
-// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#directory-listings
-func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {
- var bbcTreeEntries []*TreeEntry
- params := url.Values{}
- // NOTE: There is no way to ask the Bitbucket Cloud API to return all
- // subdirectories recursively, 10 levels down is just a good guess.
- params.Add("max_depth", "10")
- params.Add("q", `type="commit_file"`)
- params.Add("pagelen", strconv.Itoa(apiPageSize))
- next := fmt.Sprintf("%s/repositories/%s/src/%s/%s?%s", p.APIURL(instanceURL), repositoryID, url.PathEscape(ref), url.PathEscape(filePath), params.Encode())
- for next != "" {
- var err error
- var treeEntries []*TreeEntry
- treeEntries, next, err = p.fetchPaginatedRepositoryFileList(ctx, oauthCtx, next)
- if err != nil {
- return nil, errors.Wrap(err, "fetch paginated list")
- }
- bbcTreeEntries = append(bbcTreeEntries, treeEntries...)
- }
-
- var treeNodes []*vcs.RepositoryTreeNode
- for _, n := range bbcTreeEntries {
- treeNodes = append(treeNodes,
- &vcs.RepositoryTreeNode{
- Path: n.Path,
- Type: n.Type,
- },
- )
- }
- return treeNodes, nil
-}
-
-// fetchPaginatedRepositoryFileList fetches files under a repository tree
-// recursively in given page. It returns the paginated results along with a
-// string indicating URL of the next page (if exists).
-func (p *Provider) fetchPaginatedRepositoryFileList(ctx context.Context, oauthCtx *common.OauthContext, url string) (_ []*TreeEntry, next string, err error) {
- 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 fetch repository file list from URL %s", url)
- } else if code >= 300 {
- return nil, "",
- errors.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- var resp struct {
- Values []*TreeEntry `json:"values"`
- Next string `json:"next"`
- }
- if err := json.Unmarshal([]byte(body), &resp); err != nil {
- return nil, "", errors.Wrap(err, "unmarshal body")
- }
- return resp.Values, resp.Next, nil
-}
-
-// 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
-func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (*vcs.FileMeta, error) {
- url := fmt.Sprintf("%s/repositories/%s/src/%s/%s?format=meta", p.APIURL(instanceURL), repositoryID, url.PathEscape(refInfo.RefName), url.PathEscape(filePath))
- 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 read file from URL %s", url)
- } else if code >= 300 {
- return nil,
- errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- var treeEntry TreeEntry
- if err = json.Unmarshal([]byte(body), &treeEntry); err != nil {
- return nil, errors.Wrap(err, "unmarshal body")
- }
-
- if treeEntry.Type != "commit_file" {
- return nil, errors.Errorf("%q is not a file", filePath)
- }
-
- return &vcs.FileMeta{
- Name: path.Base(treeEntry.Path),
- Path: treeEntry.Path,
- Size: treeEntry.Size,
- LastCommitID: treeEntry.Commit.Hash,
- }, nil
-}
-
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#raw-file-contents
diff --git a/backend/plugin/vcs/bitbucket/bitbucket_test.go b/backend/plugin/vcs/bitbucket/bitbucket_test.go
index f7ae8414a4..ecd062acc5 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket_test.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket_test.go
@@ -64,143 +64,6 @@ func TestProvider_FetchAllRepositoryList(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_FetchRepositoryFileList(t *testing.T) {
- // Example response derived from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#directory-listings
- const response = `
-{
- "pagelen": 10,
- "values": [
- {
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py"
- },
- "meta": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py?format=meta"
- }
- },
- "path": "tests/__init__.py",
- "commit": {
- "type": "commit",
- "hash": "eefd5ef5d3df01aed629f650959d6706d54cd335",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/commit/eefd5ef5d3df01aed629f650959d6706d54cd335"
- },
- "html": {
- "href": "https://bitbucket.org/atlassian/bbql/commits/eefd5ef5d3df01aed629f650959d6706d54cd335"
- }
- }
- },
- "attributes": [],
- "type": "commit_file",
- "size": 0
- }
- ],
- "page": 1,
- "size": 1
-}
-`
- t.Run("no path prefix", func(t *testing.T) {
- ctx := context.Background()
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader(response)),
- }, nil
- })
-
- got, err := p.FetchRepositoryFileList(ctx, &common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "eefd5ef", "")
- require.NoError(t, err)
-
- want := []*vcs.RepositoryTreeNode{
- {
- Path: "tests/__init__.py",
- Type: "commit_file",
- },
- }
- assert.Equal(t, want, got)
- })
-
- t.Run("has path prefix", func(t *testing.T) {
- ctx := context.Background()
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/tests", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: io.NopCloser(strings.NewReader(response)),
- }, nil
- })
-
- got, err := p.FetchRepositoryFileList(ctx, &common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "eefd5ef", "tests")
- require.NoError(t, err)
-
- // Non-blob type should be excluded
- want := []*vcs.RepositoryTreeNode{
- {
- Path: "tests/__init__.py",
- Type: "commit_file",
- },
- }
- assert.Equal(t, want, got)
- })
-}
-
-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)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response derived from https://developer.atlassian.com/cloud/bitbucket/rest/api-group-source/#file-meta-data
- Body: io.NopCloser(strings.NewReader(`
-{
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py"
- },
- "meta": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/src/eefd5ef5d3df01aed629f650959d6706d54cd335/tests/__init__.py?format=meta"
- }
- },
- "path": "tests/__init__.py",
- "commit": {
- "type": "commit",
- "hash": "eefd5ef5d3df01aed629f650959d6706d54cd335",
- "links": {
- "self": {
- "href": "https://api.bitbucket.org/2.0/repositories/atlassian/bbql/commit/eefd5ef5d3df01aed629f650959d6706d54cd335"
- },
- "html": {
- "href": "https://bitbucket.org/atlassian/bbql/commits/eefd5ef5d3df01aed629f650959d6706d54cd335"
- }
- }
- },
- "attributes": [],
- "type": "commit_file",
- "size": 100
-}
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.ReadFileMeta(ctx, &common.OauthContext{}, bitbucketCloudURL, "atlassian/bbql", "tests/__init__.py", vcs.RefInfo{
- RefType: vcs.RefTypeCommit,
- RefName: "eefd5ef",
- })
- require.NoError(t, err)
-
- want := &vcs.FileMeta{
- Name: "__init__.py",
- Path: "tests/__init__.py",
- Size: 100,
- LastCommitID: "eefd5ef5d3df01aed629f650959d6706d54cd335",
- }
- assert.Equal(t, want, got)
-}
-
func TestProvider_ReadFileContent(t *testing.T) {
p := newMockProvider(func(r *http.Request) (*http.Response, error) {
assert.Equal(t, "/2.0/repositories/atlassian/bbql/src/eefd5ef/tests/__init__.py", r.URL.Path)
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index 4967476558..ad32939cdc 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -10,7 +10,6 @@ import (
"net/http"
"net/url"
"strconv"
- "strings"
"time"
"github.com/pkg/errors"
@@ -59,12 +58,6 @@ func (*Provider) APIURL(instanceURL string) string {
return fmt.Sprintf("%s/api/v3", instanceURL)
}
-// User represents a GitHub API response for a user.
-type User struct {
- Name string `json:"name"`
- Email string `json:"email"`
-}
-
// Repository represents a GitHub API response for a repository.
type Repository struct {
ID int64 `json:"id"`
@@ -76,50 +69,6 @@ type Repository struct {
} `json:"permissions"`
}
-// RepositoryTree represents a GitHub API response for a repository tree.
-type RepositoryTree struct {
- Tree []RepositoryTreeNode `json:"tree"`
-}
-
-// RepositoryTreeNode represents a GitHub API response for a repository tree
-// node.
-type RepositoryTreeNode struct {
- Path string `json:"path"`
- Type string `json:"type"`
-}
-
-// Reference represents a GitHub API response for a reference.
-type Reference struct {
- Ref string `json:"ref"`
- NodeID string `json:"node_id"`
- URL string `json:"url"`
- Object struct {
- Type string `json:"type"`
- SHA string `json:"sha"`
- URL string `json:"url"`
- } `json:"object"`
-}
-
-// File represents a GitHub API response for a repository file.
-type File struct {
- Encoding string `json:"encoding"`
- Size int64 `json:"size"`
- Name string `json:"name"`
- Path string `json:"path"`
- Content string `json:"content"`
- SHA string `json:"sha"`
-}
-
-// WebhookType is the GitHub webhook type.
-type WebhookType string
-
-const (
- // WebhookPush is the webhook type for push.
- WebhookPush WebhookType = "push"
- // WebhookPing is the webhook type for ping.
- WebhookPing WebhookType = "ping"
-)
-
// WebhookInfo represents a GitHub API response for the webhook information.
type WebhookInfo struct {
ID int `json:"id"`
@@ -164,39 +113,6 @@ type WebhookRepository struct {
HTMLURL string `json:"html_url"`
}
-// WebhookCommitAuthor is the API message for webhook commit author.
-type WebhookCommitAuthor struct {
- Name string `json:"name"`
- Email string `json:"email"`
-}
-
-// WebhookSender is the API message for webhook sender.
-type WebhookSender struct {
- Login string `json:"login"`
-}
-
-// WebhookCommit is the API message for webhook commit.
-type WebhookCommit struct {
- ID string `json:"id"`
- Distinct bool `json:"distinct"`
- Message string `json:"message"`
- Timestamp time.Time `json:"timestamp"`
- URL string `json:"url"`
- Author WebhookCommitAuthor `json:"author"`
- Added []string `json:"added"`
- Modified []string `json:"modified"`
-}
-
-// WebhookPushEvent is the API message for webhook push event.
-type WebhookPushEvent struct {
- Ref string `json:"ref"`
- Before string `json:"before"`
- After string `json:"after"`
- Repository WebhookRepository `json:"repository"`
- Sender WebhookSender `json:"sender"`
- Commits []WebhookCommit `json:"commits"`
-}
-
// CommitAuthor represents a GitHub API response for a commit author.
type CommitAuthor struct {
// Date expects corresponding JSON value is a string in RFC 3339 format,
@@ -304,149 +220,6 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
return repos, len(repos) >= apiPageSize, nil
}
-// FetchRepositoryFileList fetches the all files from the given repository tree
-// recursively.
-//
-// Docs: https://docs.github.com/en/rest/git/trees#get-a-tree
-//
-// TODO: GitHub returns truncated response if the number of items in the tree
-// array exceeded their maximum limit. It is not noted what exactly is the
-// maximum limit and requires making non-recursive request to each sub-tree.
-func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {
- url := fmt.Sprintf("%s/repos/%s/git/trees/%s?recursive=true", p.APIURL(instanceURL), repositoryID, ref)
- 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 fetch repository file list from URL %s", url)
- } else if code >= 300 {
- return nil,
- errors.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- var repoTree RepositoryTree
- if err := json.Unmarshal([]byte(body), &repoTree); err != nil {
- return nil, errors.Wrap(err, "unmarshal body")
- }
-
- if filePath != "" && !strings.HasSuffix(filePath, "/") {
- filePath += "/"
- }
-
- var allTreeNodes []*vcs.RepositoryTreeNode
- for _, n := range repoTree.Tree {
- // GitHub does not support filtering by path prefix, thus simulating the
- // behavior here.
- if n.Type == "blob" && strings.HasPrefix(n.Path, filePath) {
- allTreeNodes = append(allTreeNodes,
- &vcs.RepositoryTreeNode{
- Path: n.Path,
- Type: n.Type,
- },
- )
- }
- }
- return allTreeNodes, nil
-}
-
-// ReadFileMeta reads the metadata of the given file in the repository.
-//
-// Docs: https://docs.github.com/en/rest/repos/contents#get-repository-content
-func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (*vcs.FileMeta, error) {
- lastCommitID, err := p.getLastCommitID(ctx, oauthCtx, instanceURL, repositoryID, refInfo.RefName)
- if err != nil {
- return nil, errors.Wrap(err, "get last commit ID")
- }
-
- url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), lastCommitID)
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return nil, errors.Wrapf(err, "GET %s", url)
- }
-
- // TODO(zp): should check non-200 return value?
- if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, "failed to read file meta from URL %s", url)
- } else if code >= 300 {
- return nil,
- errors.Errorf("failed to read file meta from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- // This API endpoint returns a JSON array if the path is a directory, and we do
- // not want that.
- if body != "" && body[0] == '[' {
- return nil, errors.Errorf("%q is a directory not a file", filePath)
- }
-
- var file File
- if err = json.Unmarshal([]byte(body), &file); err != nil {
- return nil, errors.Wrap(err, "unmarshal body")
- }
-
- return &vcs.FileMeta{
- Name: file.Name,
- Path: file.Path,
- Size: file.Size,
- SHA: file.SHA,
- LastCommitID: lastCommitID,
- }, nil
-}
-
-// getLastCommitID gets the last commit ID of given reference in the repository.
-//
-// Docs: https://docs.github.com/en/rest/git/refs?apiVersion=2022-11-28#get-a-reference
-func (p *Provider) getLastCommitID(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, ref string) (string, error) {
- url := fmt.Sprintf("%s/repos/%s/git/ref/heads/%s", p.APIURL(instanceURL), repositoryID, ref)
-
- code, _, body, err := oauth.Get(
- ctx,
- p.client,
- url,
- oauthCtx.AccessToken,
- )
- if err != nil {
- return "", errors.Wrapf(err, "GET %s", url)
- }
-
- if code == http.StatusNotFound {
- return "", common.Errorf(common.NotFound, "failed to get last commit ID from URL %s", url)
- } else if code >= 300 {
- return "",
- errors.Errorf("failed to get last commit ID from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- var reference Reference
- if err = json.Unmarshal([]byte(body), &reference); err != nil {
- return "", errors.Wrap(err, "unmarshal body")
- }
-
- return reference.Object.SHA, nil
-}
-
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://docs.github.com/en/rest/repos/contents#get-repository-content
diff --git a/backend/plugin/vcs/github/github_test.go b/backend/plugin/vcs/github/github_test.go
index f4d696f51f..a52329e3d3 100644
--- a/backend/plugin/vcs/github/github_test.go
+++ b/backend/plugin/vcs/github/github_test.go
@@ -178,164 +178,6 @@ func TestProvider_FetchAllRepositoryList(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_FetchRepositoryFileList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/repos/octocat/Hello-World/git/trees/main", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.github.com/en/rest/git/trees#get-a-tree
- Body: io.NopCloser(strings.NewReader(`
-{
- "sha": "9fb037999f264ba9a7fc6274d15fa3ae2ab98312",
- "url": "https://api.github.com/repos/octocat/Hello-World/trees/9fb037999f264ba9a7fc6274d15fa3ae2ab98312",
- "tree": [
- {
- "path": "file.rb",
- "mode": "100644",
- "type": "blob",
- "size": 30,
- "sha": "44b4fc6d56897b048c772eb4087f854f46256132",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/44b4fc6d56897b048c772eb4087f854f46256132"
- },
- {
- "path": "subdir",
- "mode": "040000",
- "type": "tree",
- "sha": "f484d249c660418515fb01c2b9662073663c242e",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/f484d249c660418515fb01c2b9662073663c242e"
- },
- {
- "path": "subdir/exec_file",
- "mode": "100755",
- "type": "blob",
- "size": 75,
- "sha": "45b983be36b73c0788dc9cbcb76cbb80fc7bb057",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/45b983be36b73c0788dc9cbcb76cbb80fc7bb057"
- },
- {
- "path": "anotherdir/.gitignore",
- "mode": "100755",
- "type": "blob",
- "size": 75,
- "sha": "5ff01e0bbbd12a36679ddf2ddd186bac8ad5c6b4",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/5ff01e0bbbd12a36679ddf2ddd186bac8ad5c6b4"
- }
- ],
- "truncated": false
-}
-`)),
- }, nil
- },
- )
-
- t.Run("no path prefix", func(t *testing.T) {
- ctx := context.Background()
- got, err := p.FetchRepositoryFileList(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "main", "")
- require.NoError(t, err)
-
- // Non-blob type should excluded
- want := []*vcs.RepositoryTreeNode{
- {
- Path: "file.rb",
- Type: "blob",
- },
- {
- Path: "subdir/exec_file",
- Type: "blob",
- },
- {
- Path: "anotherdir/.gitignore",
- Type: "blob",
- },
- }
- assert.Equal(t, want, got)
- })
-
- t.Run("has path prefix", func(t *testing.T) {
- ctx := context.Background()
- got, err := p.FetchRepositoryFileList(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "main", "subdir")
- require.NoError(t, err)
-
- // Non-blob type should be excluded
- want := []*vcs.RepositoryTreeNode{
- {
- Path: "subdir/exec_file",
- Type: "blob",
- },
- }
- assert.Equal(t, want, got)
- })
-}
-
-func TestProvider_ReadFileMeta(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- switch r.URL.Path {
- case "/repos/octocat/Hello-World/contents/README.md":
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response derived from https://docs.github.com/en/rest/repos/contents#get-repository-content
- Body: io.NopCloser(strings.NewReader(`
-{
- "type": "file",
- "encoding": "base64",
- "size": 442,
- "name": "README.md",
- "path": "README.md",
- "content": "IyBTYW1wbGUgR2l0TGFiIFByb2plY3QKClRoaXMgc2FtcGxlIHByb2plY3Qgc2hvd3MgaG93IGEgcHJvamVjdCBpbiBHaXRMYWIgbG9va3MgZm9yIGRlbW9uc3RyYXRpb24gcHVycG9zZXMuIEl0IGNvbnRhaW5zIGlzc3VlcywgbWVyZ2UgcmVxdWVzdHMgYW5kIE1hcmtkb3duIGZpbGVzIGluIG1hbnkgYnJhbmNoZXMsCm5hbWVkIGFuZCBmaWxsZWQgd2l0aCBsb3JlbSBpcHN1bS4KCllvdSBjYW4gbG9vayBhcm91bmQgdG8gZ2V0IGFuIGlkZWEgaG93IHRvIHN0cnVjdHVyZSB5b3VyIHByb2plY3QgYW5kLCB3aGVuIGRvbmUsIHlvdSBjYW4gc2FmZWx5IGRlbGV0ZSB0aGlzIHByb2plY3QuCgpbTGVhcm4gbW9yZSBhYm91dCBjcmVhdGluZyBHaXRMYWIgcHJvamVjdHMuXShodHRwczovL2RvY3MuZ2l0bGFiLmNvbS9lZS9naXRsYWItYmFzaWNzL2NyZWF0ZS1wcm9qZWN0Lmh0bWwpCg==",
- "sha": "3d21ec53a331a6f037a91c368710b99387d012c1",
- "url": "https://api.github.com/repos/octocat/Hello-World/contents/README.md",
- "git_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1",
- "html_url": "https://github.com/octocat/Hello-World/blob/master/README.md",
- "download_url": "https://raw.githubusercontent.com/octocat/Hello-World/master/README.md",
- "_links": {
- "git": "https://api.github.com/repos/octocat/Hello-World/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1",
- "self": "https://api.github.com/repos/octocat/Hello-World/contents/README.md",
- "html": "https://github.com/octocat/Hello-World/blob/master/README.md"
- }
-}
-`)),
- }, nil
- case "/repos/octocat/Hello-World/git/ref/heads/master":
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response derived from https://docs.github.com/en/rest/git/refs?apiVersion=2022-11-28#get-a-reference
- Body: io.NopCloser(strings.NewReader(`
-{
- "ref": "refs/heads/master",
- "node_id": "MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlQQ==",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/refs/heads/master",
- "object": {
- "type": "commit",
- "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd",
- "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"
- }
-}
- `)),
- }, nil
- default:
- assert.Truef(t, false, "Unsupported API: %s", r.URL.Path)
- return nil, nil
- }
- },
- )
-
- ctx := context.Background()
- got, err := p.ReadFileMeta(ctx, &common.OauthContext{}, githubComURL, "octocat/Hello-World", "README.md", vcs.RefInfo{
- RefType: vcs.RefTypeBranch,
- RefName: "master",
- })
- require.NoError(t, err)
-
- want := &vcs.FileMeta{
- Name: "README.md",
- Path: "README.md",
- Size: 442,
- SHA: "3d21ec53a331a6f037a91c368710b99387d012c1",
- LastCommitID: "aa218f56b14c9653891f9e74264a383fa43fefbd",
- }
- assert.Equal(t, want, got)
-}
-
func TestProvider_ReadFileContent(t *testing.T) {
const want = `# Sample GitLab Project
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index ad4e5983c9..8d57feecb7 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -237,91 +237,6 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx *c
return repos, len(repos) >= apiPageSize, nil
}
-// FetchRepositoryFileList fetches the all files from the given repository tree
-// recursively.
-//
-// Docs: https://docs.gitlab.com/ee/api/repositories.html#list-repository-tree
-func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {
- var gitlabTreeNodes []RepositoryTreeNode
- page := 1
- for {
- treeNodes, hasNextPage, err := p.fetchPaginatedRepositoryFileList(ctx, oauthCtx, instanceURL, repositoryID, ref, filePath, page)
- if err != nil {
- return nil, errors.Wrap(err, "fetch paginated list")
- }
- gitlabTreeNodes = append(gitlabTreeNodes, treeNodes...)
-
- if !hasNextPage {
- break
- }
- page++
- }
-
- var allTreeNodes []*vcs.RepositoryTreeNode
- for _, n := range gitlabTreeNodes {
- if n.Type == "blob" {
- allTreeNodes = append(allTreeNodes,
- &vcs.RepositoryTreeNode{
- Path: n.Path,
- Type: n.Type,
- },
- )
- }
- }
- return allTreeNodes, nil
-}
-
-// fetchPaginatedRepositoryFileList fetches files under a repository tree
-// recursively in given page. It return the paginated results along with a
-// boolean indicating whether the next page exists.
-func (p *Provider) fetchPaginatedRepositoryFileList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, ref, filePath string, page int) (treeNodes []RepositoryTreeNode, hasNextPage bool, err error) {
- url := fmt.Sprintf("%s/projects/%s/repository/tree?recursive=true&ref=%s&path=%s&page=%d&per_page=%d", p.APIURL(instanceURL), repositoryID, ref, filePath, page, apiPageSize)
- 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.StatusNotFound {
- return nil, false, common.Errorf(common.NotFound, "failed to fetch repository file list from URL %s", url)
- } else if code >= 300 {
- return nil, false,
- errors.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",
- url,
- code,
- body,
- )
- }
-
- if err := json.Unmarshal([]byte(body), &treeNodes); err != nil {
- return nil, false, errors.Wrap(err, "unmarshal body")
- }
-
- // NOTE: We deliberately choose to not use the Link header for checking the next
- // page to avoid introducing a new dependency, see
- // https://github.com/bytebase/bytebase/pull/1423#discussion_r884278534 for the
- // discussion.
- return treeNodes, len(treeNodes) >= apiPageSize, 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
-func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx *common.OauthContext, instanceURL, repositoryID, filePath string, refInfo vcs.RefInfo) (*vcs.FileMeta, error) {
- file, err := p.readFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, refInfo)
- if err != nil {
- return nil, errors.Wrap(err, "read file")
- }
-
- return &vcs.FileMeta{
- LastCommitID: file.LastCommitID,
- }, nil
-}
-
// ReadFileContent reads the content of the given file in the repository.
//
// Docs: https://docs.gitlab.com/ee/api/repository_files.html#get-file-from-repository
diff --git a/backend/plugin/vcs/gitlab/gitlab_test.go b/backend/plugin/vcs/gitlab/gitlab_test.go
index 52c7de0015..e848e023de 100644
--- a/backend/plugin/vcs/gitlab/gitlab_test.go
+++ b/backend/plugin/vcs/gitlab/gitlab_test.go
@@ -69,78 +69,6 @@ func TestProvider_FetchAllRepositoryList(t *testing.T) {
assert.Equal(t, want, got)
}
-func TestProvider_FetchRepositoryFileList(t *testing.T) {
- p := newMockProvider(func(r *http.Request) (*http.Response, error) {
- assert.Equal(t, "/api/v4/projects/1/repository/tree", r.URL.Path)
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response taken from https://docs.gitlab.com/ee/api/repositories.html#list-repository-tree
- Body: io.NopCloser(strings.NewReader(`
-[
- {
- "id": "a1e8f8d745cc87e3a9248358d9352bb7f9a0aeba",
- "name": "html",
- "type": "tree",
- "path": "files/html",
- "mode": "040000"
- },
- {
- "id": "7d70e02340bac451f281cecf0a980907974bd8be",
- "name": "whitespace",
- "type": "blob",
- "path": "files/whitespace",
- "mode": "100644"
- }
-]
-`)),
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.FetchRepositoryFileList(ctx, &common.OauthContext{}, "", "1", "main", "")
- require.NoError(t, err)
-
- // Non-blob type should excluded
- want := []*vcs.RepositoryTreeNode{
- {
- Path: "files/whitespace",
- Type: "blob",
- },
- }
- assert.Equal(t, want, got)
-}
-
-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)
- header := http.Header{}
- header.Set("x-gitlab-file-name", "key.rb")
- header.Set("x-gitlab-file-path", "app/models/key.rb")
- header.Set("x-gitlab-size", "3")
- header.Set("x-gitlab-last-commit-id", "27329d3afac51fbf2762428e12f2635d1137c549")
- return &http.Response{
- StatusCode: http.StatusOK,
- // Example response derived from https://docs.gitlab.com/ee/api/repository_files.html#get-file-from-repository
- Body: io.NopCloser(strings.NewReader(`key`)),
- Header: header,
- }, nil
- },
- )
-
- ctx := context.Background()
- got, err := p.ReadFileMeta(ctx, &common.OauthContext{}, "", "1", "app/models/key.rb", vcs.RefInfo{
- RefType: vcs.RefTypeBranch,
- RefName: "master",
- })
- require.NoError(t, err)
-
- want := &vcs.FileMeta{
- LastCommitID: "27329d3afac51fbf2762428e12f2635d1137c549",
- }
- assert.Equal(t, want, got)
-}
-
func TestProvider_ReadFileContent(t *testing.T) {
p := newMockProvider(func(r *http.Request) (*http.Response, error) {
assert.Equal(t, "/api/v4/projects/1/repository/files/app%2Fmodels%2Fkey.rb/raw", r.URL.RawPath)
diff --git a/backend/plugin/vcs/vcs.go b/backend/plugin/vcs/vcs.go
index 2d0e1d81c0..8187609a51 100644
--- a/backend/plugin/vcs/vcs.go
+++ b/backend/plugin/vcs/vcs.go
@@ -215,24 +215,6 @@ type Provider interface {
// instanceURL: VCS instance URL
FetchAllRepositoryList(ctx context.Context, oauthCtx *common.OauthContext, instanceURL string) ([]*Repository, error)
- // Fetch the repository file list
- //
- // oauthCtx: OAuth context to read the repository tree
- // 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)
- // ref: the unique name of a repository tree, could be a branch name in GitLab or a tree sha in GitHub
- // 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)
-
- // Reads the file metadata
- //
- // oauthCtx: OAuth context to fetch the file metadata
- // instanceURL: VCS instance URL
- // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
- // filePath: file path to be read
- // ref: the specific file version to be read, could be a name of branch, tag or commit
- 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
diff --git a/backend/tests/fake/bitbucket.go b/backend/tests/fake/bitbucket.go
index 37fb0f8131..c652667353 100644
--- a/backend/tests/fake/bitbucket.go
+++ b/backend/tests/fake/bitbucket.go
@@ -9,7 +9,6 @@ import (
"net/http"
"net/url"
"strconv"
- "strings"
"time"
"github.com/labstack/echo/v4"
@@ -117,23 +116,6 @@ func (bb *Bitbucket) getRepositoryContent(c echo.Context) error {
return err
}
- if strings.Contains(c.QueryString(), `type="commit_file"`) {
- var treeEntries []*bitbucket.TreeEntry
- for filePath := range r.files {
- treeEntries = append(treeEntries,
- &bitbucket.TreeEntry{
- Type: "blob",
- Path: filePath,
- },
- )
- }
- resp, err := json.Marshal(map[string]any{"values": treeEntries})
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository content: %v", err))
- }
- return c.String(http.StatusOK, string(resp))
- }
-
filePathEscaped := c.Param("filepath")
filePath, err := url.QueryUnescape(filePathEscaped)
if err != nil {
@@ -144,20 +126,6 @@ func (bb *Bitbucket) getRepositoryContent(c echo.Context) error {
if !ok {
return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", filePath))
}
-
- if strings.Contains(c.QueryString(), `format=meta`) {
- resp, err := json.Marshal(
- bitbucket.TreeEntry{
- Type: "commit_file",
- Path: filePath,
- Size: int64(len(content)),
- },
- )
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository file meta: %v", err))
- }
- return c.String(http.StatusOK, string(resp))
- }
return c.String(http.StatusOK, content)
}
diff --git a/backend/tests/fake/github.go b/backend/tests/fake/github.go
index 51291d817b..046e252d4b 100644
--- a/backend/tests/fake/github.go
+++ b/backend/tests/fake/github.go
@@ -12,7 +12,6 @@ import (
"net"
"net/http"
"net/url"
- "path"
"strconv"
"time"
@@ -67,7 +66,6 @@ func NewGitHub(port int) VCSProvider {
g := e.Group("/api/v3")
g.POST("/repos/:owner/:repo/hooks", gh.createRepositoryWebhook)
g.GET("/repos/:owner/:repo/git/commits/:commitID", gh.getRepositoryCommit)
- g.GET("/repos/:owner/:repo/git/trees/:ref", gh.getRepositoryTree)
g.GET("/repos/:owner/:repo/contents/:filePath", gh.readRepositoryFile)
g.PUT("/repos/:owner/:repo/contents/:filePath", gh.createRepositoryFile)
g.GET("/repos/:owner/:repo/git/ref/heads/:branchName", gh.getRepositoryBranch)
@@ -123,32 +121,6 @@ func (gh *GitHub) getRepositoryCommit(c echo.Context) error {
return c.String(http.StatusOK, string(buf))
}
-func (gh *GitHub) getRepositoryTree(c echo.Context) error {
- r, err := gh.validRepository(c)
- if err != nil {
- return err
- }
-
- var treeNodes []github.RepositoryTreeNode
- for filePath := range r.files {
- treeNodes = append(treeNodes,
- github.RepositoryTreeNode{
- Path: filePath,
- Type: "blob",
- },
- )
- }
- buf, err := json.Marshal(
- github.RepositoryTree{
- Tree: treeNodes,
- },
- )
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository tree: %v", err))
- }
- return c.String(http.StatusOK, string(buf))
-}
-
func (gh *GitHub) readRepositoryFile(c echo.Context) error {
r, err := gh.validRepository(c)
if err != nil {
@@ -170,20 +142,7 @@ func (gh *GitHub) readRepositoryFile(c echo.Context) error {
return c.String(http.StatusOK, content)
}
- buf, err := json.Marshal(
- github.File{
- Encoding: "base64",
- Size: int64(len(content)),
- Name: path.Base(filePath),
- Path: filePath,
- Content: base64.StdEncoding.EncodeToString([]byte(content)),
- SHA: "fake_github_commit_sha",
- },
- )
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository file: %v", err))
- }
- return c.String(http.StatusOK, string(buf))
+ return c.String(http.StatusBadRequest, "must accept vnd.github.raw")
}
func (gh *GitHub) createRepositoryFile(c echo.Context) error {