gitea源码

content_store.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package packages
  4. import (
  5. "io"
  6. "net/url"
  7. "path"
  8. "strings"
  9. "code.gitea.io/gitea/modules/setting"
  10. "code.gitea.io/gitea/modules/storage"
  11. "code.gitea.io/gitea/modules/util"
  12. )
  13. // BlobHash256Key is the key to address a blob content
  14. type BlobHash256Key string
  15. // ContentStore is a wrapper around ObjectStorage
  16. type ContentStore struct {
  17. store storage.ObjectStorage
  18. }
  19. // NewContentStore creates the default package store
  20. func NewContentStore() *ContentStore {
  21. contentStore := &ContentStore{storage.Packages}
  22. return contentStore
  23. }
  24. func (s *ContentStore) OpenBlob(key BlobHash256Key) (storage.Object, error) {
  25. return s.store.Open(KeyToRelativePath(key))
  26. }
  27. func (s *ContentStore) ShouldServeDirect() bool {
  28. return setting.Packages.Storage.ServeDirect()
  29. }
  30. func (s *ContentStore) GetServeDirectURL(key BlobHash256Key, filename, method string, reqParams url.Values) (*url.URL, error) {
  31. return s.store.URL(KeyToRelativePath(key), filename, method, reqParams)
  32. }
  33. // FIXME: Workaround to be removed in v1.20
  34. // https://github.com/go-gitea/gitea/issues/19586
  35. func (s *ContentStore) Has(key BlobHash256Key) error {
  36. _, err := s.store.Stat(KeyToRelativePath(key))
  37. return err
  38. }
  39. // Save stores a package blob
  40. func (s *ContentStore) Save(key BlobHash256Key, r io.Reader, size int64) error {
  41. _, err := s.store.Save(KeyToRelativePath(key), r, size)
  42. return err
  43. }
  44. // Delete deletes a package blob
  45. func (s *ContentStore) Delete(key BlobHash256Key) error {
  46. return s.store.Delete(KeyToRelativePath(key))
  47. }
  48. // KeyToRelativePath converts the sha256 key aabb000000... to aa/bb/aabb000000...
  49. func KeyToRelativePath(key BlobHash256Key) string {
  50. return path.Join(string(key)[0:2], string(key)[2:4], string(key))
  51. }
  52. // RelativePathToKey converts a relative path aa/bb/aabb000000... to the sha256 key aabb000000...
  53. func RelativePathToKey(relativePath string) (BlobHash256Key, error) {
  54. parts := strings.SplitN(relativePath, "/", 3)
  55. if len(parts) != 3 || len(parts[0]) != 2 || len(parts[1]) != 2 || len(parts[2]) < 4 || parts[0]+parts[1] != parts[2][0:4] {
  56. return "", util.ErrInvalidArgument
  57. }
  58. return BlobHash256Key(parts[2]), nil
  59. }