git_blobs.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2013 The go-github AUTHORS. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. package github
  6. import (
  7. "bytes"
  8. "context"
  9. "fmt"
  10. )
  11. // Blob represents a blob object.
  12. type Blob struct {
  13. Content *string `json:"content,omitempty"`
  14. Encoding *string `json:"encoding,omitempty"`
  15. SHA *string `json:"sha,omitempty"`
  16. Size *int `json:"size,omitempty"`
  17. URL *string `json:"url,omitempty"`
  18. NodeID *string `json:"node_id,omitempty"`
  19. }
  20. // GetBlob fetches a blob from a repo given a SHA.
  21. //
  22. // GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob
  23. func (s *GitService) GetBlob(ctx context.Context, owner string, repo string, sha string) (*Blob, *Response, error) {
  24. u := fmt.Sprintf("repos/%v/%v/git/blobs/%v", owner, repo, sha)
  25. req, err := s.client.NewRequest("GET", u, nil)
  26. if err != nil {
  27. return nil, nil, err
  28. }
  29. // TODO: remove custom Accept header when this API fully launches.
  30. req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview)
  31. blob := new(Blob)
  32. resp, err := s.client.Do(ctx, req, blob)
  33. return blob, resp, err
  34. }
  35. // GetBlobRaw fetches a blob's contents from a repo.
  36. // Unlike GetBlob, it returns the raw bytes rather than the base64-encoded data.
  37. //
  38. // GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob
  39. func (s *GitService) GetBlobRaw(ctx context.Context, owner, repo, sha string) ([]byte, *Response, error) {
  40. u := fmt.Sprintf("repos/%v/%v/git/blobs/%v", owner, repo, sha)
  41. req, err := s.client.NewRequest("GET", u, nil)
  42. if err != nil {
  43. return nil, nil, err
  44. }
  45. req.Header.Set("Accept", "application/vnd.github.v3.raw")
  46. var buf bytes.Buffer
  47. resp, err := s.client.Do(ctx, req, &buf)
  48. return buf.Bytes(), resp, err
  49. }
  50. // CreateBlob creates a blob object.
  51. //
  52. // GitHub API docs: https://developer.github.com/v3/git/blobs/#create-a-blob
  53. func (s *GitService) CreateBlob(ctx context.Context, owner string, repo string, blob *Blob) (*Blob, *Response, error) {
  54. u := fmt.Sprintf("repos/%v/%v/git/blobs", owner, repo)
  55. req, err := s.client.NewRequest("POST", u, blob)
  56. if err != nil {
  57. return nil, nil, err
  58. }
  59. // TODO: remove custom Accept header when this API fully launches.
  60. req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview)
  61. t := new(Blob)
  62. resp, err := s.client.Do(ctx, req, t)
  63. return t, resp, err
  64. }