code.gitea.io/gitea@v1.22.3/modules/packages/content_store.go (about)

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