You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

blob.go 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package git
  6. import (
  7. "encoding/base64"
  8. "io"
  9. "io/ioutil"
  10. "gopkg.in/src-d/go-git.v4/plumbing"
  11. )
  12. // Blob represents a Git object.
  13. type Blob struct {
  14. ID SHA1
  15. gogitEncodedObj plumbing.EncodedObject
  16. name string
  17. }
  18. // DataAsync gets a ReadCloser for the contents of a blob without reading it all.
  19. // Calling the Close function on the result will discard all unread output.
  20. func (b *Blob) DataAsync() (io.ReadCloser, error) {
  21. return b.gogitEncodedObj.Reader()
  22. }
  23. // Size returns the uncompressed size of the blob
  24. func (b *Blob) Size() int64 {
  25. return b.gogitEncodedObj.Size()
  26. }
  27. // Name returns name of the tree entry this blob object was created from (or empty string)
  28. func (b *Blob) Name() string {
  29. return b.name
  30. }
  31. // GetBlobContentBase64 Reads the content of the blob with a base64 encode and returns the encoded string
  32. func (b *Blob) GetBlobContentBase64() (string, error) {
  33. dataRc, err := b.DataAsync()
  34. if err != nil {
  35. return "", err
  36. }
  37. defer dataRc.Close()
  38. pr, pw := io.Pipe()
  39. encoder := base64.NewEncoder(base64.StdEncoding, pw)
  40. go func() {
  41. _, err := io.Copy(encoder, dataRc)
  42. _ = encoder.Close()
  43. if err != nil {
  44. _ = pw.CloseWithError(err)
  45. } else {
  46. _ = pw.Close()
  47. }
  48. }()
  49. out, err := ioutil.ReadAll(pr)
  50. if err != nil {
  51. return "", err
  52. }
  53. return string(out), nil
  54. }