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 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package git
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "io"
  9. "code.gitea.io/gitea/modules/typesniffer"
  10. "code.gitea.io/gitea/modules/util"
  11. )
  12. // This file contains common functions between the gogit and !gogit variants for git Blobs
  13. // Name returns name of the tree entry this blob object was created from (or empty string)
  14. func (b *Blob) Name() string {
  15. return b.name
  16. }
  17. // GetBlobContent Gets the limited content of the blob as raw text
  18. func (b *Blob) GetBlobContent(limit int64) (string, error) {
  19. if limit <= 0 {
  20. return "", nil
  21. }
  22. dataRc, err := b.DataAsync()
  23. if err != nil {
  24. return "", err
  25. }
  26. defer dataRc.Close()
  27. buf, err := util.ReadWithLimit(dataRc, int(limit))
  28. return string(buf), err
  29. }
  30. // GetBlobLineCount gets line count of the blob
  31. func (b *Blob) GetBlobLineCount() (int, error) {
  32. reader, err := b.DataAsync()
  33. if err != nil {
  34. return 0, err
  35. }
  36. defer reader.Close()
  37. buf := make([]byte, 32*1024)
  38. count := 1
  39. lineSep := []byte{'\n'}
  40. c, err := reader.Read(buf)
  41. if c == 0 && err == io.EOF {
  42. return 0, nil
  43. }
  44. for {
  45. count += bytes.Count(buf[:c], lineSep)
  46. switch {
  47. case err == io.EOF:
  48. return count, nil
  49. case err != nil:
  50. return count, err
  51. }
  52. c, err = reader.Read(buf)
  53. }
  54. }
  55. // GetBlobContentBase64 Reads the content of the blob with a base64 encode and returns the encoded string
  56. func (b *Blob) GetBlobContentBase64() (string, error) {
  57. dataRc, err := b.DataAsync()
  58. if err != nil {
  59. return "", err
  60. }
  61. defer dataRc.Close()
  62. pr, pw := io.Pipe()
  63. encoder := base64.NewEncoder(base64.StdEncoding, pw)
  64. go func() {
  65. _, err := io.Copy(encoder, dataRc)
  66. _ = encoder.Close()
  67. if err != nil {
  68. _ = pw.CloseWithError(err)
  69. } else {
  70. _ = pw.Close()
  71. }
  72. }()
  73. out, err := io.ReadAll(pr)
  74. if err != nil {
  75. return "", err
  76. }
  77. return string(out), nil
  78. }
  79. // GuessContentType guesses the content type of the blob.
  80. func (b *Blob) GuessContentType() (typesniffer.SniffedType, error) {
  81. r, err := b.DataAsync()
  82. if err != nil {
  83. return typesniffer.SniffedType{}, err
  84. }
  85. defer r.Close()
  86. return typesniffer.DetectContentTypeFromReader(r)
  87. }