-
Notifications
You must be signed in to change notification settings - Fork 0
/
rwfs.go
96 lines (78 loc) · 1.79 KB
/
rwfs.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
package xfilesystem
import (
"io/fs"
"os"
"path/filepath"
"sort"
)
type RwFS interface {
fs.FS
BasePath() string
Sub(dir string) (RwFS, error)
Mkdir(name string) error
CreateFile(name string) (*os.File, error)
CleanupNewFiles() error
}
type rwFilesystem struct {
filesystem
newFilesMap map[string]bool
}
func NewRWFileSystem(path string, fsys fs.FS) RwFS {
return &rwFilesystem{
filesystem: filesystem{
basePath: path,
fsys: fsys,
},
newFilesMap: make(map[string]bool),
}
}
func (f *rwFilesystem) Mkdir(name string) error {
if found, _ := exists(filepath.Join(f.basePath, name)); found {
return os.ErrExist
}
f.newFilesMap[filepath.Join(f.basePath, name)] = true
return os.Mkdir(filepath.Join(f.basePath, name), 0755)
}
func (f *rwFilesystem) CreateFile(name string) (*os.File, error) {
if found, _ := exists(filepath.Join(f.basePath, name)); found {
return nil, os.ErrExist
}
f.newFilesMap[filepath.Join(f.basePath, name)] = false
return os.Create(filepath.Join(f.basePath, name))
}
func (f *rwFilesystem) Sub(dir string) (RwFS, error) {
newFs, err := f.filesystem.Sub(dir)
if err != nil {
return nil, err
}
return &rwFilesystem{
filesystem: filesystem{
basePath: newFs.BasePath(),
fsys: newFs,
},
newFilesMap: f.newFilesMap,
}, nil
}
func (f *rwFilesystem) CleanupNewFiles() error {
toDelete := make([]string, 0, len(f.newFilesMap))
for path := range f.newFilesMap {
toDelete = append(toDelete, path)
}
sort.Sort(sort.Reverse(sort.StringSlice(toDelete)))
for _, path := range toDelete {
if err := os.Remove(path); err != nil {
return err
}
}
return nil
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}