forked from knadh/stuffbin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs.go
329 lines (281 loc) · 7.3 KB
/
fs.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package stuffbin
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
// FileSystem represents a simple filesystem abstraction
// that implements the http.fileSystem interface.
type FileSystem interface {
Add(f *File) error
List() []string
Len() int
Size() int64
Get(path string) (*File, error)
Glob(pattern string) ([]string, error)
Read(path string) ([]byte, error)
Open(path string) (http.File, error)
Delete(path string) error
Merge(f FileSystem) error
FileServer() http.Handler
}
// memFS implements an in-memory FileSystem.
type memFS struct {
files map[string]*File
// size is the total size of all files in the filesystem.
size int64
}
// localFS implements a passthrough to the local filesystem.
type localFS struct {
files map[string]*File
// size is the total size of all files in the filesystem.
size int64
}
// File represents an abstraction over http.File.
type File struct {
path string
info os.FileInfo
b []byte
rd *bytes.Reader
}
// ErrNotSupported indicates interface methods
// that are implemented but not supported.
var ErrNotSupported = errors.New("this method is not supported")
// NewFS returns a new instance of FileSystem.
func NewFS() (FileSystem, error) {
return &memFS{
files: make(map[string]*File),
}, nil
}
// NewLocalFS returns a new instance of FileSystem
// with the given list of local files and directories mapped to it.
func NewLocalFS(rootPath string, paths ...string) (FileSystem, error) {
fs, _ := NewFS()
if err := walkPaths(func(srcPath, targetPath string, fInfo os.FileInfo) error {
f, err := os.Open(srcPath)
if err != nil {
return err
}
// Copy bytes.
buf := new(bytes.Buffer)
_, err = io.Copy(buf, f)
if err != nil {
return err
}
// Add the file to the filesystem.
return fs.Add(NewFile(targetPath, fInfo, buf.Bytes()))
}, rootPath, paths...); err != nil {
return nil, err
}
return fs, nil
}
// Add adds a file to the FileSystem.
func (fs *memFS) Add(f *File) error {
p := f.Path()
if _, ok := fs.files[p]; ok {
return fmt.Errorf("file already exists: %v", p)
}
// Clean the path. This also ensures that all files are
// always mounted to /. For instance, /mock/foo and mock/bar
// will be mounted as /mock/foo and /mock/bar respectively.
fs.files[cleanPath("", f.Path())] = f
// Append the filesize to the FileSystem.
s, err := f.Stat()
if err != nil {
return err
}
fs.size += s.Size()
return nil
}
// List returns the list of the file paths in the FileSystem.
func (fs *memFS) List() []string {
var (
out = make([]string, len(fs.files))
i = 0
)
for p := range fs.files {
out[i] = p
i++
}
return out
}
// Len returns the number of files in the FileSystem.
func (fs *memFS) Len() int {
return len(fs.files)
}
// Size returns the total size of all the files in the FileSystem.
func (fs *memFS) Size() int64 {
return fs.size
}
// Get returns a copy of a File from the FileSystem by its path.
func (fs *memFS) Get(fPath string) (*File, error) {
f, ok := fs.files[cleanPath("/", fPath)]
if !ok {
return nil, os.ErrNotExist
}
return NewFile(f.path, f.info, f.b), nil
}
// Glob returns the file paths in the filesystem matching
// a pattern.
func (fs *memFS) Glob(pattern string) ([]string, error) {
var out []string
for _, f := range fs.List() {
ok, err := filepath.Match(pattern, f)
if err != nil {
return nil, err
}
if ok {
out = append(out, f)
}
}
return out, nil
}
// Read returns a copy of a File's bytes from the FileSystem by its path.
func (fs *memFS) Read(fPath string) ([]byte, error) {
f, err := fs.Get(fPath)
if err != nil {
return nil, err
}
return f.ReadBytes(), nil
}
// Open returns an http.File from the Filesystem given its path.
func (fs *memFS) Open(path string) (http.File, error) {
return fs.Get(path)
}
// Delete deletes the given path.
func (fs *memFS) Delete(fPath string) error {
fPath = cleanPath("/", fPath)
_, ok := fs.files[fPath]
if !ok {
return os.ErrNotExist
}
delete(fs.files, fPath)
return nil
}
// Merge merges a given source FileSystem into this instance.
func (fs *memFS) Merge(src FileSystem) error {
return MergeFS(fs, src)
}
// FileServer returns an http.Handler that serves the files from
// the file system like http.FileServer.
func (fs *memFS) FileServer() http.Handler {
return http.FileServer(fs)
}
// NewFile creates and returns a new instance of File.
func NewFile(path string, info os.FileInfo, b []byte) *File {
f := &File{
path: path,
info: info,
b: make([]byte, len(b)),
}
copy(f.b, b)
f.rd = bytes.NewReader(f.b)
return f
}
// Path returns the path of the file.
func (f *File) Path() string {
return f.path
}
// ReadBytes returns the bytes of the given file.
func (f *File) ReadBytes() []byte {
b := make([]byte, len(f.b))
copy(b, f.b)
return b
}
// Close emulates http.File's Close but internally,
// it simply seeks the File's reader to 0.
func (f *File) Close() error {
_, err := f.Seek(0, 0)
return err
}
// Read reads the file contents.
func (f *File) Read(b []byte) (int, error) {
return f.rd.Read(b)
}
// Readdir is a dud.
func (f *File) Readdir(count int) ([]os.FileInfo, error) {
return nil, ErrNotSupported
}
// Seek seeks the given offset in the file.
func (f *File) Seek(offset int64, whence int) (int64, error) {
return f.rd.Seek(offset, whence)
}
// Stat returns the file's os.FileInfo.
func (f *File) Stat() (os.FileInfo, error) {
return f.info, nil
}
func cleanPath(rootPath, p string) string {
if rootPath == "" {
rootPath = "/"
}
// A preceding / is attempted to get rid of paths
// that begins with dots.
if filepath.Separator == '/' {
p = "/" + p
}
p = filepath.Join(rootPath, filepath.Clean(p))
p = strings.Replace(p, `\`, "/", -1)
p = strings.Replace(p, filepath.VolumeName(p), "", -1)
return p
}
// ParseTemplatesGlob takes a file system, a file path pattern,
// and parses matching files into a template.Template with an
// optional template.FuncMap that will be applied to the compiled
// templates.
func ParseTemplatesGlob(f template.FuncMap, fs FileSystem, pattern string) (*template.Template, error) {
paths, err := fs.Glob(pattern)
if err != nil {
return nil, err
}
if len(paths) == 0 {
return nil, fmt.Errorf("pattern %s matches no files", pattern)
}
return ParseTemplates(f, fs, paths...)
}
// ParseTemplates takes a file system, a list of file paths,
// and parses them into a template.Template.
func ParseTemplates(f template.FuncMap, fs FileSystem, path ...string) (*template.Template, error) {
tpl := template.New(filepath.Base(path[0]))
if f != nil {
tpl = tpl.Funcs(f)
}
if len(path) == 0 {
return nil, fmt.Errorf("no files named in call to ParseTemplates")
}
for _, p := range path {
f, err := fs.Read(p)
if err != nil {
return nil, fmt.Errorf("%s: %v", p, err)
}
_, err = tpl.Parse(string(f))
if err != nil {
return nil, err
}
}
return tpl, nil
}
// MergeFS merges FileSystem b into a, overwriting conflicting paths.
func MergeFS(dest FileSystem, src FileSystem) error {
for _, path := range src.List() {
// Get from target.
f, err := src.Get(path)
if err != nil {
return err
}
// Check if the path exists in the target. If yes, remove.
if err, _ := dest.Get(path); err != nil {
if err := dest.Delete(path); err != nil {
return err
}
}
// Add to destination.
dest.Add(f)
}
return nil
}