-
Notifications
You must be signed in to change notification settings - Fork 43
/
read_write_wrapper.go
88 lines (75 loc) · 1.82 KB
/
read_write_wrapper.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
88
package files
import (
"context"
"io"
"os"
"github.com/FleekHQ/space-daemon/log"
"github.com/FleekHQ/space-daemon/core/space"
)
// Wrapper around space files read and write logic.
// On close, it pushes changes to space.Service
type SpaceFilesHandler struct {
service space.Service
localFile *os.File
remotePath string
bucketName string
editted bool
}
func OpenSpaceFilesHandler(
service space.Service,
localFilePath,
remoteFilePath,
bucketName string,
) (*SpaceFilesHandler, error) {
localFile, err := os.Open(localFilePath)
if err != nil {
return nil, err
}
return &SpaceFilesHandler{
service: service,
localFile: localFile,
remotePath: remoteFilePath,
bucketName: bucketName,
editted: false,
}, nil
}
func (s *SpaceFilesHandler) Read(ctx context.Context, b []byte, offset int64) (int, error) {
_, err := s.localFile.Seek(offset, io.SeekStart)
if err != nil {
return 0, err
}
return s.localFile.Read(b)
}
func (s *SpaceFilesHandler) Write(ctx context.Context, b []byte, offset int64) (int, error) {
_, err := s.localFile.Seek(offset, io.SeekStart)
if err != nil {
return 0, err
}
n, err := s.localFile.Write(b)
if err == nil {
s.editted = true
}
return n, err
}
func (s *SpaceFilesHandler) Close(ctx context.Context) error {
log.Debug("Closing access to SpaceFileHandler", "remotePath:"+s.remotePath, "localPath:"+s.localFile.Name())
defer s.localFile.Close()
if s.editted {
_, err := s.localFile.Seek(0, 0)
if err != nil {
log.Error("Error seeking local file to beginning for upload", err)
return err
}
_, err = s.service.AddItemWithReader(
ctx,
s.localFile,
s.remotePath,
s.bucketName,
)
if err != nil {
return err
}
}
log.Debug("Adding files update complete", "remotePath:"+s.remotePath, "localFileName:"+s.localFile.Name())
return nil
}