-
Notifications
You must be signed in to change notification settings - Fork 0
/
boltfs.go
123 lines (96 loc) · 2.1 KB
/
boltfs.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package boltfs
import (
"fmt"
"io"
"io/fs"
"path/filepath"
"time"
"go.etcd.io/bbolt"
)
type ByteFile struct {
cursor int
path string
data []byte
}
var _ fs.File = &ByteFile{data: []byte{}}
func (bf *ByteFile) Read(data []byte) (int, error) {
len := copy(data, bf.data[bf.cursor:])
if len <= 0 {
return 0, io.EOF
}
bf.cursor += len
return len, nil
}
func (bf *ByteFile) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
bf.cursor = int(offset)
case io.SeekCurrent:
bf.cursor += int(offset)
case io.SeekEnd:
bf.cursor = (len(bf.data) - 1) - int(offset)
default:
panic(fmt.Errorf("unknown 'whence': %d", whence))
}
if bf.cursor < 0 || bf.cursor >= len(bf.data) {
return 0, fmt.Errorf("cursor value %d is outside of bounds: %w",
bf.cursor, io.EOF)
}
return int64(bf.cursor), nil
}
func (bf *ByteFile) Stat() (fs.FileInfo, error) {
return bf, nil
}
func (bf *ByteFile) Close() error {
return nil
}
func (bf *ByteFile) Name() string {
return filepath.Base(bf.path)
}
func (bf *ByteFile) Size() int64 {
return int64(len(bf.data))
}
func (bf *ByteFile) Mode() fs.FileMode {
return 0
}
func (bf *ByteFile) ModTime() time.Time {
return time.Time{}
}
func (bf *ByteFile) IsDir() bool {
return false
}
func (bf *ByteFile) Sys() any {
return nil
}
type BoltFS struct {
bucket []byte
*bbolt.DB
}
func NewBoltFS(db *bbolt.DB, bucketKey []byte) *BoltFS {
return &BoltFS{
bucket: bucketKey,
DB: db,
}
}
var _ fs.FS = &BoltFS{}
func (f *BoltFS) Open(path string) (fs.File, error) {
filename := filepath.Base(path)
file := ByteFile{path: path}
err := f.View(func(tx *bbolt.Tx) error {
bucket := tx.Bucket(f.bucket)
if bucket == nil {
return fmt.Errorf("bucket %q does not exist", f.bucket)
}
content := bucket.Get([]byte(filename))
if content == nil {
return fmt.Errorf("key %q in bucket %q does not exist", filename, f.bucket)
}
file.data = make([]byte, len(content))
copy(file.data, content)
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to start read-only transaction: %w", err)
}
return &file, nil
}