Skip to content

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

feat(github): implement `FetchRepositoryFileList` (#1865)

Joe Chencfd961b08185
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index e72e30e1d0..4b7b53a6b8 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -84,6 +84,18 @@ type Repository struct {
HTMLURL string `json:"html_url"`
}
+// 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"`
+}
+
// fetchUserInfo fetches user information from the given resourceURI, which
// should be either "user" or "users/{username}".
func (p *Provider) fetchUserInfo(ctx context.Context, oauthCtx common.OauthContext, resourceURI string) (*vcs.UserInfo, error) {
@@ -440,9 +452,68 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx co
return repos, len(repos) >= 100, nil
}
-// FetchRepositoryFileList fetch the files from repository tree
-func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {
- return nil, errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// 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, _, repositoryID, ref, filePath string) ([]*vcs.RepositoryTreeNode, error) {
+ url := fmt.Sprintf("%s/repos/%s/git/trees/%s?recursive=true", apiURL, repositoryID, ref)
+ code, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch repository file list from URL %s", url))
+ } else if code >= 300 {
+ return nil,
+ fmt.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
}
// CreateFile creates a file.
diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.go
index 372430e962..130b494721 100644
--- a/plugin/vcs/github/github_test.go
+++ b/plugin/vcs/github/github_test.go
@@ -592,6 +592,102 @@ func TestProvider_FetchAllRepositoryList(t *testing.T) {
assert.Equal(t, want, got)
}
+func TestProvider_FetchRepositoryFileList(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: 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{}, "", "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{}, "", "octocat/Hello-World", "main", "subdir")
+ require.NoError(t, err)
+
+ // Non-blob type should excluded
+ want := []*vcs.RepositoryTreeNode{
+ {
+ Path: "subdir/exec_file",
+ Type: "blob",
+ },
+ }
+ assert.Equal(t, want, got)
+ })
+}
+
func TestOAuth_RefreshToken(t *testing.T) {
ctx := context.Background()
client := &http.Client{
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index a612b7b6b7..4e6ddd5dab 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -117,7 +117,8 @@ type FileCommit struct {
LastCommitID string `json:"last_commit_id,omitempty"`
}
-// RepositoryTreeNode is the API message for git tree node.
+// RepositoryTreeNode represents a GitLab API response for a repository tree
+// node.
type RepositoryTreeNode struct {
Path string `json:"path"`
Type string `json:"type"`
@@ -568,9 +569,45 @@ func (p *Provider) fetchPaginatedRepositoryActiveMemberList(ctx context.Context,
return members, len(members) >= 100, nil
}
-// FetchRepositoryFileList fetch the files from repository tree
+// 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) {
- url := fmt.Sprintf("%s/projects/%s/repository/tree?recursive=true&ref=%s&path=%s", p.APIURL(instanceURL), repositoryID, ref, filePath)
+ 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,
@@ -587,32 +624,29 @@ func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.
),
)
if err != nil {
- return nil, fmt.Errorf("failed to fetch repository tree on GitLab instance %s, err: %w", instanceURL, err)
- }
- if code >= 300 {
- return nil, fmt.Errorf("failed to fetch repository tree on GitLab instance %s, status code: %d",
- instanceURL,
- code,
- )
+ return nil, false, errors.Wrapf(err, "GET %s", url)
}
- var nodeList []*RepositoryTreeNode
- if err := json.Unmarshal([]byte(body), &nodeList); err != nil {
- return nil, fmt.Errorf("failed to unmarshal repository tree from GitLab instance %s, err: %w", instanceURL, err)
+ if code == http.StatusNotFound {
+ return nil, false, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch repository file list from URL %s", url))
+ } else if code >= 300 {
+ return nil, false,
+ fmt.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
}
- // Filter out folder nodes, we only need the file nodes.
- var fileList []*vcs.RepositoryTreeNode
- for _, node := range nodeList {
- if node.Type == "blob" {
- fileList = append(fileList, &vcs.RepositoryTreeNode{
- Path: node.Path,
- Type: node.Type,
- })
- }
+ if err := json.Unmarshal([]byte(body), &treeNodes); err != nil {
+ return nil, false, errors.Wrap(err, "unmarshal body")
}
- return fileList, nil
+ // 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) >= 100, nil
}
// CreateFile creates a file.
diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.go
index 921542a433..402727cd16 100644
--- a/plugin/vcs/gitlab/gitlab_test.go
+++ b/plugin/vcs/gitlab/gitlab_test.go
@@ -250,6 +250,7 @@ func TestProvider_FetchRepositoryActiveMemberList(t *testing.T) {
got, err := p.FetchRepositoryActiveMemberList(ctx, common.OauthContext{}, "", "1")
require.NoError(t, err)
+ // Non-active member should be excluded
want := []*vcs.RepositoryMember{
{
@@ -422,7 +423,6 @@ func TestProvider_FetchAllRepositoryList(t *testing.T) {
got, err := p.FetchAllRepositoryList(ctx, common.OauthContext{}, "")
require.NoError(t, err)
- // Non-active member should be excluded
want := []*vcs.Repository{
{
ID: 4,
@@ -434,6 +434,55 @@ func TestProvider_FetchAllRepositoryList(t *testing.T) {
assert.Equal(t, want, got)
}
+func TestProvider_FetchRepositoryFileList(t *testing.T) {
+ p := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: 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 TestOAuth_RefreshToken(t *testing.T) {
ctx := context.Background()
client := &http.Client{