-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
144 lines (113 loc) · 2.29 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
136
137
138
139
140
141
142
143
144
package store
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"github.com/murtaza-u/z/age/agelib"
"github.com/rwxrob/fs/file"
)
type Storer interface {
GetPath() string
List() []string
ListFull() []string
Delete(...string) error
EntryExists(string) bool
WriteEntry(string, []byte) error
Insert(string) ([]byte, error)
Decrypt(string) ([]byte, error)
}
type S struct {
C *Config
InputSecret func() (string, error)
}
func New(c *Config) *S {
return &S{C: c, InputSecret: func() (string, error) {
pswd := agelib.ReadHidden("password: ")
_cpswd := agelib.ReadHidden("confirm password: ")
if pswd != _cpswd {
return "", fmt.Errorf("passwords do not match")
}
return pswd, nil
}}
}
func (s S) GetPath() string {
return s.C.Pass.Store
}
func (s S) List() []string {
path := s.GetPath()
var list []string
err := filepath.Walk(path, func(sub string, i fs.FileInfo, err error) error {
if err != nil {
return err
}
if sub == path {
return nil
}
if i.IsDir() {
return nil
}
rel, err := filepath.Rel(path, sub)
if err != nil {
return err
}
list = append(list, rel)
return nil
})
if err != nil {
return []string{}
}
return list
}
func (s S) ListFull() []string {
path := s.GetPath()
var list []string
err := filepath.Walk(path, func(sub string, i fs.FileInfo, err error) error {
if err != nil {
return err
}
if sub == path {
return nil
}
if i.IsDir() {
return nil
}
list = append(list, sub)
return nil
})
if err != nil {
return nil
}
return list
}
func (s S) Delete(entries ...string) error {
for _, e := range entries {
if !s.EntryExists(e) {
return fmt.Errorf("entry %q does not exist", e)
}
y := confirm(fmt.Sprintf("delete %q?", e))
if !y {
fmt.Printf("skipping %q\n", e)
continue
}
path := s.GetPath()
path = filepath.Join(path, e)
err := os.Remove(path)
if err != nil {
return fmt.Errorf("failed to delete %q: %w", path, err)
}
}
return nil
}
func (s S) EntryExists(entry string) bool {
path := s.GetPath()
path = filepath.Join(path, entry)
return file.Exists(path)
}
func (s S) WriteEntry(entry string, out []byte) error {
path := s.GetPath()
path = filepath.Join(path, entry)
dir := filepath.Dir(path)
os.MkdirAll(dir, 0700)
return os.WriteFile(path, out, 0600)
}