forked from gopasspw/gopass
/
store.go
135 lines (112 loc) · 2.38 KB
/
store.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
124
125
126
127
128
129
130
131
132
133
134
135
package inmem
import (
"context"
"fmt"
"sort"
"strings"
"sync"
"github.com/blang/semver"
)
// InMem is a in-memory store
type InMem struct {
sync.Mutex
data map[string][]byte
}
// New creates a new mock
func New() *InMem {
return &InMem{
data: make(map[string][]byte, 10),
}
}
// Get retrieves a value
func (m *InMem) Get(ctx context.Context, name string) ([]byte, error) {
m.Lock()
defer m.Unlock()
sec, found := m.data[name]
if !found {
return nil, fmt.Errorf("entry not found")
}
return sec, nil
}
// Set writes a value
func (m *InMem) Set(ctx context.Context, name string, value []byte) error {
m.Lock()
defer m.Unlock()
m.data[name] = value
return nil
}
// Delete removes a value
func (m *InMem) Delete(ctx context.Context, name string) error {
m.Lock()
defer m.Unlock()
delete(m.data, name)
return nil
}
// Exists checks is a value exists
func (m *InMem) Exists(ctx context.Context, name string) bool {
m.Lock()
defer m.Unlock()
_, found := m.data[name]
return found
}
// List shows all values
func (m *InMem) List(ctx context.Context, prefix string) ([]string, error) {
m.Lock()
defer m.Unlock()
keys := make([]string, 0, len(m.data))
for k := range m.data {
keys = append(keys, k)
}
sort.Strings(keys)
return keys, nil
}
// IsDir returns true if the entry is a directory
func (m *InMem) IsDir(ctx context.Context, name string) bool {
m.Lock()
defer m.Unlock()
for k := range m.data {
if strings.HasPrefix(k, name+"/") {
return true
}
}
return false
}
// Prune removes a directory
func (m *InMem) Prune(ctx context.Context, prefix string) error {
m.Lock()
defer m.Unlock()
deleted := 0
for k := range m.data {
if strings.HasPrefix(k, prefix+"/") {
delete(m.data, k)
deleted++
}
}
if deleted < 1 {
return fmt.Errorf("not found")
}
return nil
}
// Name returns the name of this backend
func (m *InMem) Name() string {
return "inmem"
}
// Version returns the version of this backend
func (m *InMem) Version(context.Context) semver.Version {
return semver.Version{Major: 1}
}
// String implement fmt.Stringer
func (m *InMem) String() string {
return "inmem()"
}
// Available will check if this backend is useable
func (m *InMem) Available(ctx context.Context) error {
if m.data == nil {
return fmt.Errorf("not initialized")
}
return nil
}
// Fsck always returns nil
func (m *InMem) Fsck(ctx context.Context) error {
return nil
}