-
Notifications
You must be signed in to change notification settings - Fork 31
/
file.go
66 lines (58 loc) · 1.56 KB
/
file.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
package file
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"github.com/kelindar/talaria/internal/encoding/block"
"github.com/kelindar/talaria/internal/encoding/key"
"github.com/kelindar/talaria/internal/monitor"
"github.com/kelindar/talaria/internal/monitor/errors"
"github.com/kelindar/talaria/internal/storage/writer/base"
)
// Writer represents a local file writer.
type Writer struct {
*base.Writer
directory string
}
// New creates a new writer.
func New(directory, filter, encoding string, monitor monitor.Monitor) (*Writer, error) {
dir, err := filepath.Abs(directory)
if err != nil {
return nil, errors.Internal("file: unable to create file writer", err)
}
baseWriter, err := base.New(filter, encoding, monitor)
if err != nil {
return nil, errors.Newf("file: %v", err)
}
return &Writer{
Writer: baseWriter,
directory: dir,
}, nil
}
// Write writes the data to the sink.
func (w *Writer) Write(key key.Key, blocks []block.Block) error {
if len(blocks) == 0 {
return nil
}
filename := path.Join(w.directory, string(key))
dir := path.Dir(filename)
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
err := os.MkdirAll(dir, 0777)
if err != nil {
return errors.Internal("file: unable to create directory", err)
}
} else {
return errors.Internal("file: unable to write", err)
}
}
buffer, err := w.Writer.Encode(blocks)
if err != nil {
return errors.Newf("file: %v", err)
}
if err := ioutil.WriteFile(filename, buffer, 0644); err != nil {
return errors.Internal("file: unable to write", err)
}
return nil
}