Skip to content

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

feat(github): implement `CreateFile` and `OverwriteFile` (#1885)

Joe Chene68f8cc739a3
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index 4b7b53a6b8..034efdeb9e 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -3,6 +3,7 @@ package github
import (
"bytes"
"context"
+ "encoding/base64"
"encoding/json"
"fmt"
"io"
@@ -96,6 +97,16 @@ type RepositoryTreeNode struct {
Type string `json:"type"`
}
+// 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"`
+}
+
// 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) {
@@ -155,6 +166,14 @@ type Commit struct {
} `json:"author"`
}
+// FileCommit represents a GitHub API request for committing a file.
+type FileCommit struct {
+ Message string `json:"message"`
+ Content string `json:"content"`
+ SHA string `json:"sha,omitempty"`
+ Branch string `json:"branch,omitempty"`
+}
+
// FetchCommitByID fetches the commit data by its ID from the repository.
func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, commitID string) (*vcs.Commit, error) {
url := fmt.Sprintf("%s/repos/%s/git/commits/%s", apiURL, repositoryID, commitID)
@@ -516,24 +535,141 @@ func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.
return allTreeNodes, nil
}
-// CreateFile creates a file.
-func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommit vcs.FileCommitCreate) error {
- return errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// 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, _, repositoryID, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
+ body, err := json.Marshal(
+ FileCommit{
+ Message: fileCommitCreate.CommitMessage,
+ Content: base64.StdEncoding.EncodeToString([]byte(fileCommitCreate.Content)),
+ Branch: fileCommitCreate.Branch,
+ SHA: fileCommitCreate.LastCommitID,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal file commit")
+ }
+
+ url := fmt.Sprintf("%s/repos/%s/contents/%s", apiURL, repositoryID, url.QueryEscape(filePath))
+ code, _, err := oauth.Put(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "PUT %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, fmt.Errorf("failed to create/update file through URL %s", url))
+ }
+ if code >= 300 {
+ return fmt.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+ return nil
}
-// OverwriteFile overwrite the content of a file.
-func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath string, fileCommit vcs.FileCommitCreate) error {
- return errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// 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 file metadata.
-func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (*vcs.FileMeta, error) {
- return nil, errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// 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, _, repositoryID, filePath, ref string) (*vcs.FileMeta, error) {
+ file, err := p.readFile(ctx, oauthCtx, repositoryID, filePath, ref)
+ if err != nil {
+ return nil, errors.Wrap(err, "read file")
+ }
+
+ return &vcs.FileMeta{
+ Name: file.Name,
+ Path: file.Path,
+ Size: file.Size,
+ LastCommitID: file.SHA,
+ }, nil
}
-// ReadFileContent reads the file content.
-func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (string, error) {
- return "", errors.New("not implemented yet") // TODO: https://github.com/bytebase/bytebase/issues/928
+// ReadFileContent reads the content of the given file in the repository.
+//
+// Docs: https://docs.github.com/en/rest/repos/contents#get-repository-content
+func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, _, repositoryID, filePath, ref string) (string, error) {
+ file, err := p.readFile(ctx, oauthCtx, repositoryID, filePath, ref)
+ if err != nil {
+ return "", errors.Wrap(err, "read file")
+ }
+ return file.Content, nil
+}
+
+// readFile reads the given file in the repository.
+func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, repositoryID, filePath, ref string) (*File, error) {
+ url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", apiURL, repositoryID, url.QueryEscape(filePath), 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 read file from URL %s", url))
+ } else if code >= 300 {
+ return nil,
+ fmt.Errorf("failed to read file 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")
+ }
+
+ 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
}
// CreateWebhook creates a webhook in a GitLab project.
diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.go
index 130b494721..1c54170064 100644
--- a/plugin/vcs/github/github_test.go
+++ b/plugin/vcs/github/github_test.go
@@ -688,6 +688,294 @@ func TestProvider_FetchRepositoryFileList(t *testing.T) {
})
}
+func TestProvider_CreateFile(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/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{},
+ "",
+ "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 := newProvider(
+ vcs.ProviderConfig{
+ Client: &http.Client{
+ Transport: &common.MockRoundTripper{
+ MockRoundTrip: 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{},
+ "",
+ "octocat/Hello-World",
+ "notes/hello.txt",
+ vcs.FileCommitCreate{
+ Branch: "master",
+ Content: "my new file contents",
+ CommitMessage: "update file",
+ LastCommitID: "7638417db6d59f3c431d3e1f261cc637155684cd",
+ },
+ )
+ require.NoError(t, err)
+}
+
+func TestProvider_ReadFileMeta(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/contents/README.md", r.URL.Path)
+ 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
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.ReadFileMeta(ctx, common.OauthContext{}, "", "octocat/Hello-World", "README.md", "master")
+ require.NoError(t, err)
+
+ want := &vcs.FileMeta{
+ Name: "README.md",
+ Path: "README.md",
+ Size: 442,
+ LastCommitID: "3d21ec53a331a6f037a91c368710b99387d012c1",
+ }
+ assert.Equal(t, want, got)
+}
+
+func TestProvider_ReadFileContent(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/contents/README.md", r.URL.Path)
+ 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
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.ReadFileContent(ctx, common.OauthContext{}, "", "octocat/Hello-World", "README.md", "master")
+ require.NoError(t, err)
+
+ want := `# Sample GitLab Project
+
+This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,
+named and filled with lorem ipsum.
+
+You can look around to get an idea how to structure your project and, when done, you can safely delete this project.
+
+[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)
+`
+ assert.Equal(t, want, got)
+}
+
func 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 4e6ddd5dab..7235b6085b 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -109,7 +109,7 @@ type Commit struct {
CreatedAt time.Time `json:"created_at"`
}
-// FileCommit is the API message for file commit.
+// FileCommit represents a GitLab API request for committing a file.
type FileCommit struct {
Branch string `json:"branch"`
Content string `json:"content"`
@@ -124,7 +124,7 @@ type RepositoryTreeNode struct {
Type string `json:"type"`
}
-// File is the API message for file metadata.
+// File represents a GitLab API response for a repository file.
type File struct {
FileName string `json:"file_name"`
FilePath string `json:"file_path"`
@@ -649,15 +649,19 @@ func (p *Provider) fetchPaginatedRepositoryFileList(ctx context.Context, oauthCt
return treeNodes, len(treeNodes) >= 100, nil
}
-// CreateFile creates a file.
+// 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,
- })
+ body, err := json.Marshal(
+ FileCommit{
+ Branch: fileCommitCreate.Branch,
+ CommitMessage: fileCommitCreate.CommitMessage,
+ Content: fileCommitCreate.Content,
+ },
+ )
if err != nil {
- return fmt.Errorf("failed to marshal file commit: %w", err)
+ return errors.Wrap(err, "marshal file commit")
}
url := fmt.Sprintf("%s/projects/%s/repository/files/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))
@@ -678,9 +682,12 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,
),
)
if err != nil {
- return fmt.Errorf("failed to create file %s on GitLab instance %s, err: %w", filePath, instanceURL, err)
+ return errors.Wrapf(err, "POST %s", url)
}
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, fmt.Errorf("failed to create file through URL %s", url))
+ }
if code >= 300 {
return fmt.Errorf("failed to create file %s on GitLab instance %s, status code: %d",
filePath,
@@ -691,16 +698,20 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,
return nil
}
-// OverwriteFile overwrite the content of a file.
+// 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,
- CommitMessage: fileCommitCreate.CommitMessage,
- Content: fileCommitCreate.Content,
- LastCommitID: fileCommitCreate.LastCommitID,
- })
+ body, err := json.Marshal(
+ FileCommit{
+ Branch: fileCommitCreate.Branch,
+ Content: fileCommitCreate.Content,
+ CommitMessage: fileCommitCreate.CommitMessage,
+ LastCommitID: fileCommitCreate.LastCommitID,
+ },
+ )
if err != nil {
- return fmt.Errorf("failed to marshal file commit: %w", err)
+ return errors.Wrap(err, "marshal file commit")
}
url := fmt.Sprintf("%s/projects/%s/repository/files/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))
@@ -721,11 +732,14 @@ func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthConte
),
)
if err != nil {
- return fmt.Errorf("failed to create file %s on GitLab instance %s, error: %w", filePath, instanceURL, err)
+ return errors.Wrapf(err, "PUT %s", url)
}
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, fmt.Errorf("failed to overwrite file through URL %s", url))
+ }
if code >= 300 {
- return fmt.Errorf("failed to create file %s on GitLab instance %s, status code: %d",
+ return fmt.Errorf("failed to overwrite file %s on GitLab instance %s, status code: %d",
filePath,
instanceURL,
code,
@@ -734,11 +748,13 @@ func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthConte
return nil
}
-// ReadFileMeta reads the file metadata.
-func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, ref string) (*vcs.FileMeta, error) {
+// 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, ref string) (*vcs.FileMeta, error) {
file, err := p.readFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, ref)
if err != nil {
- return nil, fmt.Errorf("failed to read file metadata %s from GitLab instance %s: %w", filePath, instanceURL, err)
+ return nil, errors.Wrap(err, "read file")
}
return &vcs.FileMeta{
@@ -749,13 +765,14 @@ func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContex
}, nil
}
-// ReadFileContent reads the file content.
-func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, ref string) (string, error) {
+// ReadFileContent reads the content of the given file in the repository.
+//
+// Docs: https://docs.gitlab.com/ee/api/repository_files.html#get-file-from-repository
+func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (string, error) {
file, err := p.readFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, ref)
if err != nil {
- return "", fmt.Errorf("failed to read file content %s from GitLab instance %s: %w", filePath, instanceURL, err)
+ return "", errors.Wrap(err, "read file")
}
-
return file.Content, nil
}
@@ -861,7 +878,10 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConte
return nil
}
-// readFile reads the file data including metadata and content.
+// readFile reads the given file in the repository.
+//
+// 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 string, repositoryID string, filePath string, 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(
@@ -880,39 +900,33 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i
),
)
if err != nil {
- return nil, errors.Wrap(err, "GET")
+ return nil, errors.Wrapf(err, "GET %s", url)
}
+
if code == http.StatusNotFound {
- return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read file data from GitLab instance %s", instanceURL))
+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to read file from URL %s", url))
} else if code >= 300 {
- return nil, fmt.Errorf("failed to read file data from GitLab instance %s, status code: %d",
- instanceURL,
- code,
- )
+ return nil,
+ fmt.Errorf("failed to read file %s on GitLab instance %s, status code: %d",
+ filePath,
+ instanceURL,
+ code,
+ )
}
- file := &File{}
- if err := json.Unmarshal([]byte(body), file); err != nil {
- return nil, fmt.Errorf("failed to unmarshal file from GitLab instance %s: %w", instanceURL, err)
+ var file File
+ if err = json.Unmarshal([]byte(body), &file); err != nil {
+ return nil, errors.Wrap(err, "unmarshal body")
}
- content := file.Content
if file.Encoding == "base64" {
decodedContent, err := base64.StdEncoding.DecodeString(file.Content)
if err != nil {
- return nil, fmt.Errorf("failed to decode file content, err %w", err)
+ return nil, errors.Wrap(err, "decode file content")
}
- content = string(decodedContent)
+ file.Content = string(decodedContent)
}
-
- return &File{
- FileName: file.FileName,
- FilePath: file.FilePath,
- Size: file.Size,
- Encoding: file.Encoding,
- Content: content,
- LastCommitID: file.LastCommitID,
- }, nil
+ return &file, 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.go
index 402727cd16..2b3b758138 100644
--- a/plugin/vcs/gitlab/gitlab_test.go
+++ b/plugin/vcs/gitlab/gitlab_test.go
@@ -483,6 +483,188 @@ func TestProvider_FetchRepositoryFileList(t *testing.T) {
assert.Equal(t, want, got)
}
+func TestProvider_CreateFile(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/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 := 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/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 := 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/files/lib%2Fclass.rb", r.URL.RawPath)
+ 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
+}
+`)),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.ReadFileMeta(ctx, common.OauthContext{}, "", "1", "lib/class.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)
+}
+
+func TestProvider_ReadFileContent(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/files/lib%2Fclass.rb", r.URL.RawPath)
+ 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
+}
+`)),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.ReadFileContent(ctx, common.OauthContext{}, "", "1", "lib/class.rb", "master")
+ require.NoError(t, err)
+
+ want := `# Sample GitLab Project
+
+This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,
+named and filled with lorem ipsum.
+
+You can look around to get an idea how to structure your project and, when done, you can safely delete this project.
+
+[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)
+`
+ assert.Equal(t, want, got)
+}
+
func TestOAuth_RefreshToken(t *testing.T) {
ctx := context.Background()
client := &http.Client{