Skip to content

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

feat: implement `FetchCommitByID` for GitHub VCS provider (#1417)

Joe Chen2b145ae53e4d
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index 7af4a8df3a..048aa37a19 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -10,6 +10,7 @@ import (
"net/url"
"strconv"
"strings"
+ "time"
"github.com/pkg/errors"
"go.uber.org/zap"
@@ -102,9 +103,54 @@ func (p *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, _
return p.fetchUserInfo(ctx, oauthCtx, "user")
}
-// FetchCommitByID fetch the commit data by id.
-func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, commitID string) (*vcs.Commit, error) {
- return nil, errors.New("not implemented yet")
+// Commit represents a GitHub API response for a commit.
+type Commit struct {
+ SHA string `json:"sha"`
+ Author struct {
+ // Date expects corresponding JSON value is a string in RFC 3339 format,
+ // see https://pkg.go.dev/time#Time.MarshalJSON.
+ Date time.Time `json:"date"`
+ Name string `json:"name"`
+ } `json:"author"`
+}
+
+// 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)
+ 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.Wrap(err, "GET")
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, errors.New("failed to fetch commit data from GitHub.com, not found"))
+ } else if code >= 300 {
+ return nil, fmt.Errorf("failed to fetch commit data from GitHub.com, status code: %d, body: %s", code, body)
+ }
+
+ commit := &Commit{}
+ if err := json.Unmarshal([]byte(body), commit); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal commit data from GitHub.com, err: %w", err)
+ }
+
+ return &vcs.Commit{
+ ID: commit.SHA,
+ AuthorName: commit.Author.Name,
+ CreatedTs: commit.Author.Date.Unix(),
+ }, nil
}
// FetchUserInfo fetches user info of given user ID.
diff --git a/plugin/vcs/github/github_test.go b/plugin/vcs/github/github_test.go
index c2a6c10af2..0f3b9e27b5 100644
--- a/plugin/vcs/github/github_test.go
+++ b/plugin/vcs/github/github_test.go
@@ -91,6 +91,71 @@ func TestProvider_FetchUserInfo(t *testing.T) {
assert.Equal(t, want, got)
}
+func TestProvider_FetchCommitByID(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/commits/7638417db6d59f3c431d3e1f261cc637155684cd", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://docs.github.com/en/rest/git/commits#get-a-commit
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "sha": "7638417db6d59f3c431d3e1f261cc637155684cd",
+ "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==",
+ "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd",
+ "html_url": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd",
+ "author": {
+ "date": "2014-11-07T22:01:45Z",
+ "name": "Monalisa Octocat",
+ "email": "[email protected]"
+ },
+ "committer": {
+ "date": "2014-11-07T22:01:45Z",
+ "name": "Monalisa Octocat",
+ "email": "[email protected]"
+ },
+ "message": "added readme, because im a good github citizen",
+ "tree": {
+ "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb",
+ "sha": "691272480426f78a0138979dd3ce63b77f706feb"
+ },
+ "parents": [
+ {
+ "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5",
+ "sha": "1acc419d4d6a9ce985db7be48c6349a0475975b5",
+ "html_url": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd"
+ }
+ ],
+ "verification": {
+ "verified": false,
+ "reason": "unsigned",
+ "signature": null,
+ "payload": null
+ }
+}
+`)),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.FetchCommitByID(ctx, common.OauthContext{}, "", "octocat/Hello-World", "7638417db6d59f3c431d3e1f261cc637155684cd")
+ require.NoError(t, err)
+
+ want := &vcs.Commit{
+ ID: "7638417db6d59f3c431d3e1f261cc637155684cd",
+ AuthorName: "Monalisa Octocat",
+ CreatedTs: 1415397705,
+ }
+ assert.Equal(t, want, got)
+}
+
func TestProvider_ExchangeOAuthToken(t *testing.T) {
p := newProvider(
vcs.ProviderConfig{
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index 4757967323..a19780654e 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -112,7 +112,9 @@ type WebhookPushEvent struct {
type Commit struct {
ID string `json:"id"`
AuthorName string `json:"author_name"`
- CreatedAt string `json:"created_at"`
+ // CreatedAt expects corresponding JSON value is a string in RFC 3339 format,
+ // see https://pkg.go.dev/time#Time.MarshalJSON.
+ CreatedAt time.Time `json:"created_at"`
}
// FileCommit is the API message for file commit.
@@ -407,7 +409,7 @@ func (p *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, i
return p.fetchUserInfo(ctx, oauthCtx, instanceURL, "user")
}
-// FetchCommitByID fetch the commit data by id.
+// 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(
@@ -431,9 +433,10 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon
if code == http.StatusNotFound {
return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch commit data from GitLab instance %s, not found", instanceURL))
} else if code >= 300 {
- return nil, fmt.Errorf("failed to fetch commit data from GitLab instance %s, status code: %d",
+ return nil, fmt.Errorf("failed to fetch commit data from GitLab instance %s, status code: %d, body: %s",
instanceURL,
code,
+ body,
)
}
@@ -442,15 +445,10 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthCon
return nil, fmt.Errorf("failed to unmarshal commit data from GitLab instance %s, err: %w", instanceURL, err)
}
- createdTime, err := time.Parse(time.RFC3339, commit.CreatedAt)
- if err != nil {
- return nil, fmt.Errorf("failed to parse commit created_at field, err: %w", err)
- }
-
return &vcs.Commit{
ID: commit.ID,
AuthorName: commit.AuthorName,
- CreatedTs: createdTime.Unix(),
+ CreatedTs: commit.CreatedAt.Unix(),
}, nil
}
diff --git a/plugin/vcs/gitlab/gitlab_test.go b/plugin/vcs/gitlab/gitlab_test.go
index 5f8c41c534..d97cd7e330 100644
--- a/plugin/vcs/gitlab/gitlab_test.go
+++ b/plugin/vcs/gitlab/gitlab_test.go
@@ -67,6 +67,66 @@ func TestProvider_FetchUserInfo(t *testing.T) {
assert.Equal(t, want, got)
}
+func TestProvider_FetchCommitByID(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/5/repository/commits/6104942438c14ec7bd21c6cd5bd995272b3faff6", r.URL.Path)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ // Example response taken from https://docs.gitlab.com/ee/api/commits.html#get-a-single-commit
+ Body: io.NopCloser(strings.NewReader(`
+{
+ "id": "6104942438c14ec7bd21c6cd5bd995272b3faff6",
+ "short_id": "6104942438c",
+ "title": "Sanitize for network graph",
+ "author_name": "randx",
+ "author_email": "[email protected]",
+ "committer_name": "Dmitriy",
+ "committer_email": "[email protected]",
+ "created_at": "2021-09-20T09:06:12.300+03:00",
+ "message": "Sanitize for network graph",
+ "committed_date": "2021-09-20T09:06:12.300+03:00",
+ "authored_date": "2021-09-20T09:06:12.420+03:00",
+ "parent_ids": [
+ "ae1d9fb46aa2b07ee9836d49862ec4e2c46fbbba"
+ ],
+ "last_pipeline" : {
+ "id": 8,
+ "ref": "master",
+ "sha": "2dc6aa325a317eda67812f05600bdf0fcdc70ab0",
+ "status": "created"
+ },
+ "stats": {
+ "additions": 15,
+ "deletions": 10,
+ "total": 25
+ },
+ "status": "running",
+ "web_url": "https://gitlab.example.com/thedude/gitlab-foss/-/commit/6104942438c14ec7bd21c6cd5bd995272b3faff6"
+}
+`)),
+ }, nil
+ },
+ },
+ },
+ },
+ )
+
+ ctx := context.Background()
+ got, err := p.FetchCommitByID(ctx, common.OauthContext{}, "", "5", "6104942438c14ec7bd21c6cd5bd995272b3faff6")
+ require.NoError(t, err)
+
+ want := &vcs.Commit{
+ ID: "6104942438c14ec7bd21c6cd5bd995272b3faff6",
+ AuthorName: "randx",
+ CreatedTs: 1632117972,
+ }
+ assert.Equal(t, want, got)
+}
+
func TestProvider_ExchangeOAuthToken(t *testing.T) {
p := newProvider(
vcs.ProviderConfig{
diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.go
index b1701e3440..8c3f1dabdf 100644
--- a/tests/fake/gitlab.go
+++ b/tests/fake/gitlab.go
@@ -10,10 +10,11 @@ import (
"strings"
"time"
- "github.com/bytebase/bytebase/plugin/vcs"
- "github.com/bytebase/bytebase/plugin/vcs/gitlab"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
+
+ "github.com/bytebase/bytebase/plugin/vcs"
+ "github.com/bytebase/bytebase/plugin/vcs/gitlab"
)
// GitLab is a fake implementation of GitLab.
@@ -201,7 +202,7 @@ func (gl *GitLab) getFakeCommit(c echo.Context) error {
commit := gitlab.Commit{
ID: "fake_gitlab_commit_id",
AuthorName: "fake_gitlab_bot",
- CreatedAt: time.Now().Format(time.RFC3339),
+ CreatedAt: time.Now(),
}
buf, err := json.Marshal(commit)
if err != nil {