forked from mxpv/podsync
/
local.go
87 lines (69 loc) · 1.79 KB
/
local.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package fs
import (
"context"
"io"
"net/http"
"os"
"path/filepath"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// LocalConfig is the storage configuration for local file system
type LocalConfig struct {
DataDir string `toml:"data_dir"`
}
// Local implements local file storage
type Local struct {
rootDir string
}
func NewLocal(rootDir string) (*Local, error) {
return &Local{rootDir: rootDir}, nil
}
func (l *Local) Open(name string) (http.File, error) {
path := filepath.Join(l.rootDir, name)
return os.Open(path)
}
func (l *Local) Delete(_ctx context.Context, name string) error {
path := filepath.Join(l.rootDir, name)
return os.Remove(path)
}
func (l *Local) Create(_ctx context.Context, name string, reader io.Reader) (int64, error) {
var (
logger = log.WithField("name", name)
path = filepath.Join(l.rootDir, name)
)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return 0, errors.Wrapf(err, "failed to mkdir: %s", path)
}
logger.Infof("creating file: %s", path)
written, err := l.copyFile(reader, path)
if err != nil {
return 0, errors.Wrap(err, "failed to copy file")
}
logger.Debugf("written %d bytes", written)
return written, nil
}
func (l *Local) copyFile(source io.Reader, destinationPath string) (int64, error) {
dest, err := os.Create(destinationPath)
if err != nil {
return 0, errors.Wrap(err, "failed to create destination file")
}
defer dest.Close()
written, err := io.Copy(dest, source)
if err != nil {
return 0, errors.Wrap(err, "failed to copy data")
}
return written, nil
}
func (l *Local) Size(_ctx context.Context, name string) (int64, error) {
file, err := l.Open(name)
if err != nil {
return 0, err
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return 0, err
}
return stat.Size(), nil
}