123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- package lfsutil
- import (
- "io"
- "os"
- "path/filepath"
- "github.com/pkg/errors"
- "gogs.io/gogs/internal/osutil"
- )
- var ErrObjectNotExist = errors.New("Object does not exist")
- type Storager interface {
-
- Storage() Storage
-
-
-
- Upload(oid OID, rc io.ReadCloser) (int64, error)
-
-
-
- Download(oid OID, w io.Writer) error
- }
- type Storage string
- const (
- StorageLocal Storage = "local"
- )
- var _ Storager = (*LocalStorage)(nil)
- type LocalStorage struct {
-
- Root string
- }
- func (s *LocalStorage) Storage() Storage {
- return StorageLocal
- }
- func (s *LocalStorage) storagePath(oid OID) string {
- if len(oid) < 2 {
- return ""
- }
- return filepath.Join(s.Root, string(oid[0]), string(oid[1]), string(oid))
- }
- func (s *LocalStorage) Upload(oid OID, rc io.ReadCloser) (int64, error) {
- if !ValidOID(oid) {
- return 0, ErrInvalidOID
- }
- var err error
- fpath := s.storagePath(oid)
- defer func() {
- rc.Close()
- if err != nil {
- _ = os.Remove(fpath)
- }
- }()
- err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm)
- if err != nil {
- return 0, errors.Wrap(err, "create directories")
- }
- w, err := os.Create(fpath)
- if err != nil {
- return 0, errors.Wrap(err, "create file")
- }
- defer w.Close()
- written, err := io.Copy(w, rc)
- if err != nil {
- return 0, errors.Wrap(err, "copy file")
- }
- return written, nil
- }
- func (s *LocalStorage) Download(oid OID, w io.Writer) error {
- fpath := s.storagePath(oid)
- if !osutil.IsFile(fpath) {
- return ErrObjectNotExist
- }
- r, err := os.Open(fpath)
- if err != nil {
- return errors.Wrap(err, "open file")
- }
- defer r.Close()
- _, err = io.Copy(w, r)
- if err != nil {
- return errors.Wrap(err, "copy file")
- }
- return nil
- }
|