Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

content_store.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package lfs
  2. import (
  3. "code.gitea.io/gitea/models"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "errors"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. )
  11. var (
  12. errHashMismatch = errors.New("Content hash does not match OID")
  13. errSizeMismatch = errors.New("Content size does not match")
  14. )
  15. // ContentStore provides a simple file system based storage.
  16. type ContentStore struct {
  17. BasePath string
  18. }
  19. // Get takes a Meta object and retrieves the content from the store, returning
  20. // it as an io.Reader. If fromByte > 0, the reader starts from that byte
  21. func (s *ContentStore) Get(meta *models.LFSMetaObject, fromByte int64) (io.ReadCloser, error) {
  22. path := filepath.Join(s.BasePath, transformKey(meta.Oid))
  23. f, err := os.Open(path)
  24. if err != nil {
  25. return nil, err
  26. }
  27. if fromByte > 0 {
  28. _, err = f.Seek(fromByte, os.SEEK_CUR)
  29. }
  30. return f, err
  31. }
  32. // Put takes a Meta object and an io.Reader and writes the content to the store.
  33. func (s *ContentStore) Put(meta *models.LFSMetaObject, r io.Reader) error {
  34. path := filepath.Join(s.BasePath, transformKey(meta.Oid))
  35. tmpPath := path + ".tmp"
  36. dir := filepath.Dir(path)
  37. if err := os.MkdirAll(dir, 0750); err != nil {
  38. return err
  39. }
  40. file, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0640)
  41. if err != nil {
  42. return err
  43. }
  44. defer os.Remove(tmpPath)
  45. hash := sha256.New()
  46. hw := io.MultiWriter(hash, file)
  47. written, err := io.Copy(hw, r)
  48. if err != nil {
  49. file.Close()
  50. return err
  51. }
  52. file.Close()
  53. if written != meta.Size {
  54. return errSizeMismatch
  55. }
  56. shaStr := hex.EncodeToString(hash.Sum(nil))
  57. if shaStr != meta.Oid {
  58. return errHashMismatch
  59. }
  60. if err := os.Rename(tmpPath, path); err != nil {
  61. return err
  62. }
  63. return nil
  64. }
  65. // Exists returns true if the object exists in the content store.
  66. func (s *ContentStore) Exists(meta *models.LFSMetaObject) bool {
  67. path := filepath.Join(s.BasePath, transformKey(meta.Oid))
  68. if _, err := os.Stat(path); os.IsNotExist(err) {
  69. return false
  70. }
  71. return true
  72. }
  73. func transformKey(key string) string {
  74. if len(key) < 5 {
  75. return key
  76. }
  77. return filepath.Join(key[0:2], key[2:4], key[4:])
  78. }