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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. // GetBlobContent Gets the content of the blob as raw text
  32. func (b *Blob) GetBlobContent() (string, error) {
  33. dataRc, err := b.DataAsync()
  34. if err != nil {
  35. return "", err
  36. }
  37. defer dataRc.Close()
  38. buf := make([]byte, 1024)
  39. n, _ := dataRc.Read(buf)
  40. buf = buf[:n]
  41. return string(buf), nil
  42. }
  43. // GetBlobContentBase64 Reads the content of the blob with a base64 encode and returns the encoded string
  44. func (b *Blob) GetBlobContentBase64() (string, error) {
  45. dataRc, err := b.DataAsync()
  46. if err != nil {
  47. return "", err
  48. }
  49. defer dataRc.Close()
  50. pr, pw := io.Pipe()
  51. encoder := base64.NewEncoder(base64.StdEncoding, pw)
  52. go func() {
  53. _, err := io.Copy(encoder, dataRc)
  54. _ = encoder.Close()
  55. if err != nil {
  56. _ = pw.CloseWithError(err)
  57. } else {
  58. _ = pw.Close()
  59. }
  60. }()
  61. out, err := ioutil.ReadAll(pr)
  62. if err != nil {
  63. return "", err
  64. }
  65. return string(out), nil
  66. }