-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmemfs.go
487 lines (416 loc) · 8.83 KB
/
memfs.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package memfs
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
syspath "path"
"strings"
"sync"
"time"
)
// FS is an in-memory filesystem that implements
// io/fs.FS
type FS struct {
dir *dir
openHook func(path string, existingContent []byte, origErr error) ([]byte, error)
}
// New creates a new in-memory FileSystem.
func New(opts ...Option) *FS {
var fsOpt fsOption
for _, opt := range opts {
opt.setOption(&fsOpt)
}
fs := FS{
dir: &dir{
children: make(map[string]childI),
},
}
fs.openHook = fsOpt.openHook
return &fs
}
// MkdirAll creates a directory named path,
// along with any necessary parents, and returns nil,
// or else returns an error.
// The permission bits perm (before umask) are used for all
// directories that MkdirAll creates.
// If path is already a directory, MkdirAll does nothing
// and returns nil.
func (rootFS *FS) MkdirAll(path string, perm os.FileMode) error {
if !fs.ValidPath(path) {
return fmt.Errorf("invalid path: %s: %w", path, fs.ErrInvalid)
}
if path == "." {
// root dir always exists
return nil
}
parts := strings.Split(path, "/")
next := rootFS.dir
for _, part := range parts {
cur := next
cur.mu.Lock()
child := cur.children[part]
if child == nil {
newDir := &dir{
name: part,
perm: perm,
children: make(map[string]childI),
}
cur.children[part] = newDir
next = newDir
} else {
childDir, ok := child.(*dir)
if !ok {
return fmt.Errorf("not a directory: %s: %w", part, fs.ErrInvalid)
}
next = childDir
}
cur.mu.Unlock()
}
return nil
}
func (rootFS *FS) getDir(path string) (*dir, error) {
if path == "" {
return rootFS.dir, nil
}
parts := strings.Split(path, "/")
cur := rootFS.dir
for _, part := range parts {
err := func() error {
cur.mu.Lock()
defer cur.mu.Unlock()
child := cur.children[part]
if child == nil {
return fmt.Errorf("not a directory: %s: %w", part, fs.ErrNotExist)
} else {
childDir, ok := child.(*dir)
if !ok {
return fmt.Errorf("no such file or directory: %s: %w", part, fs.ErrNotExist)
}
cur = childDir
}
return nil
}()
if err != nil {
return nil, err
}
}
return cur, nil
}
func (rootFS *FS) get(path string) (childI, error) {
if path == "" {
return rootFS.dir, nil
}
parts := strings.Split(path, "/")
var (
cur = rootFS.dir
chld childI
err error
)
for i, part := range parts {
chld, err = func() (childI, error) {
cur.mu.Lock()
defer cur.mu.Unlock()
child := cur.children[part]
if child == nil {
return nil, fmt.Errorf("not a directory: %s: %w", part, fs.ErrNotExist)
} else {
_, isFile := child.(*File)
if isFile {
if i == len(parts)-1 {
return child, nil
} else {
return nil, fmt.Errorf("no such file or directory: %s: %w", part, fs.ErrNotExist)
}
}
childDir, ok := child.(*dir)
if !ok {
return nil, errors.New("not a directory")
}
cur = childDir
}
return child, nil
}()
if err != nil {
return nil, err
}
}
return chld, nil
}
func (rootFS *FS) create(path string) (*File, error) {
if !fs.ValidPath(path) {
return nil, fmt.Errorf("invalid path: %s: %w", path, fs.ErrInvalid)
}
if path == "." {
// root dir
path = ""
}
dirPart, filePart := syspath.Split(path)
dirPart = strings.TrimSuffix(dirPart, "/")
dir, err := rootFS.getDir(dirPart)
if err != nil {
return nil, err
}
dir.mu.Lock()
defer dir.mu.Unlock()
existing := dir.children[filePart]
if existing != nil {
_, ok := existing.(*File)
if !ok {
return nil, fmt.Errorf("path is a directory: %s: %w", path, fs.ErrExist)
}
}
newFile := &File{
name: filePart,
perm: 0666,
}
dir.children[filePart] = newFile
return newFile, nil
}
// WriteFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it with permissions perm
// (before umask); otherwise WriteFile truncates it before writing, without changing permissions.
func (rootFS *FS) WriteFile(path string, data []byte, perm os.FileMode) error {
if !fs.ValidPath(path) {
return fmt.Errorf("invalid path: %s: %w", path, fs.ErrInvalid)
}
if path == "." {
// root dir
path = ""
}
f, err := rootFS.create(path)
if err != nil {
return err
}
f.content = data
f.perm = perm
return nil
}
// Open opens the named file.
func (rootFS *FS) Open(name string) (fs.File, error) {
if !fs.ValidPath(name) {
return nil, &fs.PathError{
Op: "open",
Path: name,
Err: fs.ErrInvalid,
}
}
child, err := rootFS.open(name)
if rootFS.openHook != nil {
var exitingContent []byte
if child != nil {
stat, _ := child.Stat()
if stat.Mode().IsDir() {
return child, err
}
exitingContent, err = io.ReadAll(child)
if err != nil {
return nil, err
}
newContent, err := rootFS.openHook(name, exitingContent, err)
if err != nil {
return nil, err
}
f := child.(*File)
f.content = newContent
f.reader = bytes.NewReader(newContent)
return f, nil
}
}
return child, err
}
func (rootFS *FS) open(name string) (fs.File, error) {
if name == "." {
// root dir
name = ""
}
child, err := rootFS.get(name)
if err != nil {
return nil, err
}
switch cc := child.(type) {
case *File:
handle := &File{
name: cc.name,
perm: cc.perm,
content: cc.content,
reader: bytes.NewReader(cc.content),
}
return handle, nil
case *dir:
handle := &fhDir{
dir: cc,
}
return handle, nil
}
return nil, fmt.Errorf("unexpected file type in fs: %s: %w", name, fs.ErrInvalid)
}
// Sub returns an FS corresponding to the subtree rooted at path.
func (rootFS *FS) Sub(path string) (fs.FS, error) {
dir, err := rootFS.getDir(path)
if err != nil {
return nil, err
}
return &FS{dir: dir}, nil
}
type dir struct {
mu sync.Mutex
name string
perm os.FileMode
modTime time.Time
children map[string]childI
}
type fhDir struct {
dir *dir
idx int
}
func (d *fhDir) Stat() (fs.FileInfo, error) {
fi := fileInfo{
name: d.dir.name,
size: 4096,
modTime: d.dir.modTime,
mode: d.dir.perm | fs.ModeDir,
}
return &fi, nil
}
func (d *fhDir) Read(b []byte) (int, error) {
return 0, errors.New("is a directory")
}
func (d *fhDir) Close() error {
return nil
}
func (d *fhDir) ReadDir(n int) ([]fs.DirEntry, error) {
d.dir.mu.Lock()
defer d.dir.mu.Unlock()
names := make([]string, 0, len(d.dir.children))
for name := range d.dir.children {
names = append(names, name)
}
// directory already exhausted
if n <= 0 && d.idx >= len(names) {
return nil, nil
}
// read till end
var err error
if n > 0 && d.idx+n > len(names) {
err = io.EOF
if d.idx > len(names) {
return nil, err
}
}
if n <= 0 {
n = len(names)
}
out := make([]fs.DirEntry, 0, n)
for i := d.idx; i < n && i < len(names); i++ {
name := names[i]
child := d.dir.children[name]
f, isFile := child.(*File)
if isFile {
stat, _ := f.Stat()
out = append(out, &dirEntry{
info: stat,
})
} else {
d := child.(*dir)
fi := fileInfo{
name: d.name,
size: 4096,
modTime: d.modTime,
mode: d.perm | fs.ModeDir,
}
out = append(out, &dirEntry{
info: &fi,
})
}
d.idx = i + 1
}
return out, err
}
type File struct {
name string
perm os.FileMode
content []byte
reader *bytes.Reader
modTime time.Time
closed bool
}
func (f *File) Stat() (fs.FileInfo, error) {
if f.closed {
return nil, fs.ErrClosed
}
fi := fileInfo{
name: f.name,
size: int64(len(f.content)),
modTime: f.modTime,
mode: f.perm,
}
return &fi, nil
}
func (f *File) Read(b []byte) (int, error) {
if f.closed {
return 0, fs.ErrClosed
}
return f.reader.Read(b)
}
func (f *File) Seek(offset int64, whence int) (int64, error) {
if f.closed {
return 0, fs.ErrClosed
}
return f.reader.Seek(offset, whence)
}
func (f *File) Close() error {
if f.closed {
return fs.ErrClosed
}
f.closed = true
return nil
}
type childI interface{}
type fileInfo struct {
name string
size int64
modTime time.Time
mode fs.FileMode
}
// base name of the file
func (fi *fileInfo) Name() string {
return fi.name
}
// length in bytes for regular files; system-dependent for others
func (fi *fileInfo) Size() int64 {
return fi.size
}
// file mode bits
func (fi *fileInfo) Mode() fs.FileMode {
return fi.mode
}
// modification time
func (fi *fileInfo) ModTime() time.Time {
return fi.modTime
}
// abbreviation for Mode().IsDir()
func (fi *fileInfo) IsDir() bool {
return fi.mode&fs.ModeDir > 0
}
// underlying data source (can return nil)
func (fi *fileInfo) Sys() interface{} {
return nil
}
type dirEntry struct {
info fs.FileInfo
}
func (de *dirEntry) Name() string {
return de.info.Name()
}
func (de *dirEntry) IsDir() bool {
return de.info.IsDir()
}
func (de *dirEntry) Type() fs.FileMode {
return de.info.Mode() & fs.ModeType
}
func (de *dirEntry) Info() (fs.FileInfo, error) {
return de.info, nil
}