-
Notifications
You must be signed in to change notification settings - Fork 3
/
filter_fs_storer.go
64 lines (51 loc) · 1.47 KB
/
filter_fs_storer.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
package filters
import (
"bytes"
"io"
"io/fs"
"os"
"path"
"regexp"
"github.com/go-bond/bond"
)
type FilterFSStorer struct {
path string
noASCIIRegexp *regexp.Regexp
}
func NewFSFilterStorer(path string) *FilterFSStorer {
return &FilterFSStorer{path: path, noASCIIRegexp: regexp.MustCompile("[^A-Za-z0-9_.]")}
}
func (f *FilterFSStorer) Get(key []byte, batch ...bond.Batch) (data []byte, closer io.Closer, err error) {
filePath := f.prepareFilePath(f.path, string(key))
data, err = os.ReadFile(filePath)
if err != nil {
return nil, nil, err
}
return data, io.NopCloser(nil), nil
}
func (f *FilterFSStorer) Set(key []byte, value []byte, opt bond.WriteOptions, batch ...bond.Batch) error {
filePath := f.prepareFilePath(f.path, string(key))
err := os.WriteFile(filePath, value, 0660)
if err != nil {
return err
}
return nil
}
func (f *FilterFSStorer) DeleteRange(start []byte, end []byte, opt bond.WriteOptions, batch ...bond.Batch) error {
startFile := []byte(f.prepareFilePath("", string(start)))
dirFS := os.DirFS(f.path)
err := fs.WalkDir(dirFS, ".", func(filePath string, d fs.DirEntry, err error) error {
if bytes.Compare([]byte(filePath), startFile) >= 0 {
return os.Remove(path.Join(f.path, filePath))
}
return nil
})
return err
}
func (f *FilterFSStorer) prepareFilePath(root, fileName string) string {
return path.Join(
root,
f.noASCIIRegexp.ReplaceAllLiteralString(fileName, ""),
)
}
var _ bond.FilterStorer = &FilterFSStorer{}