Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: use raw api to get GitLab file content (#2806)
h3n4l238d1dd9808c
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 29f98699b0..9a6fba2ea2 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -206,7 +206,7 @@ type WebhookPushEvent struct {// should be either "user" or "users/{username}".func (p *Provider) fetchUserInfoImpl(ctx context.Context, oauthCtx common.OauthContext, instanceURL, resourceURI string) (*vcs.UserInfo, error) {url := fmt.Sprintf("%s/%s", p.APIURL(instanceURL), resourceURI)- code, body, err := oauth.Get(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -272,7 +272,7 @@ type FileCommit struct {// 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(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -389,7 +389,7 @@ func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx// indicating whether the next page exists.func (p *Provider) fetchPaginatedRepositoryCollaborators(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, page int) (collaborators []RepositoryCollaborator, hasNextPage bool, err error) {url := fmt.Sprintf("%s/repos/%s/collaborators?page=%d&per_page=%d", p.APIURL(instanceURL), repositoryID, page, apiPageSize)- code, body, err := oauth.Get(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -535,7 +535,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.O// with a boolean indicating whether the next page exists.func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, page int) (repos []Repository, hasNextPage bool, err error) {url := fmt.Sprintf("%s/user/repos?page=%d&per_page=%d", p.APIURL(instanceURL), page, apiPageSize)- code, body, err := oauth.Get(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -586,7 +586,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx co// 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(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -658,7 +658,7 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,}url := fmt.Sprintf("%s/repos/%s/contents/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))- code, _, err := oauth.Put(+ code, _, _, err := oauth.Put(ctx,p.client,url,@@ -728,7 +728,7 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthCon// readFile reads the given file in the repository.func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (*File, error) {url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), ref)- code, body, err := oauth.Get(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -784,7 +784,7 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i// Docs: https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhookfunc (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {url := fmt.Sprintf("%s/repos/%s/hooks", p.APIURL(instanceURL), repositoryID)- code, body, err := oauth.Post(+ code, _, body, err := oauth.Post(ctx,p.client,url,@@ -830,7 +830,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthConte// Docs: https://docs.github.com/en/rest/webhooks/repos#update-a-repository-webhookfunc (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(+ code, _, body, err := oauth.Patch(ctx,p.client,url,@@ -867,7 +867,7 @@ func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContex// Docs: https://docs.github.com/en/rest/webhooks/repos#delete-a-repository-webhookfunc (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string) error {url := fmt.Sprintf("%s/repos/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)- code, body, err := oauth.Delete(+ code, _, body, err := oauth.Delete(ctx,p.client,url,diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.goindex 8a387058b0..5744bf4c6d 100644--- a/plugin/vcs/github/github_test.go+++ b/plugin/vcs/github/github_test.go@@ -1126,7 +1126,7 @@ func TestOAuth_RefreshToken(t *testing.T) {return nil}- _, _, err := oauth.Get(+ _, _, _, err := oauth.Get(ctx,client,"https://api.github.com/users/octocat",diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 39f8d6f792..3dce9fb43d 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -4,7 +4,6 @@ package gitlabimport ("bytes""context"- "encoding/base64""encoding/json""fmt""io"@@ -121,12 +120,8 @@ type RepositoryTreeNode struct {// File represents a GitLab API response for a repository file.type File struct {- FileName string `json:"file_name"`- FilePath string `json:"file_path"`- Encoding string `json:"encoding"`- Content string `json:"content"`- Size int64 `json:"size"`- LastCommitID string `json:"last_commit_id"`+ Content string+ LastCommitID string}// ProjectRole is the role of the project member.@@ -292,7 +287,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx co// We will use user's token to create webhook in the project, which requires the// token owner to be at least the project maintainer(40).url := fmt.Sprintf("%s/projects?membership=true&simple=true&min_access_level=40&page=%d&per_page=%d", p.APIURL(instanceURL), page, apiPageSize)- code, body, err := oauth.Get(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -337,7 +332,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx co// should be either "user" or "users/{userID}".func (p *Provider) fetchUserInfoImpl(ctx context.Context, oauthCtx common.OauthContext, instanceURL, resourceURI string) (*vcs.UserInfo, error) {url := fmt.Sprintf("%s/%s", p.APIURL(instanceURL), resourceURI)- code, body, err := oauth.Get(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -381,7 +376,7 @@ func (p *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, i// 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(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -521,7 +516,7 @@ func (p *Provider) fetchPaginatedRepositoryActiveMemberList(ctx context.Context,// The "state" filter only available in GitLab Premium self-managed, GitLab// Premium SaaS, and higher tiers, but worth a try for less abandoned results.url := fmt.Sprintf("%s/projects/%s/members/all?state=active&page=%d&per_page=%d", p.APIURL(instanceURL), repositoryID, page, apiPageSize)- code, body, err := oauth.Get(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -601,7 +596,7 @@ func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.// 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(+ code, _, body, err := oauth.Get(ctx,p.client,url,@@ -658,7 +653,7 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,}url := fmt.Sprintf("%s/projects/%s/repository/files/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))- code, _, err := oauth.Post(+ code, _, _, err := oauth.Post(ctx,p.client,url,@@ -707,7 +702,7 @@ func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthConte}url := fmt.Sprintf("%s/projects/%s/repository/files/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))- code, _, err := oauth.Put(+ code, _, _, err := oauth.Put(ctx,p.client,url,@@ -749,9 +744,6 @@ func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContex}return &vcs.FileMeta{- Name: file.FileName,- Path: file.FilePath,- Size: file.Size,LastCommitID: file.LastCommitID,}, nil}@@ -772,7 +764,7 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthCon// Docs: https://docs.gitlab.com/ee/api/projects.html#add-project-hookfunc (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, payload []byte) (string, error) {url := fmt.Sprintf("%s/projects/%s/hooks", p.APIURL(instanceURL), repositoryID)- code, body, err := oauth.Post(+ code, _, body, err := oauth.Post(ctx,p.client,url,@@ -823,7 +815,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthConte// Docs: https://docs.gitlab.com/ee/api/projects.html#edit-project-hookfunc (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(+ code, _, body, err := oauth.Put(ctx,p.client,url,@@ -860,7 +852,7 @@ func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContex// Docs: https://docs.gitlab.com/ee/api/projects.html#delete-project-hookfunc (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string) error {url := fmt.Sprintf("%s/projects/%s/hooks/%s", p.APIURL(instanceURL), repositoryID, webhookID)- code, body, err := oauth.Delete(+ code, _, body, err := oauth.Delete(ctx,p.client,url,@@ -896,8 +888,10 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConte// TODO: The same GitLab API endpoint supports using the HEAD request to only// get the file metadata.func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (*File, error) {- url := fmt.Sprintf("%s/projects/%s/repository/files/%s?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), url.QueryEscape(ref))- code, body, err := oauth.Get(+ // Since GitLab of stale version doesn't support get large file content well, we move to use the raw api.+ // See https://gitlab.com/gitlab-org/gitlab-pages/-/issues/315 for more details.+ url := fmt.Sprintf("%s/projects/%s/repository/files/%s/raw?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), url.QueryEscape(ref))+ code, header, body, err := oauth.Get(ctx,p.client,url,@@ -927,19 +921,10 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i)}- var file File- if err = json.Unmarshal([]byte(body), &file); err != nil {- return nil, errors.Wrap(err, "unmarshal body")- }-- if file.Encoding == "base64" {- decodedContent, err := base64.StdEncoding.DecodeString(file.Content)- if err != nil {- return nil, errors.Wrap(err, "decode file content")- }- file.Content = string(decodedContent)- }- return &file, nil+ return &File{+ Content: body,+ LastCommitID: header.Get("x-gitlab-last-commit-id"),+ }, nil}// oauthContext is the request context for refreshing oauth token.diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.goindex fd0cff0c94..a066d24d0c 100644--- a/plugin/vcs/gitlab/gitlab_test.go+++ b/plugin/vcs/gitlab/gitlab_test.go@@ -578,25 +578,17 @@ func TestProvider_ReadFileMeta(t *testing.T) {Client: &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {- assert.Equal(t, "/api/v4/projects/1/repository/files/lib%2Fclass.rb", r.URL.RawPath)+ 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(`-{- "file_name": "key.rb",- "file_path": "app/models/key.rb",- "size": 442,- "encoding": "base64",- "content": "IyBTYW1wbGUgR2l0TGFiIFByb2plY3QKClRoaXMgc2FtcGxlIHByb2plY3Qgc2hvd3MgaG93IGEgcHJvamVjdCBpbiBHaXRMYWIgbG9va3MgZm9yIGRlbW9uc3RyYXRpb24gcHVycG9zZXMuIEl0IGNvbnRhaW5zIGlzc3VlcywgbWVyZ2UgcmVxdWVzdHMgYW5kIE1hcmtkb3duIGZpbGVzIGluIG1hbnkgYnJhbmNoZXMsCm5hbWVkIGFuZCBmaWxsZWQgd2l0aCBsb3JlbSBpcHN1bS4KCllvdSBjYW4gbG9vayBhcm91bmQgdG8gZ2V0IGFuIGlkZWEgaG93IHRvIHN0cnVjdHVyZSB5b3VyIHByb2plY3QgYW5kLCB3aGVuIGRvbmUsIHlvdSBjYW4gc2FmZWx5IGRlbGV0ZSB0aGlzIHByb2plY3QuCgpbTGVhcm4gbW9yZSBhYm91dCBjcmVhdGluZyBHaXRMYWIgcHJvamVjdHMuXShodHRwczovL2RvY3MuZ2l0bGFiLmNvbS9lZS9naXRsYWItYmFzaWNzL2NyZWF0ZS1wcm9qZWN0Lmh0bWwpCg==",- "content_sha256": "71dd06da8f5915544335e547e4447de6377ef369d67b6a5214c8a780d336b2e2",- "ref": "master",- "blob_id": "79f7bbd25901e8334750839545a9bd021f0e4c83",- "commit_id": "27329d3afac51fbf2762428e12f2635d1137c549",- "last_commit_id": "27329d3afac51fbf2762428e12f2635d1137c549",- "execute_filemode": false-}-`)),+ Body: io.NopCloser(strings.NewReader(`key`)),+ Header: header,}, nil},},@@ -605,13 +597,10 @@ func TestProvider_ReadFileMeta(t *testing.T) {)ctx := context.Background()- got, err := p.ReadFileMeta(ctx, common.OauthContext{}, "", "1", "lib/class.rb", "master")+ got, err := p.ReadFileMeta(ctx, common.OauthContext{}, "", "1", "app/models/key.rb", "master")require.NoError(t, err)want := &vcs.FileMeta{- Name: "key.rb",- Path: "app/models/key.rb",- Size: 442,LastCommitID: "27329d3afac51fbf2762428e12f2635d1137c549",}assert.Equal(t, want, got)@@ -623,25 +612,25 @@ func TestProvider_ReadFileContent(t *testing.T) {Client: &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {- assert.Equal(t, "/api/v4/projects/1/repository/files/lib%2Fclass.rb", r.URL.RawPath)+ 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(`-{- "file_name": "key.rb",- "file_path": "app/models/key.rb",- "size": 442,- "encoding": "base64",- "content": "IyBTYW1wbGUgR2l0TGFiIFByb2plY3QKClRoaXMgc2FtcGxlIHByb2plY3Qgc2hvd3MgaG93IGEgcHJvamVjdCBpbiBHaXRMYWIgbG9va3MgZm9yIGRlbW9uc3RyYXRpb24gcHVycG9zZXMuIEl0IGNvbnRhaW5zIGlzc3VlcywgbWVyZ2UgcmVxdWVzdHMgYW5kIE1hcmtkb3duIGZpbGVzIGluIG1hbnkgYnJhbmNoZXMsCm5hbWVkIGFuZCBmaWxsZWQgd2l0aCBsb3JlbSBpcHN1bS4KCllvdSBjYW4gbG9vayBhcm91bmQgdG8gZ2V0IGFuIGlkZWEgaG93IHRvIHN0cnVjdHVyZSB5b3VyIHByb2plY3QgYW5kLCB3aGVuIGRvbmUsIHlvdSBjYW4gc2FmZWx5IGRlbGV0ZSB0aGlzIHByb2plY3QuCgpbTGVhcm4gbW9yZSBhYm91dCBjcmVhdGluZyBHaXRMYWIgcHJvamVjdHMuXShodHRwczovL2RvY3MuZ2l0bGFiLmNvbS9lZS9naXRsYWItYmFzaWNzL2NyZWF0ZS1wcm9qZWN0Lmh0bWwpCg==",- "content_sha256": "71dd06da8f5915544335e547e4447de6377ef369d67b6a5214c8a780d336b2e2",- "ref": "master",- "blob_id": "79f7bbd25901e8334750839545a9bd021f0e4c83",- "commit_id": "27329d3afac51fbf2762428e12f2635d1137c549",- "last_commit_id": "27329d3afac51fbf2762428e12f2635d1137c549",- "execute_filemode": false-}+ Body: io.NopCloser(strings.NewReader(`# Sample GitLab Project++This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,+named and filled with lorem ipsum.++You can look around to get an idea how to structure your project and, when done, you can safely delete this project.++[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)`)),+ Header: header,}, nil},},@@ -650,7 +639,7 @@ func TestProvider_ReadFileContent(t *testing.T) {)ctx := context.Background()- got, err := p.ReadFileContent(ctx, common.OauthContext{}, "", "1", "lib/class.rb", "master")+ got, err := p.ReadFileContent(ctx, common.OauthContext{}, "", "1", "app/models/key.rb", "master")require.NoError(t, err)want := `# Sample GitLab Project@@ -793,7 +782,7 @@ func TestOAuth_RefreshToken(t *testing.T) {return nil}- _, _, err := oauth.Get(+ _, _, _, err := oauth.Get(ctx,client,"https://gitlab.example.com/api/v4/users/octocat",diff --git a/plugin/vcs/internal/oauth/oauth.go b/plugin/vcs/internal/oauth/oauth.goindex 6f33032c53..6da6b6f302 100644--- a/plugin/vcs/internal/oauth/oauth.go+++ b/plugin/vcs/internal/oauth/oauth.go@@ -35,69 +35,69 @@ func requester(ctx context.Context, client *http.Client, method, url string, tok// Post makes a HTTP POST request to the given URL using the token. It refreshes// token and retries the request in the case of the token has expired.-func Post(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+func Post(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, header http.Header, respBody string, err error) {return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodPost, url, token, body))}// Get makes a HTTP GET request to the given URL using the token. It refreshes// token and retries the request in the case of the token has expired.-func Get(ctx context.Context, client *http.Client, url string, token *string, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+func Get(ctx context.Context, client *http.Client, url string, token *string, tokenRefresher TokenRefresher) (code int, header http.Header, respBody string, err error) {return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodGet, url, token, nil))}// Put makes a HTTP PUT request to the given URL using the token. It refreshes// token and retries the request in the case of the token has expired.-func Put(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+func Put(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, header http.Header, respBody string, err error) {return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodPut, url, token, body))}// Patch makes a HTTP PATCH request to the given URL using the token. It// refreshes token and retries the request in the case of the token has expired.-func Patch(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+func Patch(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, header http.Header, respBody string, err error) {return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodPatch, url, token, body))}// Delete makes a HTTP DELETE request to the given URL using the token. It refreshes// token and retries the request in the case of the token has expired.-func Delete(ctx context.Context, client *http.Client, url string, token *string, tokenRefresher TokenRefresher) (code int, respBody string, err error) {+func Delete(ctx context.Context, client *http.Client, url string, token *string, tokenRefresher TokenRefresher) (code int, header http.Header, respBody string, err error) {return retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodDelete, url, token, nil))}const maxRetries = 3-func retry(ctx context.Context, client *http.Client, token *string, tokenRefresher TokenRefresher, f func() (*http.Response, error)) (code int, respBody string, err error) {+func retry(ctx context.Context, client *http.Client, token *string, tokenRefresher TokenRefresher, f func() (*http.Response, error)) (code int, header http.Header, respBody string, err error) {var resp *http.Responsevar body []bytefor retries := 0; retries < maxRetries; retries++ {select {case <-ctx.Done():- return 0, "", ctx.Err()+ return 0, nil, "", ctx.Err()default:}resp, err = f()if err != nil {- return 0, "", err+ return 0, nil, "", err}body, err := io.ReadAll(resp.Body)if err != nil {- return 0, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)+ return 0, nil, "", errors.Wrapf(err, "read response body with status code %d", resp.StatusCode)}if err = getOAuthErrorDetails(resp.StatusCode, body); err != nil {if _, ok := err.(*oauthError); ok {// Refresh the tokenif err := tokenRefresher(ctx, client, token); err != nil {- return 0, "", err+ return 0, nil, "", err}continue}- return 0, "", errors.Errorf("got unexpected OAuth error %T", err)+ return 0, nil, "", errors.Errorf("got unexpected OAuth error %T", err)}- return resp.StatusCode, string(body), nil+ return resp.StatusCode, resp.Header, string(body), nil}- return 0, "", errors.Errorf("retries exceeded for OAuth refresher with status code %d and body %q", resp.StatusCode, string(body))+ return 0, nil, "", errors.Errorf("retries exceeded for OAuth refresher with status code %d and body %q", resp.StatusCode, string(body))}type oauthError struct {diff --git a/plugin/vcs/internal/oauth/oauth_test.go b/plugin/vcs/internal/oauth/oauth_test.goindex 4251dd889d..d54ba90496 100644--- a/plugin/vcs/internal/oauth/oauth_test.go+++ b/plugin/vcs/internal/oauth/oauth_test.go@@ -31,7 +31,7 @@ func TestPost(t *testing.T) {},}token := "token"- _, _, err := Post(ctx, client, "", &token, strings.NewReader("POST body"), nil)+ _, _, _, err := Post(ctx, client, "", &token, strings.NewReader("POST body"), nil)require.NoError(t, err)}@@ -48,7 +48,7 @@ func TestGet(t *testing.T) {},}token := "token"- _, _, err := Get(ctx, client, "", &token, nil)+ _, _, _, err := Get(ctx, client, "", &token, nil)require.NoError(t, err)}@@ -69,7 +69,7 @@ func TestPut(t *testing.T) {},}token := "token"- _, _, err := Put(ctx, client, "", &token, strings.NewReader("PUT body"), nil)+ _, _, _, err := Put(ctx, client, "", &token, strings.NewReader("PUT body"), nil)require.NoError(t, err)}@@ -90,7 +90,7 @@ func TestPatch(t *testing.T) {},}token := "token"- _, _, err := Patch(ctx, client, "", &token, strings.NewReader("PATCH body"), nil)+ _, _, _, err := Patch(ctx, client, "", &token, strings.NewReader("PATCH body"), nil)require.NoError(t, err)}@@ -107,7 +107,7 @@ func TestDelete(t *testing.T) {},}token := "token"- _, _, err := Delete(ctx, client, "", &token, nil)+ _, _, _, err := Delete(ctx, client, "", &token, nil)require.NoError(t, err)}@@ -115,7 +115,7 @@ func TestRetry_Exceeded(t *testing.T) {ctx := context.Background()token := "expired"- _, _, err := retry(ctx, nil, &token,+ _, _, _, err := retry(ctx, nil, &token,func(_ context.Context, _ *http.Client, _ *string) error {return nil},diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex 6a06dffa9f..a6454a50b1 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -9,6 +9,7 @@ import ("net/http""net/url""path/filepath"+ "strconv""strings""time"@@ -59,7 +60,6 @@ func NewGitLab(port int) VCSProvider {projectGroup.GET("/projects/:id/repository/commits/:commitID", gl.getFakeCommit)projectGroup.GET("/projects/:id/repository/tree", gl.readProjectTree)projectGroup.GET("/projects/:id/repository/files/:filePath/raw", gl.readProjectFile)- projectGroup.GET("/projects/:id/repository/files/:filePath", gl.readProjectFileMetadata)projectGroup.POST("/projects/:id/repository/files/:filePath", gl.createProjectFile)projectGroup.PUT("/projects/:id/repository/files/:filePath", gl.createProjectFile)@@ -160,46 +160,19 @@ func (gl *GitLab) readProjectFile(c echo.Context) error {return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))}- content, ok := pd.files[filePath]- if !ok {- return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", filePath))- }-- return c.String(http.StatusOK, content)-}--// readProjectFileMetadata reads a project file metadata.-func (gl *GitLab) readProjectFileMetadata(c echo.Context) error {- projectID := c.Param("id")- filePathEscaped := c.Param("filePath")- filePath, err := url.QueryUnescape(filePathEscaped)- if err != nil {- return c.String(http.StatusBadRequest, fmt.Sprintf("failed to query unescape %q, error: %v", filePathEscaped, err))- }+ fileName := filepath.Base(filePath)- pd, ok := gl.projects[projectID]+ content, ok := pd.files[filePath]if !ok {- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))- }-- if _, ok := pd.files[filePath]; !ok {return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", filePath))}- fileName := filepath.Base(filePath)- content := pd.files[filePath]+ c.Response().Header().Set("x-gitlab-file-name", fileName)+ c.Response().Header().Set("x-gitlab-file-path", filePath)+ c.Response().Header().Set("x-gitlab-size", strconv.Itoa(len([]byte(content))))+ c.Response().Header().Set("x-gitlab-last-commit-id", "fake_gitlab_commit_id")- buf, err := json.Marshal(&gitlab.File{- FileName: fileName,- FilePath: filePath,- Content: content,- LastCommitID: "fake_gitlab_commit_id",- })- if err != nil {- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal FileMeta, error %v", err))- }-- return c.String(http.StatusOK, string(buf))+ return c.String(http.StatusOK, content)}// getFakeCommit get a fake commit data.