diff --git a/github/git_blobs.go b/github/git_blobs.go index 9d8fd27bcca..5290c5538a8 100644 --- a/github/git_blobs.go +++ b/github/git_blobs.go @@ -6,6 +6,7 @@ package github import ( + "bytes" "context" "fmt" ) @@ -20,7 +21,7 @@ type Blob struct { NodeID *string `json:"node_id,omitempty"` } -// GetBlob fetchs a blob from a repo given a SHA. +// GetBlob fetches a blob from a repo given a SHA. // // GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob func (s *GitService) GetBlob(ctx context.Context, owner string, repo string, sha string) (*Blob, *Response, error) { @@ -38,6 +39,23 @@ func (s *GitService) GetBlob(ctx context.Context, owner string, repo string, sha return blob, resp, err } +// GetBlobRaw fetches a blob's contents from a repo. +// Unlike GetBlob, it returns the raw bytes rather than the base64-encoded data. +// +// GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob +func (s *GitService) GetBlobRaw(ctx context.Context, owner, repo, sha string) ([]byte, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/git/blobs/%v", owner, repo, sha) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + req.Header.Set("Accept", "application/vnd.github.v3.raw") + + var buf bytes.Buffer + resp, err := s.client.Do(ctx, req, &buf) + return buf.Bytes(), resp, err +} + // CreateBlob creates a blob object. // // GitHub API docs: https://developer.github.com/v3/git/blobs/#create-a-blob diff --git a/github/git_blobs_test.go b/github/git_blobs_test.go index d4ae22beaee..f753e285275 100644 --- a/github/git_blobs_test.go +++ b/github/git_blobs_test.go @@ -6,6 +6,7 @@ package github import ( + "bytes" "context" "encoding/json" "fmt" @@ -51,6 +52,28 @@ func TestGitService_GetBlob_invalidOwner(t *testing.T) { testURLParseError(t, err) } +func TestGitService_GetBlobRaw(t *testing.T) { + client, mux, _, teardown := setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/git/blobs/s", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + testHeader(t, r, "Accept", "application/vnd.github.v3.raw") + + fmt.Fprint(w, `raw contents here`) + }) + + blob, _, err := client.Git.GetBlobRaw(context.Background(), "o", "r", "s") + if err != nil { + t.Errorf("Git.GetBlobRaw returned error: %v", err) + } + + want := []byte("raw contents here") + if !bytes.Equal(blob, want) { + t.Errorf("GetBlobRaw returned %q, want %q", blob, want) + } +} + func TestGitService_CreateBlob(t *testing.T) { client, mux, _, teardown := setup() defer teardown()